dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def generate_styles(self):
# Parse prompt and get image URLs
style_inputs = self.prompt.split(", ")
style_inputs = [None if input ==
"None" else input for input in style_inputs]
self.style_inputs = style_inputs
for idx, input in enumerate(style_inputs):
... | The main task of the code is to generate a stylized video by first creating style references, fetching input frames, retrieving style information, fetching output frames, and finally synthesizing the stylized video. The method sequentially executes these steps with print statements to indicate progress, ensuring struct... | def run(self):
print("Generating style references")
self.generate_styles()
print("Fetching input frames")
self.fetch_pre_frames()
print("Fetching style reference info")
self.fetch_style_refs()
print("Fetching output frames")
self.fetch_post_frames()
... |
def resetBoard():
board.clear()
for i in range(0,9):
board.append([0, 0, 0, 0, 0, 0, 0, 0, 0])
def fillBoard():
for i in range(0,81):
row=i//9
col=i%9
if board[row][col]==0:
shuffle(numbers)
for n in numbers:
if isSafe(row,col,n):
... | The code generates a customized board by resetting, populating, and finalizing its structure. It shuffles positions to randomly remove entries, creating a dynamic configuration. The final board is returned as the result. | def generateBoard():
resetBoard()
fillBoard()
setFinalBoard()
removeEntries(shufflePositions())
return finalBoard |
def get_latest_release():
RELEASES_API = "https://api.github.com/repos/vhive-serverless/vSwarm-u/releases/latest"
print("Releases API: " + RELEASES_API)
headers = {}
response = requests.get(RELEASES_API, headers=headers)
# print("debug: " + str(response.status_code))
RELEASE = response.json()... | The code downloads and moves specific assets (kernel, client, and disk image) from a specified release version. It retrieves URLs for these assets, validates their existence, downloads them, and relocates them to a target directory. The function supports version flexibility, handles exceptions for missing assets, and u... | def downloadMoveAssets(version="latest"):
if version == "latest":
release=get_latest_release()
else:
release=get_release(version)
print(f"Download Artifacts from version: {get_version(release)}")
name = f"vmlinux-{ args.os_version }-{ args.arch }"
kernel_url = get_url(release=relea... |
def get_latest_release():
RELEASES_API = "https://api.github.com/repos/vhive-serverless/vSwarm-u/releases/latest"
print("Releases API: " + RELEASES_API)
headers = {}
response = requests.get(RELEASES_API, headers=headers)
# print("debug: " + str(response.status_code))
RELEASE = response.json()... | The main task of the code is to download specific assets (vmlinux, client, and disk-image) from the latest release of a software project. It reads configuration from a JSON file, retrieves URLs for each asset using helper functions, and sequentially downloads them. The disk-image download is noted to take longer, indic... | def downloadAssets():
with open(args.file) as f:
artifacts = json.load(f)
release=get_latest_release()
print("Download Artifacts")
name = "vmlinux"
url = get_url(release=release,name=name)
downloadAsset(url)
name = "client"
url = get_url(release=release,name=name)
downloadA... |
def setDiskImage(self, img_path):
""" Set the disk image
@param img_path path on the host to the image file for the disk
"""
# Can have up to two master disk images.
# This can be enabled with up to 4 images if using master-slave pairs
disk0 = CowDisk(img_path)
... | This code initializes a simulated x86 system with KVM support, configuring CPUs, memory, interrupt controllers, and I/O components. It sets up a memory bus, loads a kernel and disk image with specified boot parameters, creates CPU and cache hierarchies, and prepares the system for execution with virtualization capabili... | def __init__(self, kernel, disk, num_cpus=2, CPUModel=AtomicSimpleCPU, kvm=True):
super(SklSystem, self).__init__()
self._host_parallel = True if kvm and num_cpus > 1 else False
# Set up the clock domain and the voltage domain
self.clk_domain = SrcClockDomain()
self.clk_domain.... |
def _setup_socket(sClient):
server_address = (sClient.target, sClient.port)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
sock.connect(server_address)
return sock
def getServerChallenge(sClient, sock):
nonce = (
b"\x00\x00\x00\x00\x00\x00\x00\x2b\x03\x41\x4d... | This function validates a SASL secret for Spark authentication by establishing a socket connection, extracting server challenges, verifying the 'md5-sess' algorithm, and sending a challenge response. It returns the secret if authentication succeeds, False on SASL exceptions, or None for invalid challenges. | def isSecretSaslValid(sClient, secret, username="sparkSaslUser", quiet=False):
sock = _setup_socket(sClient)
rawServerChall = getServerChallenge(sClient, sock)
if rawServerChall is None:
# whine(
# "Could not fetch server SASL challenge. Try reducing the number of pools",
# "er... |
def setup_speed_button_and_label(self, win):
self.speed_minus = tkinter.Button(win,
text="-", command=(lambda: self.increment_speed(.5)))
self.speed_minus.grid(row=0, column=0)
self.speed_label = tkinter.Label(win, text='Step Delay: %.5f' % (self.tick_t... | This method initializes a GUI interface by setting up a window, grid layout, and various interactive elements including buttons and labels for parameters like Epsilon, Gamma, and Alpha. It configures a canvas for visualization and prepares controls for simulation settings, though some components like the exit button an... | def __init_gui(self, win):
# Window
self.win = win
# Initialize Frame
win.grid()
self.dec = -.5
self.inc = .5
self.tick_time = 0.1
# Epsilon Button + Label
self.setup_speed_button_and_label(win)
self.setup_epsilon_button_and_label(win)
... |
def chk(task=None,min_verbose=1,*,timer=True):
"""
Displays status of python code.
Parameters
----------
task: str, optional
String describing the current task.
Passing None will end the current timer without starting a new one
min_verbosity: int, optional
minimum verbos... | (The main task processes medical data to analyze drug prescriptions, clustering patients by drug usage patterns. It loads BNF codes, calculates scores, filters data, clusters prescriptions, and generates reports on demographic and socioeconomic factors. Key steps include data preprocessing, clustering, and statistical ... | def main():
"""Main pipeline. Will execute when the program is run at top level, i.e, not imported"""
import pandas as pd
chk("starting",timer=False)
bnfCSV=inputCSV("data/new_bnf_lkp.csv")
bnfDict=BNF_to_dict(bnfCSV)
lit_dfs=inputCSV("data/lozano.csv")
acb=unify_score(lit_dfs,bnfDict)
... |
def updateParams(self, ad):
# Pre-computes parameters that are used repeatedly in wave
# speed calculations
nacc = len(self.tens['cp']['accch'])
# Compute the bandpass filter parameters
self.tens['pp']['bf'], self.tens['pp']['af'] = signal.butter(3, ... | The code processes wavespeed data by updating parameters, calculating wave speeds, and optionally plotting results alongside ancillary data, with additional processing triggered by the 'accch' flag. | def process(self, ad):
# Main function called to process wavespeed data
# update processing params
self.updateParams(ad)
# calculate wave speeds
acc = self.wsCalc(ad)
# plot computed wavespeed and ancillary data
if self.plot['option']:
for i in rang... |
def _validate_input_file(self) -> None:
if not exists(self.input_file):
raise ValueError(f"Input file '{self.input_file}' doesn't exist")
def _validate_output_dir(self) -> None:
if not exists(self.output_dir):
raise ValueError(f"Output dir '{self.output_dir}' doesn't exist")
def _process_archive(self) -> None... | The main task of the code is to validate input files and output directories, download a language-specific UDPipe model using spaCy, load the model, and process an archive. It ensures prerequisites are met before executing the core processing logic. | def process(self) -> None:
self._validate_input_file()
self._validate_output_dir()
spacy_udpipe.download(self.lang)
self._nlp = spacy_udpipe.load(self.lang)
self._process_archive() |
def create_model(cfg, args):
logger.info('==> Preparing networks for baseline...')
# use gpu
device = torch.device("cuda")
assert torch.cuda.is_available(), "CUDA is not available"
# model and optimizer
model = create_deit_model(
cfg.MODEL.ARCH,
pretrained=False,
num_clas... | The code's main task is to configure and execute a machine learning model's evaluation pipeline. It sets up directories, initializes logging, loads data, creates model components, evaluates the model on a test dataset, logs results, saves metrics in JSON format, and optionally visualizes predictions at an optimal thres... | def main():
args = update_config()
# root dir
# create checkpoint directory
ds_dir= cfg.DATA.DATADIR.split("/")[-1]
workdir= f"{ds_dir}_{cfg.MODEL.ARCH}"
cfg.BASIC.SAVE_DIR= os.path.join(cfg.BASIC.SAVE_ROOT, workdir)
cfg.BASIC.ROOT_DIR = "."
log_dir = os.path.join(cfg.BASIC.SAVE_D... |
def getFilesByFolderId(self, folder_id):
page_token = None
query = f"'{folder_id}' in parents and trashed = false"
files = []
while True:
response = self.__service.files().list(supportsTeamDrives=True,
includeTeamDriveItems=T... | This function recursively clones a remote folder (and its contents) to a local directory by syncing files and subfolders, tracking total folders/files processed, and handling errors during file copying. It returns the new directory ID or parent ID after processing. | def cloneFolder(self, name, local_path, folder_id, parent_id):
LOGGER.info(f"Syncing: {local_path}")
files = self.getFilesByFolderId(folder_id)
new_id = None
if len(files) == 0:
return parent_id
for file in files:
if file.get('mimeType') == self.__G_DRIVE_... |
def getIdFromUrl(link: str):
if "folders" in link or "file" in link:
regex = r"https://drive\.google\.com/(drive)?/?u?/?\d?/?(mobile)?/?(file)?(folders)?/?d?/([-\w]+)[?+]?/?(w+)?"
res = re.search(regex, link)
if res is None:
raise IndexError("Drive ID not foun... | This function clones a file or folder from a drive by copying its metadata, handling errors like rate limits or missing files, and returning a formatted message with details like size, type, and transfer stats along with a download link button. | def clone(self, link, parent_id: FOLDER_ID):
self.transferred_size = 0
self.total_files = 0
self.total_folders = 0
try:
file_id = self.getIdFromUrl(link)
except (KeyError, IndexError):
msg = "Drive ID not found"
LOGGER.error(f"{msg}")
... |
def get_terms_multi(self):
document = self.service.documents().get(documentId=self.DOCUMENT_ID).execute()
tables = self.get_tables(document.get('body').get('content'))
output = []
for table in tables:
entry = []
for item in table:
entry.append(ite... | The main task of the code is to alphabetize the first table in a document by sorting its terms and definitions, replacing placeholders with sorted values, and updating the file. It retrieves unsorted terms/definitions, sorts them, replaces original content with temporary markers, and then substitutes these markers with... | def alphabetize(self, definitions_completed):
'''
This function alphabetizes the first table in the document.
'''
unsorted_terms_list = self.get_terms_multi()
unsorted_definitions_list = self.get_definitions_multi()
for j in range(len(unsorted_definitions_list)):
... |
def updatelist(self):
region = self.path.split('/')[4]
fw_version = re.search(r'Download\/1.00 libhttp\/(.+?) \(PlayStation 4\)', self.headers['user-agent'])
path = os.path.join(UPDATE_LOC, 'ps4-updatelist.xml')
with open(path, 'rb') as buf:
xml = buf.read()
if fw_v... | This code handles HTTP GET requests for PS4 update and exploit-related endpoints by routing requests to specific methods based on URL patterns, including serving update lists, features, PUP files, network tests, and static content, while enforcing firmware compatibility checks and returning appropriate responses or err... | def do_GET(self):
try:
if re.match(r'^\/update\/ps4\/list\/[a-z]{2}\/ps4\-updatelist\.xml', self.path):
self.updatelist()
elif re.match(r'^\/update\/ps4\/html\/[a-z]{2}\/[a-z]{2}\/ps4\-updatefeature\.html', self.path):
self.updatefeature()
elif... |
def menu_header():
print_line()
print('# Exploit Host by Al Azif #')
print_line()
def check_root():
try:
root = bool(os.getuid() == 0)
except AttributeError:
root = True
return root
def closer(message):
print(message)
if message != '\r>> Ex... | The main task of the code is to run a system requiring root privileges, validate settings, check for updates using MD5 hashes, start servers, display IP information, and maintain an infinite loop to keep the service running until interrupted. It ensures proper initialization, update verification, and persistent operati... | def main():
menu_header()
if not check_root():
closer('ERROR: This must be run by root as it requires port 53 & 80')
try:
version_check()
default_settings()
import_settings()
check_update_pup('SYSTEM', SETTINGS['Update']['System_MD5'])
check_update_pup('RE... |
def generate_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename", default="test.txt")
return parser
def read_file(file: pathlib.Path) -> list[str]:
if not file.exists():
raise FileNotFoundError
with file.open() as in_file:
... | The main task of the code is to read a text file (with automatic `.txt` extension if missing), process its contents to calculate the sum of calibration values, and print the total. It uses command-line arguments for the filename, handles file not found errors, and exits if the file is invalid. The core functionality re... | def main() -> None:
parser = generate_arg_parser()
args = parser.parse_args()
file_name = args.filename if ".txt" in args.filename else f"{args.filename}.txt"
try:
raw_data = read_file(CURRENT_PATH / file_name)
except FileNotFoundError:
print(f"Unable to find the file '{file_name}', ... |
def generate_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename", default="test.txt")
return parser
def read_file(file: pathlib.Path) -> list[str]:
if not file.exists():
raise FileNotFoundError
with file.open() as in_file:
... | The code processes a text file containing time and distance data to calculate the number of ways to win a race. It first extracts individual time/distance values, computes winning strategies, then concatenates these values into single numbers for a second calculation, printing both results. | def main() -> None:
parser = generate_arg_parser()
args = parser.parse_args()
file_name = args.filename if ".txt" in args.filename else f"{args.filename}.txt"
try:
raw_data = read_file(CURRENT_PATH / file_name)
except FileNotFoundError:
print(f"Unable to find the file '{file_name}', ... |
def in_bull_sight(current_position, target_position):
if abs(current_position[0] - target_position[0]) <= 2 and abs(current_position[1] - target_position[1]) <= 2:
return True
else:
return False
def approaching_mode(self, target_position):
start_cell = Cell(self.position)... | The code determines the movement strategy of an agent based on its position relative to a bull. It selects between approaching, navigating, or guiding modes depending on visibility and distance, updates the strategy log, and appends the new position to a path. The primary task is to compute the agent's next position wh... | def move(self, bull_position):
if not self.in_bull_sight(self.position, bull_position):
current_position = self.approaching_mode(bull_position)
self.strategy.append("app")
elif self.in_bull_sight(self.position, bull_position) and (abs(self.x_position[0] - bull_position[0])>3 or a... |
def in_bull_sight(current_position, target_position):
if abs(current_position[0] - target_position[0]) <= 2 and abs(current_position[1] - target_position[1]) <= 2:
return True
else:
return False
def approaching_mode(self, target_position):
start_cell = Cell(self.position)... | This code determines an agent's movement strategy based on its position relative to a bull. It checks visibility and distance, selecting between approaching, navigating, or guiding modes. The chosen mode updates the strategy log, appends the new position to a path, and returns it for movement execution. | def move(self, bull_position):
if not self.in_bull_sight(self.position, bull_position):
current_position = self.approaching_mode(bull_position)
self.strategy.append("app")
elif self.in_bull_sight(self.position, bull_position) and (abs(self.x_position[0] - bull_position[0])>3 or a... |
def __check_near_positions(self, player, field, diff):
fields = []
f = self.__check_position((field[0] + diff, field[1] - 1))
if not f is None:
fields.append(f)
f = self.__check_position((field[0] + diff, field[1] + 1))
if not f is None:
fields.append(f)... | The code generates valid pawn moves for a board game, considering standard pawn movement rules (e.g., forward steps, captures, and potential future moves). It checks adjacent positions, handles initial moves, captures of opponent pieces, and recursively explores subsequent moves while avoiding invalid positions based o... | def __pawn_moves(self, piece, player, diff, previous_move):
moves = []
fields = self.__check_near_positions(player, piece, diff)
for field in fields:
# if this is first move and there is no piece on the field then this is possible move
if field[0] == VOID and previous_mo... |
def get_window():
window = Tk()
window.title("Chekers")
window.geometry(str(WIDTH) + "x" + str(HEIGHT))
window.resizable(False, False)
return window
def draw_level_choice_window(window: Tk):
winner_frame = Frame(window, background=RED, height=300, width=300, bd=4, relief="groove")
easy_butt... | The main task of the code is to create and configure a main menu window for a checkers game. It sets up a red-themed window with the title "CHECKERS" and two buttons: "Singleplayer" (launching a level selection) and "Multiplayer" (starting a game). The function returns the configured window for display. | def get_main_menu_window():
window = get_window()
frames.get_board_frame(window)
label = Label(window, text="CHECKERS", font=("Comic Sans MS", 56), background=RED, bd=4, relief="groove")
label.place(x = 155, y = 20)
buttons_frame = Frame(window, background=RED, height=300, width=300, bd=4, rel... |
def possible_moves_for_piece(self, player, piece: tuple):
if player == PLAYER_1_KING or player == PLAYER_2_KING:
return self.__king_moves(piece, player, -1)
elif player == PLAYER_1:
return self.__pawn_moves(piece, player, -1, None)
else:
return self.__pawn_mo... | The code generates all possible moves for a player's pieces on an 8x8 board, prioritizing capture moves. It iterates through each position, collects valid moves for the player's pieces and allied pieces (via `player + 2`), filters for capture moves, and returns them if present; otherwise, returns all valid moves. | def get_all_possible_moves(self, player):
moves = []
# create list with all possible moves for all active player's pieces
for i in range(0, 8):
for j in range(0, 8):
if self.current_positions[i][j] == player:
moves.extend(self.possible_moves_for_... |
def cr_nbhs(obj):
nbhs = []
step = int(360 / len(obj.get_angles()))
# creating a few objects around object and connecting center object with periphery
langle = step
while langle <= 360:
if obj.get_angles()[langle] is None:
# new object of RegularPoligon
nbhs.append(R... | The code processes a list of geometric objects (hs) by expanding their neighbors and applying transformations. If the list is empty, it initializes with a polygon and generates neighbors. It then iterates up to r-1 times, adjusting parameters (s) to perform operations (cl_2d) that modify the list's structure, likely fo... | def hs2d(hs, r):
if len(hs) == 0:
hs.append(RegularPoligon([0, 0, 0], 6))
hs.extend(cr_nbhs(hs[0]))
cpo_bt(hs)
s = 1
for i in range(1, r - 1):
f = len(hs)
cl_2d(hs, s, f)
s += i * 6 |
def total_error(self, training, labels):
sum = 0
for i, sample in enumerate(training):
res = self.predict(sample)
for j, component in enumerate(res):
sum += 1/2 * (res[j] - labels[i][j])**2
return sum/len(training)
def _get_batch(self, training_inputs, lab... | This code trains a neural network using batch gradient descent with backpropagation. It processes input data in batches, computes forward passes with sigmoid activations, calculates layer-wise derivatives, and updates weights to minimize error. Training stops early if the error falls below a threshold, and weights are ... | def train(self, training_inputs, labels, learning_rate, epochs, batch_size, error_threshold=1e-2):
self.errors.append(self.total_error(training_inputs, labels))
for epoch in range(epochs):
dW_tot = [np.zeros(w.shape) for w in self.weights_ext]
batch_in, batch_out = self._get_b... |
def get_real_variables(formula):
return {a for a in formula.get_free_variables() if a.get_type() == REAL}
def get_coefficients(atom: FNode):
"""
obtain coefficient of variable x in atom of form a * x + b * y + const
note that when there is a * x + b * x, simplify() doesn't do multiplication
but stil... | The main task of the code is to derive bounds on a variable $ x $ from a given inequality (atom), returning a bound expression and its type (upper/lower). It analyzes coefficients of $ x $ and other variables in the inequality's sides, calculates the bound using coefficient differences, and adjusts for additional varia... | def atom_to_bound(atom: FNode, x_symbol: FNode):
"""
obtain bounds on variable x from inequality atom
:param atom: must be of plus form or a single term on each side
:param x_symbol:
:return:
"""
assert atom.is_le() or atom.is_lt()
variables = list(get_real_variables(atom))
if x_symb... |
def get_real_variables(formula):
return {a for a in formula.get_free_variables() if a.get_type() == REAL}
def categorize_bounds(formula: FNode, sender_symbol: FNode):
"""
categorize symbolic bounds for a given variable
:param formula: FNode formula in CNF form
:param sender_symbol: FNode of the boun... | The code identifies critical points for recipient variables by analyzing bounds from the edge formula, recipient domain intervals, and sender domain constraints. It extracts symbolic variables, categorizes bounds, solves equations for recipient atoms, converts domain intervals to points, and combines results. Duplicate... | def find_edge_critical_points(sender_domains: FNode,
recipient_domains: FNode,
edge_formula: FNode):
"""
collect critical points for recipients
:param sender_domains: CNF involving child variable only
:param recipient_domains: CNF involving par... |
def categorize_bounds(formula: FNode, sender_symbol: FNode):
"""
categorize symbolic bounds for a given variable
:param formula: FNode formula in CNF form
:param sender_symbol: FNode of the bounded variable
:return: upper_bounds, lower_bounds, parent_atoms
"""
clauses = set()
formula = s... | The function `clause_to_intervals` converts a logical clause (OR node or atom) into a list of intervals, representing valid ranges for a recipient variable based on bounds derived from the clause. It uses a test point to evaluate bounds, categorizing them into upper/lower limits. If bounds overlap, it returns a single ... | def clause_to_intervals(clause: FNode,
sender_symbol: FNode,
test_point: float):
"""
turn clause into a list of intervals,
where there are at most two intervals
:param clause: OR FNode or a single atom
:param sender_symbol:
:param test_point: an i... |
def midi2array(mid, min_msg_pct=0.1):
# https://medium.com/analytics-vidhya/convert-midi-file-to-numpy-array-in-python-7d00531890c
"""Converts midi file to a set of arrays (one array for each track)
Args:
mid: Midi file content
min_msg_pct: Minimum number of messages in a track... | The code processes MIDI files in a folder by extracting and adjusting soprano, alto, tenor, and bass voices. It converts MIDI to piano rolls, identifies notes, handles missing voices via distance calculation, and applies resolution adjustments. The function returns processed voice lists with adjusted granularity. | def load_all_midi_in_folder(path, resolution):
"""Reads all midi files in folder and extracts a list of each processed soprano, alto, tenor, bass voices
Args:
path: Path of the folder
resolution: Granularity to apply
Returns:
Distance between the note and the ... |
def decompose_all_blockquote_headers(soup: BeautifulSoup) -> None:
block: bs4elem.Tag
for block in soup.find_all("blockquote"):
block.find("div").decompose()
def decompose_all_spoiler_headers(soup: BeautifulSoup) -> None:
spoilerheader: bs4elem.Tag
for spoilerheader in soup.find_all("div",{"clas... | The main task of the code is to process an HTML document by removing specific elements (blockquote headers, spoilers, footers), modifying image links to avoid duplication, converting media elements (MP4, iframes) to links, propagating attributes to child elements, and handling tables and spoilers. The function aims to ... | def process_html_tag(soup: BeautifulSoup) -> None:
decompose_all_blockquote_headers(soup)
decompose_all_spoiler_headers(soup)
decompose_all_edited_on_footers(soup)
strip_image_links_to_avoid_double_links(soup)
convert_mp4_to_link(soup)
convert_iframes_to_link(soup)
propagate_elements_to_chil... |
def text(et, key):
v = et.findtext(key)
if v == "":
return None
return v
def import_analysis(self, et, session, **kwargs):
"""
AnalysisFraction -> analysis
"""
def data_iterator(et, key, unit, model="ValueModel"):
return iter(et.find(key).findall(model))
... | This method imports data from an XML element tree into a database session by parsing dates, handling IGSN identifiers, creating or retrieving sample sessions, associating publications, and importing analysis fractions. It processes XML elements to extract certified dates, resolves IGSN values, links samples, and stores... | def __import_element_tree(self, et):
"""
Aliquot -> session
"""
dates = [i.text for i in et.findall(".//dateCertified")]
date = max(set(dates), key=dates.count)
if not date:
date = datetime.min()
# Set IGSN
igsn = text(et, "aliquotIGSN")
... |
def get_order_and_till_sub_images(input_image):
# https://stackoverflow.com/questions/57282935/how-to-detect-area-of-pixels-with-the-same-color-using-opencv#57300889
# https://docs.opencv.org/4.x/d9/d61/tutorial_py_morphological_ops.html
# https://docs.opencv.org/3.4/da/d0c/tutorial_bounding_rects_circles.h... | This function tests object detection in images by comparing detected objects to expected sets for "order" and "till" regions. It processes test images, segments sub-images, detects objects, and verifies detected keys match expected values using assertions, allowing selective testing via command-line arguments. | def run_test_detect_objects(args):
for img_name, expected_order in TEST_IMG_ORDERS.items():
# Allow selective testing of individual cases
if args and img_name not in args:
continue
expected_order = {
QUERY_DISPLAY_NAMES[query_name]
for query_name in expec... |
def detect_graph_space(image_path, show_graph=False):
# Load the image
image = cv2.imread(image_path)
dark_image = has_dark_background(image_path, 50)
if dark_image:
image = cv2.bitwise_not(image)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
... | The main task of the code is to extract bounding boxes of data points from a scatterplot image using image processing. It processes the image with thresholding, contour detection, and filtering based on grid/axes positioning, returning coordinates of detected points while optionally visualizing them with bounding boxes... | def get_points(image_path, num_points, show_plot=False):
"""
Extract the bounding boxes of the data points from a scatterplot image.
Args:
image_path (str): The path to the scatterplot image file.
num_points (int): Number of points in the scatterplot
show_plot (bool, optional): Whet... |
def parse_label(self):
return self.consume('LABEL').value
def parse_arrow(self):
self.consume('ARROW')
def parse_text(self, expected_type):
self.consume(expected_type)
return self.consume('TEXT').value.strip('"') | The main task of the code is to parse an instruction by extracting a label, handling an arrow, and retrieving text segments before and after specific markers. It returns these components as a dictionary with keys 'label', 'after', and 'before'. | def parse_instruction(self):
label = self.parse_label()
self.parse_arrow()
after_text = self.parse_text('AFTER')
before_text = self.parse_text('BEFORE')
return {'label': label, 'after': after_text, 'before': before_text} |
def get_any_socket(url, get_cert_format=None):
# tries to open a socket through https(preferred) or http
# returns (socket, cert, https)
urls = format_url(url)
for HTTPS, addr, path in urls:
results = get_socket_and_cert(addr, path, https=HTTPS, get_cert_format=get_cert_format)
if result... | The function retrieves a socket connection, SSL certificate, and HTTPS status for a given URL. It first attempts to obtain these using `get_any_socket`, then falls back to `get_certificate` if the initial certificate is missing and `get_cert_format` is specified. If HTTPS status is invalid, it uses `last_resort_https` ... | def get_any_socket_cert(url, get_cert_format=None):
socket, cert, https = get_any_socket(url, get_cert_format)
if cert is None and get_cert_format is not None:
cert = get_certificate(url)
if https is False or https is None:
https = last_resort_https(url)
return socket, cert, https |
def get_any_socket_cert(url, get_cert_format=None):
socket, cert, https = get_any_socket(url, get_cert_format)
if cert is None and get_cert_format is not None:
cert = get_certificate(url)
if https is False or https is None:
https = last_resort_https(url)
return socket, cert, https
def ve... | The main task of the code is to check a website's SSL/TLS certificate details, including verifying HTTPS support, certificate retrieval, chain validation, and hostname matching. It handles cases where initial checks fail by attempting a fallback certificate verification method, then returns formatted results about the ... | def check_all(url):
sock = get_any_socket_cert(url, get_cert_format=True)
#print("Checking {}\n".format(url))
https = "Website supports https: {}".format(str(sock[2]))
cert = "Certificate retrieved: {}".format(str(sock[1] is not None))
cert_chain = "Certificate chain verified: {}".format(str(verify... |
def display_stats(self):
player_loc = "Player at " + str(self.player_x) + ", " + str(self.player_y)
status = self.font_set[3].render(player_loc, True, color_lookup("BRIGHTGREEN"))
self.screen.blit(status, ((10),(10)))
health = self.font_set[3].render("{}".format(self.player_health), True, color_lookup("BRIG... | The code renders the game's current view by clearing the screen, updating character tiles based on the player's position, handling sprite or font-based display modes, rendering the player's position, and maintaining a 60 FPS cap. It calculates visible map coordinates, checks for a round world, and updates the display w... | def next_frame(self, latest_key=pygame.K_DOWN):
player_x, player_y = 0,0
#Clear the screen
self.screen.fill(color_lookup("DAY_SKY"))
self.display_stats()
if self.edit_enabled and self.edit_mode:
self.set_char_to_edit()
#Render each character in view onto a surface
for y in range(self.vie... |
def change_zoom(self, new_size):
if not(new_size < 0) and not(new_size >= NUM_SIZES):
self.size = new_size
self.view_max_x, self.view_max_y = view_size_lookup(self.size)
self.box_size = box_size_lookup(self.size)
def at(self, char):
return self.get_char() is char
def adjust_location(self):
self.player_x,... | This function handles player interactions with different terrain types by adjusting zoom levels, modifying player attributes (health, cash), and triggering movement or visual effects based on the character at the player's current position. It checks for specific tiles ('m', 'M', '^', 'x', etc.) to apply corresponding a... | def check_area(self):
if self.temporary_zoom:
self.temporary_zoom = False
self.change_zoom(4)
if self.detect_collision:
#See more from hills
if self.at('m'):
self.change_zoom(3)
self.temporary_zoom = True
#See far from mountains
elif self.at('M'):
self.change_zoo... |
def return_engwordrep(inp):
return english_word_representation(alphabet_index_eng,inp)
def hindi_word_representation(index_of_the_letter,hindi_w, device = device_gpu):
zer = 0
one = 1
len_of_hindi_word = int(return_len_of_word(hindi_w))
temp = len_of_hindi_word+one
hindi_word_rep = torch.zeros([... | The function computes the training loss for a model using teacher forcing, processes English and Hindi word batches, calculates loss per sample with a specified method, accumulates gradients, averages the loss over the batch, and updates model parameters via the optimizer. It handles gradient retention for multiple bac... | def loss_compute_for_training(model, optimizer, method, bsize_, device =device_gpu, teacher_forcing = False):
ZER = 0
batchsize = bsize_
tforce = teacher_forcing
eng_batch, hindi_batch = data_training.extract_batch_for_lang(bsize_)
model.train().to(device)
optimizer.zero_grad()
TO... |
def return_engwordrep(inp):
return english_word_representation(alphabet_index_eng,inp)
def hindi_word_representation(index_of_the_letter,hindi_w, device = device_gpu): # word representation for hindi words
zer = 0
one = 1
len_of_hindi_word = int(return_len_of_word(hindi_w))
temp = len_... | This function computes the training loss for a sequence-to-sequence model using teacher forcing. It processes batches of English and Hindi word representations, feeds them through the model (with Hindi words as ground truth if teacher forcing is active), calculates per-output loss, accumulates gradients, averages the l... | def loss_compute_for_training(model, optimizer, method, bsize_, device =device_gpu, teacher_forcing = False):
ZER = 0
batchsize = bsize_
tforce = teacher_forcing
eng_batch, hindi_batch = data_training.extract_batch_for_lang(bsize_)
model.train().to(device)
optimizer.zero_grad()
TO... |
def cli_parser(argv=None):
parser = argparse.ArgumentParser(
description='Generating configuration commands by finding differences'
' between two Cisco IOS style configuration files')
parser.add_argument('--origin', metavar='origin',
type=str, help='Origin con... | The code compares two network configuration files (origin and target) for iOS devices. It loads a configuration file, cleans the input files, identifies differences between them, and prints the resulting differences line by line. | def cmp(origin, target):
args = cli_parser("")
args.origin = origin
args.target = target
args.vendor = "ios"
args.config = "netcompare.yml"
with open(args.config, 'r') as f:
config = yaml.load(f)
origin_list = clean_file(args.origin, args.vendor, config)
target_list = clean_fi... |
def cli_parser(argv=None):
parser = argparse.ArgumentParser(
description='Generating configuration commands by finding differences'
' between two Cisco IOS style configuration files')
parser.add_argument('--origin', metavar='origin',
type=str, help='Origin con... | The main task of the code is to compare two configuration lists (origin_list and target_list) by splitting them into lines, cleaning them using a YAML configuration file, identifying differences with a network comparison tool, and returning the formatted differences as a string. The process involves parsing CLI argumen... | def compareConfigs(origin_list, target_list):
origin_list = origin_list.split("\r\n")
target_list = target_list.split("\r\n")
args = cli_parser("")
args.vendor = "ios"
args.config = "netcompare.yml"
with open(args.config, 'r') as f:
config = yaml.load(f, Loader=yaml.BaseLoader)
o... |
def openDevicesFile():
global devices
global devicesFile
try:
f = open(devicesFile, "r")
rawData = f.read()
f.close()
devices = rawData.split("\n")
devices = [dev for dev in devices if dev != ""]
except:
printMessage(devicesFile + " is missing.")
d... | The code's main task is to back up configurations from all open network devices listed in a file. It opens the devices file, checks each device's status, downloads configurations for open devices, and reports successful backups. The function uses global variables to track devices and logs progress, ensuring only active... | def backupAll():
openDevicesFile()
global devices
devDone = []
for ip in devices:
if isOpen(ip):
print("Creating back-up for: " + ip)
downloadConfig(ip)
devDone.append(ip)
if len(devDone) > 0:
print("Back-up successfull for: ")
for ip in d... |
def help():
global exitTag
global currentDevice
print("0. Back-up all online devices.")
print("1. Select a device.")
print("2. Add a new device.")
print("3. Remove a device.")
if currentDevice != "":
print("4. Back-up the configuration.")
print("5. Display backed-up configur... | The main task of the code is to repeatedly display help information, read user input, clear the screen, and process the input until the user enters an exit command. The loop continues unless the input matches the predefined exit tag, at which point the program terminates. | def main():
answer = ""
while answer.upper() != exitTag:
help()
answer = readAnswer()
os.system("cls")
if answer.upper() != exitTag:
process(answer) |
def _do_atomic_action(self, action):
step_size = 0.025 # agent moves by this much if we move with velocity 1 for ten sim steps (old setup)
step_size = 0.25 # increasing to make it easier to solve!
pos = self.agent.get_position()
if action == 0:
# north
new_pos ... | The function `atomic_step` executes a single atomic action, computes the resulting reward, checks if the episode is done, and returns the new observation, reward vector, episode done status, info messages, and episode success status. It processes the action, calculates rewards, verifies termination conditions, and pack... | def atomic_step(self, action):
self._do_atomic_action(action)
reward_vector = self._calc_atomic_reward()
eps_done, done_msg, eps_success, reward_vector = self._check_atomic_done(reward_vector) # check done and potentially give reward bonus
observation = self.get_atomic_obs()
in... |
def setTheme(self,type="light"):
self.tk.call('source', f'theme/forest-{type}.tcl')
ttk.Style().theme_use(f'forest-{type}')
def top(self):
top = ttk.Frame(self.tab1, style='Accent.TFrame', padding=(5, 6, 7, 8))
# search bar
self.searchBar = ttk.Entry(top)
self.searchBar.p... | This code initializes a GUI application with a tabbed interface, creating a 'tmp' directory if needed, setting up two tabs ('Main' and 'Play'), configuring window properties, and initializing components like a downloader API and thumbnail display logic. | def __init__(self):
if not os.path.isdir("tmp"):
os.makedirs("tmp", exist_ok=True)
super().__init__()
self.tabControl = ttk.Notebook(self)
self.tab1 = ttk.Frame(self.tabControl)
self.tab2 = ttk.Frame(self.tabControl)
self.tabControl.add(self.tab1, text ='Main'... |
def solvePhase1():
global solution, cube
with open('Phase_1_sol.txt', 'r') as file:
dbSolution = file.read().split('\n')
with open('Phase_1_states.txt', 'r') as file:
dbStates = file.read().split('\n')
stateId = str(calulatePhaseOneId())
index = dbStates.index(stateId)
soluti... | The code solves a Rubik's Cube by applying a sequence of moves derived from the input 'shuffle', breaking the solution into four phases. It processes each move, formats them (e.g., converting 'u' to 'U2'), and prints the step-by-step solution. Finally, it displays the cube with the formatted moves. | def solveCube(shuffle=''):
global solution
solution = []
for i in shuffle:
eval(movesp1[moves.index(i)])
solvePhase1()
solvePhase2()
solvePhase3()
solvePhase4()
solution_f = []
for i in solution[0]:
solution_f.append(i)
print(solution[0], end="")
for i ... |
def count_delegates(party_list):
"""
Sums all delegates from all parties. Return 0 if something fails.
Parameters
----------
party_list : <list>
Data for each party, a dict with the following format : [
{
'name': <str>,
... | The function generates an SVG diagram from input data by calculating delegate counts, determining row layouts, positioning elements, and saving the output as a uniquely named file. It processes party lists, dense rows, and delegate sums to create visual arrangements, then renders and returns the SVG filename. | def treat_inputlist(input_list):
# Create a filename that will be unique each time.
# Old files are deleted with a cron script.
svg_filename = filename
party_list = input_list['parties']
dense_rows = input_list['denser_rows']
sum_delegates = count_delegates(part... |
def make_utxos(self):
block = self.build_block_on_tip()
self.test_node.send_and_ping(msg_block(block))
assert(int(self.nodes[0].getbestblockhash(), 16) == block.sha256)
self.nodes[0].generate(100)
total_value = block.vtx[0].vout[0].nValue
out_value = total_value // 10
... | The main task of the code is to run a series of network protocol tests using a test node. It sets up P2P connections, initializes a network thread, waits for handshake confirmation, generates UTXOs for transaction testing, and executes multiple test cases involving compact block handling, block requests, and error resp... | def run_test(self):
# Setup the p2p connections and start up the network thread.
self.test_node = TestNode()
connections = []
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.test_node))
self.test_node.add_connection(connections[0])
NetworkThrea... |
def plotData(X,y):
data = np.c_[X,y]
positives = data[data[:,2] == 1]
negatives = data[data[:,2] == 0]
plt.scatter(negatives[:,0], negatives[:,1], c='y', marker='o',label='Not Admitted')
plt.scatter(positives[:,0], positives[:,1], c='b', marker='+', label='Admitted')
plt.legend()
return
def... | The code performs logistic regression for binary classification. It loads training data, prepares features and labels, initializes parameters, computes initial cost and gradient, optimizes theta via an optimization function, plots the decision boundary, predicts admission probabilities, and evaluates training accuracy.... | def main():
try:
data = np.genfromtxt('ex2data1.txt', delimiter=',')
except:
print("error loading file")
return -1
X = data[:, (0,1)] # first two columns are input data
y = data[:, 2].reshape(-1,1) # output is the last column
m = np.size(y) # number of training e... |
def get_audio_files_for_tokens(query, max_results=None, audio_file=None):
"""
Get the audio files for a given list of words.
param words (list): List of words.
return: List of audio files.
"""
session = Session()
audio_files = []
print(f"get_audio_files_for_tokens: query: {query}, audio_... | The function creates an audio clip by concatenating audio files containing phrases matching a user query. It retrieves query parameters, fetches relevant audio files, combines them, and returns a text response with the concatenated audio URL and extracted phrases. | def create_audio():
"""
Create an audio clip by concatenating audio files of phrases containing the given string
"""
print("create_audio route")
query = request.form.get("query")
# mode = request.form.get("mode")
# print(f"mode: {mode}")
if not query:
return "No query provided", ... |
def checkPurity(data):
if len(numpy.unique(data[:, -1])) == 1:
return True
else:
return False
def classifyData(data):
uniqueClasses, uniqueClassesCounts = numpy.unique(
data[:, -1], return_counts=True)
return uniqueClasses[uniqueClassesCounts.argmax()]
def getPotentialSplits(data... | The function builds a decision tree recursively by selecting the best attribute-value split to partition data, applying stopping conditions (purity, minimum samples, max depth), and combining subtrees. It supports random attribute selection and splits, returning a nested dictionary representing the tree structure with ... | def buildDecisionTree(dataFrame, currentDepth=0, minSampleSize=2, maxDepth=1000, randomAttributes=None, randomSplits=None):
if currentDepth == 0:
global COLUMN_HEADERS
COLUMN_HEADERS = dataFrame.columns
data = dataFrame.values
if randomAttributes != None and randomAttributes <= len(C... |
def convolve(self, data, width):
data2 = data.copy()
data2['RATE'] = conv(np.array(data['RATE']),
kernel=g1d(width), boundary='extend')
return data2
def bgdata(self):
c = self.data.copy()
remove = []
for i in range(len(self.start)):
... | This code processes time-series data by convolving input data, detecting peaks using scipy, extracting peak widths, fitting curves to peaks, and storing parameters like background data, standard deviation, and fitted curve segments for further analysis. | def __init__(self, data_path, convo_size=60):
self.data_raw = Table.read(data_path).to_pandas()
# we will use convolved data for most of our purposes
self.data = self.convolve(self.data_raw, convo_size)
# calls scipy function to detect peaks
self.peak_list, _ = find_peaks(
... |
def mode_10_per_day(flashcardContext: FlashcardContext):
'''
Enter 10 cards per day and review all cards based on day.
Counter refreshes every 5 days
:return: None
'''
day = flashcardContext.day
sets_of_flashcards = flashcardContext.setsOfFlashcards
place = day % 5
# check current... | The code initializes a flashcard application, allowing users to manage entries via commands like 'put entry', 'remove entry', and 'list entries'. It runs a predefined daily mode if set, otherwise enters a loop to process user inputs for interacting with flashcard data, with an exit option. | def start():
flashcardContext = FlashcardContext()
# if input("would you like a quiz?\n") == "yes":
# quiz(flashcardContext, 30)
if default_mode == "10_per_day":
mode_10_per_day(flashcardContext)
exit_flashcard_app(flashcardContext)
while True:
print("What command wou... |
def FindCorrespondingSourceFile( filename ):
if IsHeaderFile( filename ):
basename = p.splitext( filename )[ 0 ]
for extension in SOURCE_EXTENSIONS:
replacement_file = basename + extension
if p.exists( replacement_file ):
return replacement_file
return filename
def GetBFSHeaderDir(wk, d... | The code defines a `Settings` function that generates compiler flags and settings based on the specified programming language. For 'cfamily' languages, it locates source files, expands paths, collects dependencies, and returns flags/include paths. For 'python', it specifies the interpreter path. The function returns st... | def Settings( **kwargs ):
language = kwargs[ 'language' ]
flags = []
if language == 'cfamily':
filename = FindCorrespondingSourceFile(kwargs[ 'filename' ])
cwd = os.getcwd()
hmpath = path.expanduser("~")
flags.extend(oldflags)
if filename.startswith(cwd) and filename != hmpath:
GetB... |
def seek_c_to(self, c):
p = self.seek_c(c)
if p > -1:
self.offset = self.offset + p
return p
def lexer_next(self, reverse = False):
iden = ""
while True:
c = self.lexer_next_c(reverse)
if c == '\n' or c == '\0':
break
... | This function parses a C function prototype by extracting the function name and parameters from the input. It creates a FunctionProto object, identifies the function name using a lexer, parses parameters starting from the first "(", and sets the return type to "None" by default. | def parse_c_proto(self):
proto = FunctionProto()
p = self.seek_c_to("(")
if p == -1:
return
proto.func_name = self.lexer_next(True)
if not proto.func_name: # space
proto.func_name = self.lexer_next(True)
proto.params = self.parse_params(p)
... |
def get_filelang(self, filename):
if filename.endswith(".c"):
return FileType.LANG_C
elif filename.endswith(".py"):
return FileType.LANG_PYTHON
elif filename.endswith(".cs"):
return FileType.LANG_CSHARP
elif filename.endswith(".js"):
return... | This code generates a function comment based on the file's programming language (C, JS, C#, Python) by determining the function prototype, formatting parameters with language-specific syntax, replacing placeholders in comment templates, and applying indentation. It returns the properly structured comment lines for the ... | def get_comment(self):
filename = VimPy.fullname()
lang = self.get_filelang(filename)
comment = None
if lang in [FileType.LANG_C, FileType.LANG_JS, FileType.LANG_CSHARP]:
self.line = VimPy.lines_s("{")
elif lang == FileType.LANG_PYTHON:
self.line = VimPy.... |
def play_music(self, music_file):
pygame.mixer.music.load(music_file)
pygame.mixer.music.play(-1)
def wait_for_input_start_screen(self):
waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.runni... | The code manages a game loop with three states: 'START', 'RUNNING', and 'FINISH'. It initializes the game with a start screen, plays music, handles user input, updates game logic, and renders frames at 120 FPS during gameplay. Upon finishing, it displays a game-over screen, records scores, and resets to the start state... | def run(self):
while self.running:
if self.state == 'START':
self.play_music(self.start_menu_music)
top_scores = read_scores()
show_start_screen(self.screen, top_scores)
self.wait_for_input_start_screen()
self.state = '... |
def handle_input(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
elif event.type == pygame.MOUSEBUTTONDOWN and self.game_over:
self.restart_game()
elif event.type == pygame.KEYDOWN:
if event.ke... | This code manages a game loop for a Tetris-like game. It handles user input, updates the game state based on key presses (specifically for soft dropping pieces), checks if the drop counter exceeds a threshold to trigger updates, renders the game, and displays a game-over screen if applicable. The loop continues until i... | def run(self):
while self.handle_input():
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
self.drop_counter += self.soft_drop_speed
else:
self.drop_counter += self.clock.tick(60)
if not self.game_ov... |
def parse(path):
candidates = []
with open(path) as File:
register = csv.reader(File)
for row in register:
c = Contract(row[0], int(row[1]), int(row[2]))
if 0 <= c.start() <= 167 and 0 <= c.end() <= 167 and c.start() != c.end():
candidates.append(c)
r... | The main task of the code is to process input data by parsing candidate contracts, filtering accepted ones using `get_contracts`, and writing the results to output. It validates input length, processes the provided argument, and executes the workflow to generate filtered contract outputs. | def main(argv):
assert len(argv) == 2
candidates = parse(argv[1])
accepted = get_contracts(candidates)
write_output(accepted) |
def compute(strings):
edges = strings[1:]
strs = strings[0].split()
output_folder = 'static/output/' + random_out_folder() + '/'
drawer = graph_drawer.GraphDrawer(strs, output_folder + 'hier', False)
hier_sol, hier_graph = hierarchical_graph.construct_greedy_solution(strs, drawer)
hier = get_pat... | This function handles a web interface for processing input strings. It processes POST requests for computation, random input generation, or reset actions. For GET requests, it loads standard input/solution data and renders the index page. Errors are logged and displayed to the user. | def index():
try:
if request.method == "POST":
if 'compute-button' in request.form:
input = request.form['strings']
input_strings = input.splitlines()
return compute(input_strings)
elif 'random-button' in request.form:
w... |
def compute1(strings):
# input_check = validate(strings)
input_strings = '\n'.join(strings)
# if input_check:
# return empty_sol(input_strings, input_check)
output_folder = 'static/output/' + random_out_folder() + '/'
drawer = graph_drawer.GraphDrawer(strings, output_folder + 'hier', False)
... | This function handles web requests for a solution interface. It processes POST submissions to compute solutions, select random presets, or reset. For GET requests, it loads standard input/solution data and renders a template. Exceptions are logged and result in error messages. | def index1():
try:
if request.method == "POST":
if 'compute-button' in request.form:
input = request.form['strings']
input_strings = input.splitlines()
return compute1(input_strings)
elif 'random-button' in request.form:
... |
def draw_canvas():
canvas_size = 500
open_canvas(canvas_size + canvas_size/5, canvas_size)
def draw_player_number_selection():
set_background_color("maroon")
draw_string("Select Number of Players:", 300, 30, 27)
draw_button(100, 100, 100, 100, "1 Player", 20, "orange")
draw_button(250, 100, 100,... | The code manages a character selection interface for a game, allowing users to select players, games, and characters from a predefined roster. It handles navigation between screens, restarts, and character limits, using a loop structure to manage states like player selection, game choice, and character assignment, with... | def main():
closeApp = False
characterRoster = [
["Mario", 'mario.png'],
["Donkey Kong", "dk.png"],
["Link", "link.png"],
["Samus", "samus.png"],
["Yoshi", "yoshi.png"],
["Kirby", "kirby.png"],
["Fox", "fox.png"],
["Pikachu", "pikachu.png"],
... |
def inorder(self, bst: BSTTable):
self._inorder(bst._root)
def preorder(self, bst: BSTTable):
node = bst._root
#check stopping condition
if node is None:
return None
#append the node from the beginng
self.values.append(node)
self.preorder(node.left)
... | This code initializes a tree traversal mechanism by setting up the traversal type (inorder, preorder, or postorder) and invoking the corresponding traversal method on the provided BSTTable. It prepares to collect traversal results in 'self.values' and initializes an index for later access. | def __init__(self, tree: BSTTable, traversalType: DFSTraversalTypes):
self.tree=tree
self.traversalType=traversalType
self.values = []
self.index = 0
if self.traversalType == DFSTraversalTypes.INORDER:
self.inorder(self.tree)
elif self.traversalType == DFSTra... |
def createPicDisplay(self):
self.pixmap = QLabel()
hbox = QHBoxLayout()
btnForward = QPushButton(self)
btnBackward = QPushButton(self)
# Make widgets reponsive
btnForward.setSizePolicy(QP.Preferred, QP.Expanding)
btnBackward.setSizePolicy(QP.Preferred, QP.Expanding)
self.pixmap.setSizePolicy(QP.Expa... | This code initializes a `PicWidget` class by loading image paths and data, setting the first image as active, and creating UI components for image display and operations. It calls methods to setup the display, operations, and UI, then shows the widget. The `TODO` suggests potential future implementation steps. | def __init__(self, *args, **kwargs):
super(PicWidget, self).__init__(*args, **kwargs)
# TODO:
self.paths = utility.getPaths()
self.images = utility.getImages(self.paths['cd'])
self.activeImage = self.images[0] if self.images else None
self.createPicDisplay()
self.createPicOp()
self.setImages()
self.s... |
def _login(self, **kwargs):
# kaniko doesn't support login, docker CLI doesn't support insecure, so use skopeo
args = ["login"]
registry = None
password = None
authfile = None
for k, v in kwargs.items():
if k == "password":
password = v
... | This code defines a `build` method that constructs and executes Docker image builds using Kaniko. It processes parameters like build arguments, cache settings, registry credentials, and image tags to form command-line arguments. The method handles Kaniko-specific options, manages temporary build contexts, and executes ... | def build(
self,
*,
buildargs=None,
cache_from=None,
container_limits=None,
tag="",
custom_context=False,
dockerfile="",
fileobj=None,
path="",
labels=None,
platform=None,
**kwargs,
):
log_debug("kaniko e... |
def migrate_configs(s_system, s_headers, t_system, t_headers,pagesize):
migrate_entities(s_system, s_headers, t_system, t_headers, pagesize,configs)
exclude_fields = ['id','ident']
#update_table(configs['jfield_def'].format(s_system),s_headers,configs['jfield_def'].format(t_system),t_headers,exclude_fields... | This script processes command-line arguments to migrate or purge specified entities (configs, objs, etc.) between source and target servers using API authentication tokens. It handles SSL certificate verification, validates entity types, and executes migration/purge operations by calling corresponding functions with se... | def main():
p = argparse.ArgumentParser()
p.add_argument('-s', '--src', default="local", help="URL of the source adapter server if reading data for a migration. If the adapter is listening on a specific port other than the default, include the port.")
p.add_argument('-t', '--target', default="local", help="... |
def format_algorithms(algorithms):
return ' & '.join(format_algorithm(algorithm) for algorithm in algorithms)
def format_averages_block(algorithms):
means = [np.round(get_mean(MEANS[algorithm]), 1) for algorithm in algorithms]
formatted = format_averages(means)
formatted_block = (
f'{formatted} \\hspace{{.6cm}} ... | This code generates a LaTeX table to present algorithm performance data across different environments and buffers, formatting headers, averages, and data blocks with specific column alignment and styling. It constructs the table structure, integrates color definitions, and combines formatted components into a complete ... | def format_table(algorithms, buffers, environments):
justify_str = 'll' + 'P' * (len(algorithms) - 1) + 'r'
algorithm_str = format_algorithms(['Dataset', 'Environment'] + algorithms)
averages_str = format_averages_block(algorithms)
color_prefix = format_color_defs()
table_prefix = (
'\\newcolumntype{P}{>{\\ragge... |
def _load_data(basedir, subject_id, factor=None, width=None, height=None, load_imgs=True):
data_dir = os.path.join(basedir, subject_id)
poses_arr = np.load(os.path.join(data_dir, 'poses_bounds.npy'))
poses = poses_arr[:, :-2].reshape([-1, 3, 5]).transpose([1,2,0])
bds = poses_arr[:, -2:].transpose... | The main task of the code is to load and preprocess LLFF dataset, including adjusting camera poses, rescaling depth values, recentering coordinates, generating spiral rendering paths, and splitting data into training/test sets for neural rendering tasks. It returns images, camera poses, intrinsic parameters, and data s... | def load_llff_data(basedir, subject_id, factor=8, recenter=True, bd_factor=.75, spherify=False, path_zflat=False):
poses, bds, imgs = _load_data(basedir, subject_id, factor=factor) # factor=8 downsamples original imgs by 8x
print('Loaded', basedir, bds.min(), bds.max())
# Correct rotation matrix orderi... |
def read_tree(data: bytes) -> tp.List[tp.Tuple[int, str, str]]:
result = []
while data:
mode, name_sha = data.split(b" ")[:2]
name, sha = name_sha.split(b"\0")[:2]
# print(f"Mode: {mode}, Name: {name}, SHA: {sha}")
result.append((int(oct(int(mode, 8))[2:]), name.decode(), sha[:20... | This function recursively traverses Git tree objects to collect all files and their SHA hashes. It processes each tree entry: if an entry is a sub-tree, it recursively expands it, prepending the current directory name to form full paths. Non-tree entries are added directly as (filename, SHA) tuples. The result is a lis... | def find_tree_files(tree_sha: str, gitdir: pathlib.Path) -> tp.List[tp.Tuple[str, str]]:
result = []
for mode, name, sha in read_tree(read_object(tree_sha, gitdir)[1]):
if read_object(sha, gitdir)[0] == "tree":
tree = find_tree_files(sha, gitdir)
for i in tree:
re... |
def check_number(number: str) -> bool:
return "+" in number or "_" in number
def quote(string, safe='/', encoding=None, errors=None):
if isinstance(string, str):
if not string:
return string
if encoding is None:
encoding = 'utf-8'
if errors is None:
er... | The function sends an instant WhatsApp message to a specified phone number via WhatsApp Web. It validates the phone number, opens the WhatsApp URL, waits for a send button (with fallback), clicks it, and optionally closes the tab after a delay. | def enviar_mensaje_instantaneamente( phone_no: str, message: str, wait_time: int = 8, tab_close: bool = False, close_time: int = 3,) -> None:
if not check_number(number=phone_no):
raise print("Country Code Missing in Phone Number!")
web.open(f"https://web.whatsapp.com/send?phone={phone_no}&text={quote(m... |
def _web(receiver: str, message: str) -> None:
if check_number(number=receiver):
web.open("https://web.whatsapp.com/send?phone="+ receiver+ "&text="+ quote(message))
else:
web.open("https://web.whatsapp.com/accept?code="+receiver)
def copy_image(path: str) -> None:
if system().lower() == "li... | This function sends an image with a caption to a specified receiver via a web interface. It waits, copies the image, types the caption (handling line breaks on non-numeric receivers), pastes the image, and clicks the send button. OS-specific keybindings (Command+V or Ctrl+V) are used for pasting, with a delay to ensure... | def send_image(path: str, caption: str, receiver: str, wait_time: int) -> None:
_web(message=caption, receiver=receiver)
time.sleep(wait_time)
copy_image(path=path)
if not check_number(number=receiver):
for char in caption:
if char == "\n":
hotkey("shift", "enter")
... |
def check_number(number: str) -> bool:
return "+" in number or "_" in number
def send_image(path: str, caption: str, receiver: str, wait_time: int) -> None:
_web(message=caption, receiver=receiver)
time.sleep(wait_time)
copy_image(path=path)
if not check_number(number=receiver):
for char in ... | This function sends an image to a specified phone number via a messaging app, validates the phone number format, and optionally closes the app tab after a delay. It checks if the phone number includes a valid country code, sends the image with an optional message, and manages tab closure based on user input parameters. | def enviar_imagen(phone_no: str, img_path: str, msg: str = "", wait_time: int = 15, tab_close: bool = False, close_time: int = 3,) -> None:
if (not phone_no.isalnum()) and (not check_number(number=phone_no)):
raise print("Country Code Missing in Phone Number!")
send_image(path=img_path, caption=msg, rec... |
def advance( self ):
self.idx += 1
self.cur_tok = self.tokens[self.idx] if self.idx < len( self.tokens ) else None
def or_chain( self ):
return self.bin_op_term( self.or_operand, lambda x : x.value == 'or' ) | This function parses variable assignments or expressions. It handles new variable declarations ('var name = value') by creating a VarAssignNode with AT_NEW, or existing variable assignments (expr = value) by creating a VarAssignNode with AT_OLD. It validates syntax elements like identifiers and '=' operators, returning... | def value_expr( self ):
if self.cur_tok.value == 'var':
self.advance()
name_tok = self.cur_tok
if name_tok.type != Constants.TT_IDENTIFIER:
return None, SyntaxError( "Expected Identifier", self.cur_tok.start_pos, self.cur_tok.end_pos )
... |
def gradient_descent(X,y,d,learning_rate,iterations,init_theta):
m = len(y)
theta_G=init_theta
X_b = grad_matrix(X, d)
for it in range(iterations):
prediction = np.dot(X_b,theta_G)
theta_G = theta_G -(1/m)*learning_rate*( X_b.T.dot(prediction - y)+2*wd*theta_G)
... | The main task of the code is to compare three gradient descent variants (GD, SGD, mini-batch GD) by training them on input data, evaluating their mean squared error (MSE) on training and test sets, and visualizing model predictions against original data. It returns trained coefficients and error metrics for analysis. | def fitData(X,y,d):
theta1,X_b=gradient_descent(X,y,d,learning_rate,iterations,init_theta)
print("Gradient descent coeffients: ", theta1.T)
print("MSE for grdient descent: ", getMSE(theta1,X_b,y))
print("================================================\n")
theta... |
def _generate_playername_arr_lineup(self, lineup_names_arr: List[str]) -> None:
'''
Sets the players in the input name list to be the players in the lineup
Player names in form: last_name,first_name
'''
# read the player data from the stats csv
stat_lines = pkgut... | This method sets players in a lineup using either a provided list of names, a file, or random generation. It resets the player list, determines the generation method based on inputs, creates the lineup, and prints the resulting players. If no input is given, it generates a random lineup and marks it as such. | def set_players(self,
lineup_filename: Optional[str] = None,
lineup_names_arr: Optional[List[str]] = None
) -> None:
'''
Sets the players in this lineup
'''
# reset to default
self.players = []
self.random_lineup = False
# add the players... |
def compute_clusters(self, *, adj, x, h, nodes, **kwargs):
leader_idx, mask = self._select_leader(adj, h, nodes)
clusters = batch_index_select(h, 1, leader_idx)
attn = self.compute_attention(adj, h, clusters, mask)
return attn, clusters
def compute_adj(self, *, mapper, adj, **kw... | The code processes graph data through clustering and pooling steps. It transforms input graphs into batched tensors, computes clusters using adjacency matrices and node features, adjusts the graph structure, and generates new features. The main task is to hierarchically cluster nodes, update graph connectivity, and pro... | def forward(self, x, edge_index, ptr, batch, return_loss=False, **kwargs):
h = self.net(x,edge_index)
device = x.device
#transporm x, edge_index,mask to 3-dimations
#original lapool compute pooling the leader from each single graph
batch_size =len(ptr) -1
max_nodes = int(... |
def receive_client_request(client_socket):
"""
:param client_socket:
read from the socket
"""
raw_size = client_socket.recv(MSG_LEN_PROTOCOL)
size = raw_size.decode()
if size.isdigit():
raw_request = client_socket.recv(int(size))
request = raw_request.decode()
# spli... | The function handles a single client's requests by receiving, validating, and processing commands. It sends appropriate responses, terminates the session on 'EXIT', and manages errors. | def handle_single_client(client_socket):
"""check if the request is valid,
make a response and sent it to the client"""
try:
request = ""
done = False
while not done:
request, params = receive_client_request(client_socket)
valid = check_client_request(request... |
def colormap(self, image) -> np.ndarray:
"""
Recolor the depth map from grayscale to colored
Args:
image (np.ndarray): Grayscale image
Returns:
np.ndarray: Colored map image
"""
depth_map = self.get_depth(image)
depth_map = (depth_map/256... | The code runs a video camera, capturing and displaying frames with FPS calculation. It uses live rendering or standard camera modes, allows frame capture via spacebar, and exits on Esc. It handles exceptions, releases resources, and closes windows, ensuring proper shutdown of the camera system. | def run(self) -> None:
"""
Run the video camera.
"""
self.is_running = True
print(f'[{self.device.upper()}] Running depth scan...')
try:
while self.is_running:
frame_start_time = perf_counter()
ret, frame = self.camera.... |
def switch_tar(self):
self.switch_def()
elem=self.driver.find_element(By.ID,"ptifrmtgtframe")
self.driver.switch_to.frame(elem)
def cf_wait_check(self):
self.switch_def()
self.switch_tar()
try:
elem1=self.driver.find_element(By.XPATH,'//*[@id="WAIT_win0"]')
... | This function automates saving data by interacting with a web element ("#ICSave"), handling popups/confirmations through recursive checks. It increments a counter, triggers saves, and presses "OK" buttons if conditions (cf_wait_check, cf_okay_check) are met, ensuring completion via recursive calls until successful save... | def cf_save(self,itera):
#this function doubles as a check on db call events that sometimes create popups
if itera==0:
self.switch_tar()
self.driver.find_element_by_id("#ICSave").click()
itera+=1
if self.cf_wait_check():
if self.cf_okay_check():
... |
def cf_save(self,itera):
#this function doubles as a check on db call events that sometimes create popups
if itera==0:
self.switch_tar()
self.driver.find_element_by_id("#ICSave").click()
itera+=1
if self.cf_wait_check():
if self.cf_okay_check():
... | This code selects a dropdown option by ID and text, handles retries on click errors, and saves configurations, returning True on success or retrying exceptions like element not found or click interception. | def dropdownselector(self,idstr,selected):
try:
delay=2
select = Select(WebDriverWait(self.driver, delay).until(EC.element_to_be_clickable((By.ID, idstr))))
select.select_by_visible_text(selected)
select.send_keys(Keys.TAB)
select = Select(WebDriverWai... |
def ipxapi(ip):
url = "https://ipxapi.com/api/ip?ip="+ip
headers = {
'Accept': "application/json",
'Content-Type': "application/json",
'Authorization': "Bearer 825|TYdYvsByrjJPNR7qk7srT1I1BJk5EEsPskHS4tk4",
'cache-control': "no-cache"
}
response = requests.reque... | The code processes an IP address to fetch income data via an API, performs regression analysis using income, last donation, and user info to predict donations, rounds results to nearest multiples of 25, and returns the rounded values. | def main(ip, lastdono, userinfo):
apiresponse = ipxapi(ip)
income = zip_to_income(apiresponse.text)
donos = regression(income, lastdono, userinfo)
print(donos)
rounded_donos = [25*round(x/25) for x in donos]
return rounded_donos |
def segment_line(line, max_distance):
segments = []
points = list(line.coords)
current_segment = [points[0]]
for point in points[1:]:
if Point(point).distance(Point(current_segment[-1])) > max_distance:
if len(current_segment) > 1: # Check if the current_segm... | The code clusters points using DBSCAN, segments lines by removing intersections, splits lines at directional changes, and groups continuous segments into boundaries. It processes spatial data to refine clustered lines into clean, continuous geographic boundaries. Your return | def get_clustering(points):
dataset = np.array(points)
### PART 2 : cluster using distance between points
# DBSCAN
db = DBSCAN(eps=0.000025, min_samples=3).fit(dataset)
labels = db.labels_
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
### PART 3 : separate intersections
... |
def spline_smoothing(points, smoothing_factor=0.0000000000001):
if len(points) < 3:
# print('/!\\ skipped a boundary as it contains less than 3 points /!\\')
return np.array(points) # Not enough points to fit a cubic spline
# Calculate cumulative distance along the curve
distances = [0]
... | The function applies smoothing to each boundary in the input dictionary using the specified method, retaining original points. It supports methods like univariate spline, Savitzky-Golay, Chaikin, SPL, and optimized spline (which uses a corresponding boundary for refinement). The output dictionary contains original poin... | def smooth_boundaries(boundaries, method):
"""
Apply smoothing to each boundary and retain the original points.
:param boundaries: Dictionary of boundaries, each containing points and associated lanes.
:param smoothing_factor: Factor to control the smoothing level.
:return: A dictionary with origin... |
def loadData(self, filePath):
lines = []
with open(filePath) as f:
content = csv.reader(f)
for line in content:
lines.append(line)
return lines
def balance_data(self, samples, visulization_flag, N=60, K=1, bins=100):
angles = []
for line i... | The code loads and balances training data from a CSV file, splits it into training and validation sets, creates data generators, defines a neural network model, compiles it with MSE loss and Adam optimizer, and saves the model to a file. The training process is commented out, so the model is not trained in this code. | def create_model(self, route_name):
# load the csv file
basePath = str(pathlib.Path().resolve()) + "/" + str(route_name) + "/training_data.csv"
print('loading the data...')
samples = self.loadData(basePath)
print(samples)
# balance the data with smooth the histogram of ... |
def fetch_questions(self):
try:
with open("questions.json", "r") as file:
questions_data = json.load(file)
return questions_data["questions"]
except FileNotFoundError:
print("Error: questions.json not found.")
# Return sample questions for ... | The code initializes a quiz GUI application with a maximized window, fetching questions and setting up a yes/no interface to display and track user responses to each question. | def __init__(self, dashboard_screen):
super().__init__()
self.title("Quiz")
self.geometry("400x300")
self.state('zoomed') # Maximize the window
self.resizable(False, False) # Set resizable to False for both width and height
self.dashboard_screen = dashboard_screen
... |
def _header(self, data):
"""Retrieves format and swapping from header.
Returns type(0-2), endianness (str), compressed size, decompressed size"""
name = data[0:3].decode(errors='ignore')
if name!="EDL":
return -1, None, 0, 0
## work out byte order and format
d... | This function decompresses EDL data by identifying the compression type from the header. It uses _decEDL0 or _decEDL1 methods for types 0/1, validates decompressed data length for type 1, returns original data for type -1, and handles unsupported types with an error message. | def decompress_pyEDL(self, data):
data_t, endian, cmp_s, dec_s = self._header(data)
if data_t == 0:
d = self._decEDL0(data[12:12+cmp_s], cmp_s, dec_s, endian)
if data_t == 1:
d = self._decEDL1(data[12:12+cmp_s], cmp_s, dec_s, endian)
assert(len(d) == dec_s)
... |
def compute_donut_outlines(self, cell):
self.donut_outlines_in = deepcopy(cell.outlines)
self.donut_outlines_out = deepcopy(cell.outlines)
for tid, t in enumerate(cell.times):
for zid, z in enumerate(cell.zs[tid]):
outline = cell.outlines[tid][zid]
hul... | This code initializes a class to process cell data by setting parameters for padding, donut width, and hull computation methods. It selects an internal hull calculation method (Delaunay, cross, or linprog), computes donut outlines and masks for the cell, and generates a nuclei mask. The class prepares masks for further... | def __init__(self, cell, innerpad=1, outterpad=1, donut_width=1, min_outline_length=50, inhull_method="delaunay"):
self.inpad = innerpad
self.outpad = outterpad
self.dwidht = donut_width
self._min_outline_length = min_outline_length
if inhull_method=="delaunay": self._inhull=sel... |
def execute_erkktr(self, cell, innerpad, outterpad, donut_width, min_outline_length):
return ERKKTR_donut(cell, innerpad, outterpad, donut_width, min_outline_length, "delaunay")
def correct_cell_to_cell_overlap(self, cells):
print()
for _, t in enumerate(range(self.times)):
for _, z ... | The main task of the code is to generate donut-shaped structures (Donuts) from input cells using parallel processing, apply corrections for overlaps between cells, embryos, and nuclei, and compute masks. It initializes donut parameters, processes cells either sequentially or via multiprocessing, performs overlap correc... | def create_donuts(self, cells, EmbSeg, innerpad=None, outterpad=None, donut_width=None, change_threads=False):
for cell in cells:
cell.extract_all_XYZ_positions()
if innerpad is None: innerpad = self.inpad
if outterpad is None: outterpad = self.outpad
if donut_width is None: ... |
def solve(a=None, b=None, c=None, A=None, B=None, C=None, ssa_flag='forbid'):
"""
Solve to find all the information about a triangle, given partial
information.
a, b, c, A, B, and C are the three sides and angles. (e.g. A is the angle
opposite the side of length a.) Out of these six possibilities, y... | The code tests the correctness of a triangle-solving function (`solve`) by verifying it produces consistent results across various input scenarios (SSS, SAS, SAA/ASA, SSA). It checks if the computed sides and angles match the original triangle using `tuple_isclose` assertions. The test covers all standard triangle-solv... | def test_solver(a,b,c):
""" Test that the program works, for a triangle of sides a,b,c."""
# first find the angles, testing SSS
a1,b1,c1,A,B,C = solve(a=a,b=b,c=c)
assert tuple_isclose((a,b,c), (a1,b1,c1))
test_triangle(a,b,c,A,B,C)
tri = (a,b,c,A,B,C)
# SAS tests
assert tuple_isclose(t... |
def define_palette(self):
'''
Computes palettes for image
Parameters
----------
None
Returns
-------
dictionary to convert base pallete (keys) to final palette (values)
'''
img = self.raw_image
width, height = img.size
... | The function converts an image's colors to a predefined base palette by mapping each raw color to its closest match in the base palette, replaces pixels accordingly, and optionally displays or saves the modified image. It also collects and processes color usage statistics for the transformed image. | def flatten_image(self, show = False, save = False):
'''
Creates image with all colors changed to base palette
Parameters
----------
show : bool
Determines if the palette will be shown to the user
save : bool
Determines if the ima... |
def flatten_image(self, show = False, save = False):
'''
Creates image with all colors changed to base palette
Parameters
----------
show : bool
Determines if the palette will be shown to the user
save : bool
Determines if the ima... | The main task of the code is to extract and process symbols from an image by isolating color-based regions, mapping them to a palette, cropping each symbol with a buffer, and generating a square, resized image of the symbols. It also allows saving or displaying the final result. | def extract_symbol(self, save = False, show = False):
if not hasattr(self, 'base_stats'):
self.flatten_image()
volumes = [self.base_stats[x]['volume'] for x in self.base_stats.keys() if type(self.base_stats[x]) == dict]
base_colors = list(self.base_stats.keys())[2:]
symbol_co... |
def moderate(self, message):
flagged = False
if not flagged:
try:
moderate = openai.Moderation.create(input=message,) #run through the moderation endpoint
flagged = moderate["results"][0]["flagged"] #true or false
except:
pass
... | This code processes IRC messages by handling user commands like .ai (chat), .x (collaborative chat), .persona (change bot personality), and .custom (set prompts). It moderates content, maintains user-specific histories, and uses threading for async responses. Admin commands allow channel joins/exits. Violations trigger... | def on_pubmsg(self, c, e):
#message parts
self.channel = e.target
message = e.arguments[0]
sender = e.source
sender = sender.split("!")
sender = sender[0]
#if the bot didn't send the message
if sender != self.nickname:
#basic use
i... |
def probable_move(x_pos, y_pos):
'''checks if coin placed at this position connects4'''
for i in [7, 5]:
gameboard[y_pos][x_pos] = i
if check_connect_4(x_pos, y_pos) == '4connected':
gameboard[y_pos][x_pos] = 0
return '4connected'
gameboard[y_pos][x_pos] = 0
... | The main task of the code is to determine the optimal move in a Connect 4 game by checking for potential 4-in-a-row connections, prioritizing moves that either create or block such connections. It uses a combination of random selection, Q-learning (epsilon-greedy strategy), and iterative checks to avoid moves that inad... | def stop_4_connecting():
'''check_connect_4(takes x_pos and then y_pos) to highest y_pos and check for every x_pos'''
if TURN == 0:
random.choice([2, 3, 4])
if TURN == 1:
if top[3] == 4:
return random.choice([2, 4])
return 3
length = len(top)
for i in range(len... |
def stop_4_connecting():
'''check_connect_4(takes x_pos and then y_pos) to highest y_pos and check for every x_pos'''
if TURN == 0:
random.choice([2, 3, 4])
if TURN == 1:
if top[3] == 4:
return random.choice([2, 4])
return 3
length = len(top)
for i in range(len... | The function implements a Q-learning algorithm to determine the next move in a game, updating a Q-table with rewards and temporal differences. It checks if the current board state exists in the Q-table, initializes it if not, calculates a reward for the chosen action, and updates the Q-value using the temporal differen... | def generate_next_move(board_state):
'''next move is generated either through random or highest q value, EPSILION mediates this'''
gameboard_as_key = ''.join(str(item)
for innerlist in board_state for item in innerlist)
if gameboard_as_key not in q_table:
q_table[gam... |
def _check_exists(self):
return (os.path.exists(os.path.join(self.processed_folder,
self.training_file)) and
os.path.exists(os.path.join(self.processed_folder,
self.test_file)))
def read_image_file(path):
... | The code's main task is to download the MNIST dataset if it doesn't exist in the processed folder. It creates necessary directories, downloads and extracts raw data files from specified URLs, processes image and label data, then saves them as PyTorch-compatible files in the processed folder. The function ensures data i... | def download(self):
"""Download the MNIST data if it doesn't exist in processed_folder already."""
if self._check_exists():
return
os.makedirs(self.raw_folder, exist_ok=True)
os.makedirs(self.processed_folder, exist_ok=True)
# download files
for url, md5 in... |
def download(self):
"""Download the MNIST data if it doesn't exist in processed_folder already."""
if self._check_exists():
return
os.makedirs(self.raw_folder, exist_ok=True)
os.makedirs(self.processed_folder, exist_ok=True)
# download files
for url, md5 in... | This code initializes a custom MNIST dataset, handling download/checks, loading training/test data, and configuring open-set parameters by updating class counts and inclusion rules for training and testing. | def __init__(self, root, train=True, transform=None, target_transform=None,
download=False, train_class_num=5, test_class_num=7, includes_all_train_class=True):
super(MNIST, self).__init__(root, transform=transform,
target_transform=target_transform)
... |
def parse_title(self, response, jep):
return response.xpath('//h1/text()').extract_first().split(':')[1].strip()
def parse_summary(self, response, jep):
summaries = response.xpath('//div[@class = "markdown"]/*').getall()
summaries = [summary.replace('<div class="markdown">','').replace('</div>',... | The main task of the code is to parse a web response into a structured `JepItem` object by extracting key data fields like ID, title, summary, full link, and table rows. It initializes a `JepItem`, assigns the provided `jep_id`, and uses helper methods to parse the title and summary from the response. The full URL is s... | def parse_jep(self, response, jep_id):
jep = JepItem()
jep['id'] = jep_id
jep['title'] = self.parse_title(response, jep)
jep['summary'] = self.parse_summary(response, jep)
jep['full_jep_link'] = response.url
self.parse_table_rows(response, jep)
return jep |
def directory_tree(path, make_links=False):
"""Generate a markdown-style directory tree structure for directories tracked by Git."""
tree = []
tracked_dirs = git_tracked_directories(path)
for dir in tracked_dirs:
level = dir.count("/")
indent = " " * level # Two spaces per level for ma... | The function generates a README.md file by combining predefined content, directory structure, CLI usage instructions, Nix flake information, and optional user-provided header/footer files, dynamically assembling sections based on input parameters like `include_dir_tree` or `include_flake_info`. | def generate_readme(
path,
include_dir_tree,
include_links,
include_flake_show,
include_flake_info,
markdown_prefix_file,
markdown_footer_file,
author=None,
repo_name=None,
include_cli_usage=False,
use_nix_for_cli=False,
):
"""Generate README content based on the provided... |
def parse_arguments():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Generate README.md content.")
parser.add_argument("-a", "--author", help="GitHub username", type=str)
parser.add_argument("-r", "--repo", help="GitHub repository name", type=str)
parser.add_argum... | (The code's main task is to parse command-line arguments, generate a README file content using specified parameters like directory, links, headers, and author info, then write the generated content to an output file. It leverages functions to handle argument parsing, README generation with customizable options, and fil... | def main():
args = parse_arguments()
readme_content = generate_readme(
".",
args.dir,
args.links,
args.flake_show,
args.flake_info,
args.header,
args.footer,
args.author,
args.repo,
include_cli_usage=args.usage,
use_nix_for_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.