dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_mask_info(
self,
cat_to_max_inst,
img_list,
image,
scale_range,
enhancer_range,
scale,
total_num_instances,
all_img_arr,
binary_mask_arr,
all_category_ids,
):
"""
This function gets the mask info for each... | The main task of the code is to generate composite images by combining multiple source images using random scaling, flipping, and mask-based overlays. It creates synthetic images with COCO annotations, applies color augmentation, adds a random background, and saves the results. The process involves selecting and mergin... | def combine_operations(
self,
num_images,
scale_range,
image_list,
enhancer_range,
target_dir,
ann_id_sem,
coco_sem,
):
"""
Perform combine operations
"""
for i in tqdm(range(num_images)):
# scale factor for... |
def maybe_pickle(data_dirs, force=False):
dataset_names = []
for dir in data_dirs:
set_filename = dir + '.pickle'
dataset_names.append(set_filename)
if os.path.exists(set_filename) and not force:
# You may overwrite by setting force=True
print('%s already present ... | The main task of the code is to preprocess image datasets by splitting them into training, validation, and test sets, shuffling the data, and saving the processed datasets in compressed pickle files. It organizes cropped and augmented images from specified directories, merges subsets with defined sizes, randomizes samp... | def main():
train_dirs = [os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'train') for class_name in CLASS_NAME]
test_dirs = [os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'test') for class_name in CLASS_NAME]
train_datasets = maybe_pickle(train_dirs)
test_datasets = maybe_pickle(test_dirs)
vali... |
def expected_value(random_variable):
return reduce((lambda x, y: x + y), random_variable) / len(random_variable)
def sample_variance(random_variable):
return expected_value(np.square(random_variable)) - pow(expected_value(random_variable), 2)
def unbiased_sample_variance(random_variable):
n = len(random_var... | The code reads a dataset, computes descriptive statistics (expected values, variances, standard deviations) for wind speed and temperature, calculates confidence intervals for these parameters, and performs hypothesis tests comparing the expected values of wind speed and temperature. It uses both known and unknown vari... | def main():
with open('eighthr.txt', 'r') as file:
df = pd.read_csv(file, na_values=['?'])
df = df.dropna()
wind_speed = list(map(float, df.iloc[:, 26]))
temperature = list(map(float, df.iloc[:, 52]))
alpha = 0.05
wind_speed_expected = expected_value(wind_speed)
tempera... |
def parse_file(file_name, first_attribute_column, second_attribute_column):
first_attribute = []
second_attribute = []
with open(file_name, 'r') as file:
for line in file:
parsed_data = line.split(',')
if parsed_data[first_attribute_column] != '?' and parsed_data[second_attri... | The main task of the code is to perform linear regression analysis on wind speed and temperature data from a file. It converts parsed string data into numeric arrays, trains a LinearRegression model to predict temperature based on wind speed, calculates statistical metrics (mean, variance, standard deviation, correlati... | def main():
wind_speed, temperature, parsed_data_size = parse_file('eighthr.txt', 26, 52)
# converting string lists to numeric lists
wind_speed = list(map(float, wind_speed))
temperature = list(map(float, temperature))
# converting data to 2-dimensional arrays in order to work with them
# beca... |
def generator(self):
G = Generator()
G.build(input_shape=(None, self.img_size[0], self.img_size[1], self.img_ch))
G.summary()
return G
def discriminator_adv(self):
D_adv = Discriminator(self.ch, self.n_dis, self.sn)
D_adv.build(input_shape=(None, self.img_size[0], self.im... | This code trains a Generative Adversarial Network (GAN) to generate cartoon-style images. It initializes the generator with content loss, then alternates between training adversarial and textural discriminators alongside the generator using Adam optimizers. The model saves checkpoints, validates outputs, and logs train... | def train(self):
""" Input Image"""
# load_images returns iterator to a set of images based on the batch size
real_img_op, cartoon_img_op, cartoon_smooth_op = self.real_image_generator.load_images(), \
self.cartoon_image_generator.load_im... |
def get_synonyms(*words):
"""Get synonyms of one or more words."""
if not ENABLE_API:
with open(TEST_DATA_FILE, 'r') as json_file:
test_data = json.load(json_file)
return test_data
results = {}
for word in words:
results[word] = get_synonyms_from_bighugelabs(word)
... | The code's main task is to fetch synonyms for input words, display a summary, and allow users to save the results in TXT or JSON format via terminal interaction. It uses the curses library for screen management, processes command-line arguments, and provides options for file export before exiting. | def main(screen):
words = sys.argv[1:]
max_y, max_x = screen.getmaxyx()
curses.curs_set(0)
screen.addstr(max_y - 1, 0, "Fetching results ...")
screen.refresh()
synonyms = get_synonyms(*words)
shortlist = start_shortlisting(screen, synonyms)
show_summary(synonyms, shortlist, screen)
... |
def open_yt(self):
try:
if self.connection():
self.driver.get(self.ytLink)
self.driver.implicitly_wait(10)
else:
self.open_yt()
except WebDriverException as error:
logger.critical(error.msg + "\n")
raise
def ... | The code automates YouTube interaction by opening the platform, accepting cookies, searching for "music" videos, skipping ads, and logging the process. Its main task is to streamline video search and ad bypass on YouTube with logging for tracking progress. | def run(self):
logger.info("Incepe executarea deschiderea yt")
self.open_yt()
self.agree_cookies()
self.search_for_video("music")
self.skip_ad()
logger.info("S-a executat deschiderea yt") |
def event_mouse(self, event):
"""Determine what happens if mouse keys are pressed. Used to select squares and solve.
"""
if event.type == pygame.MOUSEBUTTONDOWN:
row_num = None
col_num = None
# curr_square = Rect()
curr_x = event.pos[0]
... | The main task of the code is to initialize and display a grid-based game interface with a "SOLVE" button, draw a grid structure using horizontal and vertical lines, and handle user interactions (mouse clicks and key presses) for input. It continuously updates the display and checks for events to manage game logic, such... | def main(self):
"""Main method to keep program running.
"""
self.screen.fill(self.white)
self.solve_button = Rect(200, 500, 150, 100)
pygame.draw.rect(self.screen, self.blue, self.solve_button)
text_surface = self.text_font.render("SOLVE", True, self.black)
self... |
def close(self):
"""Close the environment and stop the SUMO simulation."""
if self.sumo is None:
return
# if not LIBSUMO:
# traci.switch(self.label)
# traci.close()
if self.disp is not None:
self.disp.stop()
self.disp = None
... | This code resets the simulation environment for a new episode, initializing traffic light controllers based on the specified mode (e.g., phase duration control or real-time phase switching), tracking metrics, and preparing the environment for interaction. It handles seed setting, simulation startup, state observation s... | def reset(self, seed: Optional[int] = None, **kwargs):
"""Reset the environment."""
super().reset(seed=seed, **kwargs)
if self.episode != 0:
self.close()
self.save_csv(self.out_csv_name, self.episode)
self.episode += 1
self.metrics = []
if seed i... |
def get_harmonics (self):
'''
returns amount of harmonics
'''
harmonics = int(self.instrument[0][0])
return harmonics
def get_amplitude (self):
'''
Returns a dictionary, where the keys are the harmonics and the values are the amplitudes
'''
harmoni... | The function generates a musical note signal by summing harmonic sine waves. It calculates time points, initializes an output array, retrieves harmonic frequencies and amplitudes, and constructs the note by adding weighted sine waves for each harmonic. The result is modulated using a helper method, scaled down, and ret... | def gen_tone(self, frec, end , tstart = 0):
'''
Creates an array of the notes signal that contains the sum of the harmonics given
the sample rate
PARAMS:
-> frec: frecuency of the note
-> end: time of duration of the note complete (atack, sustained and decay)
-> ... |
def get_learner(learner) -> Learner:
if isinstance(learner, type):
# TODO: Do this for any Callable? (Need distinguish with callable instance)
learner = learner()
return learner
def get_xy_factory_for_estimator(estimator: Estimator) -> XYFactory:
kind = estimator_kind(estimator)
if isin... | This function measures the equivalence between two machine learning models by fitting them on provided data, applying a specified model action (or default), and scoring the similarity of their outputs using a given scorer (or default). It handles various estimator types and allows customization of data, actions, and sc... | def learner_equivalence(
learner_1, learner_2, xy=None, model_action=None, equivalence_scorer=None
):
"""Returns an score that measures how much the two learners are equivalent.
The user can specify what data to use (`xy`) to fit the learners,
what action to take on the fitted model (`model_action`),
... |
def write_suggestions_to_file(suggestions):
print("Writing suggestions to file...")
with open('suggestions.txt', 'w') as f:
for suggestion in suggestions:
file_path = suggestion['file']
suggestion_text = suggestion['suggestion']
f.write(f"File: {file_path}\n\n{suggest... | The main task of the code is to process a list of suggestions by writing them to a file, retrieving associated file paths and dictionaries, reading original code from those files, and applying each suggestion to the code. It handles errors like invalid suggestions, file access issues, and permission errors by skipping ... | def implement_suggestions(suggestions):
write_suggestions_to_file(suggestions)
for suggestion in suggestions:
try:
file_path, dictionary = get_file_path_and_dictionary(suggestion)
except ValueError as e:
print(e)
continue
try:
origina... |
def get_window_size(model):
if model == 'gpt3':
return 3000
elif model == 'gpt4':
return 7000
else:
raise ValueError("Invalid model specified.")
def check_elapsed_time(remaining_time, suggestions):
return remaining_time <= 0 and len(suggestions) > 0
def generate_dependency_graph(... | (The main task of the code is to analyze a codebase by fetching code snippets from a database, generating improvement suggestions using an AI model (e.g., GPT-4), managing rate limits, handling dependencies between files, and collecting unique suggestions while adhering to a 60-second execution window. The function ite... | def analyze_and_suggest_improvements(batch_size=100, model='gpt4'):
suggestions = set() # Initialize an empty set to store unique suggestions
window_size = get_window_size(model)
# Initialize counters for rate restrictions
user_requests_hourly = 0
user_request_timestamps = []
start_time = time... |
def set_text(progress_bar_text):
progress_bar.set_text(progress_bar_text)
gtk.main_iteration_do(False)
def guides_for_transparent(image, layer, loop_index, direction_priority):
if layer.name in has_no_guides_map:
return
has_no_guides = True
prioritize_vertical = direction_priority == VERTIC... | The main task of the code is to process an image by iteratively detecting and applying "guillotine" cuts to layers based on direction priorities, resizing the image to accommodate all layers, centering/aligning them, and removing backgrounds. It loops until no more cuts are needed, then finalizes layer positioning and ... | def sprite_guillotine(image, drawable, direction_priority, vertical_align, remove_bg_color, stop_after_initial):
image.undo_group_start()
prev_elapsed_time_sec = 0
loop_index = 0
keep_looping = True
while keep_looping:
loop_index = loop_index + 1
loop_text = 'Guillotine Loop #%d: ' %... |
def remove_correlated_features(df, drop_percentage):
log.debug("Computing correlation matrix")
corr = df.corr()
corr_relevant = corr.where(np.triu(np.ones(corr.shape), k=0) == 1)[corr != 1][
corr >= drop_percentage
]
unstacked = corr_relevant.unstack() # MxM Matrix to hierarchical index
... | The main task of the code is to preprocess structured data by cleaning irrelevant columns, handling missing values, denoising numerical features, reshaping time-series data into a wide format, and separating features into float and categorical numpy arrays for model input. It includes steps like removing correlated fea... | def preprocess(self, X, y=None):
# If any remnants from importing csv are in, delete.
junk_columns = [x for x in X.columns if 'Unnamed' in x]
for col in junk_columns:
log.debug(f'Deleting junk column: {col}')
X = X.drop(col, axis=1)
# TODO is it smart to attempt t... |
def possible_sums(total, max_leaf):
unique_partitions = set()
for partition in generate_partitions(total, max_leaf):
for perm in set(permutations(partition)):
if perm[0] == 1:
unique_partitions.add(perm)
return unique_partitions
def partition_to_matrix(partition):
ma... | The code generates all possible tree structures for a given number of nodes `n` and maximum leaf constraint `max_leaf`. It first computes valid partitions of `n` using `possible_sums`, converts each partition to an adjacency matrix via `partition_to_matrix`, constructs trees with `build_tree`, and collects their JSON r... | def make_all_trees(n, max_leaf) -> list:
"""
returns a list of all possible trees for a given n and max_leaf
:param n:
:param max_leaf:
:return:
"""
partitions = possible_sums(n, max_leaf)
trees = []
for partition in partitions:
matrix = partition_to_matrix(partition)
... |
def board_print(board):
for i in range(3):
print(board[i])
def get_indices(list2d, item):
for i in range(3):
for j in range(3):
if list2d[i][j] == item:
return i, j
def can_swap(zero_index):
cswapx = can_swap_x(zero_index[0])
cswapy = can_swap_y(zero_index[1])... | The code implements the A* algorithm with Manhattan heuristic to solve a sliding tile puzzle, exploring states by expanding the frontier, checking for the goal state, and generating new states through valid swaps, returning True if the goal is found and False otherwise. | def a_star_manhattan():
g_n = 0
cost = 0
while frontier:
frontier_boards = []
print('$$$$$$$$$$$$$$ frontier now $$$$$$$$$$$$$$$$$$$$:')
i = 0
for b in frontier:
i += 1
print('##### board number ' + str(i))
board_print(b[1])
fro... |
def board_print(board):
for i in range(3):
print(board[i])
def get_indices(list2d, item):
for i in range(3):
for j in range(3):
if list2d[i][j] == item:
return i, j
def can_swap(zero_index):
cswapx = can_swap_x(zero_index[0])
cswapy = can_swap_y(zero_index[1])... | This code implements the A* search algorithm using the Euclidean heuristic to solve a sliding puzzle problem. It explores states by prioritizing nodes with the lowest f(n) = g(n) + h(n), where g(n) is the path cost and h(n) is the Euclidean distance heuristic. The algorithm tracks explored states, generates new states ... | def a_star_euclidean():
g_n = 0
cost = 0
while frontier:
frontier_boards = []
print('$$$$$$$$$$$$$$ frontier now $$$$$$$$$$$$$$$$$$$$:')
i = 0
for b in frontier:
i += 1
print('##### board number ' + str(i))
board_print(b[1])
f... |
def get_folder_settings():
folder_settings = [[sg.Text("Folders", font=("", 15))]]
for folder_field in FOLDER_FIELDS:
folder_setting = get_folder_setting(folder_field)
folder_settings.append(folder_setting)
return folder_settings
def get_other_settings():
sweep_dur_default = sg.user_sett... | The code creates a GUI settings window with tabs for folder settings, state files, and amplitude corrections, including Save/Cancel buttons. | def get_settings_window(inst):
folder_settings = get_folder_settings()
other_settings = get_other_settings()
main_section = [
*folder_settings,
[sg.HorizontalSeparator()],
*other_settings,
]
sate_files_section = get_state_files_section()
band_setup_section = get_band_se... |
def validate_filename(inst, inst_out_folder, filename):
error_message = ""
# NOTE: these extensions are the ones used in the record_band function
# if the extensions in that function change, so should these
extensions = ["csv", "png"]
new_filenames = [f"{filename}.{ext}" for ext in extensions]
o... | The main task of the code is to execute a band instrument test by validating input settings, preparing the instrument, recording data, and saving results. It checks filename conflicts, prepares the band with specified settings, records and adjusts measurements, waits for alerts to clear, and saves trace/screenshot data... | def run_band(inst, settings, band_key, run_filename, save=True):
inst_out_folder = settings["-INST OUT FOLDER-"]
local_out_folder = settings["-LOCAL OUT FOLDER-"]
sweep_dur = float(settings["-SWEEP DUR-"])
# GET THE FILENAME AND CHECK FOR CONFLICTS
if save:
error_message = validate_filename... |
def get_settings_window(inst):
folder_settings = get_folder_settings()
other_settings = get_other_settings()
main_section = [
*folder_settings,
[sg.HorizontalSeparator()],
*other_settings,
]
sate_files_section = get_state_files_section()
band_setup_section = get_band_se... | This function launches a settings window to let users select a folder, update related fields, validate settings upon saving, and returns whether changes were made. It handles user interactions like folder selection, validation errors, and saves settings if valid, closing the window afterward. | def launch_settings_window(inst):
window = get_settings_window(inst)
settings_changed = False
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, "Cancel"):
break
if event == "-CORR FOLDER-":
filenames = get_folder_files(inst, values["-CORR F... |
def mid_val(ll): # similar to median, when even number of values takes the larger 'middle' value
sl = sorted(ll)
item = None
while len(sl) >= 2:
item = sl.pop()
sl.pop(0)
if len(sl) == 1:
return sl[0]
else:
return item
def update_m... | The function `one_d_model` fixes specified parameters (`others`) to their mid-values, updates a model with these fixed parameters alongside a given variable, and returns the decoded model results. It adjusts input parameters to analyze model behavior under controlled conditions. | def one_d_model(variable, others):
fixed = list(slider_vals)
for other in others:
col_ix = selectable_columns.index(other)
fixed[col_ix] = mid_val(selectable_columns_values[col_ix])
models = update_model(variable, None, sel_metric, sel_compare, sel_repeat, *fixed)
... |
def generate_patch_image_cv(cvimg, c_x, c_y, bb_width, bb_height, patch_width, patch_height, do_flip, scale, rot):
img = cvimg.copy()
img_height, img_width, img_channels = img.shape
if do_flip:
img = img[:, ::-1, :]
c_x = img_width - c_x - 1
trans = gen_trans_from_patch_cv(c_x, c_y, bb... | This function processes an input image by cropping it around a specified bounding box, applying transformations, and adjusting 2D keypoints. It handles various image formats (file path, tensor, numpy array), generates a cropped image patch, converts it to a tensor, and returns the cropped image, original raw image, and... | def get_single_image_crop_demo(image, bbox, kp_2d, scale=1.2, crop_size=224):
if isinstance(image, str):
if os.path.isfile(image):
image = cv2.cvtColor(cv2.imread(image), cv2.COLOR_BGR2RGB)
else:
print(image)
raise BaseException(image, 'is not a valid file!')
... |
def get_cloud_quotes_quantity(category):
soup= makeSoup(f'https://www.goodreads.com/quotes/tag/{category}?page=1&utf8=%E2%9C%93')
res= soup.find('span' ,class_='smallText')
results= res.text
if results:
tmp_str_val= ''
final_extracted_val= int()
for indx in range(len(results)-1,8... | The function retrieves a specified number of quotes from a given category. It checks if the requested quantity is valid, verifies available data, and scrapes either single or multiple pages based on the quantity, handling cases where data is insufficient or exceeds limits. | def get_quotes(category,quantity):
if quantity< 1:
print('please enter a greater number than 0')
return
cloud_quotes_quantity,soup= get_cloud_quotes_quantity(category)
if cloud_quotes_quantity <=0:
print(f"Sorry! we can't find any data for that Query. \nPlease Enter proper category l... |
def getActivity(self, dt):
wday, t = self.getScheduleDayTime(dt)
if wday == None:
return None
try:
day = self.timetable[wday]
except KeyError:
return None
if t < day[0][0]:
return None
current_ac = None
... | The main task of the code is to determine the next free time period by checking existing activities and subsequent activity slots. It first retrieves an activity, then finds the next free slot. If valid, it combines the date with the result or original time, checks for the next activity slot, and returns the first and ... | def getNextFreePeriod(self, dt):
first = self.getActivity(dt)
if first != None:
first = self.getNextFreeSlot(dt)
if first != None:
first = first[0]
second = self.getNextActivitySlot(datetime.datetime.combine(dt.date(), first or dt.time()))
if sec... |
def create_background_model(vid, begin_offset=1, end_offset=50, step=10):
vid_len = vid.get_length() - end_offset - begin_offset
try:
frame_size = vid.get_meta_data()["size"]
except Exception as e:
import pdb; pdb.set_trace()
background_model = np.zeros([frame_size[1], frame_size[0], ... | The main task of the code is to process a video file by extracting a background model, estimating activity through frame analysis, generating visualizations like activity plots and difference images, and saving cropped frames based on activity thresholds. It handles input/output paths, applies filters, and logs results... | def run_one(self, fn: Path):
"""
"""
report: Report = self.report
logger.info(f"reading file {fn}")
vid = imageio.get_reader(fn)
fnrel = fn.relative_to(self.input_path.expanduser())
fnrel.parent
odirpath = self.output_path / fnrel.parent
odirpath.m... |
def iter_entries(self) -> Iterable[dict]:
# Iterate over entries in strucures.
_structure = self.structure()
for entry in self.__iter_dict(_structure):
if isinstance(entry, dict):
if 'schema' in entry:
yield entry
else:
... | This function filters and yields unique entries from a system based on provided filters. It uses a hash to track yielded entries, ensuring each is processed once. If filters are provided, it maps system keys to hierarchy keys, checking if all filter conditions match the entry's sanitized paths. Entries without filters ... | def iter_filter(self, **filters) -> Iterable[dict]:
# Iterate over entries where key is in schema, and filters are OK
# Track what entries have been yielded
yielded: Counter = Counter()
_hash: Callable = lambda key: sum((hash(k) for k in entry['schema'].keys())) + hash(entry['path'])
... |
def filterByName(*args):
dbTree.delete(*dbTree.get_children())
for card in oracleDB:
if cardName.get().upper() in card['name'].upper():
addDBItem(card)
selectDBTop()
def select(event):
global lastCard
if event is None:
return
widget = event.widget
if type(widget) ... | The code defines a `refresh` function that triggers UI updates based on focus and search input. It filters data by name, selects items, displays images if available, and schedules itself to rerun every second using `root.after(1000, refresh)`, creating a continuous refresh loop. | def refresh(event = None):
if root.focus_get() == cin and simpleSearch.get():
filterByName()
select(event)
if imgDB:
placeImgDB()
root.after(1000, refresh) |
def parseTitle (self):
title = self.soup.find("h1", {"class": "entry-title"})
if title == None:
return False
text = title.text
text = re.sub(r'\([^)]*\)', ' ', text) # get rid of parentheticals (items within parens and parens)
text = re.sub(r"[^a-zA-Z0-9/().]+", ' ', ... | The main task of the code is to parse recipe data by sequentially validating title, ingredients, and steps. If any parsing step fails, it returns False. Non-essential fields like yield and tags are parsed optionally without affecting the overall result, which returns True only if all essential parsing steps succeed. | def parse (self):
if self.parseTitle() == False:
return False
if self.parseIngredients() == False:
return False
if self.parseSteps() == False:
return False
# non essential fields below
self.parseYield() # fills in with most common
self... |
def parseTitle (self):
if self.soup.find("h1") == None:
return False
self.title = self.soup.find("h1", {"class": "o-AssetTitle__a-Headline"}).text.strip()
return True
def parseIngredients (self):
has_ingredients = self.soup.select(".o-Ingredients__a-Ingredient")
... | The main task of the code is to parse structured data by sequentially validating and extracting essential components: title, ingredients, and steps. If any essential parsing step fails, it returns False. Non-essential fields like yield and tags are processed afterward but do not affect the overall success, returning Tr... | def parse (self):
if self.parseTitle() == False:
return False
if self.parseIngredients() == False:
return False
if self.parseSteps() == False:
return False
# non essential fields below
self.parseYield() # fills in with most co... |
def createInput (self):
input = self.raw["keywords"]
self.result += "<INPUT_START> "
i = 0
for i in range(len(input)-1):
self.result += input[i]+ " <NEXT_INPUT> "
self.result += input[i+1]+ " <INPUT_END> "
def createYield (self):
self.result += "<YIELD_START> ... | The main task of the code is to construct a formatted recipe string by sequentially appending sections like input, yield, ingredients, steps, and title to a result variable, enclosed within `<RECIPE_START>` and `<RECIPE_END>` tags. The `buildString` method orchestrates this by calling specialized methods to generate ea... | def buildString (self):
self.result = "<RECIPE_START> "
self.createInput()
self.createYield()
self.createIngredients()
self.createSteps()
self.createTitle()
self.result += "<RECIPE_END>" |
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board):
# Check rows
for row in board:
if row.count(row[0]) == len(row) and row[0] != ' ':
return True
# Check columns
for col in range(len(board[0])):
if all... | This code implements a Tic-Tac-Toe game where a human player (X) competes against an AI (O). The game alternates turns, validates player input, checks for wins/ties after each move, and displays the board state. The AI uses a predefined `get_best_move` function to determine its moves, while the human inputs coordinates... | def play_tic_tac_toe():
board = [[' ' for _ in range(3)] for _ in range(3)]
while True:
print_board(board)
# Player's move
while True:
row = int(input("Enter the row (0, 1, or 2): "))
col = int(input("Enter the column (0, 1, or 2): "))
if board[row][... |
def get_first_ray(self, X, data_cases, continuation='v', dl=0.25):
'''
args:
* X (1D-array): Array containing every point in X to be solved.
* data_cases (2D-array): A 2D array containing 2 cases to calculate\
both velocities for known and desired case. Every case mus... | The function uses Newton's method to iteratively solve for ray paths by adjusting positions (X_sol) based on a Jacobian matrix and phi array, continuing on velocities or receivers until the solution converges within a specified tolerance. It returns the computed ray interaction points with interfaces. | def newton_solve(self, data_cases, tol=1e-3, continuation='v'):
'''
args:
* data_cases (2D-array) : List of 'P' and 'S' related to known first ray.
* tol (float) : Error for calculations.
* continuation (string) : Must be either 'v' for applying continuation on\
... |
def epsilon_closure(self, srcs: t.Set[int]) -> t.Set[int]:
"""
Get the set of states reachable from the states in `srcs` via only
epsilon transitions.
"""
frontier = srcs.copy()
# Don't revisit these states
visited = set()
while True:
# Visit u... | The main task of the code is to remove epsilon transitions from an NFA-e (non-deterministic finite automaton with epsilon transitions) by propagating transitions and accept states through epsilon closures, then eliminating remaining epsilon transitions and unreachable states, converting the NFA-e into an equivalent NFA... | def remove_epsilon_transitions(self) -> "Nfa":
"""
Convert this NFA-e into an NFA. This mutates and returns the current
object. To create a new NFA from this NFA-e object, see
`Nfa.without_epsilon_transitions`.
"""
for state in self.states_:
if state not in se... |
def gaussian_kernel(self,_sigma)->np.ndarray:
#x, y = np.mgrid[-1:2, -1:2]
#n = [[-1, 0, 1]]
n=[np.arange(-np.round(self.kernel_size/2), np.round(self.kernel_size/2))]
kernel = -1*np.sign(n)*np.e**(-1 * _sigma*np.abs(n))
#print(kernel)
kernel = kernel/np.linalg.norm(kerne... | This code performs iterative superpixel merging using gradient and LoG features. It computes image gradients, applies a Gaussian kernel, and repeatedly merges superpixels until the number stabilizes (change <5). The process updates the image's mean representation, adjusts sigma (smoothing parameter) and threshold (merg... | def merge(self, _kernel_size,threshold=30):
self.threshold=threshold
self.kernel_size=_kernel_size
self.kernel=self.gaussian_kernel(self.sigma)
self.compute_feat_grad()
self.compute_feat_LoG()
self.compute_gradient()
old=99999999
new=self.superPixelNum
... |
def __verify_tuple__(self,tup):
"""
Trust, but verify. Check the tuple and its elements provided by user
:param tup: tuple
:return list of int, containing 0 for success - 1 otherwise.
"""
tstatus = []
if not isinstance(tup,tuple):
print(f"Provided para... | The code adds a new attribute to a file, creating it if it doesn't exist or appending if it does. It validates the input tuple, checks for duplicate attributes, and writes the attribute as a string to the file. It returns a list of integers indicating success (0) or failure (1) based on validation, uniqueness, and file... | def add(self,tup, sname):
"""
Record new attribute to file. If file doesn't exist - new file with file name (fn) created
and attributes are written to file
If file exist - attributes are appended to existing file
:param tup: tuple, consisting - tup[0] - attribute name type('s'),
... |
def __verify_tuple__(self,tup):
"""
Trust, but verify. Check the tuple and its elements provided by user
:param tup: tuple
:return list of int, containing 0 for success - 1 otherwise.
"""
tstatus = []
if not isinstance(tup,tuple):
print(f"Provided para... | This function updates a specific attribute's value in a database file by executing an SQL UPDATE statement. It verifies the input tuple, checks if the database exists, ensures the attribute name exists, and applies the new value. It returns the count of updated rows (1 on success) or -1 for errors like invalid input, m... | def update(self,tup,new_val,sname,/):
"""
Updates attribute's value
:param tup: tuple
:param new_val: new value to set (string)
:param sname: file name (string)
:return: for success - count of updated row (actually 1)
'-1' -otherwise
"""
... |
def __should_create_leaf_node(self, feature_matrix, labels):
if len(set(labels)) == 1:
return True
if len(feature_matrix.drop_duplicates()) == 1:
return True
if len(labels) < self.min_samples_split:
return True
return False
def __create_leaf_node(self,... | This function recursively constructs a decision tree by sampling features, determining optimal splits, and creating leaf nodes when necessary. It checks if a leaf should be formed, samples features, finds the best split parameters, partitions data, and recursively builds left/right children. If splits result in empty s... | def __build_tree_mia(self, feature_matrix, labels):
if self.__should_create_leaf_node(feature_matrix, labels):
return self.__create_leaf_node(labels)
sampled_columns = self.__get_feature_sample(feature_matrix)
if sampled_columns is None:
return self.__create_leaf_node(la... |
def __build_tree_otfi(self, feature_matrix, labels):
if self.__should_create_leaf_node(feature_matrix, labels):
return self.__create_leaf_node(labels)
sampled_columns = self.__get_feature_sample(feature_matrix)
if sampled_columns is None:
return self.__create_leaf_node(l... | The main task of the code is to construct a decision tree's root node using different algorithms based on the specified method. If the method is 'otfi' or 'mia', it calls specialized tree-building functions (`__build_tree_otfi` or `__build_tree_mia`), otherwise it uses a default `__build_tree` method. The `fit` method ... | def fit(self, feature_matrix, labels):
if self.method == 'otfi':
self.root = self.__build_tree_otfi(feature_matrix, labels)
elif self.method == 'mia':
self.root = self.__build_tree_mia(feature_matrix, labels)
else:
self.root = self.__build_tree(feature_matrix,... |
def addVelocities(mat, d):
mat1 = [[], [], [], []]
for i in range(len(mat[0])):
vels = getLidVelAt(mat, i, d)
for n in range(4):
mat1[n].append(vels[n])
lim = 20
for set in mat1:
last = set[0]
for i in range(len(set)):
if (set[i] > lim):
... | The code initializes global variables, collects data into 'trials', processes velocities for each trial, constructs network velocities, retrieves positions and lid positions, cleans 'lps', and prints "done". The main task is to prepare and process data for a simulation or analysis involving velocities, positions, and n... | def setup():
global trials, lps
for i in range(5):
trials.append(imp.getData(i + 1))
for d in range(5):
addVelocities(trials[d], d)
# print(trials[d])
constructNetVels()
getPositions()
getLidPositions()
cleanLPS()
print("done") |
def stand_up(self):
for i in range(4):
(self.legs[i].x, self.legs[i].y, self.legs[i].z) = self.legs[i].get_start_xyz()
self._commit(100)
def shift_weight_off_leg(self, id, mm=20):
if id == self.FRONT_LEFT:
self.shift_body(mm * 0.7, mm * -0.7)
elif id == self.FRONT... | The code implements a quadruped robot's walking motion by sequentially lifting and lowering each leg (BACK_RIGHT, FRONT_RIGHT, BACK_LEFT, FRONT_LEFT) while adjusting weight distribution and body position. It shifts weight off a leg, raises it, adjusts its height, lowers it, and shifts the robot's body forward, repeatin... | def walk(self):
# https://makezine.com/2016/11/22/robot-quadruped-arduino-program/
self.stand_up()
first_time = True
for _ in range(3):
self.shift_weight_off_leg(self.BACK_RIGHT, 20)
self.leg_up(self.BACK_RIGHT)
self.legs[self.BACK_RIGHT].y -= 20
... |
def change_vowels_to_0(soundexes: list[Soundex]):
update_soundex_list_with_regex(soundexes, r"""[AEIOUHWY]""", lambda regex, value: regex.sub("0", value))
def map_characters_to_digits(soundexes: list[Soundex]):
update_soundex_list_with_regex(soundexes, r"[BFPV]", lambda regex, value: regex.sub("1", value))
... | The code generates Soundex codes for alphabetic tokens by converting vowels to zeros, mapping characters to digits, removing duplicate characters, stripping zeros, and adjusting lengths to a specified maximum. It returns a list of processed Soundex objects. | def generate_soundexes(tokens: set[str], max_length: int = 4) -> list[Soundex]:
soundexes = [Soundex(token) for token in tokens if token.isalpha()]
change_vowels_to_0(soundexes)
map_characters_to_digits(soundexes)
replace_duplicates_with_one_occurrence(soundexes)
remove_all_zeros(soundexes)
chec... |
def _process_action(self, action):
action_tuple = ActionTuple(
continuous=np.reshape(action[0:self.action_space.continuous_size], (1, self.action_space.continuous_size))
)
return action_tuple
def _is_terminal(self):
decision_steps, terminal_steps = self.env.get_steps(self.beh... | The code executes a step in a reinforcement learning environment, applying an action, performing multiple substeps, and collecting observations (including goals and rewards). It checks for termination, constructs observation and info dictionaries, and resets the environment if a dense reward threshold is breached, retu... | def step(self, action=None, nsubsteps=None):
if action is not None:
self.env.set_actions(self.behavior_name, self._process_action(action))
if nsubsteps is None:
nsubsteps = self.nsubsteps
for _ in range(nsubsteps):
if self._is_terminal():
break... |
def build_mel_spectrogram_images_from_audio_file(audiofilepath, outputdirpath, window_t, min_f, max_f):
"""
Build and save mel spectrogram images built from audio file
"""
spectrograms, slices = get_mel_spectrograms_from_file(audiofilepath, window_t, min_f, max_f)
images = get_images_from_mel_spect... | The main task of the code is to recursively process audio files in a directory tree, generate spectrogram images (either Mel or standard), and save them in an output directory structure. It uses checkpointing to avoid reprocessing completed files and distributes work across ranks (e.g., for parallel processing), where ... | def navigate_directory_tree(size, rank, input_directory, output_directory, window_t=10, min_f=0, max_f=20000, mel=False):
"""
Build and save spectrogram images built from audio files from directory trees
"""
checkpoint_file_name = os.path.join(output_directory, 'Checkpoint_rank_' + str(rank) + '.txt')
... |
def import_ac(datafile: str, pg_string: str) -> bool:
fgr = BytesIO()
ac = ACfile(datafile)
ac_2 = ACfile(datafile)
while True:
try:
datadict = getAC(ac)
discipline = getACdis(ac_2)
datadict["stw"] += stw_correction(datafile)
if (
... | This function imports data files into a PostgreSQL database based on their extension, using specific handlers for .ac1, .ac2, .fba, and .shk formats. It logs the process, constructs a database connection string, checks the file type, executes the appropriate import function, and returns a dictionary with the file name,... | def import_file(
datafile: str,
host: str,
user: str,
secret: str,
db_name: str,
) -> dict[str, Any]:
logger = logging.getLogger("level0.process")
logger.setLevel(logging.INFO)
logger.info("importing file {0}".format(datafile))
pg_string = f"host={host} user={user} password={secret}... |
def rgb_to_gray(img):
"""
Converts rgb image to gray scale
Args:
img (numpy.ndarray): input image
Returns:
numpy.ndarray: gray scale version of image
"""
#extract red, green, and blue values from image
R, G, B = img[:,:,0], img[:,:,1], img[:,:,2]
#compute grayscale and... | This function computes the Histogram of Oriented Gradients (HOG) feature vector from an input image. It reads the image, converts it to grayscale, calculates gradient magnitudes and angles, and constructs the HOG feature vector using specified cell/block sizes. The function returns either normalized or non-normalized f... | def HOG(filepath, normalized = True, magnitudes = False):
"""
Computes HOG feature vector from image
Args:
filepath (string): filepath to image
Returns:
features (numpy.array): normalized HOG feature vector
"""
#read in image with RGB flag
im = cv2.imread(filepath, 1)
#... |
def nested_dict_iter(self, nested, parentKey=None):
pObj = nested
for key, value in nested.items():
ppkey = "%s,%s" % (parentKey, key)
if parentKey is None:
ppkey = key
# print(" iter.... now---> %s" % (key))
yield ppkey, key, value, pOb... | The code converts a nested data structure into a formatted string representation, handling dictionaries and lists with proper indentation and bracket closure. It uses deep copying, tracks nesting levels, and ensures correct syntax by managing open/closed braces, replacing None with "NULL", and formatting values appropr... | def dumps(self, nested):
nn = copy.deepcopy(nested)
txt = ""
prevKey = ""
spaces = " "
braces = []
brace_contexts = {}
for parentKeyString, key, value, parentObj in self.nested_dict_iter(nn):
ppKey = parentKeyString
mkey = key
... |
def nested_dict_iter(self, nested, parentKey=None):
pObj = nested
lastKey = None
for key, value in nested.items():
ppkey = "%s,%s" % (parentKey, key)
if parentKey is None:
ppkey = key
# print(" iter.... now---> %s" % (key))
yield... | This code serializes a nested data structure into a custom formatted string representation, handling dictionaries and lists with indentation and type markers. It tracks nested structures using brace contexts, adds appropriate syntax for arrays (p[...]) and dictionaries (z{...}), and ensures proper closure of nested ele... | def dumps(self, nested):
nn = copy.deepcopy(nested)
txt = ""
prevKey = ""
spaces = " "
braces = []
insideBrace = []
# wasInsideBrace = False
# insideCount = 0
prevObj = None
# prevInsideSetKey = None
brace_contexts = {}
... |
def check_audio_files(entry, name): # * Checks all Audio Files
moved_cnt = 0
for audio_extension in audio_extensions:
if name.endswith(audio_extension) or name.endswith(audio_extension.upper()):
move_file(dest_dir_music, entry, name)
logging.debug(f"Moved audio file: {name}")
... | The function `clean_downloads_folder` organizes files in a downloads directory by categorizing them into audio, video, image, and document types. It counts each category's files using helper functions, logs the number of files moved to respective destination directories, and reports the total files processed. The task ... | def clean_downloads_folder():
logging.info(f"Cleaning of: {downloads_dir} STARTED!")
# count files moved
audio_cnt = 0
video_cnt = 0
image_cnt = 0
document_cnt = 0
with scandir(downloads_dir) as entries:
for entry in entries:
name = entry.name
... |
def get_ObjVal(Tx, Ty, U_fac, lambda_regula, cla = False):
"""
Calculate the objective function value
"""
ans = 0.5 * lambda_regula * sum([np.linalg.norm(U)**2 for U in U_fac])
if cla:
res = 0
for x, y in zip(Tx, Ty):
temp_res = 1 - np.multiply(y, multi_mode_dot(x, U_fac)... | This function performs Tucker regression by iteratively estimating factor matrices U_fac from input-output tensor pairs (Tx, Ty) using gradient descent with L2 regularization. It initializes U_fac randomly or from provided values, updates each factor matrix via get_FactorU, tracks estimation error, and returns optimize... | def T_Regression(Tx, Ty, lambda_regula, U_init = None, eta = 0.1, maxiter = 10, get_history = True):
"""
Estimate factor matrices for the Tucker regression
Tx: Input Tensor in shape I1 x ... Id; list with length n
Ty: Output Tensor in shape P1 x ... Pd; list with length n
lambda_regula: regularizati... |
def get_ObjVal(Tx, Ty, U_fac, lambda_regula, cla = False):
"""
Calculate the objective function value
"""
ans = 0.5 * lambda_regula * sum([np.linalg.norm(U)**2 for U in U_fac])
if cla:
res = 0
for x, y in zip(Tx, Ty):
temp_res = 1 - np.multiply(y, multi_mode_dot(x, U_fac)... | The function `T_B_Regression` estimates factor matrices for Tucker Binary regression via alternating optimization. It takes input/output tensors (`Tx`, `Ty`), a regularization parameter (`lambda_regula`), and optional initial matrices. It iteratively updates factor matrices using a binary factorization step, applying L... | def T_B_Regression(Tx, Ty, lambda_regula, U_init = None, eta = 0.1, maxiter = 100, get_history = True):
"""
Estimate factor matrices for the Tucker Binary regression
Tx: Input Tensor in shape I1 x ... Id; list with length n
Ty: Output Tensor in shape P1 x ... Pd; list with length n
lambda_regula: re... |
def scrape_members(base):
# type: (Type) -> MembersDict
"""Scrape base for members (shallow)."""
if base is object:
return {}
base_members = {} # type: MembersDict
for name in base.__slots__:
private_name = privatize_name(base.__name__, cast(str, name))
try:
memb... | The code defines a method `__members__` that aggregates slot attributes from a class and its base classes into a dictionary. Each key is a slot name, mapping to a dictionary of classes and their corresponding slot attributes. This aids in serialization (e.g., pickling) by tracking which classes own which slots. It proc... | def __members__(cls):
# type: () -> MembersDict
"""
Get slot members by name and base. Can be used for pickling purposes.
.. code:: python
>>> from six import with_metaclass
>>> from slotted import SlottedMeta
>>> class A(with_metaclass(SlottedMeta,... |
def get_soup(url):
url_o = requests.get(url)
soup = Bsoup(url_o.text, 'html.parser')
return soup
def get_all_info(soup):
# find p tag with text "Length:"
len_tags = soup('p', text="Length:")
# get info from each of them
info = {}
for tag in len_tags:
result = find_everything(tag)... | The main task of the code is to scrape data from multiple URLs by iterating through a list, extracting information using `get_all_info`, tracking processing time for each URL, and aggregating results into a dictionary. It also provides real-time progress updates with estimated completion time. The function returns a di... | def all_page(urls):
differnt_GIs_info = {}
count = 0
oldtime = []
lens = len(urls)
for url in urls:
start = datetime.datetime.now().timestamp()
URL = urls[url]
soup = get_soup(URL)
dic = get_all_info(soup)
differnt_GIs_info[url] = dic
count += 1
... |
def get_all_url(model_url, pages):
all_URLs = []
for r in range(pages[0], pages[1]):
url = model_url + str(r*300)
all_URLs.append(url)
return all_URLs
def get_soups(urls):
soups = []
for url in urls:
url_o = requests.get(url)
soup = Bsoup(url_o.text, 'html.parser')
... | The code scrapes genetic element data from a database by generating URLs for specified pages, extracting IDs from HTML content, fetching detailed information using those IDs, cleaning the data, and writing the results to a table. | def main(argv):
# settings
model_url_list = "http://pedant.helmholtz-muenchen.de/pedant3htmlview/pedant?Method=geneticelements&Db=p3_p116_Ara_thali&GeneticelemType=all&Offset="
model_url_page = "http://pedant.helmholtz-muenchen.de/pedant3htmlview/pedant?Method=ReportGeneData&Db=p3_p116_Ara_thali&Name=blastpsel... |
def _train_step(self, X, Y, t, U, X_col, Y_col, t_col):
U_pred = self.net_U(X, Y, t)
F_S, F_E, F_I, F_R = self.net_F(X_col, Y_col, t_col)
assert U.shape == U_pred.shape
loss1 = torch.mean( (U-U_pred)**2, dim=0)
assert loss1.shape == (4,)
loss2 = (torch.... | The code trains a neural network using Adam optimizer over multiple epochs, managing two loss components (loss_U and loss_F) with dynamic weight adjustment during a warm-up phase. It tracks gradients for parameters (beta, gamma, a, etc.), updates model weights via backpropagation, and records training metrics (losses, ... | def train(self, epochs):
self.net.train() # training mode
self.history = {'loss1':[], 'loss2':[], 'nX':[], 'beta':[], 'gamma':[], 'a':[]}
self.wu, self.wf = 1, 1
grad_U_mean, grad_F_mean, grad_nX_mean = 1, 1, 1
self.grad_U = {'epoch':0}
self.grad_F = {'epoch':0}
... |
def load_table_L():
"""Table L: Electricity consumption"""
# 4 unnecessary rows at the top, column A is empty
df = pd.read_excel("Australian Energy Statistics 2022 Table L.xlsx",
sheet_name = "Aus",
skiprows = 4,
usecols = "B:J")
# Remove the row that just says "GWh"
df.drop(index = 0, inplace = True)
... | (The main task of the code is to load electricity and gas consumption/generation data from pandas DataFrames into a database, inserting records into `regions`, `energy_consumption`, and `energy_generation` tables. It first creates region entries, then iterates through regions and years to insert consumption and generat... | def load_data_into_db(connection):
elec_consumption_df = load_table_L()
elec_generation_df = load_table_O()
gas_consumption_df, gas_generation_df = load_table_Q()
region_to_id = {"Australia": 1, "Victoria": 2, "New South Wales": 3, "Queensland": 4, "South Australia": 5, "Northern Territory": 6, "Western Australia"... |
def search(self, new=True):
if (new):
query = self.searchEntry.get()
try:
self.WebEnv, self.Key, self.rescount = api.searchdb(query, self.database.get().lower(), sort=self.sort.get())
except ValueError:
self.alert("'"+self.dbEntry.get()+"' is n... | The code creates a GUI search interface with a search bar, database selector, sort options, and pagination controls. It binds the Enter key to trigger a search, updates sort options dynamically based on the selected database, and manages pagination with left/right buttons. The layout uses grid and pack for widget place... | def create_searchbar(self):
#Search entry
tk.Label(self, text="Search").grid(row=1, column=1, sticky="w")
self.searchEntry = tk.Entry(self)
self.searchEntry.grid(row=1, column=2, sticky="w")
self.searchEntry.bind("<Return>", lambda e: self.search())
#database entry
... |
def initsettings(self, default=False):
if (default):
cfg.resetsettings()
settings = cfg.loadsettings()
self.database = tk.StringVar(self, settings["database"])
self.maxresults = tk.IntVar(self, int(settings["maxresults"]))
self.links = tk.IntVar(self, settings.getint(... | This code initializes a GUI application by setting up a Tkinter frame, configuring instance variables for runtime settings, handling initial configuration with error tolerance, and creating UI components like a results box, search bar, and menu to build the application's interface and functionality. | def __init__(self, master):
tk.Frame.__init__(self, master)
self.master=master
self.pack()
#runtime settings vars
self.lastsearch = ""
self.searchindex = 1
self.rescount = 0
#ini settings vars
try:
self.initsettings()
except:
... |
def sort_rating(d: dict):
new_d = {}
for i in sorted(d.keys(), reverse=True):
new_d[i] = d[i]
return new_d
def sort_performer(lst_use: list, lst_app=[]):
for p in lst_use:
lst_use[p].sort()
for p in lst_use.values():
for n in p:
if n not in lst_app:
... | The main task of the code is to extract and process metadata from a scene object, including file paths, titles, dates, performers, studios, tags, and technical details like resolution and codecs. It organizes this information into a structured dictionary, applying formatting rules, filtering, sorting, and configuration... | def extract_info(scene: dict, template: None):
# Grabbing things from Stash
scene_information = {}
scene_information['current_path'] = str(scene['path'])
# note: contain the dot (.mp4)
scene_information['file_extension'] = os.path.splitext(scene_information['current_path'])[1]
# note: basename ... |
def __findRelationBounds(self):
# find company relation bounds
query = f"{self.allStockList[0].companyName}, {self.allStockList[1].companyName}"
self.cur.execute(f"select Final_Value from Relations where Companies = \'{query}\';")
global maxRelScore, minRelScore
maxRelScore = mi... | The code runs a GUI to visualize stock data, displaying company relations, stock change percentages, and prediction results. It uses Tkinter to create a multi-frame interface with scrollable tables, relationship graphs, and detailed analysis sections for selected stocks. The GUI includes interactive elements like butto... | def runGUI(self) -> None:
"""
Runs stock GUI to display all results, including raw stock data increase,
company relation values, and prediction values.
:return: None
"""
self.__findRelationBounds()
global root
stock_inc = []
for stock in self.a... |
def unpickle50Levels(levels):
with open('levels.pickle', 'rb') as file:
for x in range(50):
currentLevel: Level = pickle.load(file)
levels.append(currentLevel)
def loadSpecificLevel(levels, levelSelectNum):
print('Loading level ', levelSelectNum, ".", sep='')
return level... | The code loads and processes 50 levels, selects a specific level, and applies pathfinding algorithms (forwardA, backwardA, and adaptiveA) to navigate from a start to goal point. It measures execution times and node visits for each algorithm across all levels, calculates averages and standard deviations, and visualizes ... | def main():
levels = []
averageNodes = []
unpickle50Levels(levels)
levelSelectNum = input("What level from 0-49 should be loaded? ")
currentLevelSelection = loadSpecificLevel(levels, int(levelSelectNum))
#TERRAIN IS YELLOW, ITS THE 1s. IT IS LIKE A LINE, OPEN SPACES TEND TO BE MORE ROUND. ... |
def isComplete(self, result):
if not result:
return False
return len(result) == len(self.vars)
def getUnassignedVar(self, assignments):
unassignedVars = list(filter(lambda x: x not in assignments, self.vars))
sortedDomain = self.sortByMRV(unassignedVars)
biggerDomain ... | This code implements a backtracking algorithm to solve a constraint satisfaction problem. It recursively assigns values to unassigned variables, checks consistency with existing assignments, and backtracks when conflicts arise. The goal is to find a complete assignment of variables that satisfies all constraints, retur... | def backtracking(self, assignments):
if self.isComplete(assignments):
return assignments
# the main point: which var to choose?
var = self.getUnassignedVar(assignments)
# Check the possible assignments of the current character
dom = copy.deepcopy(self.vars[var].getDom... |
def sse(y, yhat):
return (residuals(y, yhat) **2).sum()
def ess(y, yhat):
return ((yhat - y.mean()) ** 2).sum()
def tss(y):
return ((y - y.mean()) ** 2).sum()
def mse(y, yhat):
n = y.shape[0]
return sse(y, yhat) / n
def rmse(y, yhat):
return math.sqrt(mse(y, yhat)) | The code calculates and returns key regression error metrics—SSE, ESS, TSS, MSE, and RMSE—using helper functions, compiling them into a pandas Series for evaluating model performance. | def regression_errors(actual, predicted):
return pd.Series({
'sse': sse(actual, predicted),
'ess': ess(actual, predicted),
'tss': tss(actual),
'mse': mse(actual, predicted),
'rmse': rmse(actual, predicted),
}) |
def sse(y, yhat):
return (residuals(y, yhat) **2).sum()
def mse(y, yhat):
n = y.shape[0]
return sse(y, yhat) / n
def rmse(y, yhat):
return math.sqrt(mse(y, yhat)) | The code calculates the sum of squared errors (SSE), mean squared error (MSE), and root mean squared error (RMSE) by using the mean of the target variable `y` as a baseline prediction. It returns these metrics in a dictionary to evaluate the performance of a simple baseline model in regression tasks. | def baseline_mean_errors(y):
yhat = y.mean()
return {
'sse': sse(y, yhat),
'mse': mse(y, yhat),
'rmse': rmse(y, yhat),
} |
def generate_points():
"""Generate random points, and ensure they are unique."""
flag = True
while flag:
points = np.vstack([[0, 0], np.random.randint(-50, 50, size=(49, 2))])
unique_points = np.unique(points, axis=0)
if unique_points.shape[0] == points.shape[0]:
flag = F... | The code evaluates simulated annealing (SA) for the Traveling Salesman Problem (TSP) by comparing it to a greedy algorithm. It runs SA multiple times with fixed parameters, collects results, sorts them by distance, and visualizes the best path and convergence. Two conditions are tested: one with 250 SA iterations and a... | def main():
np.random.seed(10) # Seed the random number generator
p = generate_points()
np.random.seed(None) # Turn off the random number generator
########################################
gpath, glength, _ = greedy_alg(p)
print("Greedy Algorithm Distance: ", glength)
# points = np.co... |
def manhattan(p1, p2):
x1, y1 = p1
x2, y2 = p2
return abs(x1 - x2) + abs(y1 - y2)
def reconstruct_shortest_path(prev_path, current, draw):
while current in prev_path:
current = prev_path[current]
pygame.time.delay(250)
current.Alien_rep()
global count
count += 1
... | This code implements the A* algorithm to find the shortest path from a start node to an end node in a grid. It uses a priority queue with f-score (g-score + heuristic) for exploration, updates predecessor paths, and reconstructs the path upon reaching the goal. Visualization is handled via Pygame, with node states upda... | def a_star(draw, grid, start, end):
count = 0
prio_queue = PriorityQueue()
prio_queue.put((0, count, start))
prev_path = {}
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] = ma... |
def make_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)
global count
for row ... | The main task of the code is to implement a game where an alien navigates a grid using the A* algorithm to find and collect gold, while avoiding pits and nanos. The code initializes a grid, randomly places gold, pits, and nano elements, handles user input for restarting/quit, and performs pathfinding when the spacebar ... | def main(win, width):
global game
ROWS = 10
grid = make_grid(ROWS, width)
global count
alienX = 0
alienY = 0
Goldx = rd.randint(1, 9) # GOLD X COORDINATE
Goldy = rd.randint(0, 9)
PitX = rd.randint(1, 9)
PitY = rd.randint(0, 9)
NanoX = rd.randint(1, 9)
NanoY = rd.rand... |
def db_connect(app_id, report_type):
credentials = get_token(app_id, report_type)
try:
cnx = mysql.connector.connect(
user=credentials['user'],
password=credentials['password'],
host=credentials['host'],
database=credentials['database'],
port=c... | The function migrates data from a database to a target dataset/table by connecting to the database, querying data using a provided function, converting results to a DataFrame, logging progress, uploading the data to the specified target, and disconnecting. It handles database connection, data retrieval, and upload proc... | def migrate_data(app_id, report_type, select_function, dataset_target, table_target, date_start, date_end, script_name):
cnx = db_connect(app_id, report_type)
if not cnx.is_connected():
return
else:
data = select_function()
df = pd.read_sql(data, con=cnx)
success_log(app_id, ... |
def get_stream(get_url, get_params, get_app_id, get_report_type):
# success_log(get_app_id, get_report_type, 1, "File downloading started.")
response = requests.request('GET', url=get_url)
if response.status_code != 200:
error_log(get_app_id, get_report_type, response.status_code, response.text)
... | The main task of the code is to fetch data from a stream using provided parameters, insert it into a database via a specified function, handle database connections and disconnections, and manage errors by logging and sending notifications. It processes data line-by-line, ensures connection validity, and terminates grac... | def get_data(url, params, app_id, report_type, insert_function, date_start, date_end, script_name):
data = get_stream(get_url=url, get_params=params, get_app_id=app_id, get_report_type=report_type)
if data is None:
return
else:
cnx = db_connect(app_id, report_type)
cursor = get_curso... |
def get_config_repo_paths(key):
require('deployment_configurations')
return map(lambda x: 'deploy/%s/%s' % (key, render_config_key(x, 'pattern')), env.deployment_configurations.get(key, []))
def get_nginx_app_target_path():
require('deployment_configurations')
if env.deployment_configurations.get('ngi... | The main task of the code is to configure Let's Encrypt certificate generation by collecting domains from configuration files, creating a temporary Nginx config for ACME challenges, verifying DNS setup for domains, uploading the config, reloading Nginx, and running a dry-run certificate update. It ensures proper domain... | def letsencrypt_configure(reconfigure_nginx=True):
require('code_dir')
domains = set()
# Collect all the domains that need a certificate
with cd(env.code_dir):
# construct a configparser object
config = ConfigParser.ConfigParser()
for filename in get_config_repo_paths('letsenc... |
def import_function_by_path(function_path: str):
""" Dynamic python import of an object of a python module. """
module_path, function_name = function_path.rsplit(".", 1)
module = importlib.import_module(module_path)
return getattr(module, function_name)
def list_function_arguments(func) -> dict:
"""... | This function executes a Python function from the command line by parsing arguments, handling config files, and overriding config settings. It imports the specified function, maps command-line arguments to function parameters, loads JSON config files if specified, and applies overrides. If the function is not callable,... | def run_function_from_commandline(function_path: str, *args):
""" Run a Python function using arguments of a command line.
First, the function is imported and the arguments that match function definition are found,
they are use when running the function as kwargs.
If a "--config path/to/co... |
def perform_configuration():
print("🔌 Applying rUv-dev configurations...")
print("📂 Creating necessary directories...")
os.makedirs(os.path.expanduser("~/dotfiles/aliases"), exist_ok=True)
os.makedirs(os.path.expanduser("~/dotfiles/bash"), exist_ok=True)
os.makedirs(os.path.expanduser("~/dotfiles... | This script provides a command-line interface to set up the rUv-dev environment, offering options to install required packages, configure settings, perform initial setup, and launch tools like liteLLM, Open Interpreter, Jupyter, and Super Coder. It includes both direct command-line arguments and an interactive mode for... | def main():
parser = argparse.ArgumentParser(description="Set up rUv-dev environment")
parser.add_argument("-i", "--install-packages", action="store_true", help="Install required packages")
parser.add_argument("-c", "--configure", action="store_true", help="Configure environment variables and settings")
... |
def verify_directory(dirname):
for f in [ "COPYING", "DESCRIPTION" ]:
if os.path.isfile(dirname + "/" + f) == False:
raise Exception("package is missing file " + f)
def get_description(descfile):
with open(descfile, 'rt', encoding='latin-1') as f:
lines = f.read().splitlines()
pat_match = re.compi... | The code installs an Octave package by unpacking a tarball, verifying its structure, configuring, uninstalling existing versions, copying files to specified directories, generating scripts, and updating the package list. It uses temporary directories, handles verbose output, and ensures cleanup. | def install_pkg(pkg, env):
pkg = os.path.abspath(pkg)
currdir = os.getcwd()
if env.verbose:
print ("Installing " + pkg)
try:
## Check that the directory in prefix exist. If it doesn't: create it!
tmpdir = tempfile.mkdtemp("-pkg","tmp", env.tmp)
os.chdir(tmpdir)
# unpack dir
if env.ve... |
def is_file_in_sync_new_content(self, path, current_contents):
return self.file_exists(path) and \
self.is_file_in_sync(path) and \
self.is_new_content(path, current_contents)
def is_file_in_sync_unchanged_content(self, path, current_contents):
return self.file_exists(path)... | The code determines the state of a file relative to provided contents, returning specific status messages like "In sync," "New file," or "File exists with different contents," or raising an exception if the state is unknown. | def get_initial_state(self, path, current_contents):
if self.is_file_in_sync_new_content(path, current_contents): return "In sync, new content"
if self.is_file_in_sync_unchanged_content(path, current_contents): return "In sync, unchanged content"
if self.is_new_file(path): return "New file"
... |
def is_file_in_sync_unchanged_content(self, path, current_contents):
return self.file_exists(path) and \
self.is_file_in_sync(path) and \
not self.is_new_content(path, current_contents)
def is_file_was_changed_by_another_process(self, path, current_contents):
return self.fi... | The code determines the state of a file at a given path by checking four conditions: if it's in sync with unchanged content, if it was modified by another process, if it was deleted, or if an unmanaged file exists. It returns one of four status strings describing the file's state relative to the system's expectations. | def get_state_change(self, path, current_contents):
if self.is_file_in_sync_unchanged_content(path, current_contents): return "In sync, unchanged content"
if self.is_file_was_changed_by_another_process(path, current_contents): return "File was changed by another process"
if self.is_file_was_dele... |
def check_external_modification(self):
state = self.file_manager.get_state_change(self.path, self.cell_content_to_save)
if state == None or state == self.state:
return
self.state = state
if self.debug: self.display_debug(self.state)
for button in (self.overwrite_but... | (This code initializes an `EditorWidget` to manage code cells in an interactive environment. It sets up file monitoring, processes cell content (removing magics), creates UI elements (buttons, outputs), and links actions like saving/running cells or refreshing content. It handles conflict resolution, debugging, and ext... | def __init__(self, file_manager, shell, line, cell, path, no_eval, \
conflict_resolution_strategy, pooling_rate=None, debug=False):
super(EditorWidget, self).__init__()
self.file_manager = file_manager
self.shell = shell
self.line = line
self.cell = cell
... |
def read_data(file_name):
data = np.genfromtxt(file_name, delimiter=',')
t = data[1:, 0]
x = data[1:, 1:]
y = data[1:, -1]
return t, x, y
def train_regression(state, kernel, learning_rate, x, y):
n = x.shape[0]
for i in range(n):
update_state(state, kernel, learning_rate, x[i], y[i])... | The code trains a regression model using a polynomial tanh kernel on simulated training data, evaluates it on test data by predicting outputs, computes the mean squared error loss between predicted and actual test values, and optionally visualizes predictions against actual values. | def main():
state = []
kernel = poly_tanh_kernel
_, x_train, y_train = read_data("sim_data_train.csv")
train_regression(state, kernel, 1e-3, x_train, y_train)
t, x_test, y_test = read_data("sim_data_test.csv")
y_predict = [predict(state, kernel, x_test[i, :]) for i in range(y_test.shape[0])]
... |
def one_sided_energy(self, dc_value=False, normalized=False):
freq, S = self.spectral_energy()
mid = self.N//2
Sdc = S[0]
if self.N % 2 == 0:
S = S[1:mid] + np.flip(S[mid+1:])
freq = freq[:mid]
else:
S = S[1:mid+1] + np.flip(S[mid+1:])
... | The code computes and returns signal analysis metrics including one-sided energy (freq, S), SNR, entropy (H), and exon check status. If `graph=True`, it plots energy vs. frequency with a title displaying entropy and SNR values. The results are returned as a dictionary containing these calculated parameters. | def results(self, graph=False):
freq, S = self.one_sided_energy(normalized=True)
snr = self.snr()
H = self.entropy()
check = self.check_exon()
res = {'freq':freq, 'S':S, 'snr':snr,
'H':H, 'exon':check}
if graph == True:
plt.title(f"H = {H:.2f}n... |
def order_directory():
for file in os.listdir(FOLDER_PATH):
#print("file found is:",file)
#i (file[0]=='0'):
list_keypoint_json.append(file)
#list of json file in order
list_keypoint_json.sort()
def decode_keypoints(path):
'''
add values to person dict
'''
#ope... | The main task of the code is to process files in a directory by iterating through JSON and PNG files. It decodes keypoints from JSON files (after a counter threshold) and processes PNG images, likely for visualization or data analysis. The function also manages OpenCV windows and includes conditional logic to handle sp... | def run_all_files():
order_directory()
print("in run all files......................... ", ANGLE_PIX)
flag = False
b = 0
#if (VIDEO.isOpened()==False): print("error in opening video stream");
#time.sleep(5)
for path in list_keypoint_json:
'''if b == 287:
VIDEO.relea... |
def count(m):
return [ (list(r).count("0"),list(r).count("1")) for r in m ]
def oxy_rating(m,pos):
counts=count(m)
if counts[pos][0] > counts[pos][1]:
# zeros are true
mask=np.invert(m.astype(bool))
else:
# ones are true
mask=m.astype(bool)
x=m.T[mask[pos]]
retur... | The code reads a binary file, processes each line into a 2D NumPy array, calculates gamma and epsilon rates by comparing bit counts, and returns their integer values alongside oxygen and CO₂ ratings computed by separate functions. | def run(file):
with open(file) as f:
m = np.asarray([ np.asarray(list(l.strip())) for l in f.readlines() ]).T
counts=count(m)
gamma=""
epsilon=""
for idx,(zero,one) in enumerate(counts):
gamma += "0" if zero < one else "1"
epsilon += "1" if zero < one... |
def _build_node(
self,
graph: nx.MultiDiGraph,
node: Island,
mapping: Dict[str, Tuple[Island, Island]],
) -> Literal | AndNode | OrNode | NotNode:
"""
build ast for the bridges of the given node, with the constraint of the number of bridges
"""
num = n... | The function `encode` transforms a given graph into a boolean abstract syntax tree (AST) by constructing nodes from the graph's structure and combining them with logical AND operations. It identifies crossing bridges and incorporates them into the AST if present. The result is a tuple containing the constructed boolean... | def encode(
self, graph: nx.MultiDiGraph, bridges: List[Tuple[Island, Island]]
) -> Tuple[AndNode | Literal, Dict[str, Tuple[Island, Island]]]:
"""
Transform the given graph into a boolean ast
"""
mapping = {}
nodes = [self._build_node(graph, node, mapping) for node i... |
def sweeping(parameters):
# Get image height and width.
width, height = parameters["image"].size
# Moves the coordinate at which convolution occurs.
for column in range(width):
for row in range(height):
filterSelectorWrapper(row, column, parameters)
def postSweeping(parameters):
... | The code performs edge detection on an image using a 35-pixel filter, processes the image through initial and post-processing stages, extracts and prints specific pixel values (f1, f2, gradients, non-max suppression), converts gradient directions to degrees, and saves the final output as "edge-detection-no-nms.png". | def main():
# Open image using PIL
imageFileName = "cman.png"
originalImage = Image.open(imageFileName)
print(f"Image opened: [{imageFileName}]")
# Create input image buffer
inputImage = originalImage.copy()
print(f"Image copy created as buffer.")
# Setting up to call edge detection w... |
def createTextFile(data):
if len(data.fileNameWrite) != 0:
checkText(data) # check to make sure text does not already exist
else:
newTime = datetime.datetime.now()
newFileName = "%s-%s-%s-%s-%s" % (
newTime.month,
newTime.day,
newTime.year,
... | The main task of the code is to execute an odor sequence by sending solenoid activation commands to an Arduino, monitor its responses, and log timestamps for solenoid activation, deactivation, and TTL signals. It iterates through predefined solenoid orders, transmits timing data to the Arduino, processes feedback messa... | def runPyInfo(data):
# Sends the information over to the arduino
if data.mode == "Execute":
if data.trigSignal == "yes":
createTextFile(data) # Update: check file name
# fileToWrite = open(data.fileNameWrite+".txt","w+") #open up the file to run
# fileToWrite.write("... |
def drawBackground(canvas, data):
if data.mode == "Input Data":
# Set the background color
canvas.create_rectangle(
0,
data.tabHeight,
data.width,
data.height,
fill=data.tabColUnselected[0],
)
# create the tabs in order
... | The function `redrawAll` updates the canvas display by first drawing the background and then rendering the appropriate interface tab based on the `data.mode` value, such as "Input Data," "Random Trials," or "DIY," by calling corresponding drawing functions. Its main task is to dynamically refresh the graphical interfac... | def redrawAll(canvas, data):
############################
drawBackground(canvas, data)
if data.mode == "Input Data":
drawInputTab(canvas, data)
elif data.mode == "Random Trials":
drawRandomizeTab(canvas, data)
elif data.mode == "Execute":
drawExecuteTab(canvas, data)
elif... |
def resetBoxColor(data):
data.boxesInput = ["white", "white", "white", "white", "white"]
data.odorsBoxesInput = len(data.odorLabels) * ["white"]
data.fileNameBoxColor = "white"
data.updateFill = rgbString(160, 210, 219)
def rgbString(red, green, blue):
# From CMU 15112: http://www.kosbie.net/cmu/spr... | This code handles mouse click events to switch between modes (Input Data, DIY, Random Trials, Single Trial), select input boxes for configuring experimental parameters (e.g., odor names, trial counts, durations), and execute trials. It updates the application state, triggers trial runs, and manages UI interactions for ... | def mousePressed(event, data):
###############################
if data.mode == "Input Data":
##For switching between tabs
if (data.tabWidths <= event.x < 2 * data.tabWidths) and (
0 < event.y < data.tabHeight
):
data.mode = "DIY"
elif (2 * data.tabWidths <... |
def checkInternetStatus(self):
url = 'http://localhost:{}/internet/status?ping_count={}'.format(
self.hardware_server_port,
self.internet_check_ping_count
)
try:
res = requests.get(url)
except Exception as err:
logging.error(err)
... | The function uploads all CTT data files from a specified directory to a server, checking for internet connectivity first. If connected, it processes each file in order, uploads them, and marks them as uploaded upon success. If any upload fails or internet is unavailable, it halts and returns False. Otherwise, returns T... | def uploadAllCttFiles(self):
filenames = glob.glob(os.path.join(self.rotated_dir, '*'))
logging.info('about to upload {} CTT data files'.format(len(filenames)))
if self.checkInternetStatus() is True:
for filename in sorted(filenames):
res = self.uploadFile(fileuri=fil... |
def checkInternetStatus(self):
url = 'http://localhost:{}/internet/status?ping_count={}'.format(
self.hardware_server_port,
self.internet_check_ping_count
)
try:
res = requests.get(url)
except Exception as err:
logging.error(err)
... | The function uploads all .gz files older than 60 minutes from a specified directory to a server if an internet connection exists. It logs the process, skips files modified within the last hour, and returns True on successful uploads or False if internet is unavailable or upload fails. | def uploadAllSgFiles(self):
filenames = glob.glob(os.path.join(self.sg_file_dir, '*', '*.gz'))
logging.info('about to upload {} SG files'.format(len(filenames)))
now = datetime.datetime.utcnow()
if self.checkInternetStatus() is True:
for filename in sorted(filenames):
... |
def createPDENarr_random(xa,xb,ya,yb,za,zb):
'''given detector dimensions & number of random sources, returns dictionary of prob densities & the array of source locations'''
print("\n@ CreatePDENarr_random()...")
then=TIME.time()
sourcearr = []
numsources = 1 #random source locations
for i ... | The code runs a simulation x times to generate and aggregate smeared probability matrices for photon detection vs. production. It creates random PDEN arrays, computes transfer matrices, normalizes aggregated results, and saves the final matrix. Time metrics per run and total execution time are logged, with optional vis... | def run_smearcodeXtimes(x):
smearX = []
timePerSource = []
thenOVERALL = TIME.time()
for i in range(x):
print("\n======================================\n===== ",i+1," out of ",x," =====")
thenRUN = TIME.time()
PDENdict_random, sourcearr = createPDENarr_random(xa,xb,ya,yb,za,z... |
def load_all_automatons( automataNames ):
for automataName in automataNames:
automatons[automataName] = read_automaton( automataName)
def all_step( topology, currentStates, inputs ):
#print(currentStates)
finalState = []
finished_automatons = []
# step automatons
for i in range(len(topo... | The code simulates a system of interconnected automatons in a predefined order, where each automaton's output depends on prior states. It processes input signals from JSON files, updates system states, and collects outputs. The results are saved to a file and specific signals (e.g., AS, VS, VP) are plotted to analyze s... | def main():
# We carefully order the automatons in the topology such that the input to the current automata depends on the outputs of the automata that have occurred before it.
# The output obtained from the above topology is equivalent to the output obtained after running the same input on the conjunction of a... |
def song_sequence(self):
song_sequence = []
npy_list = self.npy_list()
for i in range(len(npy_list)):
sequence = self.split_filename()[i][3]
song_sequence.append(sequence)
return song_sequence
def song_number(self):
song_number = []
npy_list = se... | This method converts an object's attributes and method outputs into a dictionary. It maps predefined keys to values generated by accessing object properties and calling methods like song_sequence(), song_number(), channels_name(), and read_eeg(). The resulting dictionary aggregates structured data for serialization or ... | def to_dict(self):
dict_keys = ['subject_number', 'audio_type', 'song_sequence', 'song_number', 'eeg_channels_name','eeg_midi', 'eeg_song']
dict_values = [self.subject_number, self.audio_type, self.song_sequence(),
self.song_number(), self.channels_name(), self.read_eeg(), self.r... |
def load_database_info(
path: str = os.path.join(ROOT, "report_calculation.ini")
) -> Database:
logger.info("loading postgres configuration from file %s", path)
Config = configparser.ConfigParser()
Config.read(path)
return deserialize(Database, Config._sections["database"])
def check_db_connection(d... | The function initializes a database connection, checks its status, verifies Alembic migrations, and ensures schema consistency. If migrations are pending and `update_schema` is True, it raises an error indicating the database is not up-to-date. | def initialize(update_schema: bool = False) -> None:
db = load_database_info()
logger.info("Checking database connection")
check_db_connection(db)
logger.info("Checking alembic migrations")
engine = get_engine(db, suffix="?target_session_attrs=read-write")
with engine.connect() as conn:
... |
def create_truth(pnet, abundance=0.3, concentrate_all = True):
truth_over = []
for e, nei in pnet.successors.items():
if len(nei) < 2 or random.random()<abundance:
continue
neiwei = [(t,pnet.edges[(e,t)]['weight']) for t in nei]
neiwei = sorted(neiwei, key=lambda r: r[1])#.s... | The main task of the code is to generate synthetic higher-order networks (pnets) with anomalies by creating random walks on an Erdos-Renyi network, constructing HYPA networks from these walks, and introducing controlled anomalies via the `truth_over` parameter. The function returns the generated pnets, anomaly labels, ... | def generate_pnets_with_anomaly(k_tru, num_seqs = 1500, anomaly_abundance = 0.3, maxk = 5,
topo_dens = 0.05, nnodes1 = 50, nkedges = None, implementation="scipy"):
if nkedges is None:
nkedges = int(nnodes1**2 * topo_dens / k_tru * 10)
# Erdos-Renyi weighted topology
... |
def get_username():
# load sample user
customer = db.get_random_customer()
return customer['user_name']
def get_random_timezone():
random_timezone = pytz.timezone(random.choice(ALL_TIMEZONES))
return random_timezone
def customer_login_request(username: str, time_zone=None):
login_path = '/login'... | This function generates a synthetic user request sequence, starting with a login log, optionally adding an error request, then creating 1-5 order requests with consistent IP, user agent, and referer links between requests to simulate realistic user behavior. It ensures order requests reference previous request paths an... | def get_sample_user_request():
username = get_username()
total_orders = random.randint(1, 5)
time_zone = get_random_timezone()
login_log = customer_login_request(username, time_zone=time_zone)
user_requests = [login_log]
prev_log = login_log
if faker.pybool():
user_requests.append(e... |
def get_sample_user_request():
username = get_username()
total_orders = random.randint(1, 5)
time_zone = get_random_timezone()
login_log = customer_login_request(username, time_zone=time_zone)
user_requests = [login_log]
prev_log = login_log
if faker.pybool():
user_requests.append(e... | The main task of the code is to generate 100 random sample user request logs, convert them into formatted log lines, and save them into a timestamped log file. It creates a list of log entries, constructs a filename using the current UTC time, writes the logs to a file at the specified path, and ensures the file is pro... | def generate_logs(*args, **kwargs):
# generate some random logs
log_lines = []
for _i in range(100):
logs = get_sample_user_request()
for log in logs:
log_lines.append(models.WebLog.to_log_line(log))
file_name = get_log_file_name(datetime.utcnow())
file_path = get_log_fi... |
def handleDataAsList(data):
if data is None:
return False
elif isinstance(data, str):
return False
elif hasattr(data, "__iter__") and hasattr(data, "__len__") and isSlicable(data):
return True
else:
return False
def handleListData(self, data):
length = len(data)
... | The code's main task is to determine if input data should be processed as a list or non-list. It checks `handleDataAsList(data)`; if true, it calls `handleListData(data)`, else `handleNonListData(data)`. This routes data to appropriate processing methods based on its structure. | def execute(self, data):
if handleDataAsList(data):
self.handleListData(data)
else:
self.handleNonListData(data) |
def predict_class(sentence):
bow = bagw(sentence)
res = model.predict(np.array([bow]))[0]
ERROR_THRESHOLD = 0.25
results = [[i, r] for i, r in enumerate(res)
if r > ERROR_THRESHOLD]
results.sort(key=lambda x: x[1], reverse=True)
return_list = []
for r in results:
retur... | The code processes an input 'magic' by predicting its class, generating a response based on the predicted class and predefined intents, then returns a JSON-formatted result with CORS headers. | def get(self, magic):
print(magic)
ints = predict_class(magic)
print(ints)
res = get_response(ints, intents)
return corsify_actual_response(jsonify({'magic': res})) |
def GetMpoFlag(inpStr):
if inpStr == "2":
return MpoMode.TWO
elif inpStr == "3":
return MpoMode.THREE
elif inpStr == "MAX":
return MpoMode.MAX
return MpoMode.NONE
def GenerateLef(inputFileList, outputDir, techInfo):
"""_summary_
Args:
inputFileList (_type_): _des... | (The main task of the code is to generate LEF files for semiconductor design based on input configuration parameters. It processes input files from a specified directory, constructs a technology configuration object with metal pitch, CPP width, site name, and MPO mode, then generates LEF files with BPR mode enabled. Th... | def main():
global fileList
global inputDir
global outputDir
inputDir = "./input_cfet_exp1_pinfix/"
outputDir = "./output_cfet/"
if len(sys.argv) <= 1:
print("Usage: python generate.py <siteName>\n\n")
print(" metalPitch: {int}, {int}, {int}, {int}")
print(" ... |
def load_prompter(self, prompter_path=None):
"""Load the trained visual prompter from files
"""
prompter = prompters.__dict__[self.args.prompt_method](
self.args).to(self.devicename) # prompt_method: padding, fixed_patch, random_patch
if prompter_path is not None:
... | The code performs LMErasing tuning by fine-tuning a model with a prompter, adjusting classifier heads, and optimizing using a scheduler. It tracks training/validation/testing losses/accuracies, clusters data if needed, updates the best prompter based on validation performance, and returns metric logs. | def LMErasing_tuning(self, test_data, prompter_path):
"""
Performs LMErasing tuning on the given test data using the specified prompter.
Args:
self: The instance of the class.
test_data: The test data containing train, validation, and test loaders.
prompter_p... |
def load_prompter(self, prompter_path=None):
"""Load the trained visual prompter from files
"""
prompter = prompters.__dict__[self.args.prompt_method](
self.args).to(self.devicename) # prompt_method: padding, fixed_patch, random_patch
if prompter_path is not None:
... | The code performs random partition tuning on test data using a prompter. It initializes prompters, sets up optimizers with cosine learning rates, trains the model over epochs, validates performance, updates best parameters, and tests periodically. The task involves adjusting classifiers, clustering, and optimizing prom... | def random_part_tuning(self, test_data, prompter_path):
"""
Performs random partition tuning on the given test data using the specified prompter.
Args:
self: The instance of the class.
test_data: The test data containing train, validation, and test loaders.
... |
def next_set(self, direc):
self.index += direc
if self.index == len(self.to_label):
with self.output_images:
display(HBox(children=[Label('Finished this image batch.',)],
layout=Layout(height='auto', width='auto', justify_content='center')))
return
self.progress_la... | This code initializes a UI for image labeling, setting up navigation controls (Next/Back), buttons to add/discard labels, progress tracking, and toggles for primary/secondary labels. It organizes these elements into a grid layout and prepares outputs for displaying results, enabling user interaction to label images sys... | def __init__(self, to_label, primary_labels, secondary_labels, output_path):
self.output_path = output_path
self.to_label = to_label
self.primary_labels = primary_labels
self.secondary_labels = secondary_labels
self.index = -1
self.current_img = None
self.progress_label = HBoxAlign([La... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.