dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def rebalance(node):
left_height = get_height(node.left)
right_height = get_height(node.right)
if left_height - right_height > 1: # left case
left_child = node.left
left_grandchild_height = get_height(left_child.left)
right_grandchild_height = get_height(left_child.right)
if ... | The code inserts a new node into a binary tree based on the 'low' attribute, recursively placing it in the left or right subtree. After insertion, it rebalances the tree and updates the node's height to maintain structural integrity, typical in self-balancing trees like AVL trees. | def insert_node(node, new):
"""
insert to the correct place
update max value as well
"""
if not node:
return new
if new.low < node.low:
node.left = insert_node(node.left, new)
else:
node.right = insert_node(node.right, new)
node = rebalance(node)
node.height =... |
def create_intervals(max_num, size):
intervals = []
for _ in range(1, size):
low = random.randint(1, max_num)
high = random.randint(1, max_num)
if low > high:
low, high = high, low
intervals.append((low, high))
return intervals
def build_tree(intervals):
"""
... | The main task of the code is to test the `build_tree` function by generating intervals, constructing a tree from them, and verifying its structure. It creates intervals with `create_intervals`, builds a tree, prints the root node, checks the tree's validity with `check_tree`, and confirms the test passes if no errors a... | def test_build_tree():
MAX = 100
SIZE = 10
intervals = create_intervals(MAX, SIZE)
print("intervals:", intervals)
print("=====================")
result = build_tree(intervals)
print("root: ", end="")
pprint_tree(result)
check_tree(result)
print("check pass") |
def create_intervals(max_num, size):
intervals = []
for _ in range(1, size):
low = random.randint(1, max_num)
high = random.randint(1, max_num)
if low > high:
low, high = high, low
intervals.append((low, high))
return intervals
def build_tree(intervals):
"""
... | The main task of the code is to test the correctness of an interval tree's search functionality by comparing its results with a traditional method. It generates random intervals, selects a random target value, and checks if the target lies within any interval using both the interval tree (`search_tree`) and a direct se... | def single_test():
"""
#random several interval
#random pick element
#use interval tree find out if it's inside
#use old fashion method to find out if it's inside
#compare those two result
"""
MAX = 100
SIZE = 10
intervals = create_intervals(MAX, SIZE)
t =... |
def _validate_payload(payload: Dict) -> None:
"""
Data validation step to make sure that the input is of the right type
Args:
param (Dict): A JSON blob representing the data to be processed.
Returns:
None
Raises:
TypeError: Must receieve dictionary which specific keys
... | The main task of the code is to generate an interviewer assessment report by analyzing a candidate's profile and assessment results from the input payload. It validates the data, modifies skill scores, creates visualizations, saves background images, and generates a final PDF report stored in the results directory. The... | def leadership_report(payload: Dict) -> None:
"""
Generate the interviewer assessment report by parsing the payload
The report will analyze and provide relevant questions based on the strengths and weaknesses of the candidate
Args:
param1(Dict): The candidate's profile and assessment results
... |
def _validate_payload(payload: Dict[str, Dict[str, Union[float, int, str]]]) -> None:
"""
Data validation step to make sure that the input is of the right type
Args:
param1(Dict[str, Dict[str, int | str]]): The candidate's profile and assessment results
Returns:
None
Raises:
... | The main task of the code is to generate an interviewer assessment report by analyzing a candidate's profile and assessment results from the input payload. It creates visualizations like bar charts, gauge charts, and spider plots, then generates a PDF report stored in the results directory. The function validates the p... | def talentinsights_report(
payload: Dict[str, Dict[str, Union[float, int, str]]]
) -> None:
"""
Generate the interviewer assessment report by parsing the payload
The report will analyze and provide relevant questions based on the strengths and weaknesses of the candidate
Args:
param1(Dict[... |
def get_map_from_file(file_name):
with open(file_name) as file:
map = []
for line in file:
row = [height for height in line.rstrip()]
map.append(row)
return np.array(map)
def get_viewing_distances(tree_coordinates: tuple, map):
tree_index_in_column = tree_coordinates[... | The main task of the code is to compute the maximum scenic score in a grid by calculating the product of viewing distances in four directions (up, down, left, right) for each cell, where viewing distance represents how far one can see before encountering a taller tree. The code reads a map from a file, iterates through... | def part_two_solution():
map = get_map_from_file("input.txt")
it = np.nditer(map, flags=["multi_index"])
viewing_distances_list = [
get_viewing_distances((it.multi_index[0], it.multi_index[1]), map) for _ in it
]
print(
max(
[
get_viewing_distance_score(vi... |
def build_encoder(self):
return HyperNetworkEncoder(
input_dim=self.task_embedding_dim,
hidden_dim=self.hidden_dim,
num_layers=self.num_hidden_layers,
layernorm_input=self.layernorm_input,
layernorm_output=self.layernorm_output,
dropout=sel... | The code defines a hyper-network model that generates adapter layer parameters for neural networks. It processes inputs through language/layer embeddings, an encoder, and projection heads to produce weights (down/up) and optional layer normalization parameters. The model supports configurable dimensions, activation fun... | def __init__(self,
num_languages: int,
num_layers: int,
lang_embedding_dim: int,
layer_embedding_dim: int,
mainnet_input_dim: int,
bottleneck_dim: int,
hidden_dim: int,
num_hidden_laye... |
def make_all_dataframes(self):
frames = self.slices()
for i in range(len(frames)-1):
self.make_partial_dataframe(frames[i],frames[i+1])
def concat_dataframes(self):
df = pd.concat([pd.read_pickle(f) for f in self.partialdfs])
df.reset_index(inplace=True,drop=True)
df.a... | The code's main task is to process data by generating and concatenating dataframes, creating annotated images of avocados, producing blank templates, generating GIFs from these images, and finally compiling them into a montage, likely for visualization or analysis purposes. | def run(self):
self.make_all_dataframes()
self.concat_dataframes()
self.make_avokado_images()
self.create_blanks()
self.annotate_images()
self.create_gifs()
self.montage() |
def get_vertex_buffer_object(self):
vertex_data = self.get_vertex_data()
vbo = self.ctx.buffer(vertex_data)
return vbo
def get_shader_program(self, shader_name):
with open(f"{SHADER_FOLDER}/{shader_name}.vert", "r") as file:
vertex_shader = file.read()
with open(f"{... | The code initializes a graphics object by setting up essential OpenGL resources: it links the application context, creates a vertex buffer object (VBO), loads a default shader program, configures a vertex array object (VAO), initializes a model matrix, and triggers an initialization method. This prepares the object for... | def __init__(self, app):
# application and application context
self.app = app
self.ctx = app.ctx
self.vbo = self.get_vertex_buffer_object()
self.shader_program = self.get_shader_program("default")
self.vao = self.get_vertex_array_object()
self.m_model = self.get... |
def forward_initialization(self):
# initializing list of factors for stock price used for an every step in a model. Tree should be recombining.
# initializing list of transition probabilities to each of stock prices next step
self.factors = np.zeros(self.variants)
self.probabili... | The code fits a model by initializing probabilities and factors, then constructing a forward tree for stock prices and a backward tree for option prices using specified accuracy and vocabulary parameters, ultimately returning a fitted model with input parameters. | def fit(self, accuracy = 4, vocab= False):
# input:
# accuracy - number of digits to round numbers to
# vocab - boolean variable to look for each stage output
# output: fitted model with parameters input
# initializing probabilities and factors
self.forward_initi... |
def space(number):
print("\n" * number)
def position(p, check_key, __killed_enemies, money):
duplicate = 0
letter = input(" ")
if (letter.upper() == "A" and 0 <= p <= 11 and p != 3.1 and p != 1 and p != 5 and p != 3.2 and p != 6.5 and p != 6 and p != 2.5 and p != 3.... | The code defines a function `printstatements` that manages a text-based game's user interface and narrative flow. It reads from multiple text files to display environment descriptions, options, and interactions based on the player's position (`p`). The function handles location-specific actions (e.g., exploring roads, ... | def printstatements(p, enemy, Class, strength, magic, key_check, killed_enemies, gold, hp, max_hp, xp):
road_file = ("road1.2.txt")
road = open(road_file, 'r').read()
road_file2 = ("road3.2.txt")
road3 = open(road_file2, 'r').read()
road_file3 = ("road7.txt")
road7 = open(road_file3, 'r').read()... |
def complete_sequence(self, game):
"""
refresh the copy of the current sequence played until now
"""
move = self.get_played_move(game)
self.ai_game.place(move)
self.played_sequence.append(move + 1)
def generate_population(self, game):
"""
generates a popul... | The code implements a genetic algorithm to determine the optimal move in a game. It generates an initial population, evaluates fitness, and iteratively evolves the population through selection, crossover, and mutation over multiple generations. The best solution from each generation is tracked, and the final best move ... | def ai_play(self, game):
"""
Genetic Algorithm
"""
self.complete_sequence(game)
print('Current game sequence = ', self.played_sequence)
population = self.generate_population(game)
fit_population = self.population_fitness(population)
for gen in range(GEN... |
def register_color_bars(parameters: ty.Dict) -> None:
'''
This function reads the user-defined color bars in a parameter file
(names for the bars, and a list of the colors they contain, with the
first being at the bottom of the bar, and the last at the top, and the
others in between). It then create... | The main task of the code is to generate a grid of maps using provided dataframes, color schemes, and parameters. It merges country data with geographic boundaries via ISO A3 codes, creates individual maps for each quantity, arranges them in a grid layout, adds titles, and saves the composite figure. The function relie... | def map_grid(
quantities_data: ty.List[pd.DataFrame],
quantity_display_names: ty.List[str],
quantity_colors: ty.List[str],
parameters: ty.Dict,
) -> None:
'''
This function creates a grid of maps. You need to give it the data you want
to plot, the names of the quantities, and their colors, a... |
def create_board(rows, columns):
board = np.zeros((rows, columns))
return board
def symbol_place(turn, board, size):
# Gets the mouse position
mouse_pos = pygame.mouse.get_pos()
# Divided the position by the size and rounds down to determine the row and column the player is hovering over
c = int... | The code defines a game loop for Ultimate Tic-Tac-Toe, handling player input, updating game boards, rendering visuals, checking win conditions, and saving the final board state. It manages turns, processes mouse clicks to place symbols, tracks the overall 3x3 big board, and determines the winner or draw. | def game_loop():
# Game variables
turn = 0
game_over = False
# Creates the overall board matrix
board = create_board(ROWCOUNT, COLUMNCOUNT)
# Creates the big board (the 3 x 3 matrix) that keeps track of the overall winning condition
big_board = create_board(3, 3)
# Prints players turn... |
def getData(cursor, table, print, available=False):
query = ""
if(not available):
query = f"SELECT * FROM {table}"
else:
query = f"SELECT * FROM {table} WHERE Availability = 1"
cursor.execute(query)
result = cursor.fetchall()
if(print):
ui.printData(result, table)
... | The function `borrowItem` allows a user to borrow an item by either logging in with existing credentials or creating a new account. It retrieves item data, validates user input, checks username existence, verifies passwords, and records borrowing in the database. If the user is new, it creates an account and recursivel... | def borrowItem(cursor):
rows = getData(cursor, "Item", False, True)
itemID = ui.getItemID(rows, 2)
username = ""
if(itemID == -1): return
if(ui.returningUser()):
username = ui.getUsername()
if(username == "-1"):
return
if(username in getUsernames(cursor)):
... |
def getUsernames(cursor):
rows = getData(cursor, "User", False)
usernames = []
for row in rows:
usernames.append(row[1])
return usernames
def createNewUser(cursor):
print("++++++++++++++++++++++++++++++++++")
print("Creating New User")
while(True):
username = ui.getUserna... | The function `donateItem` collects user and item details, validates the username, inserts a new item into the database with availability status, and records the donation with the current date. It ensures a valid user exists, either by creating a new account or using an existing one, then stores the item and links it to... | def donateItem(cursor):
usernames = getUsernames(cursor)
username = ""
while(True):
if(not ui.accountExists()):
username = createNewUser(cursor)
break
else:
username = ui.getUsername()
if(username in usernames):
break
... |
def getUsernames(cursor):
rows = getData(cursor, "User", False)
usernames = []
for row in rows:
usernames.append(row[1])
return usernames
def createNewUser(cursor):
print("++++++++++++++++++++++++++++++++++")
print("Creating New User")
while(True):
username = ui.getUserna... | This function registers a user to an event by checking if the user exists, retrieving their ID, selecting an event, and inserting an entry into the 'Attendee' table if they are not already registered. It handles user input validation, existing account checks, and database updates. | def registerEvent(cursor):
usernames = getUsernames(cursor)
username = ""
while(True):
if(not ui.accountExists()):
username = createNewUser(cursor)
break
else:
username = ui.getUsername()
if(username in usernames):
break
... |
def getUsernames(cursor):
rows = getData(cursor, "User", False)
usernames = []
for row in rows:
usernames.append(row[1])
return usernames
def createNewUser(cursor):
print("++++++++++++++++++++++++++++++++++")
print("Creating New User")
while(True):
username = ui.getUserna... | This function either creates a new user or selects an existing one via UI, then updates their UserType to 'Volunteer' in the database. It checks username validity, handles creation/selection, and executes the SQL update with the retrieved UserID. | def volunteerForLibrary(cursor):
usernames = getUsernames(cursor)
username = ""
while(True):
if(not ui.accountExists()):
username = createNewUser(cursor)
break
else:
username = ui.getUsername()
if(username in usernames):
break
... |
def color_progress(label: str):
return txt_color(label, fg='mn', bg='wn')
def color_options(options: str):
return txt_color(options, fg='yn')
def validated_input(check: list):
while True:
user_in = exit_check(input('>> '))
if validate(user_in, check) == 0:
return int(user_in)
... | The main task of the code is to allow users to search the web using a selected search engine and predefined scope sets. It provides an interactive menu for choosing an engine, scope set, and query, then constructs and opens a search link in the browser. The process restarts after each search, offering a loopable interf... | def main():
colorama_init()
prog_name = txt_color('REPLICANT_SEARCH', bg='gb')
dev_name = txt_color('HEX BENJAMIN', 'bb')
print('welcome to ' + prog_name + '.')
print('developed with love (& little experience) by ' + dev_name + '.')
div_str = '———\n'
with open('scopes.json', ... |
def climbs(self):
for i in range(self.n):
print("clms", i, self.ps[i])
mx = self.get_max(self.ps[i])
self.attrs.append(mx)
def merge_same(self):
uf = UnionFind(self.n)
for i in range(self.n):
for j in range(i + 1, self.n):
if dist(s... | The main task of the code is to sequentially execute four methods—climbs, merge_same, tag_outs, and merge_cluster—within the work() function, likely orchestrating a multi-step process such as image segmentation, data clustering, or feature processing, where each method performs a specific operation like climbing, mergi... | def work(self):
print("climbs")
self.climbs()
print("merge_same")
self.merge_same()
print("tag_outs")
self.tag_outs()
print("merge_cluster")
self.merge_cluster() |
def headingList(text, page):
#Replace the heading =s with unused chrs to make parsing it with regex actually possible
#TODO: programatically find 4 characters that don't appear in the text rather than using 251-4, or some sort of htmlentities()-like escaping method to guarantee unused characters
text = text... | This function retrieves and formats content from the Skullgirls wiki API, handling heading navigation and pagination. It checks for valid pages, extracts text, generates interactive buttons for navigation, and returns structured content with URL links. | def wikiHandle(page, heading='', pagination=0):
if page.upper() in ['FILIA', 'CEREBELLA', 'PEACOCK', 'PARASOUL', 'MS._FORTUNE', 'PAINWHEEL', 'VALENTINE', 'DOUBLE', 'SQUIGLY', 'BIG_BAND', 'ELIZA', 'FUKUA', 'BEOWULF', 'ROBO-FORTUNE', 'ANNIE']:
return 'I am intended for text pages, use !fd [character] [move] f... |
def countClusters(newFeats):
"""
"""
count = 0
for row in newFeats:
if row[0] != "N/A":
count += 1
return count
def getBestMergeParallel(newFeats, xSegs, lstP, beta):
"""
This function identifies the clusters that minimise the reduction in the deltaF values (i.e. the... | The function `getClusters` reduces the number of clusters in `newFeats` to a maximum of 10 by iteratively merging the most optimal cluster pairs (using `getBestMerge` or `getBestMergeParallel`). It tracks execution time, updates cluster features, and maintains merge history. The process continues until the cluster coun... | def getClusters(nXSegs, newFeats, clusters, lstP, lstMerges, beta, parallel):
import time
import math
startTime = time.time()
t = time.localtime()
print("Cell started at {:02d}:{:02d}:{:02d}".format(t.tm_hour, t.tm_min, t.tm_sec))
maxClust = 10
while countClusters(newFeats) > maxClust:
... |
def getSegmentMapping(uniq: list[str]) -> dict[int, str]:
# 0000
# 1 2
# 1 2
# 3333
# 4 5
# 4 5
# 6666
im = {}
# use frequency analysis to find 1, 4, 5
uniq_np = np.array(list("".join(uniq)))
freqs = np.unique(uniq_np, return_counts=True)
im[1] = freqs[0]... | The code calculates a cumulative total by processing each entry in the input list. For each entry, it converts the first list of strings into a segment mapping, then into a numeric mapping, and sums the result of applying this mapping to the second list of strings. The final total is returned as an integer. | def countTotal(entries: list[[list[str], list[str]]]) -> int:
acc = 0
for entry in entries:
sm = getSegmentMapping(entry[0])
nm = getNumberMapping(sm)
acc += getTotal(nm, entry[1])
return acc |
def basicPageSetup(pageNo):
global left_frame, right_frame, heading
back_img = tk.PhotoImage(file= r"D:\New Project\Facial-Recognition-for-Crime-Detection-master\img\back.png")
back_button = tk.Button(pages[pageNo], image=back_img, bg="#3E3B3C", bd=0, highlightthickness=0,
activebackground="#3E3... | This function sets up a GUI page for registering criminal details, configuring input fields, a scrollable interface, image selection options, and a 'Register' button. It initializes layout elements, labels, and widgets for data entry, including mandatory fields and an OptionMenu for profile images, preparing the interf... | def getPage1():
global active_page, left_frame, right_frame, heading, img_label
active_page = 1
img_label = None
opt_menu = None
menu_var = tk.StringVar(root)
pages[1].lift()
basicPageSetup(1)
heading.configure(text="Register Criminal", bg="#3E3B3C")
right_frame.configure(text="Ente... |
def _get_alphabet(alphabet: Optional[Iterable[str]] = None,
d_aa_only: bool = False,
include_d_aa: bool = False) -> Tuple[str]:
alphabet = alphabet or AA
alphabet_lower = tuple(set(aa.casefold() for aa in AA))
if d_aa_only:
alphabet = alphabet_lower
elif inc... | The function generates a specified number of peptides within a defined length range, using either naive sampling (for large combinatorial spaces) or exhaustive sampling with optional random selection. It calculates collision probabilities, adjusts sample size based on input parameters, and allows filtering via indexes.... | def sample_peptides_in_length_range(max_length: int,
min_length: int = 1,
by: int = 1,
n: Optional[Union[float, int]] = None,
alphabet: Optional[Iterable[str]] = None,
... |
def strip_bars(progression):
"""The input is a progression, a list of symbols within bar
separators. The output is an extracted list of just symbols.
"""
symbols = [s for s in progression if s != '|']
return symbols
def map_enharmonic(chord):
"""The symbolic processing of chords is facilitat... | The code processes a chord progression by converting slash chords, sus chords, major triads, and add9 chords into their functional equivalents. It extracts chords, maps them to enharmonically unique forms, compresses sequences, applies context-dependent transformations, and reconstructs the progression with modified ch... | def lemmatize(progression):
"""Convert all slash chords, sus chords, major triads, and add9 chords
to their functional equivalents
"""
# Extract out all the chord symbols and their indicial positions
# from the progression, skipping over the bar symbols
chords = strip_bars(progression)
#... |
def lemmatize(progression):
"""Convert all slash chords, sus chords, major triads, and add9 chords
to their functional equivalents
"""
# Extract out all the chord symbols and their indicial positions
# from the progression, skipping over the bar symbols
chords = strip_bars(progression)
#... | The function converts a chord progression in a given key to Roman numeral notation by mapping each chord's root and quality to the corresponding scale degrees, using a predefined key-to-scale mapping. It processes chords, identifies their root and type, and replaces them with Roman numerals, preserving bar symbols. | def map2roman(songkey, progression):
"""Given a key and a chord progression (consisting of chords and bar
separation symbols), map the progression to roman numeral notation
"""
target = ['i', 'bii', 'ii', 'biii', 'iii', 'iv', 'bv', 'v', 'bvi', 'vi', 'bvii', 'vii']
chordmap = {'C': ('C', 'Db',... |
def lemmatize(progression):
"""Convert all slash chords, sus chords, major triads, and add9 chords
to their functional equivalents
"""
# Extract out all the chord symbols and their indicial positions
# from the progression, skipping over the bar symbols
chords = strip_bars(progression)
#... | The code estimates the most probable major key from a chord progression by analyzing each chord's possible scales (based on type: major, minor, 7th, etc.), weighting their occurrences by beat duration, and returning the most frequent weighted key. | def estimatekey(bpm, progression):
# Find the weighted major key of each chord (except diminished) and return the
# most frequent
normalized_prog = lemmatize(progression)
chords = strip_bars(normalized_prog)
bars = ' '.join(progression).split(' | ')
cpm = [len(b.split(' ')) for b in bars] # chords pe... |
def clients(name, config=None):
try:
if not config:
filename = os.path.abspath(
os.path.join(os.path.dirname(__file__), '.gitignore', 'client_info.ini')
)
config = configparser.ConfigParser()
config.read(filename)
if name == 'reddit':
... | The code downloads images from an Imgur album specified by 'id', saves them in a directory named 'title', logs download status, and returns to the parent directory after completion. | def imgur_album(title, id):
imgur = clients('imgur')
make_dir(title)
images = imgur.get_album_images(id)
logging.info(f'Downloading imgur album')
for item in images:
name, url = imgur_image(item=item)
status = download_file(name, url)
logging.info('Imgur ' + status)
os.c... |
def slim_title(title, limit=250):
name = clean(title)
char_max = limit - len(os.path.abspath('.'))
name = name[:char_max-1] if len(name) >= char_max else name
return name
def clean(text):
return regex.sub(r"[^\s\w',]", '', text).strip()
def find_extension(url):
try:
ext = regex.search(r'... | The function downloads Reddit submissions as files, handling images, videos, and text, while managing concurrency with locks, logging metadata, and enforcing storage limits. It processes URLs, cleans content, and uses regex to identify media types, ensuring files are saved uniquely and tracking progress via queues. | def download_subs(subs, storage, ID, posts_q, gigs_q, lock):
i = 0
for submission in subs:
if submission.over_18:
continue
url = submission.url
title = slim_title(submission.title)
text = clean(submission.selftext)
extension = find_extension(url)
title... |
def __save_previous(self):
self.prev_state = self.state
self.prev_action = self.predicted_action
def __update_current(self):
self.__update_current_state()
self.predicted_action = self.__get_next_action()
def learn(self, chunks):
n = 20
gamma = 0.9
num_chunks = len... | This code processes the next step in a reinforcement learning agent by saving the previous state, updating the current state, calculating a reward based on evaluation metrics, storing transitions in a buffer, and triggering learning when the buffer reaches a specified size. | def next_step(self):
self.__save_previous()
self.__update_current()
curr_eval = self.detectors.num_passed_light / self.sum_of_cars_prev
reward = curr_eval - self.prev_eval
self.chunks.append((self.prev_state, self.prev_action, reward, self.state))
self.prev_eval = curr_e... |
def initialPermutaion(s64bits):
tempS=[]
for i in intialPermutationTable:
tempS.append(s64bits[i-1])
return tempS
def functionF(right, key):
right=expansionPbox(right)
for i in range(len(right)):
right[i]=right[i]^key[i]
right=sBox(right)
right=straightPBox(right)
return right
def bitSwap32(left,right):
re... | This code implements a Feistel network-based encryption algorithm. It performs 16 rounds of substitution-permutation operations on a 64-bit input string. Each round applies a function F to the right half, XORs it with the left half, then swaps halves. Initial and final permutations are applied, using round keys for eac... | def encryptString(s64bits,roundKeys):
s64bits=initialPermutaion(s64bits)
left=s64bits[0:32]
right=s64bits[32:]
for i in range(16):
# print("".join([str(i)for i in left])+" "+"".join([str(i)for i in right]))
tempRight=functionF(right,roundKeys[i])
for i in range(len(tempRight)):#this for loop for xor... |
def pyramid_fast(img, threshold=20, n=9, window_size=3, k=0.05, top_n=500,
pyr_depth=3, scale=1.2):
'''Function for generation of multiscale FAST features.
Input:
img - np.array, input image
threshold - int, FAST threshold
n - int, number of points for special point
... | The code implements an ORB (Oriented FAST and Rotated BRIEF) feature detector and descriptor. It detects keypoints using a FAST threshold on a multi-scale pyramid, computes their centroids, and generates BRIEF descriptors with steered filtering. The function returns keypoint locations and their corresponding descriptor... | def orb(img, fast_threshold=20, n=9, window_size=3, k=0.05, top_n=1000,
pyr_depth=3, scale=1.2, size=128, blur_size=5, brief_size=31):
'''ORB.
Input:
img - np.array, input image
fast_threshold - int, FAST threshold
n - int, number of points for special point
window_size -... |
def rescale(img):
return cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)
def rotate(image, angle):
# grab the dimensions of the image and then determine the
# center
image_center = tuple(np.array(image.shape[1::-1]) / 2)
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0... | The code compares OpenCV's ORB and a custom ORB implementation by detecting keypoints and descriptors on a dragonfly image and its transformed versions (rescaled, rotated, perspective, affine). It times both methods, matches descriptors using BFMatcher, and visualizes top 10 matches for each transformation, saving resu... | def main():
img = cv2.imread('./dragonfly.jpg')
resc_img = rescale(img)
rot_img = rotate(img, 33)
perp_img = perspective(img)
af_img = affine(img)
test_images = [resc_img, rot_img, perp_img, af_img]
st = time.time()
orbcv = cv2.ORB_create()
ks1, ds1 = orbcv.detectAndCompute(cv2.cvtCo... |
def oneHot(label,nClass):
nData = label.shape[0]
oneHot = torch.zeros(nData,nClass)
for i, lbl in enumerate(label):
oneHot[i][lbl] = 1
return oneHot
def probitFunc(meanIn,stdIn):
stdIn += 0.0001 # for safety
out = meanIn/(torch.ones(1) + (np.pi/8)*stdIn**2)**0.5
... | The main task of the code is to train a dynamic neural network with adaptive structure (growing/pruning nodes) using statistical analysis of input bias and variance, while detecting anomalies. It processes shuffled data, computes mean/variance statistics, dynamically adjusts network nodes based on significance threshol... | def nadineTrain(netList,x,y,nClass,anomaly,miuX,miuBias,miuVar,lr,dLr,criterion,device,epoch=1):
# flags
growNode = False
pruneNode = False
# shuffle the data
nData = x.shape[0]
shuffled_indices = torch.randperm(nData)
# label for bias var calculation
y_biasVar = F.one_ho... |
def try_parse_sport(self, sport_name: str, sport_date: str):
try:
return self.parse_sport(sport_name, sport_date)
except Exception as e:
if not self.check_text_availability('Try selecting a different date on the calendar.'):
raise e
return []
def data_... | This code initializes a class to process sports data from specified dates, using configurable browser settings. It replaces 'all' in sport_list with predefined sports, iterates through each sport-date pair to parse data, processes it, prints results, and inserts them into a database. Finally, it closes the browser. The... | def __init__(self,
sport_list: list[str],
sport_date_list: list[str],
fullscreen: Optional[bool] = None,
window_height: Optional[int] = None,
window_width: Optional[int] = None,
use_proxy: Optional[bool] = None):
... |
def get_payload_image(self):
if not self.is_name_active:
self.activate_name()
self.latest_response = requests.get(
self.PAYLOAD_IMAGE_URL,
headers=self._get_headers()
)
return Image.open(io.BytesIO(self.latest_response.content))
def watermark_image(s... | This code uploads user data, including a watermarked image, resume, and source code, to a server via a POST request. It prepares text fields (email, name, about me), attaches files (PDF resume, JPG image, and code), sets a custom User-Agent header, and sends the payload to a predefined URL. | def upload_data(self):
im = self.get_payload_image()
im = self.watermark_image(im, f"{self.name} {self.cookie}")
im.save(self.image_file)
text_fields = {
'email': self.email,
'name': self.name,
'aboutme': self.about,
}
files = {
... |
def train_model_using_grad_descent(X, y, alpha=0.1, max_iter=100):
beta = np.zeros(X.shape[1] + 1)
L_vals = []
for _ in tqdm(range(max_iter)):
beta = beta - alpha * grad_L(X, y, beta)
L_vals.append(eval_L(X, y, beta))
return beta, L_vals
def draw(datas, legends, xlabel, ylabel, title):
... | The code classifies breast cancer data using gradient descent (GD) and stochastic gradient descent (SGD), comparing their convergence speeds and accuracy. It standardizes features, tests multiple learning rates, plots cost vs. iterations/epochs, identifies optimal learning rates (0.1 for both), and evaluates validation... | def breast_cancer_classification():
# load cancer data
cancer_data = load_breast_cancer()
X_train, X_val, y_train, y_val = sk.model_selection.train_test_split(cancer_data.data, cancer_data.target,
test_size=0.2)
mean = np.average(X... |
def train_model_using_stochastic_grad_descent_multi(X, y, alpha=0.1, epoch=500):
beta = np.zeros((X.shape[1] + 1, y.shape[1])).astype("float64")
L_vals = []
for _ in tqdm(range(epoch)):
indexList = random.sample(range(X.shape[0]), X.shape[0])
for i in indexList:
beta = beta - alp... | The code performs digit classification on the MNIST dataset using stochastic gradient descent (SGD). It evaluates different learning rates (0.2, 0.05, 0.01), plots cost vs. epochs to identify the optimal rate (0.01), achieves 92.25% validation accuracy, and visualizes 8 most confused images. These images are misclassif... | def digit_classification():
mnist_data = sk.datasets.fetch_openml('mnist_784')
X_train, X_val, y_train, y_val = sk.model_selection.train_test_split(np.array(mnist_data.data).astype("float64"),
np.array(mnist_data.target.astype("int64")),
... |
def find_meta_clusters(df):
# function to find meta-cluster labels
print("Finding meta clusters...\n")
num_micro = df['LSH label'].nunique()
clus_ind_map = dict(zip(df['LSH label'].unique(),range(num_micro)))
micro_to_meta_map = np.zeros([num_micro, num_micro])
p = df.dropna(subset=['phone_num_cleaned_str'])
for... | The code reads and processes a dataset, clusters it using `find_meta_clusters`, maps features to cluster indices, modifies features accordingly, constructs a graph with `get_graph`, and prints cluster count and feature dimensions. The main task is to prepare clustered data and build a graph for analysis, likely for vis... | def get_data_df():
# data = pd.read_csv("marinus_labelled/merged_data_3_class_no_dupl_names_LSH_labels.csv", index_col=False)
data = pd.read_csv("marinus_canada/HT2018_final_trimmed_for_labeling_neat_preprocessed.csv", index_col=False)
data, nx_graph = find_meta_clusters(data)
feat_df = pd.read_csv("marinus_cana... |
def _calculate_total_product_price(
product_amount: int,
single_product_price: Decimal,
) -> Decimal:
return product_amount * single_product_price
def calculate_discount_price(discounts: DISCOUNTS, price: Decimal) -> Decimal:
discount_from_amount = _calculate_discount(discounts, price)
return price ... | The function `calculate_final_price` computes the final price of products after applying discounts and taxes. It calculates the total product price, applies discounts, adds taxes based on the state code, and rounds both the discounted and final taxed prices to cents using the specified rounding method. The result is a ... | def calculate_final_price(
discounts: DISCOUNTS,
taxes: TAXES,
product_amount: int,
single_product_price: Decimal,
state_code: STATE_CODE,
how_to_round=ROUND_UP,
) -> tuple[Decimal, Decimal]:
total_product_price = _calculate_total_product_price(
product_amount, single_product_price
... |
def _is_registered(self):
is_registered = self._registration is not None
log.info("Token is registered: {0}".format(is_registered))
return is_registered
def _is_refresh_expired(self):
is_refresh_expired = datetime.now() >= self.get_refresh_expiration()
log.info("Token refresh is ... | The code loads a token storage, checks if the token needs registration or refresh, and either registers or refreshes the token based on expiration status. | def _load(self):
self._registration = TokenStorage.load(self._name)
if not self._is_registered() or self._is_refresh_expired():
log.info("Token must be registered")
self._register()
elif self._is_expired():
log.info("Token is expired")
self._refres... |
def loadImage(square_size):
"""
Initialize a global directory of Knight Image
This will be called exactly once in the main.
"""
piece = 'bN'
IMAGES[piece] = p.transform.scale(p.image.load("images/" + piece + ".png"), (square_size, square_size))
def actionsForTable(listActions, currentX, currentY... | The main task of the code is to simulate and visualize a knight's movement on a chessboard of specified dimensions using a chosen algorithm (BFS, DFS, etc.). It initializes the game environment, loads assets, generates the path based on the selected algorithm, and renders the moves on the screen, allowing user input to... | def main(dimension, posX, posY,algType):
"""
The main driver for our code.
This will handle user input and updating the graphics.
"""
p.init()
p.display.set_caption('KnightMoves')
screen = p.display.set_mode((BOARD_WIDTH, BOARD_HEIGHT))
clock = p.time.Clock()
screen.fill(p.Color("wh... |
def sendPost(endpoint, jsonData):
return sendImpl('POST', endpoint, jsonData=jsonData)
def checkJobStatusOk(response, expectedStatus):
theId = response['job_status']['id']
if not replayRecordedResponses:
assertTrue(configs['overrideJobStatusUrlPrefix'] in response['job_status']['url'])
assertTru... | The function sends a POST request to initiate a job, verifies its status as 'queued', then polls the job's URL until it reaches 'completed' status, finally returning the completed job status data. | def sendPostAndGetJob(endpoint, jsonData):
jobStatus = sendPost(endpoint, jsonData)
checkJobStatusOk(jobStatus, 'queued')
response = sendGet(jobStatus['job_status']['url'])
checkJobStatusOk(response, 'completed')
return response['job_status'] |
def _generateJSON(self, subreddit, sort_option):
self.url = 'https://www.reddit.com/r/' + \
subreddit + '/' + sort_option + '.json'
print(self.url)
# session = _requests.Session()
# session.headers.update({'User-Agent': self.user})
# session.headers.update({'user-agent'... | This code downloads images and videos from a specified Reddit subreddit. It accepts parameters for the subreddit name, number of media files, sorting option (hot/new/top), and specific counts for images/videos. If image/video counts are unspecified, it randomly assigns values. The function processes the subreddit, gene... | def download(self, subreddit, number=5, sort_option=None,
num_of_images=0, num_of_videos=0):
"""
Download images and videos from given subreddit
- subreddit: name of subreddit from where to download
- number: number of media files to download
- sort_option: sort ... |
def _set_home(self):
rand = np.float32(np.random.rand(3, ))
init_x = (self.x_low_obs + self.x_high_obs) / 2 + 0.5 * (rand[0] - 0.5) * (self.x_high_obs - self.x_low_obs)
init_y = (self.y_low_obs + self.y_high_obs) / 2 + 0.5 * (rand[1] - 0.5) * (self.y_high_obs - self.y_low_obs)
init_z = ... | The main task of the code is to reset a robotic arm simulation environment by reinitializing the physics simulation, setting up obstacles, positioning the robot arm at its home configuration, adjusting distance thresholds based on success rates, and ensuring collision-free starting conditions. It also configures visual... | def reset(self):
p.resetSimulation()
self.init_home, self.init_orn = self._set_home()
self.target_position, self.obsts = self._add_obstacles()
if self.extra_obst:
self.moving_xy = choice([0, 1])
self.barrier = self._add_moving_plate()
self.obsts.app... |
def current_user():
if len(session) > 0:
return User.query.filter_by(id=session['_user_id']).first()
else:
return None
def following(uid):
# get the list of followings for a specific user id
friends = get_follows().get(uid)
return friends
def tweets_by_user():
tweets = Tweet.quer... | The main task of this code is to manage the home page of a social media application. It handles tweet creation via a POST form, stores new tweets in a database with the current user's ID, and retrieves tweets from followed users and the current user. It renders the home template with tweets, user suggestions, and login... | def home():
form = PostForm()
if request.method == 'POST':
tweet = request.form.get('Tweet')
title = request.form.get('Title')
print("nouveau tweet")
print(tweet)
print(title)
# create tweet
new_tweet = Tweet(uid=current_user().id, content=tweet, title=tit... |
def words_in_all_tweets():
tweets = Tweet.query.all()
words_dico = {}
for tweet in tweets:
title = tweet.title.lower().split(" ")
content = tweet.content.lower().split(" ")
# for every word, we put it as a key in a hashtable with as values the tweets it appears in
for word in... | This function handles a search request by retrieving form data, querying tweets containing the searched word, gathering user data, and rendering the search results page with filtered tweets, user lists, and search context. | def search():
form = SearchForm(request.form)
words_dico = words_in_all_tweets()
all_users = User.query.all()
word_searched = request.form.get('searched').lower()
if word_searched is None:
word_searched = ''
tweets = get_tweets()
id_tweets_with_word = words_dico.get(word_searched)
... |
def get_users_followed():
# gets both users followed and users not followed
follows = following(current_user().id)
all_users = User.query.all()
users_not_followed = []
users_followed = []
for user in all_users:
if follows is not None:
if ((user.id not in follows) and (user.id... | The main task of the code is to retrieve and render a user's profile page by collecting data on followed users, followers, and personal tweets, then passing these variables to the "myprofile.html" template for display. | def myprofile():
users_followed, users_not_followed = get_users_followed()
users_following_me = []
all_users = User.query.all()
for user in all_users:
if (is_followed_by(current_user().id, user.id)):
users_following_me.append(user)
perso_tweets = tweets_by_user().get(current_user... |
def user_by_id():
users = User.query.all()
users_by_id = {}
for u in users:
if users_by_id.get(u.id) is not None:
if u not in users_by_id.get(u.id):
users_by_id.get(u.id).append(u)
else:
users_by_id[u.id] = [u]
return users_by_id
def get_users_foll... | The code retrieves a user's profile data, including their followed users, tweets, and follower status, then renders the 'profile.html' template with this information for display. | def profile(user_id):
user_ = user_by_id().get(user_id)[0]
users_followed, users_not_followed = get_users_followed()
users_following_uid = []
all_users = User.query.all()
for user in all_users:
if (is_followed_by(user_.id, user.id)):
users_following_uid.append(user)
user_twee... |
def command_type(self, line):
if not line:
return 'N'
if line[0] == '@':
return 'A'
elif line[0] in "MDA0":
return 'C'
elif line[0] == '(':
return 'L'
else:
return 'N'
def configure_jump(self, line):
# in any jum... | This code reads a file line-by-line, strips comments and whitespace, identifies instruction types, processes C-instructions (dest=comp; jump), generates binary opcodes, and writes the assembled output to a .hack file. It handles jump and register manipulation commands, resets variables per line, and appends results to ... | def read_file(self):
# open file from filename and automatically close after done
with open(self.filename, 'r', encoding='utf-8') as file:
# main line-searching loop
for line in file:
line = line.strip()
if '//' in line:
line = ... |
def slope(self) -> float:
"""
:return: slope of the line
"""
if self.p1.x == self.p2.x:
return inf
return (self.p1.y - self.p2.y) / (self.p1.x - self.p2.x)
def contains_point(self, p: Point):
"""
:param p: a point
:return: True if the point is ... | The function determines if two line segments intersect by checking for parallelism, overlapping endpoints, or calculating the intersection point's validity. It returns True if lines intersect, considering both vertical and non-vertical cases, and verifies if the intersection lies within the segments. | def is_intersecting(self, other: Line) -> bool:
"""
:param other: another line
:return: True if the lines intersect
"""
if self.slope() == other.slope():
# they are parallel, so they are either no connected at all, or have a certain overlap
return self.con... |
def expand(self, corners: List[Point], acc: int) -> None:
"""
expand the corners by the expansion factor
:param corners: a list of corners of the museum
:param acc: the expansion factor
"""
for i in range(len(corners)):
corners[i].x *= acc
corners[... | This code initializes a museum map by validating the accuracy level (acc), expanding corner points, creating walls from corners, and generating sets of points for guards, walls, and the overall grid (net) to represent the museum's structure with specified precision. | def __init__(self, corners: List[Point], acc: int):
if not (type(acc) == int or (type(acc) == float and float(acc).is_integer())):
raise Exception("acc should be an integer")
if acc < 2:
raise Exception("acc should be at least 2")
self.acc: int = acc # accuracy level of ... |
def check_team(self, moves, index):
row, col = index
if moves%2 == 0:
if self.board[row][col].team == 'w':
return True
else:
print('Not your turn.')
return False
else:
if self.board[row][col].team == 'b':
... | This function determines valid moves for a chess piece based on its type and team, then highlights those moves. It checks if moves are team-specific, then delegates to specialized methods (e.g., pawn_moves_b/w, king_moves) to calculate possible moves, applying a highlight function to visualize valid positions for the s... | def select_moves(self, piece, index, moves):
if self.check_team(moves, index):
if piece.type == 'p':
if piece.team == 'b':
return self.highlight(self.pawn_moves_b(index))
else:
return self.highlight(self.pawn_moves_w(index))
... |
def _create_folder_ui(self):
default_folder = Path(cmds.workspace(rootDirectory=True, query=True))
default_folder = default_folder / "scenes"
self.folder_line_edit = QtWidgets.QLineEdit(default_folder)
self.folder_browse_button = QtWidgets.QPushButton("...")
layout = QtWidgets.QH... | The code creates a user interface for a "Smart Save" application by organizing UI elements like a title label, folder selection, filename input, success message, and save button into a vertical layout. It initializes components, arranges them using QVBoxLayout, and sets the layout as the main interface, enabling user i... | def create_ui(self):
self.title_label = QtWidgets.QLabel("Smart Save")
self.title_label.setStyleSheet("font: bold 20px")
self.folder_layout = self._create_folder_ui()
self.filename_layout = self._create_filename_ui()
self.successful_save = QtWidgets.QLabel("")
self.save_b... |
def maya_main_window():
"""Return the maya main window widget"""
main_window = omui.MQtUtil.mainWindow()
return wrapInstance(long(main_window), QtWidgets.QWidget)
def create_ui(self):
self.title_label = QtWidgets.QLabel("Scatterer")
self.title_label.setStyleSheet("font: bold 20px")
s... | This code initializes a custom GUI window for a "Scatterer" tool, setting its title, removing the context help button, instantiating a Scatterer object, and configuring the window size and layout. It prepares the user interface and establishes necessary connections for functionality, ensuring a controlled window dimens... | def __init__(self):
super(ScatterUI, self).__init__(parent=maya_main_window())
self.setWindowTitle("Scatterer")
self.setWindowFlags(self.windowFlags() ^
QtCore.Qt.WindowContextHelpButtonHint)
self.scatterer = Scatterer()
self.create_ui()
self.c... |
def maya_main_window():
"""Return the maya main window widget"""
main_window = omui.MQtUtil.mainWindow()
return wrapInstance(long(main_window), QtWidgets.QWidget)
def create_ui(self):
self.title_label = QtWidgets.QLabel("Smart Save")
self.title_label.setStyleSheet("font: bold 20px")
... | This code initializes the SmartSaveUI window by setting its title, removing the context help button, creating UI components, establishing connections, and defining size constraints to ensure a user-friendly interface for managing scene files in Maya. | def __init__(self):
super(SmartSaveUI, self).__init__(parent=maya_main_window())
self.setWindowTitle("Smart Save")
self.setWindowFlags(self.windowFlags() ^
QtCore.Qt.WindowContextHelpButtonHint)
self.scenefile = SceneFile()
self.create_ui()
sel... |
def __set_target_to_source(self, x, input_ages):
return [torch.cat((img, age * torch.ones((1, img.shape[1], img.shape[2])).to(self.device)))
for img, age in zip(x, input_ages)]
def perform_forward_pass(self, x):
y_hat, latent = self.net.forward(x, return_latents=True)
return y_hat, latent
def calc_loss(self, ... | This code trains a neural network to generate age-transformed images using a combination of real and generated data. It performs forward passes on real images and cycle passes on generated images, computing losses for both. The model incorporates aging effects, applies random no-aging steps, and uses cycle consistency ... | def train(self):
self.net.train()
while self.global_step < self.opts.max_steps:
for batch_idx, batch in enumerate(self.train_dataloader):
x, y = batch
x, y = x.to(self.device).float(), y.to(self.device).float()
self.optimizer.zero_grad()
input_ages = self.aging_loss.extract_ages(x) / 100.
#... |
def greeting_intent_behavior(intent_request):
return {
"sessionState": {
"dialogAction": {
"type": "ElicitIntent"
}
},
"messages": [
{
"contentType": "PlainText",
"content... | The main task of the code is to route incoming intent requests to corresponding handling functions based on the detected intent name. It checks the intent name from the request, dispatches to `greeting_intent_behavior`, `thankyou_intent_behavior`, or `dining_intent_behavior` for supported intents, and raises an excepti... | def dispatch(intent_request):
intent_name = intent_request['sessionState']['intent']['name']
if intent_name == 'GreetingIntent':
# print("GreetingIntent Func")
return greeting_intent_behavior(intent_request)
elif intent_name == 'ThankYouIntent':
return thankyou_intent_behavior(intent... |
def parse_input() -> tuple:
"""
parses input
:return str file: path to file
:return str year: year to search
:return float lat: latitude
:return float lon: longitude
"""
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('year', type=str,
... | The code's main task is to process movie data by year, extract locations, and generate a visual map. It parses input parameters, searches for films and locations, creates map markers, writes results to a TSV file, and generates an HTML map for visualization. | def main() -> None:
"""
the main function
"""
file, year, def_lat, def_lon = parse_input()
locations, films = search_by_year(file, year)
markers = parse_locations(locations, films, def_lat, def_lon)
write_tsv(markers)
create_html_map(year, def_lat, def_lon) |
def convert_to_jpg(pdf_path):
# Store Pdf with convert_from_path function
images = convert_from_path(pdf_path)
ret = []
for i in range(len(images)):
# Save pages as images in the pdf
img_name = './pdfs/page' + str(i) + '.jpg'
images[i].save(img_name, 'JPEG')
ret.append(im... | The main task of the code is to process scanned document pages by detecting text and blank regions, generating individual PDFs for each page, and combining them into a single output PDF. It converts input files to JPEG, analyzes each page's layout, sorts text coordinates, creates PDF canvases, saves intermediate files,... | def main(input_filename, output_filename):
img_paths = convert_to_jpg(input_filename)
i = 0
paths = []
for img_path in img_paths:
print(f"--PAGE {i}/{len(img_paths)-1}--")
image, lines = detect_blanks(img_path)
lines = lines[lines[:, 2].argsort()] # Sort coords by 3rd column
... |
def getRegf(self,reg):
write = i2c_msg.write(self.addr,[reg>>8,reg&0xFF])
read = i2c_msg.read(self.addr,2)
self.bus.i2c_rdwr(write, read)
result = list(read)
return (result[0]<<8)+result[1]
def setRegf(self, reg, value):
write = i2c_msg.write(0x33,[reg>>8,reg&0xFF, value>... | The main task of the code is to read and process two subpages of sensor data from hardware registers, applying outlier interpolation, data conversion, and bad pixel corrections, while ensuring timely data retrieval with a timeout mechanism. | def GetFrameData(self):
frame = [0,0]
t_start = time.time()
sub_cnt = 0
ctrl_reg = self.getRegf(0x800D)
self.setRegf(0x8000, ctrl_reg ^ (1 << 3)) #set new data flag to 0
new_data_flag = 0
while(sub_cnt < 2):
stat_reg = self.getRegf(0x8000) # status... |
def getRegf(self,reg):
write = i2c_msg.write(self.addr,[reg>>8,reg&0xFF])
read = i2c_msg.read(self.addr,2)
self.bus.i2c_rdwr(write, read)
result = list(read)
return (result[0]<<8)+result[1]
def setRegf(self, reg, value):
write = i2c_msg.write(0x33,[reg>>8,reg&0xFF, value>... | The function `GetFrameData` reads and processes two subpages of sensor data by waiting for a "new data" flag in hardware registers, retrieves the data from RAM, applies outlier interpolation, threshold calculation, and bad pixel corrections, then returns the processed frame data. | def GetFrameData(self):
frame = [0,0]
t_start = time.time()
sub_cnt = 0
ctrl_reg = self.getRegf(0x800D)
self.setRegf(0x8000, ctrl_reg ^ (1 << 3)) #set new data flag to 0
new_data_flag = 0
while(sub_cnt < 2):
stat_reg = self.getRegf(0x8000) # status... |
def GetRefreshRate(self):
ctrl_reg = self.getRegf(0x800D)
refreshRate = (ctrl_reg & 0x0380) >> 7
return refreshRate
def SetRefreshRate(self, refreshRate):
value = (refreshRate & 0x07)<<7
ctrl_reg = self.getRegf(0x800D)
value = (ctrl_reg & 0xFC7F) | value
self.s... | The code processes thermal camera data to stream video with adjustable frame rates, calculates heat source coordinates, applies image processing (blurring, resizing, color mapping), and displays real-time thermal imagery with position tracking and threshold-based anomaly detection. | def GetVideoStream(self, fps=8):
refresh_rate = self.GetRefreshRate()
if fps == 1:
if refresh_rate != fps:
self.SetRefreshRate(0b001);
elif fps == 2:
if refresh_rate != fps:
self.SetRefreshRate(0b010);
elif fps == 4:
... |
def GetRefreshRate(self):
ctrl_reg = self.getRegf(0x800D)
refreshRate = (ctrl_reg & 0x0380) >> 7
return refreshRate
def SetRefreshRate(self, refreshRate):
value = (refreshRate & 0x07)<<7
ctrl_reg = self.getRegf(0x800D)
value = (ctrl_reg & 0xFC7F) | value
self.s... | The main task of the code is to capture and process thermal video from a sensor, adjust the device's refresh rate based on the specified FPS, compute the average position of detected heat sources in each frame, and display the processed thermal imagery in real-time with coordinates and threshold information. It uses Ga... | def GetVideoStream(self, fps=8):
refresh_rate = self.GetRefreshRate()
if fps == 1:
if refresh_rate != fps:
self.SetRefreshRate(0b001);
elif fps == 2:
if refresh_rate != fps:
self.SetRefreshRate(0b010);
elif fps == 4:
... |
def Patients_FunctionUsedToAddAnewPatientToTheDataBase():
Department=input("Please Enter the Department Which The Patient is Assigned to : ")
Department=Department.upper()
DoctorName,flag=StaticFunction_UsedToCheckIfTheDepartmentFound(Department)
if flag==1:
ID=input("Please Enter the Patient I... | This function provides a menu-driven interface for managing patient data, allowing users to add, edit, delete, or display patient information, with a loop that continues until the user selects the exit option (0). | def Patients_MainFunction():
while 1:
print("\n\n\n\n\n\n\n\n")
print("//////////////////////////////////////")
print("**************************************")
print("To Add Patient Press 1")
print("To Edit Patient Press 2")
print("To Delete Patient Press 3")
pri... |
def load_user_token(self):
if self.file_status['usertokenPresent']:
self.load_json_file(self.USER_TOKEN_FILENAME)
else:
#your refresh token is stored
print("Please enter your refresh token from herolab")
x = input()
self.user_token['accessToken... | The main task of the code is to load essential data components for campaign management, including user tokens, campaign details, participant rosters, and necessary characters. The `load_data` method orchestrates these operations by sequentially invoking helper methods to ensure all required data is initialized and vali... | def load_data(self):
self.load_user_token()
self.load_campaign()
self.load_campaign_roster()
self.check_and_load_characters() |
def _afterpulsing_summation(
x: np.float64,
total: np.int64,
sigma_k: np.float64,
ap_beta: np.float64,
ap_prob: np.float64,
) -> np.float64:
"""
Summation of the afterpulse response (with random noise) weighted by the
binomial distribution for number of afterpulses up to 10 (expected ap_... | The function calculates the total afterpulse response by combining a weighted summation of afterpulses (adjusted for pedestal and gain shifts) with random noise, using a binomial distribution for up to 10 afterpulses and a normal distribution for variable noise, while incorporating parameters like afterpulse probabilit... | def _full_afterpulse_response(
x: np.float64,
total: np.int64,
ap_beta: np.float64,
ap_prob: np.float64,
pedestal: np.float64,
gain: np.float64,
sigma_k: np.float64,
) -> np.float64:
"""
Summation of the afterpulse response (with random noise) weighted by the
binomial distributio... |
def generalized_poisson(
k: np.int64, mean: np.float64, borel: np.float64 = 0.0
) -> np.float64:
"""Generalized Poisson distribution probability values:
P(k;m,b) = (m (m + k b)^(k-1) exp(-(m + k b))) / k!
Parameters
----------
k : numpy.int64
Number of incidents of interest.
mean :... | The function computes the SiPM lowlight response probability density by combining contributions from no photoelectron discharges (via normal and dark current distributions) and photoelectron discharges (via summation of kernel responses), incorporating parameters like gain, noise, Poisson statistics, afterpulse/dark cu... | def sipm_response(
x: np.float64,
pedestal: np.float64,
gain: np.float64,
common_noise: np.float64,
pixel_noise: np.float64,
poisson_mean: np.float64,
poisson_borel: np.float64,
ap_prob: np.float64,
ap_beta: np.float64,
dc_prob: np.float64,
dc_res: np.float64 = 1e-4,
) -> np.... |
def generalized_poisson(
k: np.int64, mean: np.float64, borel: np.float64 = 0.0
) -> np.float64:
"""Generalized Poisson distribution probability values:
P(k;m,b) = (m (m + k b)^(k-1) exp(-(m + k b))) / k!
Parameters
----------
k : numpy.int64
Number of incidents of interest.
mean :... | The function calculates the SiPM low-light probability density function without dark current effects by combining contributions from no photoelectron discharges (via generalized Poisson and normal distributions) and photoelectron discharges (via a k-summation model), incorporating parameters like gain, noise, and after... | def sipm_response_no_dark(
x: np.float64,
pedestal: np.float64,
gain: np.float64,
common_noise: np.float64,
pixel_noise: np.float64,
poisson_mean: np.float64,
poisson_borel: np.float64,
ap_prob: np.float64,
ap_beta: np.float64,
) -> np.float64:
"""
SiPM low light probability ... |
def plot_RBF_SVM_heatmap(ax, grid, param_grid):
"""Convenience function for plotting grid heatmap with preset formatting
appropriate for RBF support vector machine gridsearch. Adds the plot to
supplied Axes without showing figure so that Axes can be customised.
Parameters
----------
axs : Axes... | Your returnThe function `SVM_summary_2D` generates a 2x2 visualization summary of a support vector machine (SVM) grid search on 2D data. It creates a heatmap of hyperparameter performance, validation curves for parameter slices, and a contour plot showing the decision boundaries of the best model. The output includes a... | def SVM_summary_2D(grid, param_grid, X, y, **kwargs):
"""Produces a 2 x 2 array of plots summarising a support vector machine
grid search on 2-dimensional data. The array consists of a heatmap,
validation curves on slices of the grid search, and a countour plot
visualising the decision boundaries of t... |
def SVM_summary_2D(grid, param_grid, X, y, **kwargs):
"""Produces a 2 x 2 array of plots summarising a support vector machine
grid search on 2-dimensional data. The array consists of a heatmap,
validation curves on slices of the grid search, and a countour plot
visualising the decision boundaries of t... | The function `RBF_SVM_gridsearch` trains an RBF-kernel SVM using grid search to optimize regularization (C) and kernel scale (gamma) parameters. It employs cross-validation, scales features, and returns the best model. If enabled, it visualizes results via heatmaps, validation curves, or 2D decision boundaries. The goa... | def RBF_SVM_gridsearch(X, y, C_range = np.logspace(-3,3,7),
gamma_range = np.logspace(-3,3,7),
plot = True, **kwargs):
"""Trains a support vector machine with a radial basis kernel on the
supplied data using 2D grid search to optimise the regularisation and
length scale p... |
def draw_waves(img): # TODO make intensity vary smoothly
xs = np.arange(0, imWidth)
ys = np.arange(0, imHeight)
amp = random.randint(10,200)
x_wavelength = random.randint(100,int(imWidth/2))
thickness = random.randint(15,40)
slope = 3*(np.random.rand()-.5)
y_spacing = random.randint(thickn... | The main task of the code is to generate synthetic images by creating a numpy array, drawing wave patterns (bottleneck), adding random antinodes, applying blur/noise, pixel dropout, and mixing with real data. It saves the processed image and annotations for a specified frame number. The process includes image degradati... | def handle_one_file(outdir, framenum):
print("framenum = ",framenum)
np_dims = (imHeight, imWidth, 1) # for numpy, image dimensions are reversed
img = 128*np.ones(np_dims, np.uint8)
draw_waves(img) # this is the main bottleneck, execution-time-wise
max_antinodes = 6
num_antinodes= rando... |
def setup_pred_mask(self):
self.mask_img = None
self.mask_pred_file = 'top_losses/seg_images/'+str(Path(self.meta_file).stem)+'_pred.png'
if os.path.exists(self.mask_pred_file):
self.mask_img = Image.open(self.mask_pred_file)
if self.mask_img.size != (self.width, self.hei... | The main task of the code is to load and display a new image along with its associated annotations (bounding boxes, prediction rings) and metadata on a canvas, clearing previous content, fetching image paths, processing prediction masks, and rendering visual elements like text, bounding boxes, and ring markers for the ... | def load_new_files(self):
self.canvas.delete("all") #destroy old tokens
self.text = self.canvas.create_text(self.width+10, 10+self.y0, text=self.infostr,
anchor=tk.NW, font=tk.font.Font(size=15,family='Consolas'))
self.meta_file = self.meta_file_list[self.file_index]
self.im... |
def get_top_loss_list(
top_losses_dir, # directory where top-losses info is stored
):
"gets list of filenames with top losses for use with preferential ordering"
if (top_losses_dir==None) or (not os.path.exists(top_losses_dir)): return []
# slurp in any csv files we've got
# note they likely ha... | This code initializes a Tkinter GUI for image annotation, handling CSV metadata files, image banks, and top-loss data. It sets up a canvas for interactive annotations, manages masks, bounding boxes, and ring predictions, and binds mouse/keyboard events for navigation, editing, and saving annotations. The class supports... | def __init__(self, parent, # tk class and parent window
meta_file_list, # list of csv files to edi
img_bank='images/', # where images are stored
tldir=None, # directory where top-losses info is stored
seq=True, # ignore top losses and do sequential selec... |
def speak(audio):
engine.say(audio)
print(audio)
engine.runAndWait()
def takecommand(self):
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source, phrase_time_limit=5)
try:
... | The code's main task is to authenticate user commands via voice input, prompting for a password and executing predefined tasks ("TaskExecution") when specific phrases like "wake up buddy" or "are you there" are detected. It exits gracefully on "goodbye buddy" or reports incorrect passwords otherwise, using speech synth... | def run(self):
# self.TaskExecution()
speak("Please say correct password to proceed")
while True:
self.command = self.takecommand()
if "wake up buddy" in self.command or "are you there" in self.command:
self.TaskExecution()
elif "goodbye buddy"... |
def i2bin(i, l):
actual = bin(i)[2:]
if len(actual) > l:
raise AppError("bit size is larger than expected.")
while len(actual) < l:
actual = "0"+actual
return actual
def put_bits(self, bits):
for bit in bits:
self.put_bit(bit)
def char2bin(c):
return i2bin(ord(c), 8) | The code embeds text into an image by first converting the text's length to a 16-bit binary value and storing it in the first 16 cells. Then, each character of the text is converted to an 8-bit binary string and sequentially embedded into subsequent cells. This process prepares the text for steganographic insertion int... | def embed(self, text):
# calculate text length and convert it to binary with length 16 bit
text_length = i2bin(len(text), self.MAX_BIT_LENGTH)
# put length to first 16 cell
self.put_bits(text_length)
# put every character on text to image
for c in text:
# convert character into binary wit... |
def does_master_exist(controller_list):
"""
Check if there's already a controller with a quorum. If so that one is the new master.
:return: Return controller with quorum of None
"""
master_list = {}
for controller in controller_list: # calculate how many controllers voted for this controller as... | The function determines and sets the current master controller by checking if an existing valid master exists (with quorum) using `does_master_exist`; if valid, it sets that controller as master. If not, it identifies a new master address via `determine_new_master` and sets it, ensuring controller leadership is establi... | def determine_master():
"""
The function is called when a new master needs to be determined for a controller.
:return:
"""
# check if there's a master with quorum
controller = does_master_exist(controller_list)
if controller is not None: # if controller is valid
set_master(controll... |
def get_master():
"""
Getter method of master
:return: master address as string or None if controller has no master
"""
return controller_list[my_address][1]
def set_master(address):
"""
Setter method for master. The master is stored in controller_list dictionary
:param address: The addr... | The function checks if a majority of registered controllers are active to form a quorum. If so, it determines a master (e.g., at startup). If a master exists, it verifies its availability; if unavailable, it selects a new master. If quorum isn't met, it clears the master. | def check_master():
"""
Check whether there is a majority so a quorum can be made due to potentially new controllers.
If more that half of all registered controllers are active determine master, e.g. at startup.
If a master already exists check if it is available. If not determine new master.
:retur... |
def i_am_worker():
"""
Function that is called when a controller becomes worker. It executes a certain script that can be stated in
program args.
:return:
"""
if worker_script != "":
execute_script(worker_script)
else:
print("I am worker!")
def check_other_controller_status()... | The main task of the code is to activate a controller by marking it as alive, designate it as a worker (not master), and continuously monitor the system by checking other controllers' statuses and verifying master availability every 5 seconds in an infinite loop. | def scan():
"""
The method is called at the start of a controller. It sets the controller as active and calls the function
i_am_worker, because the new controller can not enter the environment as master.
Then it basically starts an endless loop checking the other controllers and making sure the master i... |
def perform_vhv_calibration(self):
"""perform vhv calibration"""
# run vhv
self.write_byte(VL53L0X_REG_SYSTEM_SEQUENCE_CONFIG, 0x01)
self.perform_single_ref_calibration(0x40)
# read vhv from device
self.ref_calibration_io(0xCB)
# restore static sequence config
... | The code performs reference calibration for a sensor, executing VHV and phase calibration steps, then restores the original system sequence configuration by writing to a specific register. | def perform_ref_calibration(self):
"""perform ref calibration, including vhv and phase one"""
self.perform_vhv_calibration()
self.perform_phase_calibration()
# restore static sequence config
self.write_byte(VL53L0X_REG_SYSTEM_SEQUENCE_CONFIG, self.static_seq_config) |
def write_byte(self, reg, data):
"""write byte data to a given register address"""
self.bus.write_byte_data(self.address, reg, data)
def perform_ref_calibration(self):
"""perform ref calibration, including vhv and phase one"""
self.perform_vhv_calibration()
self.perform_phase_cal... | This function configures the VL53L0X sensor's reference SPAD (Single Photon Avalanche Diode) management by writing specific register values to set dynamic SPAD parameters, enable reference SPADs, and adjust power settings. It then triggers reference calibration and signal measurement processes to ensure accurate distan... | def perform_ref_spad_management(self):
"""perform ref spad management"""
self.write_byte(0xFF, 0x01)
self.write_byte(VL53L0X_REG_DYNAMIC_SPAD_REF_EN_START_OFFSET, 0x00)
self.write_byte(VL53L0X_REG_DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, 0x2C)
self.write_byte(0xFF, 0x00)
self... |
def data_init(self):
"""data initialization"""
# set i2c standard mode
self.write_byte(0x88, 0x00)
# read whoami
self.read_byte(0xC0)
# use internal default settings
self.write_byte(0x80, 0x01)
self.write_byte(0xFF, 0x01)
self.write_byte(0x00, 0x... | The main task of the code is to configure a device during its initial startup by initializing data structures, static parameters, performing reference calibration, and managing SPAD (Single-Photon Avalanche Diode) components, ensuring the device is properly set up for operation. | def setup(self):
"""configure the device when it first starts up"""
self.data_init()
self.static_init()
self.perform_ref_calibration()
self.perform_ref_spad_management() |
def _acquire_items(self):
acquired_items = [i for i in self.location.inventory_items if random() < i.acquire_probability]
for item in acquired_items:
print('You find: ' + item.name)
self.inventory.append(item)
self.location.inventory_items.remove(item)
sle... | The main task of the code is to run a game loop that repeatedly displays the current location's description, processes item acquisition and events when the location changes, shows player attributes and inventory, and handles player actions and transitions. The loop continues indefinitely until the game ends, managing d... | def play(self):
'Play the game.'
print(bright(self.introduction))
sleep(0.5)
last_location = None
while True:
print()
print(bright(self.location.description))
if self.location != last_location:
self._acquire_items()
... |
def load_occurrence_rates(subdivide=1, bound='', mass=True, usebins=False):
# Note: I turned this into a wrapper for separate read-in functions because
# I could not follow the "use r and p as variables no matter what quantities we're working with" notation.
'''
load_occurrence_rates.py
This p... | This function generates synthetic planetary systems around stars using Monte Carlo methods based on occurrence rates, ensuring orbital stability. It assigns planet properties (mass, radius, orbit parameters) while adhering to input constraints, adjusts for system orientations, and optionally adds Earth-like planets. Th... | def generate_planets(stars, settings, bound='', nomcdraw=False, addearth=False, usebins=False, subdivide=1):
settings = settings
rng = np.random.default_rng(seed=settings.seed)
subdivide = max(1,min(subdivide,10))
if settings.emax < settings.emin:
print('Error: emax must be greate... |
def handle_site(self, point):
self.insert_arc(point)
def handle_event(self, event):
if event.valid:
# start new edge
edge = Edge(event.point)
self.output.append(edge)
# remove associated arc (parabola)
arc = event.arc
if arc.prev i... | The code processes events from the event queue by handling site events and other events, then finalizes edges once all events are processed. | def compute(self):
while not self.event_queue.empty():
next_event = self.event_queue.get()[1]
if next_event.is_site:
self.handle_site(next_event.point)
else:
self.handle_event(next_event)
self.complete_edges() |
def findParent(self, root, key):
if not root or (not root.left and not root.right):
return None
if (root.left and root.left.key == key) or (root.right and root.right.key == key):
return root
if key < root.key:
return self.findParent(root.left, key)
els... | The function resolves red-black tree violations after insertion by recoloring nodes and performing rotations. It checks for parent/uncle color configurations, adjusts colors, and applies left/right rotations to maintain balance, ensuring the tree adheres to red-black properties. | def fixViolation(self, root, key):
if not root:
return None
# If the newly inserted node is at the root
if not root.left and not root.right:
root.color = 'black'
return root
# If the parent is black, no violation, so return
if root.left and r... |
def get_top_tracks(limit, offset=0):
session['token_info'], authorized = get_token()
session.modified = True
if not authorized:
print('user not logged in')
return redirect(url_for('login', _external=False))
sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))
... | The code generates a combined list of top and saved tracks by removing duplicates between them, ensuring the top tracks list has at least 15 items. It repeatedly fetches additional top tracks if needed, then merges the cleaned lists for output. | def get_tracks():
top_tracks = get_top_tracks(limit = 20)
saved_tracks = get_saved_tracks()
#
# get most recent tracks
# get top tracks
#
# afterwards, verify if there is any repeated song from the recent tracks amongst the top tracks (*)
# if there is, remove such song from the top ... |
def get_token():
token_valid = False
token_info = session.get('token_info', {})
if not (session.get('token_info', False)):
token_valid = False
return token_info, token_valid
now = int(time.time())
is_expired = token_info['expires_at'] - now < 60
if is_expired:
sp_oau... | The main task of the code is to create or update a Spotify playlist named "[user's display name]'s AutoPlaylist" with specified tracks. It checks if the playlist exists, deletes existing tracks if it does, and adds new tracks. If the playlist doesn't exist, it creates it. The code uses the Spotify API, handles user aut... | def create_playlist():
session['token_info'], authorized = get_token()
session.modified = True
if not authorized:
print('user not logged in')
return redirect(url_for('login', _external=False))
sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))
#
# get ... |
def h(point1, point2):
x1, y1 = point1
x2, y2 = point2
return abs(x1 - x2) + abs(y1 - y2)
def reconstruct_path(came_from, current, draw):
while current in came_from:
current = came_from[current]
current.make_path()
draw()
def draw(win, grid, rows, width):
win.fill(WHITE)
for row in grid:
for spot in row:... | This code implements the A* pathfinding algorithm on a grid. It uses a priority queue to explore nodes, updating g-scores (cost from start) and f-scores (g + heuristic). When the end node is reached, it reconstructs the path and returns True; otherwise, it continues until the queue is empty, returning False if no path ... | def algorithm(draw, grid, start, end):
count = 0
open_set = PriorityQueue()
open_set.put((0, count, start))
came_from = {}
g_score = {spot: float("inf") for row in grid for spot in row}
g_score[start] = 0
f_score = {spot: float("inf") for row in grid for spot in row}
f_score[start] = h(start.get_position(), end... |
def making_grid(rows, width):
grid = []
gap = width // rows
for i in range(rows):
grid.append([])
for j in range(rows):
spot = Spot(i, j, gap, rows)
grid[i].append(spot)
return grid
def draw(win, grid, rows, width):
win.fill(WHITE)
for row in grid:
for spot in row:
spot.draw(win)
draw_grid(win,... | This code implements a pathfinding visualization tool using Pygame. It initializes a grid, allows users to set start/end points and barriers via mouse clicks, and runs a pathfinding algorithm (e.g., A*) when the spacebar is pressed. The 'c' key clears the grid, and 'e' exits the program. The main task is to provide an ... | def main(win, width):
ROWS = 50
grid = making_grid(ROWS, width)
start = None
stop = None
run = True
while run:
draw(win, grid, ROWS, width)
for event in pygame.event.get():
if event.type == quit:
run = False
# for LEFT
if pygame.mouse.get_pressed()[0]:
pos = pygame.mouse.get_pos()
row,... |
def _get_video(self, name):
"""Video loader"""
frames, frame_idxs = read_frames_from_video(
os.path.join(self.video_setting.VIDEO_PATH, name),
self.video_setting.NUM_FRAMES,
self.video_setting.SAMPLE,
self.video_setting.FIX_START
)
retu... | The main task of the code is to load and preprocess video frames and corresponding captions for a given index. It retrieves video data, extracts frames, applies transformations, processes text captions, and returns them as a tuple for model training or evaluation. | def __getitem__(self, index):
"""Load data"""
video_name, total_frames, captions = self.data[index]
frames, frame_idxs = self._get_video(video_name)
# preprocess frames
frames = prepare_frames(frames, self.transform)
captions = self._get_text(captions)
return fram... |
def _get_video(self, name, total_frames):
"""Frames loader"""
frames, frame_idxs = read_frames_from_folder(
os.path.join(self.video_setting.VIDEO_PATH, name),
total_frames,
self.video_setting.NUM_FRAMES,
self.video_setting.SAMPLE,
self.video_se... | The main task of the code is to load and preprocess video data and corresponding captions for a given index. It retrieves video frames and captions from the dataset, applies transformations to the frames, and returns the processed frames along with the captions. This function is typically used in PyTorch datasets to en... | def __getitem__(self, index):
"""Load data"""
video_name, total_frames, captions = self.data[index]
frames, frame_idxs = self._get_video(video_name)
# preprocess frames
frames = prepare_frames(frames, self.transform)
captions = self._get_text(captions)
return fram... |
def extractFile (filePath, ner_tagger):
f = open(filePath,'r')
txt = f.read()
f.close()
date = extractDate(filePath)
tokens = word_tokenize(txt)
fileName = filePath.split('/')[-1]
names = extractNames(tokens, date, fileName, ner_tagger)
return(names)
def extract_useful_information_from_t... | This function processes text files to extract named entities (PERSON/ORGANIZATION) using NLP, then updates databases with extracted information while handling errors. It uses Stanford NER to tag entities, filters relevant data based on user-defined parameters, and stores results in databases with duplication checks. | def generate_nlp_process( targetFiles,targetFilesAdress, importantWords , entityClassifierAddress, englishModelAddress,
scrapePerson , scrapeOrganization, con, dublicationLimit ):
ner_tagger = StanfordNERTagger(englishModelAddress, entityClassifierAddress)
# encoding='utf8'
for i i... |
def create_batches(self, data, labels, batch_size):
"""
Parameters
----------
data : np.array of input data
labels : np.array of input labels
batch_size : int size of batch
Returns
-------
list
list of tuples of (data batch of... | The code trains a neural network using Stochastic Gradient Descent (SGD) on provided training data. It iterates over epochs, splits data into mini-batches, performs forward and backward propagation, updates weights and biases with the learning rate, and optionally evaluates validation accuracy each epoch. The primary t... | def fit(self, training_data, validation_data=None):
"""Fit (train) the Neural Network on provided training data. Fitting is
carried out using Stochastic Gradient Descent Algorithm.
Parameters
----------
training_data : tuple of list
A tuple of numpy arrays, ordered a... |
def get_dataset(dataset_name: str, transform: Callable, transform_train=None) -> Dict:
if transform_train is None:
transform_train = transform
root = "data"
if dataset_name == "sop":
from dataset import SOP
trainset = SOP(root, "train", transform_train)
testset = SOP(root, "... | This code initializes distributed training, loads a model, and performs evaluation if specified. Otherwise, it trains the model using distributed data parallelism (DDP), configuring optimizers (AdamW/SGD), learning rate schedulers (cosine/linear), and gradient accumulation. It includes data loading, loss computation, a... | def main():
if world_size >= 1:
distributed.init_process_group(backend="nccl")
if args.eval:
model, transform_clip = unicom.load(args.model_name)
model = model.cuda()
model = WarpModule(model)
dataset_dict: Dict = get_dataset(args.dataset, transform_clip)
score =... |
def sendString(s):
try:
oculusock.sendall(s+"\r\n")
except socket.error:
restart("socket send error, restarting in 30 sec",30)
print("> "+s)
def waitForReplySearch(pattern):
while True:
try:
servermsg = (oculusfileIO.readline()).strip()
print(servermsg)
if re.search(pattern, servermsg, re.IGNORECAS... | The function rotates a robot, adjusts lighting based on ambient light levels, initiates motion detection, waits up to 10 seconds for motion, and returns detected motion data or an empty string if none. | def rotateAndCheckForMotion():
result=""
# rotate a bit
sendString("move right")
time.sleep(turnseconds)
sendString("move stop")
time.sleep(0.5) # allow to come to full stop
# if too dark, turn lights on
sendString("getlightlevel")
s = waitForReplySearch("getlightlevel:")
lightlevel = int(re.findall("\d+... |
def generate_name(self):
return self.names[randint(0, len(self.names)-1)]
def generate_surname(self):
return self.surnames[randint(0, len(self.surnames)-1)]
def generate_partonymic(self):
return self.patronymic[randint(0, len(self.patronymic)-1)]
def generate_job_position(self):
return s... | The main task of the code is to generate a synthetic user profile by combining randomly selected attributes like name, surname, patronymic, job, email, login, and gender. It returns a structured dictionary with these details, using helper methods for each component and introducing randomness in email/login selection an... | def generate_user(self):
name = self.generate_name()
surname = self.generate_surname()
patron = self.generate_partonymic()
return {
"name": name,
"surname": surname,
"patronymic": patron,
"job": self.generate_job_position(),
"ma... |
def display_query_menu():
print("option 1 is selected\n")
print("1. Display all customers\n")
print("2. Display all tools (optionally by job)")
print("3. Display all rentals (optionally by customer)")
innerinput=input("Enter your option please\n")
if innerinput=='1':
allCosto... | The code defines a main menu for managing tool rentals, allowing users to query data, insert new rentals, delete existing ones, or exit. It loops until the user selects 'x', handling each option by calling corresponding functions like display_query_menu, customerInsert, and deleteRowofTable. | def display_main_menu():
userinput=0
while userinput!="x":
print("1. Queries (sub-menu)")
print("2. Insert tool rental")
print("3. Delete tool rental")
print("x. Exit")
userinput=input("Enter your option please\n")
if userinput=='1':
display_query... |
def fastq_iterator(fastq_filename):
if re.search(".gz$", fastq_filename):
fh = gzip.open(fastq_filename, "rt", encoding="utf-8")
else:
fh = open(fastq_filename, "rt", encoding="utf-8")
have_records = True
while have_records:
try:
readname = next(fh).rstrip()
... | This code trims polyA tails from sequencing reads (single-end or paired-end) using configurable parameters. It processes input FASTQ files, applies trimming rules based on match/mismatch scores and minimum length thresholds, writes trimmed reads to output files, and tracks trimming outcomes via counters. | def main():
parser = argparse.ArgumentParser(
description="strips polyA from reads", formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("--left_fq", required=True, type=str, help="left fastq file")
parser.add_argument("--right_fq", required=False, type=str, help="righ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.