dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def __remove_docker_images(self):
self.logger.info('>>> Remove Docker images.')
script = """
cat ~/.passwd | sudo -S -p '' docker rmi -f {}
cat ~/.passwd | sudo -S -p '' docker rmi -f {}
cat ~/.passwd | sudo -S -p '' docker rmi -f {}
""".format(
s... | The main task of the code is to perform cleanup operations by removing Docker images and unlocking both remote and local task home directories, ensuring system resources are released and task environments are reset after completion. | def __cleanup(self):
self.__remove_docker_images()
self.__unlock_remote_task_home()
self.__unlock_local_task_home() |
def create_panorama(img_paths: list, rois: list = None, downscale_factor=4, kernel_size=3, ratio_thresh=0.7, k=2, ransac_thresh=4) -> (np.ndarray, list):
"""
Creates a panorama by subsequently stitching neighbouring images
Image paths must be sorted but can be from right to left or the other way around
... | The function creates a centered panorama by splitting images into two halves, stitching each half into a panorama, and combining them using homography. For more than 3 images, it stitches left/right halves separately, matches center images' features, computes homography, and merges panoramas. For fewer images, it uses ... | def create_centered_panorama(img_paths: list, rois: list = None, downscale_factor=4, kernel_size=3, ratio_thresh=0.7, k=2, ransac_thresh=4) -> np.ndarray:
"""
Creates a centered panorama by subsequently stitching neighbouring images for both halfs of the images and then combining those two panoramas
Image p... |
def _merge_conv_data(self, conversation):
augmented_convs = []
last_role = None
dialog = conversation['dialog']
for utt in dialog:
text_token_ids = [self.tok2ind.get(word, self.unk_token_idx) for word in utt["text"]]
movie_ids = [self.entity2id[movie] for movie in... | This function processes raw conversation data by merging and augmenting each conversation. It iterates through input data, applies model-specific augmentation (RevCoreRec or default), and compiles results into a list of processed conversation dictionaries for subsequent use in recommendation tasks. | def _raw_data_process(self, raw_data):
augmented_convs = {conversation['conv_id']: self._merge_conv_data(conversation) for conversation in tqdm(raw_data)}
augmented_conv_dicts = []
for conv_id, conv in tqdm(augmented_convs.items()):
if self.opt["rec_model"] == 'RevCoreRec':
... |
def getFilteredSpectrogram(genDataF, fs=fs):
f, t, Sxx = sp.spectrogram(genDataF, fs)
ind = Sxx > getNoiseThresh(Sxx)
freqs = np.tile(np.array(f), (len(t), 1)).T[ind]
return freqs, Sxx[ind]
def weighted_mean(var, wts):
"""Calculates the weighted mean"""
return np.average(var, weights=wts)
def ... | The function `filterAndCalc` processes seismic data by filtering it, detecting clicks/peaks, and computing statistical features from the coda and click spectra. It calculates weighted mean, standard deviation, skewness, and kurtosis for both the filtered data's coda spectrum and individual click segments. The results i... | def filterAndCalc(data):
""" calculate stats for unit i out of N per bit:t level"""
# replace in-place
data = sp.sosfilt(fltr, data)
peaks, nclicks = clickDetector(data, fltr=False)
ff, codaSpectrum = sp.periodogram(data, fs=fs, window="hamming")
freqs, Sxx = getFilteredSpectrogram(data)
... |
def _partial_update(self, update: dict):
"""
Update the given values in the dict
:param update: values to update, use dot notation to update maps e,g `map.key` otherwise the map will be overwritten
:return:
"""
if not self._write_blocked:
self._doc_ref.set(upd... | The code initializes a task's start time, updates its status to "RUNNING," executes the task (yielding control), and sets status to "COMPLETE" on success. If an error occurs, it marks the task as "FAILED," logs the error, and re-raises the exception. Finally, it records the end time and writes full task data to the met... | def start(self):
try:
self._start_time = firestore.SERVER_TIMESTAMP
self._partial_update({"start_time": self.start_time,
"status": self.RUNNING})
yield self
self.status = self.COMPLETE
except Exception as e:
se... |
def cancel_action(query, message):
query.answer()
query.bot.send_message(query.message.chat_id, message, parse_mode=ParseMode.MARKDOWN)
return ConversationHandler.END
def show_matching_car(query, watchlist_id, update, context):
try:
watchlist = get_watchlist(watchlist_id)
query.answer()
... | This function handles user actions related to a watchlist via callback queries. It processes options like viewing matching cars, editing, or removing a watchlist. If '/cancel' is selected, it cancels the action. Depending on the chosen option, it invokes specific functions (e.g., show_matching_car, input_watchlist, per... | def perform_watchlist_action(update, context):
query = update.callback_query
option = query.data
if option == '/cancel':
return cancel_action(query, 'Cancelled')
watchlist_id = context.user_data['watchlist_id']
if option == 'View matching cars':
show_matching_car(query, watchlist_id... |
def cancel_action(query, message):
query.answer()
query.bot.send_message(query.message.chat_id, message, parse_mode=ParseMode.MARKDOWN)
return ConversationHandler.END
def save_watchlist(update, context):
query = update.callback_query
try:
query.answer()
user = get_user(update.effecti... | The main task of this code is to handle user interactions for managing a watchlist or car search feature. It processes user responses (e.g., cancel, save, or proceed) and directs the flow accordingly. If no explicit action is taken, it prompts the user to select options like adding car parameters (year, mileage, price)... | def confirm_watchlist_details(update, context):
query = update.callback_query
user_answer = query.data
if user_answer == '/cancel' or user_answer == 'No':
return cancel_action(query, 'Adding watchlist cancelled')
if user_answer == 'Save watchlist' or user_answer == 'Yes':
return save_wat... |
def _convert_label_object(self, obj):
converted = self._convert_annotation(obj)
converted.update({
'label_id': cast(obj.label, int),
})
return converted
def _convert_mask_object(self, obj):
converted = self._convert_annotation(obj)
if isinstance(obj, RleMask... | This function converts an item's data into a structured dictionary format, handling attributes, image paths, and annotations. It processes each annotation type (e.g., Label, Mask, Bbox) by converting them using specific methods, appends the results to the item's annotations list, and stores the final structured item de... | def write_item(self, item):
annotations = []
item_desc = {
'id': item.id,
'annotations': annotations,
}
if item.attributes:
item_desc['attr'] = item.attributes
if item.path:
item_desc['path'] = item.path
if item.has_image:
... |
def _count_bits(value):
count = 0
while value:
count += value & 1
value >>= 1
return count
def _send_command(self, cmd, data=None):
self._drain_serial()
if self._port is None:
raise Exception("serial port has been closed")
if data is None:
data... | The main task of the code is to continuously yield data frames of specified types by sending commands, reading packets, decoding them, and controlling the frame emission rate with a minimum interval, while respecting a maximum count limit or stop signal to prevent buffer overflow. | def stream_frames(self, frame_codes, max_count=-1, min_frame_interval=0):
"""Yield a stream of data frames of various types
:param frame_codes: flags for which frame types to be returned
:type frame_codes: kld7.FrameCode
:param max_count: maximum number of frame sets to return (or -1 fo... |
def _send_command(self, cmd, data=None):
self._drain_serial()
if self._port is None:
raise Exception("serial port has been closed")
if data is None:
data = b''
if isinstance(data, int):
data = struct.pack("<i", data)
if isinstance(cmd, str):
... | The code reads a specific frame by sending the 'GNFD' command with the given frame code, decodes the received packet, and returns the extracted payload data. | def _read_single_frame(self, frame_code):
self._send_command('GNFD', frame_code)
_, payload = _decode_frame(*self._read_packet())
return payload |
def extractZip(zipPath, extractFolder):
try:
zipLoc = zipfile.ZipFile(zipPath)
zipLoc.extractall(extractFolder)
return True
except:
pass
return False
def extractTar(tarPath, extractFolder):
tar = tarfile.open(tarPath)
for member in tar:
member.mode = stat.S_... | This function determines the type of input file (ZIP, TAR, or large image) and processes it by extracting contents to a specified directory, returning the resulting path. It checks file type and size, using specific extraction functions, and defaults to returning the original path if no extraction is needed. | def tryAllInputs(inputPath, extractedRoot):
newInput = False
if zipfile.is_zipfile(inputPath):
newInput = extractZip(inputPath, extractedRoot)
elif tarfile.is_tarfile(inputPath):
newInput = extractTar(inputPath, extractedRoot)
elif os.path.getsize(inputPath) > 1073741824:
newInpu... |
def recreate_database():
'''
Handles running the code normally managed by create tables.
- Will Drop then create the database
- Will then drop any of our tables that may exist.
- Will then create our tables.
'''
cur, conn = create_tables.create_database()
create_tables.dro... | The main task of the code is to execute a regeneration process by recreating a database, reprocessing data, and verifying the creation, ensuring system readiness for subsequent operations. | def _main():
'''
Main function to handle running the regeneration
'''
recreate_database()
reprocess_data()
check_creation() |
def load_data(self):
data = get_reader_data(self.data_name)
return [self.format_row(row) for row in data]
def max_column_value(self, data, column: str):
column_data = self.columns[column]
column_index = column_data['index']
max_element = max(data, key=lambda element: element[colu... | The main task of the code is to process data based on parameters: it filters data by maximum/minimum values (after type validation), sorts data by a column, or converts data to JSON if no parameters are specified. The function checks column types against allowed extremes (integer, float, date, datetime) and applies cor... | def get_processed_data(self):
data = self.load_data()
sort_column = self.params.get('sort')
max_column = self.params.get('max')
min_column = self.params.get('min')
extreme_types = [Types.integer, Types.float, Types.date, Types.datetime]
if max_column is not None:
... |
def check_python_version():
"""
Makes sure that the script is run with Python 3.6 or newer.
"""
if sys.version_info.major == 3 and sys.version_info.minor >= 6:
return
version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
raise RuntimeError("Unsupported Python version {... | This code installs GPU drivers and the CUDA Toolkit on a Linux system, requiring root privileges. It checks prerequisites like Python version, system distribution, and GPU presence. If drivers are already installed (and --force isn't used), it exits. It installs dependencies, verifies GPU hardware, and executes driver ... | def install(args: argparse.Namespace):
# Prerequisites
check_python_version()
if os.geteuid() != 0:
print("This script needs to be run with root privileges!")
sys.exit(1)
# Set up the log directory.
Logger.setup_log_dir()
if check_driver_installed() and not args.force:
... |
def parse_args():
parser = argparse.ArgumentParser(description='Install or verify GPU drivers.')
parser.add_argument("action", choices=['install', 'verify'], default="install", nargs="?")
parser.add_argument("--force", help="Forces driver installation, even if there is no GPU detected.",
... | The main task of the code is to handle driver installation and verification. It parses command-line arguments, checks if the NVIDIA driver is installed when the 'verify' action is specified, and triggers the installation process when the 'install' action is specified, ensuring proper driver status checks and user feedb... | def main():
"""
Main function of the installation script.
"""
args = parse_args()
if args.action == 'verify':
if not check_driver_installed():
print("The driver is not installed.")
else:
print("The driver seems to be installed. Run `nvidia-smi` to check detai... |
def __assignPosRand(self):
'''
Private Method. Spawns agents randomly on the grid.
'''
for i in range(len(self.agents)):
x,y = self.__chooseXYrand()
self.agents[i].pos = {'x':x,'y':y}
self.__populateMat(self.agents[i])
return
def __populat... | The code performs a single simulation iteration by sequentially executing internal methods: assigning agent positions, populating food, optionally rendering steps, picking food, transitioning to 'night', logging population data, and resetting food. The 't' parameter controls rendering. | def iterate(self,t):
'''
Runs a single Iteration. Calls Internal methods in a
logical sequence.
'''
self.__assignPosRand()
self.__populateFood()
if not t:
self.__render(1)
self.__pickFood()
if not t:
self.__render(... |
def reverse(lcg_edges):
rev = {}
for i in lcg_edges:
rev[i] = []
for i in lcg_edges:
for j in lcg_edges[i]:
rev[j].append(i)
return rev
def rank(lcg_edges): # suppose there is no scc, returns the topological rank of an SLCG
rev_lcg_edges = reverse(lcg_edges)
ranking ... | This function processes a graph (lcg_edges, lcg_nodes) by iteratively updating a dictionary 'val' to track node groupings. It uses a ranking of nodes, reverses edges when updates occur, and reorders the ranking to prioritize nodes with changed groupings. The main task is to partition the graph into subsets based on edg... | def cut_set(lcg_edges, lcg_nodes): # use simplified lcg
val = {}
rev_lcg_edge = reverse(lcg_edges)
ranking = rank(lcg_edges)
for i in ranking:
val[i] = []
while ranking:
val_temp = update(val, ranking.pop(0), lcg_edges, lcg_nodes) # could use a subset of lcg_nodes
if val_te... |
def reverse(lcg_edges):
rev = {}
for i in lcg_edges:
rev[i] = []
for i in lcg_edges:
for j in lcg_edges[i]:
rev[j].append(i)
return rev
def rank(lcg_edges): # suppose there is no scc, returns the topological rank of an SLCG
rev_lcg_edges = reverse(lcg_edges)
ranking ... | This function processes a graph's edges and nodes to compute a transition state. It initializes a dictionary, ranks nodes, iteratively updates the state by processing nodes in order, and adjusts the processing sequence based on reversed edges if changes occur. The goal is to determine a final transition state by propag... | def cut_set_transition(lcg_edges, lcg_nodes): # use simplified lcg
val = {}
rev_lcg_edge = reverse(lcg_edges)
ranking = rank(lcg_edges)
for i in ranking:
val[i] = []
while ranking:
val_temp = update_transition(val, ranking.pop(0), lcg_edges, lcg_nodes) # could use a subset of lcg_n... |
def rank(lcg_edges): # suppose there is no scc, returns the topological rank of an SLCG
rev_lcg_edges = reverse(lcg_edges)
ranking = []
# rank_num = 0
to_check = []
checked = []
for i in lcg_edges:
if not lcg_edges[i]:
to_check.append(i)
while to_check:
for i in ... | This function computes a completion set for nodes in a graph by iteratively updating values based on edge dependencies. It ranks nodes, processes them in order, and adjusts the processing sequence using reversed edges when updates occur. The goal is to propagate initial states through the graph's structure to determine... | def completion_set(lcg_edges, lcg_nodes, initial_state):
val = {}
ranking = rank(lcg_edges)
rev_lcg_edge = reverse(lcg_edges)
for i in ranking:
val[i] = []
while ranking:
val_temp = update_completion(val, ranking.pop(0), lcg_edges, initial_state)
if val_temp != val:
... |
def init_inserted_times():
try:
global inserted_dates
dates = get_publish_dates()
print(dates)
print(len(dates))
logging.info(dates)
logging.info(len(dates))
for date in dates:
inserted_dates[date[0]] = 1
except sqlite3.DatabaseError as e:
... | This function inserts an article into a database if all required fields are present. It checks if the article's publish date is already registered, connects to the database, executes an INSERT query with the article's data, and updates tracking records. Error handling ensures database issues are logged. | def insert_article(article):
if article['author'] and article['publish_date'] and article['category'] and article['currency'] and article['title'] and article['content'] and article['summary'] and article['link']:
try:
global current_inserted_date
current_inserted_date = article['pub... |
def retrieve(query):
query = normalize(query)
print("RETRIEVE: QUERY IS {}".format(query))
s_query = query.split()
candidates = {}
for w in s_query:
if w in inverse_index.keys():
# print('RETRIEVE: FOUND {} IN INV_IND'.format(w))
for d in inverse_index[w]:
... | The main task of the code is to sort documents by their relevance to a query using vector similarity. It retrieves candidate documents, vectorizes the query and each document's content, calculates squared differences between vectors, and ranks documents by these scores, returning the most relevant ones first. | def sort_relevance(query):
candidates = retrieve(query)
query_emb = vectorize_text(normalize(query))
rating = []
for i, freq in candidates:
curr_doc = Document.read_doc(i)
rating.append(((np.average(vectorize_text(normalize(curr_doc.question+curr_doc.answer))-query_emb))**2, curr_doc))
... |
def explore_walls_iterative_ortho(grid, tile_set):
"""
Iteratively explores walls from a set of points,
- returns a list of all coordinates in that cavern - orthogonal version
:param grid: LifeMap object
:param tile_set: list of tuple int x y coordinates
:return: closest "live" coordinates of n... | The function connects disconnected caverns in a grid by iteratively linking the smallest caverns first. It identifies the closest accessible floor tile from each cavern using flood fill, then creates corridors to connect them. After each connection, the grid is updated, and remaining small caverns are filled. This repe... | def connect_caverns_closest(grid, caverns, min_cavern_size):
"""
Connect caverns using closest tiles rather than random tiles
- strategy: sort the caverns smallest to largest
- start with the smallest cavern
- flood fill neighboring WALLS until a FLOOR neighbor is detected that is NOT part of cur... |
def cycle(grid, survive_min, survive_max, resurrect_min, resurrect_max):
"""
Heart of the Conway's Game Of Life algorithm for our purposes
(credit to https://gridbugs.org/cellular-automata-cave-generation/)
:param grid: list of lists of booleans denoting map
:param survive_min: minimum number of nei... | The code generates a cave-like map using cellular automata by iterating a LifeMap, cleaning up connected regions, creating zones (rooms), and connecting them with corridors. It returns the final map, zones, and corridors for dungeon generation. | def create_caverns(map_width, map_height, survive_min, survive_max, resurrect_min, resurrect_max, iterations,
zone_seed_min_distance, min_cavern_size):
# create random LifeMap object
life_map = LifeMap(map_width=map_width, map_height=map_height)
life_map.make_random()
# cycle Li... |
def read_top_file(topfile: str) -> dict:
"""
Extract the molecules from topology (.top) file.
PARAMETERS:
topfile - the .top file from GROMACS with number of molecules.
OUTPUT:
top_data - nested dictionary -> {moltype: {'resname': str, 'amount': int}}
"""
# Create a nested dictionary with topology data
top_... | This function randomly removes solvent molecules from a molecular system described by GROMACS .gro and .top files, generating new configuration and topology files after each evaporation cycle. It calculates the number of molecules to remove based on either a specified count (evapN) or a percentage (evapRate), adjusts i... | def random_remover(grofile: str, topfile: str, evapRate: float, cycle: int, evapN: int):
"""
Randomly remove the solvent and generate new .gro and .top files.
PARAMETERS:
grofile - the .gro file from GROMACS with atomic positions
topfile - the .top file from GROMACS with number of molecules
evapRate [type: float... |
def read_top_file(topfile: str) -> dict:
"""
Extract the molecules from topology (.top) file.
PARAMETERS:
topfile - the .top file from GROMACS with number of molecules.
OUTPUT:
top_data - nested dictionary -> {moltype: {'resname': str, 'amount': int}}
"""
# Create a nested dictionary with topology data
top_... | The code removes solvent molecules that escape the original PBC box after NVT simulations by identifying atoms outside the box dimensions, appending their molecule IDs to a removal list, and generating updated `.gro` and `.top` files for each cycle. It supports cluster-specific workflows, including doubling the box vol... | def thermo_remover(grofile: str, topfile: str, evapRate: float, cycle: int, cluster: str):
"""
Removes molecules that escape from original PBC box after NVT simulations.
PARAMETERS:
grofile - the .gro file from GROMACS with atomic positions
topfile - the .top file from GROMACS with number of molecules
evapRate ... |
def read_top_file(topfile: str) -> dict:
"""
Extract the molecules from topology (.top) file.
PARAMETERS:
topfile - the .top file from GROMACS with number of molecules.
OUTPUT:
top_data - nested dictionary -> {moltype: {'resname': str, 'amount': int}}
"""
# Create a nested dictionary with topology data
top_... | The function performs iterative solvent removal and GROMACS NPT simulations to model solvent evaporation in a molecular system. It dynamically or statically reduces solvent molecules based on specified rates (evapRate) and total removal (evapTotal), using either thermodynamic or random methods. Output includes intermed... | def solvent_evaporation(grofile: str, topfile: str, evapRate: float, evapTotal: float, cluster: str, dynamic: bool, thermo: bool):
"""
Perform a loop of solvent removal and GROMACS NPT simulation.
PARAMETERS:
grofile - the .gro file from GROMACS with atomic positions
topfile - the .top file from GROMACS with numb... |
def match(tt1, tt2, cardinal):
if cardinal == N:
return stackv(tt2, tt1)
if cardinal == S:
return stackv(tt1, tt2)
if cardinal == W:
return stackh(tt2, tt1)
if cardinal == E:
return stackh(tt1, tt2)
def neighbours(coord):
i, j = coord
return (
((i+di, j+dj... | The code recursively solves a puzzle by selecting the next coordinate with minimal Manhattan distance, validating possible tiles against neighbors, and backtracking if a tile placement leads to a dead end, aiming to find a complete valid state configuration. | def solve(state):
remaining_coords = coordinates - set(state)
if not remaining_coords:
return state
coord = min(remaining_coords, key=mhatnorm)
possibilities = (
tt
for tt in transformed_tiles
if not any(
tt.id == other.id
for other in state.values... |
def process_subtitle_file(file_path, total_duration, subtitle_index):
with open(file_path, 'r') as infile:
lines = infile.readlines()
adjusted_lines = []
i = 0
while i < len(lines):
# Check if the line is a number (indicating a new subtitle block)
if lines[i].strip().isdigit():
... | This code concatenates multiple subtitle files (ending with .srt) from a specified directory into a single unified subtitle file. It processes each file sequentially, adjusts their timecodes by adding cumulative durations from previous files, and writes the merged content to an output file named after the base name. Th... | def concatenate_subtitles(base_name, source_directory):
file_pattern = os.path.join(source_directory, f"{base_name}_*.srt")
subtitle_files = sorted(glob.glob(file_pattern))
output_file_path = os.path.join(source_directory, f"{base_name}.srt")
# Initialize total duration and subtitle index
total_du... |
def parse(s):
'''Parse a source string into an abstract syntax tree.'''
toks = tokenize(s)
tree = parse_partree(toks)
return parse_parexpr(tree)
def reduce_full(expr, ct_cycles=False):
global cycle_ctr
if ct_cycles:
cycle_ctr = 0
ct = 0
while reduce_expr(expr):
ct += 1
#print('@@churchnums.'... | The code parses input source code (from file or stdin), evaluates it using a reduction process, and reports the number of evaluation cycles, CPU time, and real time taken, while outputting a transformed version of the original expression with numeric values replaced. | def main():
#sys.setrecursionlimit(10000)
if len(sys.argv) >= 2:
src = '@@include {}.main'.format(sys.argv[1])
else:
src = sys.stdin.read()
expr = parse(src)
import time
t = time.time()
cpu_t = time.process_time()
#print(unparse(expr)); print()
cycles = reduce_full(expr, True)
cpu_t = time.p... |
def count_coverage_at_regions(
coverage_df: pd.DataFrame,
dnase_bw_file: str,
atac_bw_file: str,
) -> pd.DataFrame:
regions_to_skip = set()
with pyBigWig.open(atac_bw_file) as atac_bw:
with pyBigWig.open(dnase_bw_file) as dnase_bw:
atac_total = estimate_bigwig_total_reads(atac_bw... | The code generates plots comparing CRISPR guide regions (positives/negatives) and custom BED regions against ATAC-seq/DNase-seq coverage data, saving results in a PDF. It processes input files, calculates coverage metrics, and visualizes differences in chromatin accessibility between regions, with conditional logic for... | def main(
abc_regions: Optional[str],
atac_bw: str,
dnase_bw: str,
crispr_file: str,
bed_file: Optional[str],
output_file: str,
) -> None:
crispr_df = pd.read_csv(crispr_file, sep="\t")
crispr_df.rename(columns={"chromStart": "start", "chromEnd": "end"}, inplace=True)
with PdfPages(... |
def _get_pressed_key(self):
for key_char in CYCLE_ORDER:
key = self._get_key(key_char)
if key.pressed:
self.logger.debug(f"Key {key_char} is pressed")
return key_char, key
return None, None
def turn_all_keys_off(self):
self.set_all_keys((0,... | The code manages temperature input and display states via a keypad interface. It detects key presses to switch between modes (e.g., temperature input/display), updates animations, and handles user input for target temperature values. It also times out inputs, commits entered temperatures, and cycles through display mod... | def update(self):
self.keypad.update()
self.animator.update()
# Check for input
pressed_code, pressed_key = self._get_pressed_key()
if pressed_key:
if (
pressed_code == KEY_BEGIN_TEMPERATURE_INPUT
and self.mode in DISPLAY_MODES_CYCLE_O... |
def _retrieve_data(self, cluster: int, ignore_unallocated=False) -> bytes:
"""Read in the data for a given file allocation table entry number (i.e., the cluster number).
Important: this function returns all bytes in the cluster, even the slack data past the
actual filesize.
Because the... | The main task of the code is to recursively parse a directory cluster in a file system, extracting metadata for each entry (e.g., name, type, size, sectors) into structured dictionaries. It identifies directories, files, and deleted entries, handles nested directories, and retrieves content details like file size, cont... | def parse_dir(self, cluster: int, parent="") -> list[dict]:
"""Parse a directory cluster, returns a list of dictionaries, one dict per entry.
This function recursively parses any entry that is itself a directory.
Each dictionary contains the following keys (7 keys total):
- parent:... |
def login_page():
st.title("Login")
username = st.text_input("Username")
password = st.text_input("Password", type='password')
if st.button("Login"):
if verify_user(username, password): # Assuming verify_user is your authentication function
st.session_state["logged_in"] = True
... | The code initializes a Streamlit app with a logo, manages user login state via session variables, and conditionally displays either a login page or the main application layout based on authentication status, while also adding a footer. | def main():
# Initialize session state for logged_in if not present
if "logged_in" not in st.session_state:
st.session_state["logged_in"] = False
logo_img = Image.open('logo.png')
st.set_page_config(page_title="SPT", page_icon=logo_img, layout="wide", initial_sidebar_state="expanded")
if n... |
def _sanityCheck(self):
# Check if there are more than one edge to an ingress.
# Consider using the octocat tool, if you need to connect more than one outputs to a single input
for node in self.graph.nodes:
if self.graph.in_degree(node) > 1:
inEdges = self.graph.in_edges(node, data=True)
... | The code generates a pipeline configuration as a list of shell commands, handling different modes ("tail" or "monitor") to set up proxies, execute resources, create pipes, and manage logging. It includes sanity checks, node labeling, and constructs a script with preamble, commands, and post-processing steps like loggin... | def createPipeline(self, mode="tail"):
if mode not in ["tail", "monitor", None]:
raise Exception(f"Unsupported pipeline mode: ${mode}")
self._sanityCheck()
self._labelNodes()
commands = []
commands += self._createProxies()
commands += self._executeLocalResources()
self._getMonitoringP... |
def _press_key(self, text):
selector = 'button.absurdle__button'
key_el = self._find_element_by_text(selector, text)
if key_el:
key_el.click()
return True
else:
return False
def _get_result(self):
if self._find_element_by_text(
... | The function processes a guess by simulating key presses for each letter, submits the guess, waits, retrieves the result, clears the input if no result, and returns the result. | def update(self, guess):
for letter in guess.upper(): self._press_key(letter)
self._press_key("enter")
time.sleep(1)
result = self._get_result()
if not result:
self._clear_row()
return result |
def _press_key(self, letter):
keyboard = self._find_el_by_class_substr('Keyboard-module_keyboard')
key_el = keyboard.find_element('css selector', f'button[data-key="{letter.lower()}"]')
# TODO: why are clicks spamming 'QA--QAQA True'?
key_el.click()
def _get_result(self):
tiles =... | The code simulates typing a guess by pressing each letter, then the Enter key, waits 5 seconds, retrieves the result, clears the input row if no result is found, and returns the result. It automates input submission and result handling in a game or application, likely for tasks like Wordle where guesses are validated a... | def update(self, guess):
for letter in guess: self._press_key(letter)
self._press_key("↵")
time.sleep(5)
result = self._get_result()
if not result:
self._clear_row()
return result |
def in_bounds(self):
if self.rect.centerx <= 0 or self.rect.centerx >=800 or self.rect.centery <=0 or self.rect.centery >= 400:
self.kill()
def shoot(self,target):
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and self.x_velo == 0:
correction_angle = 90
... | The main task of the code is to execute three actions in sequence: check if the object is within bounds, shoot at the specified target, and then move the object. This method updates the object's state by ensuring boundary compliance, attacking the target, and initiating movement. | def update(self,target):
self.in_bounds()
self.shoot(target)
self.move() |
def kNNG_gen(inputs, k, pos_range, name = 'kNNG_gen'):
p, _, idx, edg = bip_kNNG_gen(inputs, inputs, k, pos_range, name)
return p, idx, edg
def autofc(inputs, outDim, act = None, bias = True, name = 'fc', forceSN = False, W_init = None):
input_shape = inputs.shape.as_list()
inputs = tf.reshape(inp... | The code implements a neural network simulator for particle dynamics, using graph convolutions and optionally GRU units. It processes particle positions and features to predict displacement (dPos), updating positions via learned transformations. The model includes graph generation, hidden state computation, and refinem... | def simulator(self, pos, particles, name = 'Simluator', is_train = True, reuse = False):
w_init = tf.random_normal_initializer(stddev = 0.005 * self.wdev)
w_init_pref = tf.random_normal_initializer(stddev = 0.001 * self.wdev)
b_init = tf.constant_initializer(value=0.0)
with tf.variable... |
def kNNGPooling_farthest(inputs, pos, k):
# with tf.variable_scope(name):
bs = pos.shape[0]
N = pos.shape[1]
k = min(N, k)
idx = farthest_point_sample(k, pos) # [bs, k]
# Pick them
batches = tf.broadcast_to(tf.reshape(tf.range(bs), [bs, 1]), [bs, k])
gather_idx = tf.stack([batches, i... | This function encodes particle data into a lower-dimensional feature representation using a deep neural network with graph convolutions, residual blocks, and pooling operations. It processes input particles through multiple blocks, progressively reducing their count while extracting features, and returns encoded featur... | def particleEncoder(self, input_particle, output_dim, early_stop = 0, is_train = False, reuse = False, returnPool = False):
# w_init = tf.random_normal_initializer(stddev=self.wdev)
w_init = tf.random_normal_initializer(stddev = 0.01 * self.wdev)
# w_init = tf.contrib.layers.xavier_initializer(... |
def autofc(inputs, outDim, act = None, bias = True, name = 'fc', forceSN = False, W_init = None):
input_shape = inputs.shape.as_list()
inputs = tf.reshape(inputs, [-1, input_shape[-1]])
with tf.variable_scope(name):
w = tf.get_variable('W', shape = [input_shape[-1], outDim], dtype = d... | The code implements a particle decoder neural network that generates 3D point cloud particles from latent features. It uses multiple decoding blocks with different generator structures (concat, AdaIN, final_selection) to refine coarse cluster positions into dense point clouds. The decoder incorporates convolutional ope... | def particleDecoder(self, cluster_pos, local_feature, groundTruth_card, output_dim, begin_block = 0, is_train = False, reuse = False):
w_init = tf.random_normal_initializer( stddev = 0.01 * self.wdev)
w_init_fold = tf.random_normal_initializer(stddev = 0.01 * self.wdev)
w_init_pref = tf.ran... |
def particleEncoder(self, input_particle, output_dim, early_stop = 0, is_train = False, reuse = False, returnPool = False):
# w_init = tf.random_normal_initializer(stddev=self.wdev)
w_init = tf.random_normal_initializer(stddev = 0.01 * self.wdev)
# w_init = tf.contrib.layers.xavier_initializer(... | This code builds a neural network combining autoencoding and simulation for point cloud data. It normalizes inputs, encodes them into latent representations, decodes for reconstruction, and computes Chamfer loss. When enabled, it simulates forward/backward transformations between states (X→Y→X), accumulating reconstruc... | def build_network(self, is_train, reuse, loopSim = True, includeSim = True):
normalized_X = (self.ph_X[:, :, 0:self.outDim] - tf.broadcast_to(self.normalize['mean'], [self.batch_size, self.gridMaxSize, self.outDim])) / tf.broadcast_to(self.normalize['std'], [self.batch_size, self.gridMaxSize, self.outDim])
... |
def CheckHeight(tree):
if tree is None:
return -1
else:
return max(CheckHeight(tree.getLeft())+1,CheckHeight(tree.getRight())+1)
def printTree(tree):
printTree_(tree,"") | The function verifies the balance factor of an AVL tree. It checks if each node's calculated balance factor matches the tree's reported value and ensures the absolute difference between left and right subtree heights is less than 2. If discrepancies are found, it prints the incorrect balance factor, tree structure, and... | def CheckAVL(tree):
if CheckHeight(tree) > 0:
l = 0 if tree.getLeft() is None else CheckHeight(tree.getLeft())+1
r = 0 if tree.getRight() is None else CheckHeight(tree.getRight())+1
b = l-r
if abs(b) >= 2 or b != tree.getBalanceFactor():
print(f"balance factor is {b} and... |
def CheckHeight(tree):
if tree is None:
return -1
else:
return max(CheckHeight(tree.getLeft())+1,CheckHeight(tree.getRight())+1)
def CheckBST(tree):
flag = True
if tree.getLeft() is not None:
if tree.getData() <= tree.getLeft().getData():
return False
else:
... | The code tests the correctness of a Binary Search Tree (BST) and AVL tree implementation. It verifies height calculation, insertion/search functionality, min/max value retrieval, removal operations, and AVL rotations/properties. Multiple test phases check tree behavior under various conditions, yielding success/failure... | def Test(lib, seed=0, size=10, rounds=10, verbose=False):
random.seed(a=seed)
# Test MyTree
flag = True
n = random.randint(0, size)
flag = True
m = size*3
n = random.randint(size, size*2)
try:
bst = lib.MyBST(n)
for i in range(1,5):
bst.insert(n+i)
... |
def f(audio):
if l == "hin":
trans(audio)
if l == "eng":
engine.setProperty('voice', voices[3].id)
engine.say(audio)
engine.runAndWait()
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as ... | The code determines the time of day to greet the user (morning, afternoon, evening), asks if they want to speak Hindi, captures the user's yes/no response to set a global language preference variable (`l`), and breaks the loop. The `place()` function is called afterward, though its purpose isn't defined in the provided... | def wishMe():
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour<12:
f("Good Morning!")
elif hour>=12 and hour<18:
f("Good Afternoon!")
else:
f("Good Evening!")
f("Sir, do you want me to speak hindi")
while True:
global l
query = takeCommand().lo... |
def m(audio):
if l == "hin":
transl(audio)
if l == "eng":
engine.setProperty('voice', voices[0].id)
engine.say(audio)
engine.runAndWait()
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as... | This code defines a security assistant function that provides voice-guided directions and assistance for hotel/services navigation. It processes user queries to guide to locations (reception, food court, etc.), handle requests (parking, cleaning, medical), show maps, check time, and exit. It uses conditional checks for... | def sequrity():
m("welcome sir how can i help you")
while True:
query = takeCommand().lower()
if 'reception' in query:
m("you must go straight and there is reception")
guirec()
elif 'exit' in query or 'by' in query or 'sleep' in query or 'jao' in query:
... |
def f(audio):
if l == "hin":
trans(audio)
if l == "eng":
engine.setProperty('voice', voices[3].id)
engine.say(audio)
engine.runAndWait()
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as ... | This code defines a reception function that handles user queries via voice commands, providing directions to hotel staff (waiter, chef, manager, security), information about amenities (rooms, food, facilities), services (cab, medical, laundry), and external resources (maps, nearby attractions). It terminates on exit co... | def reception():
f("welcome sir how can i help you")
while True:
query = takeCommand().lower()
if 'waiter' in query:
f("you must go straight and there is waiter")
guiwait()
elif 'chef' in query:
f("you must go straight and there is chef")
g... |
def m(audio):
if l == "hin":
transl(audio)
if l == "eng":
engine.setProperty('voice', voices[0].id)
engine.say(audio)
engine.runAndWait()
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as... | The code defines a hotel manager assistant that guides users to specific departments (reception, chef, waiter, security), addresses complaints about cleanliness, service, and food, provides time updates, opens maps, and exits on commands. It responds to queries in English and Hindi, offering assistance or apologies, an... | def manager():
m("welcome sir i am the hotel manager how can i help you")
while True:
query = takeCommand().lower()
if 'reception' in query:
m("you must go straight and there is reception")
guirec()
elif 'eat' in query:
m("you must go straight and ther... |
def m(audio):
if l == "hin":
transl(audio)
if l == "eng":
engine.setProperty('voice', voices[0].id)
engine.say(audio)
engine.runAndWait()
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as... | This code defines a 'waiter' function that interacts with users via voice commands, guiding them to specific locations (reception, chef, manager, security), displaying a menu, showing maps, providing time updates, handling complaints, and exiting the program, all while offering multilingual support and defaulting to re... | def waiter():
m("welcome sir i am here to help you ")
while True:
query = takeCommand().lower()
if 'reception' in query:
m("you must go straight and there is reception")
guirec()
elif 'chef' in query:
m("you must go straight and there is waiter")
... |
def m(audio):
if l == "hin":
transl(audio)
if l == "eng":
engine.setProperty('voice', voices[0].id)
engine.say(audio)
engine.runAndWait()
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as... | The code defines a `chef()` function that acts as a virtual assistant in a hospitality setting, responding to voice commands to guide users to departments like reception, waiter, manager, or security, display a menu, show maps, provide time, handle complaints, and exit. It supports multilingual queries and uses subproc... | def chef():
m("welcome sir i am the chef how can i help you")
while True:
query = takeCommand().lower()
if 'reception' in query:
m("you must go straight and there is reception")
reception()
elif 'waiter' in query:
m("you must go straight and there is w... |
def _sumo_step(self):
self.conn.simulationStep()
def _apply_actions(self, actions):
for cs, action in actions.items():
close_vehicle = self.charging_stations[cs].consider_vehicle
self.handle_actions(action, close_vehicle, cs)
def _run_steps(self):
self._sumo_step()
def up... | This function executes a simulation step in a SUMO environment, processing actions to update the simulation state. It applies actions, runs steps, updates visual elements, and computes observations, rewards, termination flags, and environment info for reinforcement learning. The step handles both action-driven and pass... | def step(self, actions: Union[dict, int]):
logging.debug("Step")
logging.debug("Actions: {actions}")
if actions is None or actions == {}:
for _ in range(self.delta_time):
self._sumo_step()
else:
self._apply_actions(actions)
self._run_s... |
def get_dist_to_station(self, vehicle):
vehicle_edge = self.traci_connection.vehicle.getRoadID(
vehicle)
dist_to_station = self.traci_connection.simulation.getDistanceRoad(
vehicle_edge, 0, self.edge_id, self.cs_end_pos, isDriving=True)
return float(dist_to_station)
def... | The function computes an observation vector for a charging station by determining the closest electric vehicle's battery level, the station's current busy status, and nearby stations' busy statuses. It returns these values as a numpy array or zeros if no close EVs are detected, aiding in decision-making for EV routing ... | def compute_observation(self):
charging_station_edges = self.env.cs_edges.values()
# Get driving distance of EVs in close proximity not already rerouted or decided upon
dists_to_station = {
v: self.get_dist_to_station(v) for v in self.get_close_evs()
if
not
... |
def run_round():
your_choice = get_user_choice()
computer_choice = random.choice(CHOICES)
winner = determine_winner(your_choice, computer_choice)
print_outcome(winner, your_choice, computer_choice)
return winner
def update_score(score, winner):
if winner is not None:
score[winner] += 1
... | The code plays a best-of-n game of rock, paper, scissors, tracking scores for the user and computer. It repeatedly runs rounds, updates scores, and checks for a winner. Once the game ends, it declares whether the user won or lost based on the final score. | def play_game(best_of=3):
"""
Play a game of rock, paper, scissors
"""
score = [0, 0]
print(f'Rock, paper, scissors - best of {best_of}')
while True:
winner = run_round()
update_score(score, winner)
game_winner = game_over(best_of, score)
if game_winner is not ... |
def minimal_check():
"""
Minimal checks before executing any code.
Full checks will happen after downloading codes from the internet
"""
print("Running checks...")
exit_if_root()
exit_if_invalid_python_version()
exit_if_os_not_compatible()
exit_if_no_internet()
def bootstrap():
... | The main task of the code is to perform a minimal validation check, initialize the application or system through bootstrapping, and then execute cleanup operations to release resources or finalize processes. | def main():
minimal_check()
bootstrap()
cleanup() |
def cwd(path):
oldpwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(oldpwd)
def flatten_directory(dir_):
to_delete = []
for f in os.listdir(dir_):
if f.find("python") != -1 or f.find("java") != -1 or f.find("dotnet") != -1:
continue
dir2 = ... | The main task of the code is to repackage Indigo libraries into platform-specific archives (e.g., Windows, Linux, macOS) and generate language wrappers (Java, Python, .NET) based on user-specified configurations. It processes command-line arguments to determine build settings, joins library archives, unpacks them into ... | def main():
arc_joins = [
("./indigo-libs-%ver%-linux-shared", "indigo-libs-%ver%-linux.+-shared"),
("./indigo-libs-%ver%-win-shared", "indigo-libs-%ver%-win.+-shared"),
("./indigo-libs-%ver%-mac-shared", "indigo-libs-%ver%-mac.+-shared"),
("./indigo-libs-%ver%-linux-static", "indigo... |
def option_house():
print("You follow the child to what you believe to be their home and unsurprisingly you find it in shambles the "
"homes didn't seem to have much but what ever little they had in their humble home is broken and in "
"shambles.\nThe home has been ransacked but the perpetrators... | This code presents a narrative choice in a text-based game where the player, armed with a sword, encounters a distressed child seeking help to save their mother. The player selects from three options—immediately assisting the child, investigating further, or refusing—each leading to different story paths via function c... | def option_armed():
sword == 1
print("Sword in hand you answer the door with your usually scowl.You see a child panting hard he looks up "
"to you panic in his eyes \n 'Are your Northern hermit' you give me a nod and his panic turns to hope "
"'Please save my mommy,bad men came and they tryi... |
def option_armed():
sword == 1
print("Sword in hand you answer the door with your usually scowl.You see a child panting hard he looks up "
"to you panic in his eyes \n 'Are your Northern hermit' you give me a nod and his panic turns to hope "
"'Please save my mommy,bad men came and they tryi... | The code introduces an interactive story scenario where a character in a cottage during winter faces a mysterious knock at the door. It presents three choices—answering with a sword, ignoring the door, or peeking—to direct the narrative flow, initiating branching paths based on user input. | def intro():
print(
"So the story begins in with you enjoying the warmth of your fireplace in your cottage. "
"\nThe wind blows furiously outside,winter is beginning to pick up and most people have been holed up in their "
"home. "
"\nAs you watch the flame consume the firewood your ... |
def createFileInfo(self):
file_info = ET.SubElement(self.newRoot, "fileInfo")
filename, extension = os.path.splitext(self.file_path)
filename, extension = os.path.splitext(filename)
filename, extension = os.path.split(filename)
final_path = self.final_path + '/' + extension
... | The main task of the code is to parse a TEI document by creating file information and processing its root elements. It iterates through child elements, extracting header information if the tag is 'teiHeader' and text content if the tag is 'text', using respective parsing methods. | def main(self):
self.createFileInfo()
for childs in self.root:
if childs.tag == 'teiHeader':
self.parseHeaderInformation(childs)
elif childs.tag == 'text':
self.parseTextInformation(childs) |
def extractAcknowledgement(self, child):
pass
def extractAnnex(self, child):
pass
def extractReferences(self, child, fh):
for ch in child:
#print("REFERENCES")
fh.write("REFERENCES")
count = 0
for c in ch:
count = count + 1
... | The code extracts text from specific XML/HTML elements, writing body content to a file and handling 'back' section elements like acknowledgments, annexes, and references by calling dedicated methods. It processes nested tags, captures text, and organizes document components into a structured output. | def parseTextInformation(self,tag,fh):
for childs in tag:
if childs.tag == 'body':
for child in childs:
for ch in child:
try:
#print(ch.text)
fh.write(ch.text+'\n')
... |
def parseHeaderInformation(self,tag,fh):
for childs in tag:
if childs.tag == 'fileDesc':
self.titleAndAuthorExtraction(childs,fh)
elif childs.tag == 'profileDesc':
self.abstractExtraction(childs,fh)
def parseTextInformation(self,tag,fh):
for child... | The main task of the code is to parse an XML file using ElementTree, extract data from specific tags ('teiHeader' and 'text'), write the parsed information to a text file, and subsequently process the file with the `getBodyandCite` method. It opens a file for writing, iterates through XML elements, delegates parsing to... | def main(self):
tree = ET.parse(self.extraction_path)
root = tree.getroot()
fh = open(self.file_path,'w')
for childs in root:
if childs.tag == 'teiHeader':
self.parseHeaderInformation(childs,fh)
elif childs.tag == 'text':
self.parse... |
def isSimplyLeftUnbalanced(self):
if self.left is not None and self.computeBalance() == 2 and self.left.computeBalance() == 1:
return True
return False
def rot_right(self):
newRoot = self.left
newRightLeft = self.left.right
newRoot.right = self
newRoot.right.left = newRightLeft
return newRoot
def isSim... | This code inserts a value into an AVL tree, recursively placing it in the left or right subtree based on comparison, then checks and corrects balance using rotations (right or left) to maintain AVL properties. It handles single unbalanced cases and ensures subtree balances are also adjusted, returning the updated subtr... | def insert(self, value):
#Go Left
if value <= self.value:
if self.left == None:
self.left = AVL_Node(value)
else:
self.left.insert(value)
self.balance += 1
if self.isSimplyLeftUnbalanced():
newArbre = self.rot_right()
else:
newArbre = self
if self.left is not None and self.left.isS... |
def isSimplyLeftUnbalanced(self):
if self.left is not None and self.computeBalance() == 2 and self.left.computeBalance() == 1:
return True
return False
def rot_right(self):
newRoot = self.left
newRightLeft = self.left.right
newRoot.right = self
newRoot.right.left = newRightLeft
return newRoot
def isSim... | The main task of the code is to balance an AVL tree's root node by checking for specific imbalance conditions (simple/left/right/different) and applying corresponding rotations (right/left/differentRight/differentLeft) to restore balance. If no imbalance is detected, it returns the node itself, ensuring structural inte... | def balanceRoot(self):
if self.isSimplyLeftUnbalanced():
return self.rot_right()
if self.isSimplyRightUnbalanced():
return self.rot_left()
if self.isDifferentlyLeftUnbalanced():
return self.differentRightRotation()
if self.isDifferentlyRightUnbalanced():
return self.differentLeftRotation()
ret... |
def isLeaf(self):
if self._left is None and self._right is None:
return True
return False
def getSuccessor(self):
if self._right is None:
return self
if self._right._left is None:
return self._right
child = self._right
while child._left is not None:
child = child._left
return child
def applyBa... | This code deletes a specified value from a binary tree node. It handles three cases: if the node is a leaf (returns None if value matches, else self), if the value is in the left/right subtree (recursively deletes), or if the node itself holds the value (replaces it with its successor and rebalances the tree). The meth... | def delete(self, value):
if self.isLeaf():
if self._value != value:
return self
else:
return None
else:
#Go left
if value < self._value:
if self._left is not None:
self._left = self._left.delete(value)
else:
return self
#Go Right
if value > self._value:
if self._right i... |
def isSimplyLeftUnbalanced(self):
if self._left is not None and self.computeBalance() == 2 and self._left.computeBalance() == 1:
return True
return False
def rot_right(self):
newRoot = self._left
newRightLeft = self._left._right
newRoot._right = self
newRoot._right._left = newRightLeft
return newRoot
d... | The main task of the code is to balance a binary tree by detecting specific imbalance types (simple/left/right) and applying corresponding rotations (right/left/different rotations) to restore equilibrium, ensuring structural stability during dynamic data operations. | def balanceRoot(self):
if self.isSimplyLeftUnbalanced():
return self.rot_right()
if self.isSimplyRightUnbalanced():
return self.rot_left()
if self.isDifferentlyLeftUnbalanced():
return self.differentRightRotation()
if self.isDifferentlyRightUnbalanced():
return self.differentLeftRotation()
ret... |
def balanceRoot(self):
if self.isSimplyLeftUnbalanced():
return self.rot_right()
if self.isSimplyRightUnbalanced():
return self.rot_left()
if self.isDifferentlyLeftUnbalanced():
return self.differentRightRotation()
if self.isDifferentlyRightUnbalanced():
return self.differentLeftRotation()
ret... | The main task of the code is to insert a new value into an AVL tree node, recursively handling left or right insertion, updating balance factors, and performing rotations (left/right) to maintain AVL tree balance. It returns the newly balanced subtree root after insertion and necessary adjustments. | def insert(self, value):
newArbre = self
newArbre.append(value)
newArbre = self.balanceRoot()
newArbre.balanceChildren()
newArbre.applyBalance()
return newArbre
#Go Left
if value <= self._value:
if self._left == None:
self._left = AVL_Node(value)
else:
self._left.insert(value)
self._bal... |
def _compute_nb_physical_lines(self, text: str) -> int:
return max(1, math.ceil(len(text) / self.available_width))
def _extend(self, size):
"""
Extend the number of lines of the current session by `size` lines, by
printing enough empty lines at the end of what is already printed.
... | The code writes a new line to a session's stdout using a template string and keyword arguments, creating a Line object for dynamic updates. It manages line entries, tracks physical lines, reserves vertical space by printing empty lines, and ensures thread safety with a lock, returning the Line instance for further mani... | def line(self, template: str, **kwargs) -> 'Line':
"""
Write a new line to the end of this session's stdout and return a Line
instance allowing you to dynamically update the line later.
The `template` string can use curly braces to define variables using
the semantics of the `st... |
def _compute_nb_physical_lines(self, text: str) -> int:
return max(1, math.ceil(len(text) / self.available_width))
def _extend(self, size):
"""
Extend the number of lines of the current session by `size` lines, by
printing enough empty lines at the end of what is already printed.
... | The main task of the code is to update the terminal output when a Line object's text changes, handling dynamic line rendering by adjusting line numbers, extending/truncating output as needed, and ensuring thread-safe updates to the display. It tracks physical line counts, shifts subsequent lines when necessary, and mai... | def print_line(self, line_obj: 'Line') -> None:
"""
Given a Line object assumed to be associated with the session, update
stdout with the current text rendering of the Line.
"""
with self.printing_lock:
line_entry = self.lines_index[id(line_obj)]
text = li... |
def get_grad(
x: np.ndarray,
y: np.ndarray,
theta0: np.ndarray,
theta1: np.ndarray,
theta2: np.ndarray
) -> tuple:
a0 = np.matmul(theta0, x)
h0 = sig(a0)
a1 = np.matmul(theta1, h0)
h1 = sig(a1)
a2 = np.matmul(theta2, h1)
h2 = sig(a2)
diff = h2 - y
j = 0.5 * np.sum(dif... | The code trains a 3-layer neural network on the MNIST dataset using gradient descent. It preprocesses data, initializes weights, computes gradients in batches, updates parameters, tracks costs, visualizes a sample image, evaluates training/test costs, and saves learned weights to JSON files. | def main():
print("Preprocessing")
mndata = MNIST('samples')
images, labels = mndata.load_training()
images = np.array(images)
x = np.array(images, dtype=np.float64) / 255
n = x.shape[0]
labels = np.array([labels]).T
y = np.equal(np.arange(10), np.repeat(labels, 10, 1))
print... |
def calculate_distance(s, b):
valuex = s[0] - b[0]
valuey = s[1] - b[1]
return abs(valuex) + abs(valuey)
def perimeter_draw(max_distance, spot, sensor, row):
check = check_line(spot, sensor)
if check is False:
up = None
down = None
dirs = [[1, 1], [-1, -1], [1, -1], [-1, 1]]
... | The main task of the code is to modify a map (`cave_map`) by iteratively drawing perimeters based on calculated distances between point pairs. For each valid perimeter check, it updates the map with new perimeter points and verifies if the current row meets the updated map's constraints, ultimately printing the validat... | def part1(row):
part1_map = copy.deepcopy(cave_map)
for pair in points:
distance = calculate_distance(pair[0], pair[1])
check = perimeter_draw(distance, pair[1], pair[0], row)
if check:
part1_map = pull_perimeter_points(row, check, part1_map)
print(check_row(row, part1_ma... |
def _is_id(idv):
return isinstance(idv, str) and len(idv) > 0
def _is_iterable(seq, check_empty=True):
# Ensure sequence is not a string, which is technically iterable
# but not desired in this context
if isinstance(seq, str):
return False
try:
_ = (e for e in seq)
if check_e... | The main task of the code is to retrieve genetic profile data for specified genes from a case list using a genetic profile ID, with optional caching and batch processing. It validates inputs, checks for cached results, processes data in batches if needed, and stores results in a cache directory as a pickle file for fut... | def get_genetic_profile_data(case_list_id, genetic_profile_id, gene_ids,
batch_size=50, print_progress=True, cache_dir=None):
if not _is_id(case_list_id):
raise ValueError('Case list ID must be a non-empty string (e.g. "cellline_ccle_broad_all")')
if not _is_id(genetic_profi... |
def create_output_graph():
with tf.Graph().as_default() as graph:
model_filename = MODEL_FILE
with gfile.FastGFile(model_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
jpeg_data_tensor, final_tensor = (
tf.impor... | The code's main task is to classify images as 'cat' or 'dog' using a pre-trained TensorFlow model. It loads image data, runs inference via a graph session, and prints predictions with corresponding file paths. The script handles image input lists either in arbitrary order or sequentially, processes them through the mod... | def main():
graph, jpeg_data_tensor, final_tensor = (create_output_graph())
image_dir = IMAGE_DIRECTORY
if LOAD_ARBITRARY:
image_list = create_image_list(image_dir)
else:
image_list = create_image_list_in_order()
with tf.Session(graph=graph) as sess:
predictions, filenames =... |
def get_birthday_data():
'''returns birthday data by reading csv file'''
birthday_df = pd.read_csv("birthdays.csv")
birthday_data = []
for _, row in birthday_df.iterrows():
birthday_detail = {
"name": row.first_name,
"email": row.email,
"month": row.month,
... | The code checks if the current date matches any birthdays in a dataset. If a match is found, it prepares a message using the person's name and email address from the birthday data. | def check_birthday():
'''checks for birthday'''
birthday_data = get_birthday_data()
current_date = get_current_date()
for birthday in birthday_data:
if current_date["month"] == birthday["month"] and current_date["day"] == birthday["day"]:
data = {
"name": birthday["na... |
def shuntingYard(query):
"""
This is the Shunting-yard algorithm. It parses a query string and returns them
in Reverse Polish Notation.
"""
operatorStack = [] # enters from the back, exits from the back
output = []
queryTerms = splitQuery(query)
for term in queryTerms:
if term ... | This function processes a Boolean query using the shunting yard algorithm to handle operators, evaluates 'AND' operations between terms using postings files, and returns the result. If the result is too small, it falls back to a free-text query by removing 'AND' and quotes, ensuring a minimum result size of 50 items. | def booleanQuery(query, dictFile, postings_file):
"""
Given a Boolean query string, return
"""
tokens = shuntingYard(query)
operands = list()
while len(tokens) > 0:
token = tokens.pop(0)
if isinstance(token, str) and token != 'AND':
op = Operand(term=token)
... |
def isValidQuery(query):
"""
Given a query string, returns True if it is valid. False otherwise.
"""
quotation_count = query.count('\"')
and_count = query.count('AND')
if quotation_count % 2 == 1:
return False
if quotation_count > 2 and and_count == 0:
return False
if qu... | The code classifies a query into Boolean, Free Text, or Phrasal types based on specific markers. It checks for "AND" to trigger Boolean processing, quotes for Phrasal, and defaults to Free Text. Valid queries are routed to respective functions for further handling, while invalid ones are ignored. | def processQuery(query, dictFile, postings_file):
"""
Given a query string, classifies it as one of the 3 types of queries:
Boolean, Free Text or Phrasal.
"""
if len(query) == 0 or not isValidQuery(query):
return
if "AND" in query:
return booleanQuery(query, dictFile, postin... |
def set_path(self, file_path):
if file_path is not None:
if file_path != self.file_path:
self.dump()
self.file_path = file_path
def is_attachment(self, var):
use_np_protocol = isinstance(var, np.ndarray)
if use_np_protocol:
use_np_protocol = var.si... | This code adds data to an OrderedDict structure while ensuring key consistency and handling numpy arrays. It checks if input keys match existing columns, validates array shapes for H5 files, appends values, and periodically dumps data to the specified file path. | def add(self, row_dict, file_path):
self.set_path(file_path)
assert isinstance(row_dict, OrderedDict)
if self.data is None:
self.data = OrderedDict()
else:
msg_assert = 'input keys and my columns are different:\n'
msg_assert = msg_assert + f' input ke... |
def get_next_position(self, direction: Tuple[int, int]) -> Tuple[int, int]:
x, y = self.position
dx, dy = direction
return x + dx, y + dy
def update_power_up_state(self) -> None:
if self.powered_up:
self.power_up_timer -= 1
if self.power_up_timer <= 0:
... | This code updates an entity's position in a game level by checking valid moves based on direction, avoiding walls, updating direction if a next direction is set, handling power-up states, and checking for pellet collisions. | def update(self, level: Level) -> None:
if self.next_direction:
next_position = self.get_next_position(self.next_direction)
if not level.is_wall(*next_position):
self.direction = self.next_direction
if self.direction:
next_position = self.get_next_pos... |
def print_clusters(self):
for cluster, pts in self.clusters.items():
print("C{0} = {{{1}}}".format(cluster+1, ",".join(pts)))
for c, coords in self.centroids.items():
print("([{0}])".format(" ".join([str(x) for x in coords])))
def assign_clusters(self):
for c in self.clu... | This code trains a clustering model by iteratively assigning data points to centroids and recalculating centroids until convergence. It reads input data, initializes centroids, and uses a loop to update clusters based on distance calculations. The process stops when centroid changes fall below a tolerance threshold (1e... | def train(self, train_file, centroids_list, distance_type, dim):
self.data = self.read_data(train_file)
self.distance_type = distance_type
self.dim = dim
self.points = {}
for row in self.data:
self.points[row[-1].strip()] = [int(x) for x in row[:-1]]
self.cent... |
def get_king(self, color):
if(color not in ("black", "white")): raise InvalidColor
return self[self.get_king_position(color)]
def get_enemy(self, color):
if color == "white": return "black"
else: return "white"
def all_possible_moves(self, color):
'''
Return a list of... | This function checks if a player's king is in check. It validates the input color, retrieves the king's position and the enemy's color, then checks if the king's position is among the enemy's possible moves. Returns True if in check, False otherwise. | def is_in_check(self, color):
if(color not in ("black", "white")): raise InvalidColor
king = self.get_king(color)
enemy = self.get_enemy(color)
return king in map(self.__getitem__, self.all_possible_moves(enemy)) |
def get_enemy(self, color):
if color == "white": return "black"
else: return "white"
def all_possible_moves(self, color):
'''
Return a list of `color`'s possible moves.
Does not check for check.
'''
if(color not in ("black", "white")): raise InvalidColor
... | This code validates and executes a chess move by checking if the move is legal (turn, possible moves, check/checkmate), then updates the board state if valid. It raises exceptions for invalid moves, check, checkmate, or draw scenarios. | def move(self, p1, p2):
p1, p2 = p1.upper(), p2.upper()
piece = self[p1]
dest = self[p2]
if piece != None:
if self.player_turn != piece.color:
raise NotYourTurn("Not " + piece.color + "'s turn!")
enemy = self.get_enemy(piece.color)
possible_... |
def draw_board(state):
"""
func to draw the board for the game.
:param state: dictionary containing the state variable of the game. state["board"] will be the returned 2D array
from initialise_board(dim).
:return: None, side-effect func.
"""
for row in state["board"]:
print("".join(output_board_r... | The function `play` recursively executes the game by updating the game state until a winning condition is met. It draws the current board, checks if the board matches the winning configuration, and if not, calls itself with the updated state from `run_step_of_the_game()`. If the winning board is achieved, it exits with... | def play(state):
"""
func that recursively play until game is won. Func recurses over run_step_of_the_game(), which applies
the mutation necessary to the state dictionary for the next step in the game.
:param state: dictionary containing the state variable of the game.
:return: None or exit if game won.
"""
draw... |
def formatWithRespectToKeyOrder(inputString, keyOrder):
if (len(inputString) % keyOrder != 0):
padValue = keyOrder - (len(inputString) % keyOrder)
for i in range(padValue):
inputString = inputString + 'x'
return inputString
def splitToLength(inputString, inputValue):
def _slice(inputString, inputValue):
... | The function encrypts an input string using a combination of matrix and vector transformations. It formats the string according to a key order, splits it into chunks, and applies the `_encryption` function to each chunk with provided matrices/vectors. The resulting cipher chunks are concatenated into a final ciphertext... | def encryption(inputString, input_coordinate_Matrix, input_coordinate_Vector, input_char_matrix, input_char_vector):
cipherText = []
inputString = formatWithRespectToKeyOrder(inputString, keyOrder)
hillPlainTextChuncks = splitToLength(inputString, keyOrder)
for chunck in hillPlainTextChuncks:
cipherChunck = _enc... |
def isEmpty(self):
return self.head == None
def printEmptyList(self):
return 'The list is empty'
def checkIndex(self, index):
if index < 0 or index > self.getCount():
print("Index out of range")
return | This function inserts all elements from 'mylist' into the linked list starting at the specified 'index' position. It first checks if the list is empty or if the index is valid. If valid, it traverses to the node before the target index and sequentially inserts each element from 'mylist' by updating node pointers. | def insert_from(self, index, mylist):
if self.isEmpty():
return self.printEmptyList()
self.checkIndex(index)
count = 0
itr = self.head
while itr:
if count == index - 1:
for data in mylist:
itr.next = Node(data, itr.next)... |
def isEmpty(self):
return self.head == None
def printEmptyList(self):
return 'The list is empty'
def checkIndex(self, index):
if index < 0 or index > self.getCount():
print("Index out of range")
return | The code removes the element at a specified index from a linked list by traversing to the node before the target index and updating its next pointer to bypass the node at that index, effectively deleting it. It includes checks for empty lists and valid indices to handle edge cases. | def remove_at(self, index):
if self.isEmpty():
return self.printEmptyList()
self.checkIndex(index)
count = 0
itr = self.head
while itr:
if count == index - 1:
itr.next = itr.next.next
itr = itr.next
count += 1 |
def bin_pdw_freqPhaseCodingBlock():
"""
Creates a complete frequency and phase coding block containing header and data
for analog UXG streaming.
This block is used to describe variable length pulse frequency/phase coding setups.
This allows frequency and phase coding tables to be updated over ethern... | This function constructs a binary PDW file for Keysight UXG devices, aligning the PDW data section to a 4096-byte offset. It generates a header, optional frequency phase coding block, padding to meet alignment requirements, and the PDW data block from input pulse descriptor words, ensuring proper formatting for playbac... | def analog_bin_pdw_file_builder(pdwList):
"""
Builds a binary PDW file with a padding block to ensure the
PDW section begins at an offset of 4096 bytes (required by UXG).
See User's Guide>Streaming Use>PDW File Format section of
Keysight UXG X-Series Agile Signal Generator Online Documentation
... |
def create_matrix(seq1, seq2):
"""Create a matrix which is the size: len(seq2)*len(seq1).
:param seq1: sequence1 which is being aligned.
:param seq2: sequence2 which is being aligned.
:return: created matrix (list of lists).
"""
matrix = [[0 for j in range(len(seq2) + 1)] for i in range(len(seq... | The code aligns two sequences using dynamic programming with gap penalties, computes the optimal alignment score, and returns the aligned sequences, percentage identity, and score. It constructs matrices for scoring and backtracking, identifies the maximum score position, traces the alignment path, and generates the fi... | def align_sequences(seq1, seq2, gap_pen=0, end_gap_pen=0):
"""Aligns two sequences using a linear gap_penalty.
:param seq1: sequence1.
:param seq2: sequence2.
:param gap_pen: penalty for creating a gap.
:param end_gap_pen: penalty for creating an end-gap.
:return: a tuple of aligned strings, th... |
def parse_file(filename):
"""Parse a file to a list of sequences.
:param filename: name of file to be parsed.
:return: a list of sequences in the file.
"""
data_dict = {}
with open(filename) as file:
for line in file:
if line[0] == ">":
key = line[1:].strip(... | The code processes FASTA files to train Hidden Markov Models (HMMs), calculates emission and transition probabilities, and generates sequences. It first analyzes "test.fasta" to determine match states, train HMM parameters, and display emission matrices. It then repeats the process for "test_large.fasta," outputting pr... | def main():
"""Main code."""
# Question 1
seq_dict = parse_file("test.fasta")
len_align = len(seq_dict[list(seq_dict.keys())[0]])
match_states, n_matches = calc_match_states(seq_dict, len_align)
print("Q1\nNumber of match states {0}.\n".format(n_matches))
# Question 2
print("test.fasta... |
def _get_columns_from_headers(worksheet, index_boost: int = 0) -> dict:
return {cell.value: i + index_boost for i, cell in enumerate(worksheet[1])
if cell.value is not None and cell.value.strip() != ''}
def clean_data(data: dict) -> dict:
"""
Clean the provided data by removing empty modules and... | The main task of the code is to parse XLSX files into structured questionnaire data if they follow XLSForm conventions, or into split text content if not. It first checks for XLSForm-specific sheets (survey, choices, settings), processes their data to build a nested dictionary with modules, questions, labels, and optio... | def parse_xlsx(file_path: str, splitter: Callable = split_langchain) -> list[str] | dict:
"""
Parse an XLSX file into a dictionary with questionnaire data.
This function starts by assuming that the XLSX file is in XLSForm format, then falls back to generic parsing
in the case where XLSForm parsing fail... |
def firstClick(playBox, solutionPositions, happyLevel, numBoxes, difficulty):
""" This function is for handling the first click we make for the board.
It finds the middle col,row for the board, and attempts to set that
position. If it is a mine to begin with, we attempt to try to find
anoth... | This function automates Minesweeper by identifying safe moves, flagging bombs, and making strategic guesses. It avoids initial bombs, reveals zeros to uncover regions, and uses heuristics for guesses when necessary. The loop continues until all bombs are flagged or a loss occurs, tracking guesses and runtime. It return... | def play(difficulty, playBox, solutionPositions):
""" This function is used to play and solve minesweeper with file input. It first
finds the middle position in the board and checks if it is a bomb in the solution.
If it is a bomb, it will loop until it finds one that is not so that we don't lose
... |
def phase1(self):
if(client_validate_public_key is True):
pdu = {'header': {'msg_type' : 'dh1','timestamp':str(datetime.datetime.utcnow())},
'body': {'key':client_public_key,'username':(self.auth_user)}}
return pdu
def crc_create(self,pdu_hea... | The code implements a client-side protocol for secure communication, handling key exchange (Diffie-Hellman), encryption/decryption (using derived keys), message authentication (HMAC), and challenge-response authentication. It sends/receives structured data (PDU) with CRC checks, processes server responses, and manages ... | def client_f(self,socks,msg,user,passwd,other_user):
self.auth_user = user
self.auth_pass = passwd #(-----------------------------Client Function-------------------------)#
self.opp_client = other_user
if(msg != ''):
pdu = self.phase1() #---------... |
def record_notes_and_state(csv_reader, image_info, can_ignore):
for line in csv_reader:
image = line.get("image")
package_name = line.get("package_name")
vulnerability_id = line.get("vulnerability_id")
key = image + "-" + package_name + "-" + vulnerability_id
notes = line.get... | (The code processes CVE data from CSV files and image lists, updates CVE records with image info, generates GitHub issues for vulnerabilities, applies labels based on sources/releases, and manages rate limits by delaying requests. It creates or updates issues, closes resolved ones, and handles skipped images.) | def run():
if len(sys.argv) != 6:
print("Must pass five arguments: images text file names, names of csv files, release names, issue repository,"
"and github token.")
sys.exit(1)
cves_csv_filenames = sys.argv[1].split(",")
images_text_filenames = sys.argv[2].split(",")
rele... |
def bincode2purebits(_bin_code):
trunc = _bin_code[2:] # get just the fractional part of the string
logger.debug("trunc {}", repr(trunc))
return trunc
def encrypt(passwd, msg):
key = passwd2key(passwd)
encoded = compressed = msg
logger.info("encoded: " + repr(encoded))
esay = pyffx.Stri... | The main task of the code is to attempt decryption of an encrypted message by guessing its original length. It starts with an initial estimate, then iteratively adjusts the length (up and down) to test possible valid decodings. The function logs and prints results of decoding attempts at each guessed length, aiming to ... | def try_crypt_guess():
# First, encode and encrypt it...
# get the truncated purebits to prepare it for encryption
trunc = bincode2purebits(binary_code)
logger.debug("trunc: {}", repr(trunc))
# encrypt the trunc-purebits to the length of orig msg
msg_len = len(original_msg)
_crypted = encr... |
def __read_words(self):
text_file = open("words.txt", "r")
self.__words = text_file.readlines()
text_file.close()
def on_click_new_word(self):
if len(self.__submission) != 0:
self.clear_submission()
if len(self.__word) != 0:
self.__clear_word()
sel... | The code initializes a game screen by filling it with a light teal background, loads word data, and sets up UI elements like buttons (next, submit, clear) with their respective images and positions. It prepares the game state for handling user interactions related to word processing, including event handlers for button... | def __init__(self):
SCREEN.fill(self.__LIGHT_TEAL)
self.__read_words()
self.extra = 0
self.__new_word_icon = pygame.image.load('images/next.png')
self.new_word_rect = self.__new_word_icon.get_rect()
self.__submit_icon = pygame.image.load('images/submit.png')
self.... |
def display_meaning(self, correct):
meaning = self.get_meaning()
if correct:
title = "Yay!! Correct Submission :D "
else:
title = "You learned a new word :) "
root = Tk()
root.withdraw()
if meaning == "":
meaning += self.__word
... | This function checks if the user's submission matches a target word. If correct, it displays the word's meaning, triggers a new word request, and returns True. If incorrect, it shows an error, clears the submission, and returns False. The main task is to validate user input against a predefined word and handle feedback... | def submit_status(self):
if self.__submission == self.__word:
self.display_meaning(True)
self.on_click_new_word()
return True
else:
self.__display_incorrect()
self.clear_submission()
return False |
def set_search_dir() -> None:
CONF.search_directory = get_generic('search directory', CONF.search_directory)
def set_search_string():
CONF.string_to_replace = get_generic('string to replace', CONF.string_to_replace)
def set_replacement_string():
CONF.string_to_replace_with = get_generic('replacement string'... | The code performs a string search and replacement across files in a specified directory. It identifies target strings, prompts user input (accept/skip/accept all) for each occurrence, tracks counts of occurrences, replacements, and modified files, and generates a summary report. It supports configurable search/replace ... | def main():
print('~ STRING SEARCH AND REPLACE ~')
set_search_dir()
set_search_string()
set_replacement_string()
set_file_types()
save_app_config(CONF, CONF_FILE)
count_occurences = 0
count_replacements = 0
count_modified = 0
count_files = 0
print(f'press enter to accept ... |
def __deep_update_and_copy(source, target, typing = True):
obj = __update({}, source);
_obj = target;
for key, value in _obj.items():
if key in obj.keys():
if(typing and (type(obj[key]) != type(value))): # and (type(obj[key]) != dict and type(value) != dict)):
raise TypeE... | The code tests the functionality of deep copy and update operations in Python, particularly for nested and circular data structures. It verifies that custom functions like __deep_update_and_copy and __deep_copy correctly handle dictionaries, lists, and objects, ensuring modifications to original data do not affect copi... | def __test__():
foo = 'foo';
a1 = {foo: {1: '2', 4: 4, 5: 5, 6: {7: {9: 9}}}, 'a': 5};
a2 = {foo: {1: '1', 2: '2', 6: {7: {8: {}}}}, 'a': int(6)};
# __deep_update(a1, a2); # not overwriting all the objects
# a1.update(a2); # overwriting all the objects
a3 = __deep_update_and_copy(a1, a2);
p... |
def __parse_bitmap(self, bitmap, collision_detection):
"""
This methods converts a bitmap to a tensor according the representation
written above in the constructor, so we need at least two colours with
only one bit at 1 for obstacles and targets.
Parameters
----------qRg... | This code initializes a multi-drone simulation environment by parsing a bitmap map, setting up collision detection matrices, initializing drone positions/velocities, configuring stigmergy (pheromone-like) space parameters, and preparing rendering components. It handles batch processing, environment state tracking, and ... | def __init__(self,
bitmap,
batch_size,
observation_range,
amount_of_drones,
stigmation_evaporation_speed,
inertia,
collision_detection,
reward_function,
max_steps,
render = False,
drone_colour = [255, 255, 255]
):
se... |
def Setup_Analysis(self, current_archive_path, current_results_path, current_report_path):
#ask the user what analysis they want to perform, if they want to archive the images, if they want to export the results and if they want to produce a pdf"
start_analysis = tk.IntVar() ... | This code initializes a DICOM analysis workflow by configuring analysis parameters, selecting input directories, filtering sequences based on analysis flags, organizing DICOM data into structured dictionaries, and setting up output paths for archiving, results, and reports. It prepares the environment for subsequent im... | def __init__(self, default_paths, sequence_names_dict, n_elements):
"""
Parameters
----------
default_paths : Dictionary of file default paths
sequence_names_dict : Dictionary of sequence names - only Dicoms with a sequence name in this dictionary will be sort... |
def Produce_Magnitude_PNGs(self, magnitude_png_directory, dcm_dict):
"""
Save magnitude pngs in magnitude_png_directory
Parameters
----------
magnitude_png_directory : str
directory to save PNGs in
dcm_dict : dictionar... | The main task of the code is to generate a structured PDF report summarizing analysis results (e.g., SNR, uniformity, suppression effectiveness, contrast) from medical imaging data. It compiles graphs, tables, and magnitude images into a draft report, prompts user input for final assessment (Pass/Fail/Undetermined) and... | def __init__(self, report_directory, baseline_ss_path, results_ss_path, dcm_dict, results, date, sheet_names, pdf_header_path, pdf_txt_sizes, pdf_default_comment, pdf_glossary, report_sections):
"""
Produce pdf report summarising results.
An attempt is made to input SNR, uniformity, ... |
def CreateBagOfWordsFeatures(vocab, train=True):
"""Creates bag of words features for the reviews given a vocabulary.
Args:
vocab: List of words in vocabulary.
Returns:
bag_of_words: a numpy matrix with bag of words representation for each review as a row.
Y: true labels
"""
pos... | The function `LoadDataSet` loads a test dataset, generating features based on the specified `feature_type` (bag-of-words or TF-IDF) and returns the feature matrix `X` and true labels `Y`. If `add_bias` is True, it appends a bias term to the features. The function supports configurable feature extraction and bias inclus... | def LoadDataSet(vocab, feature_type = 'bag_of_words', train=True, add_bias=True):
"""Loads the test set.
Returns:
X: test features data
Y: true labels
"""
if(feature_type == 'bag_of_words'):
(X, Y) = CreateBagOfWordsFeatures(vocab, train)
elif(feature_type == 'tf_idf'):
(... |
def CreateDict():
"""Creates a vocab by parsing words in train dataset.
Returns:
vocab as a dict mapping word to unique idx
"""
train_pos_dir_list = os.listdir(train_pos_path)
train_neg_dir_list = os.listdir(train_neg_path)
skip_words = [
"this", "is", "that", "the", "a", "of"... | The main task of the code is to train and evaluate a linear neural network (linear_nn) using TF-IDF features on the IMDb dataset. It loads a pre-defined vocabulary, prepares training/test data, trains the model, plots training loss, and computes accuracy/precision/recall metrics for both training and test sets. | def main():
vocab_path = "/home/aniruddh_ramrakhyani/my_proj/cs229/aclImdb/my_vocab.txt"
#vocab_path = "/Users/aniruddhr/Documents/cs229/project/aclImdb/my_vocab.txt"
#plot_save_path = "/Users/aniruddhr/Documents/cs229/project/aclImdb/loss.png"
plot_save_path = "/home/aniruddh_ramrakhyani/my_proj... |
def write_header():
write_timestamp(f"{__file__}")
print(f"python=={platform.python_version()}")
print(f"mysql.connector=={mysql.connector.__version__}")
print(f"pandas=={pd.__version__}")
print(f"pandas_profiling=={pp.__version__}")
print(f"requests=={requests.__version__}")
print()
def con... | (The code connects to a database, retrieves schema information, generates a pandas data profile, saves the profile to a file, closes the database connection, and logs completion with a timestamp.) | def main():
write_header()
# connect to the database
db_connection = connect_to_db(DB_CONNECTION)
ddic = read_mysql_ddic(db_connection, DB_SCHEMA, EXCLUDE_TABLES)
pd_profile = generate_pandas_profile(db_connection, DB_SCHEMA, ddic, SQL_LIMIT)
write_pandas_profile(os.path.join(CWD, PROFILE_PATH)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.