dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def generate_summary(text, phrases_count=None):
doc = nlp(text)
tr = doc._.textrank
arr = []
limit_phrases = 20
if phrases_count != None:
limit_phrases = phrases_count
for sent in tr.summary(limit_phrases=limit_phrases, preserve_order=True):
arr.append(str(sent).replace("\n"... | The main task of the code is to generate a summary from input text by extracting key sentences, create a graph structure (nodes and links) representing relationships between these sentences, and return the graph components along with the summary and extracted sentences. It uses auxiliary functions to build the graph da... | def process_text(text, phrases_count, title):
sentences_arr = generate_summary(text, phrases_count)
summary_text = " ".join(sentences_arr)
print(summary_text)
graph_dict = dict()
relations_dict = dict()
sentence_dict = dict()
idxsentence_dict = dict()
for i in sentences_arr:
... |
def data_collector(file_names, params, is_train):
"""Data collection taking all at a time"""
if params["csv_file"] == "*_full.csv":
index = 12
elif params["csv_file"] == "*_translated.csv":
index = 23
sample_ratio = params["sample_ratio"]
type_train = params["how_train"]
sampled... | The code trains a BERT model for text classification using specified parameters, handling both English and translated datasets. It loads training/validation data, preprocesses text with a BERT tokenizer, initializes a model and optimizer, and trains over multiple epochs with a learning rate scheduler. It evaluates mode... | def train_model(params, best_val_fscore):
"""Main function that does the training"""
# In case of english languages, translation is the origin data itself.
if params["language"] == "English":
params["csv_file"] = "*_full.csv"
train_path = params["files"] + "/train/" + params["csv_file"]
va... |
def split_hashtag(the_df):
'Split the hashtags in a given data frame'
regex_hashtag = '#(\S*)'
final_tweet_list = []
indices_list = []
# loop through each row and add modfied text to our final_tweet_list
for i in range(len(the_df)):
hashtag_word_dict = {}
# 1. get list of merged ... | The main task of the code is to process and clean a DataFrame of tweets by optionally splitting hashtags, removing stopwords, final cleaning, removing short sentences, deduplicating tweets, and resetting the index. The function applies customizable preprocessing steps to enhance text quality for analysis, with paramete... | def custom_pipeline(the_df,
del_split_hashtag = False, #optional
del_stopwords = True,
del_short_tweets = False):
# 1. split hashtag
if(del_split_hashtag == True):
print('split hashtag..')
the_df = split_hashtag(the_df)
# 2. ... |
def remove_read_more(the_df):
print()
# define pattern:
regex_read_our = '(?s)(?i)(read our)(?<=read our)(.*$)'
regex_learn_more = '(?s)(?i)(learn more)(?<=learn more)(.*$)'
regex_read_more = '(?s)(?i)(read more)(?<=read more)(.*$)'
regex_find_out_more = '(?s)(?i)(find out more)(?<=find out more... | The code defines a customizable text preprocessing pipeline for a DataFrame, offering options to remove "read more" links, end hashtags, split hashtags, special characters, lemmatize text, remove stopwords, perform final cleaning, and eliminate short sentences, enabling tailored data cleaning for text analysis tasks. | def custom_pipeline(the_df,
del_read_more = True,
del_end_hashtag = True,
del_split_hashtag = False, #optional
del_special_char = True,
del_stopwords = False,
final_cleaning = True,
... |
def get_git_directory():
# start searching from the location wherever the code was called in
current_path = os.getcwd()
while current_path != '/':
git_path = os.path.join(current_path, '.git')
# if the .git directory exists in that folder, great you found it!
if os.path.exists(git_... | The main task of the code is to generate a topological ordering of Git commits from all local branches in a repository. It collects commit hashes from branch references, constructs a commit graph with parent-child relationships, performs a topological sort, and prints the ordered commits alongside their associated bran... | def topo_order_commits():
git_directory = get_git_directory()
branch_names = get_local_branch_names(git_directory)
commit_hashes = []
for branch_name in branch_names:
file_path = os.path.join(git_directory, '.git', 'refs', 'heads', branch_name)
if os.path.isfile(file_path):
... |
def _path_parse(self, path: str) -> str:
if not path:
return '.'
path: str = re.sub('%', '', path)
path: str = re.sub('$', '', path).replace("~", "HOME")
for key in os.environ.keys():
if path == key:
return os.environ[key]
return path
def s... | The code changes the current working directory using the parsed path from `arg`, then sends pickled data containing a directory listing and the updated working directory path to indicate successful navigation. | def do_cd(self, arg: str) -> None:
os.chdir(self._path_parse(arg.strip()))
self.send_pickled_data(True, [self.do_ls(".", False), os.getcwd()], "") |
def reset_addition(self):
"""
Resets and sets up the addition tab to fit the new table.
"""
self.empty_tab("addition")
counter = 0
Db.cursor.execute(f"PRAGMA table_info('{self.currentTable}');")
# build all new inputs
if sum(1 for letter in self.currentTa... | The code sets up a new active table by assigning the currently selected table from a selector, then resets addition, view, and related components to prepare for interaction with the new table. | def new_active_table(self):
"""
Sets up a new active table to interact with.
"""
self.currentTable = self.tableSelector.currentText()
self.reset_addition()
self.reset_view()
self.reset_related() |
def add_equipment_option(connector_type, connector_id):
"""
:param connector_type: states whether the row connects to a class, background or another EquipmentOption.
It's inputs are 'class', 'background' or 'equipment option'
:type connector_type: str
:param connector_id: th... | This function adds one or more classes to a database by collecting core class data (name, hit dice, abilities, magical status, saving throws) and linking related data (equipment, languages, proficiencies, magic traits) through helper functions. It uses a loop to allow adding multiple classes, generating unique IDs and ... | def add_class():
"""
Adds the first level of one or more classes into the database.
"""
# Gets the current amount of classes and ClassOptions
classId = Db.highest_id("Class")
classOptionsId = Db.highest_id("ClassOptions") + 100
addMore = True
while addMore:
# Collects the core d... |
def add_background_connections(background_id, skill_amnt, language_amnt, tool_amnt):
"""
Adds appropriate rows into all tables that connect to a background, bar EquipmentOptions.
:param background_id: the id of the current background being added
:type background_id: int
:param skill_amnt: the amount... | This function adds multiple backgrounds to a database by prompting user inputs for each background's name, skill count, tool count, and language count. It generates unique IDs, inserts records into the Background table, and links related data via helper functions for connections and equipment. The loop allows adding mu... | def add_background():
"""
Adds one or more backgrounds to the database.
"""
backgroundId = Db.highest_id("Background")
addMore = True
while addMore:
backgroundId += 1
name = input("Enter the background's name: ")
skillAmnt = Db.int_input("Enter how many skills the charact... |
def predict_class(sentence):
bow = bag_of_words(sentence)
res = model.predict(np.array([bow]))[0]
porcentajes_formateados = ["{:.2%}".format(valor) for valor in res]
print(porcentajes_formateados)
ERROR_TRESHOLD = 0.1
results = [[i, r] for i, r in enumerate(res) if r > ERROR_TRESHOLD]
result... | The code manages a job search conversation by tracking user intent and state transitions. It gathers details like job role, modality (remote/presential), hours, location, holidays, and salary expectations through a series of questions. Based on user inputs, it updates global variables, validates preferences, and provid... | def reply(message):
global job
global state
global amount_hours
global locations
global modality
global holidays
global expected_salary
tecnologia_front_end = ["html", "css", "react", "javascript", "angular", "typescript", "flutter", "Vue"]
tecnologia_back_end = ["java", "python", "r... |
def move(agent, agent_index, pitch, yaw, nearby_blocks):
enemy_index = 1 if agent_index == 0 else 0
turn_speed, pitch_speed, move_speed, strafe_speed = calc_movement(AGENT_LOCATIONS[agent_index], AGENT_LOCATIONS[enemy_index], pitch, yaw, nearby_blocks)
agent.sendCommand(f"turn {turn_speed}")
agent.sendC... | The code implements a reinforcement learning agent in a multiplayer game environment. It executes actions like attacking, weapon switching, or using items, tracks health and kills, calculates rewards based on health changes and kills, and returns observations (enemy proximity, health, weapon type, distance), reward, an... | def step(self, action):
# Reinforcement learning agent
global AGENT_KILLS, RL_AGENT_LOSS, RL_AGENT_WINS, AGENT_IDENTIFIED
rl_agents_killed = AGENT_KILLS[0]
ai_agents_killed = AGENT_KILLS[1]
action = int(action)
# Take action
done = True
observations = [0,... |
def getWordnetId2ClassName(WordnetId2ClassName_filepath):
'''
For imagenet like datasets. To convert wordnetId to class name.
'''
WordnetId2ClassName = {}
with open(WordnetId2ClassName_filepath) as fp:
for line in fp.readlines():
wordNetId = line.split()[0]
class_name... | The code evaluates a CLIP model's zero-shot performance on ImageNet or CIFAR datasets, computing top-1 and top-5 accuracies, saving class-wise results, and outputting metrics to a file. It loads a trained checkpoint, processes input data with transforms, and uses WordNet ID mappings for class names. | def main():
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint_path", default=None, type=str, required=True, help="path of trained checkpoint")
parser.add_argument("--dataset_type", default="imagenet", type=str, required=True, help="Type of eval dataset. 'imagenet' : for imagenet like dat... |
def set_up_weights(self):
self.weights = []
for i in range(1, len(self.nodeList)):
row = self.nodeList[i-1]
col = self.nodeList[i]
self.weights.append(2*np.random.random((row, col)) - 1)
def set_up_deltaWeights(self):
self.deltaWeights = [np.zeros(self.weights... | This code trains a neural network using backpropagation. It initializes network structure, applies learning rate decay, performs forward and backward propagation iteratively over epochs, adjusts weights to minimize output error, and periodically prints training progress including weight values, desired vs actual output... | def train(self, epochs, inputs, outputs, learningRate, hiddenNodeStructure):
self.nodeList = [inputs.shape[1]] + hiddenNodeStructure + [outputs.shape[1]]
decayRate = learningRate / epochs / 2
self.set_up_weights()
self.set_up_deltaWeights()
for n in ran... |
def filter_corners(self, corners):
newCorners = []
xys = []
for c in corners:
if (c[1],c[2]) not in xys:
newCorners.append(c)
for x in [c[1]-1, c[1], c[1] +1]:
for y in [c[2]-1, c[2], c[2] +1]:
xys.append((x,... | The function `choose_corner_pair` identifies the optimal corner pair between top and bottom corners by evaluating metrics like aspect ratio, size deviation, and geometric quality. It calculates weights for each pair, normalizes scores, and sorts them to return the highest-weighted pair, prioritizing alignment with pred... | def choose_corner_pair(self, topCorners, bottomCorners, paraLines, perpLines, predictedSize):
cornerPairs = []
sizeOffList = []
pairQualityList = []
ratioList = []
print(len(topCorners), len(bottomCorners))
topCorners, bottomCorners = self.filter_corners(topCorners), self... |
def get_lineList(self, thetas, res):
finder = FindLines(self.original.copy(), res)
finder.thetas = np.array(thetas)
finder.acc = [[0 for a in range(len(finder.thetas))] for b in range(len(finder.rhos))]
finder.get_lines(True)
lines = finder.lineList
for i in rang... | This function identifies corners in an image by generating lines at specific angles, calculating intersections, and selecting valid corner pairs. It returns the minor angle between key lines and the coordinates of detected corners if found. | def get_corners(self):
res = 50
paraThetas = [a*np.pi/res for a in range(-2, 3, 1)]
perpThetas = [(np.pi/2 - a*np.pi/res) for a in range(2)] + [(-np.pi/2 + a*np.pi/res) for a in range(2)]
cornerLim = 0
found = False
paraLines = self.get_lineList(para... |
def parse_events(pmid):
"""Parses a pretty_midi object into a 2D array with (time, note, is_onset) columns."""
points = []
for instrument in pmid.instruments:
if instrument.is_drum:
continue
for note in instrument.notes:
points.append((note.start, note.pitch, 1))
... | The code processes a MIDI file by parsing its events, determining partition points, identifying minimal segments, and then segmenting and labeling the MIDI data based on these partitions and segments. The main task is to analyze and structure MIDI events into labeled segments for further processing or analysis. | def label_midi(midi):
events = parse_events(midi)
p_all = get_partition_points(events)
s_m = get_minimal_segments(p_all)
return segment_and_label(p_all, s_m) |
def collate_replacement_sets(diagnostic, offset_lookup):
"""Return a dict of replacements on the same or consecutive lines, indexed by line number
We need this as we have to apply all the replacements on one line at the same time
This could break if there are replacements in with the same line
number ... | The main task of the code is to generate formatted code blocks for GitHub suggestions or diff patches based on replacement sets derived from diagnostics. It distinguishes between replacements on the same line as the diagnostic (formatted as suggestions) and others (formatted as diffs with +/- prefixes). The function re... | def format_diff_line(diagnostic, offset_lookup, source_line, line_offset, line_num):
"""Format a replacement as a Github suggestion or diff block"""
end_line = line_num
# We're going to be appending to this
code_blocks = ""
replacement_sets = collate_replacement_sets(diagnostic, offset_lookup)
... |
def find_line_number_from_offset(offset_lookup, filename, offset):
"""Work out which line number `offset` corresponds to using `offset_lookup`.
The line number (0-indexed) is the index of the first line offset
which is larger than `offset`.
"""
name = str(pathlib.Path(filename).resolve().absolute(... | The function generates a diagnostic comment containing the diagnostic message, name, and code context (including the exact location or suggested fixes). It uses file offsets to locate the source line, formats code blocks for errors or replacements, incorporates notes, and returns the constructed comment along with the ... | def make_comment_from_diagnostic(
diagnostic_name, diagnostic, filename, offset_lookup, notes
):
"""Create a comment from a diagnostic
Comment contains the diagnostic message, plus its name, along with
code block(s) containing either the exact location of the
diagnostic, or suggested fix(es).
... |
def make_comment_from_diagnostic(
diagnostic_name, diagnostic, filename, offset_lookup, notes
):
"""Create a comment from a diagnostic
Comment contains the diagnostic message, plus its name, along with
code block(s) containing either the exact location of the
diagnostic, or suggested fix(es).
... | The function generates a GitHub PR review with comments based on clang-tidy diagnostics, filtering relevant files from the PR changeset. It processes each diagnostic to create review comments, checks file inclusion in the diff, and formats multiline comments with start/end positions. Returns a structured review object ... | def create_review_file(
clang_tidy_warnings, diff_lookup, offset_lookup, build_dir
) -> Optional[PRReview]:
"""Create a Github review from a set of clang-tidy diagnostics"""
if "Diagnostics" not in clang_tidy_warnings:
return None
comments: List[PRReviewComment] = []
for diagnostic in cla... |
def filter_files(diff, include: List[str], exclude: List[str]) -> List:
changed_files = [filename.target_file[2:] for filename in diff]
files = []
for pattern in include:
files.extend(fnmatch.filter(changed_files, pattern))
print(f"include: {pattern}, file list now: {files}")
for pattern... | The main task of the code is to generate a pull request review using clang-tidy by analyzing changes in the PR, filtering relevant files, running static analysis, and compiling warnings into a structured review. It returns a review object with findings or None if no files or issues are detected. | def create_review(
pull_request: PullRequest,
build_dir: str,
clang_tidy_checks: str,
clang_tidy_binary: pathlib.Path,
config_file: str,
include: List[str],
exclude: List[str],
) -> Optional[PRReview]:
"""Given the parameters, runs clang-tidy and creates a review.
If no files were ch... |
def show_all_running_apps(self, placeholder=None):
apps_to_be_ignored = self.load_file('.ignore')
for app in self.running_apps():
if not apps_to_be_ignored == None:
print(app, '(Ignored)' if app in apps_to_be_ignored else '')
else:
print(app)
def running_apps(self):
output = subprocess.check_output... | The main task of the code is to allow users to ignore a running application by updating a `.ignore` file and removing it from the session's software list. If the app is running, it adds/removes it from the ignore list, updates the session file, and ensures the ignored app is excluded from future processing. If the sess... | def ignore(self, app_to_ignore):
application_name = app_to_ignore
if application_name == '':
self.show_all_running_apps()
print('Choose an app of the above to ignore')
else:
if application_name in self.running_apps():
os.chdir(current_directory)
if not os.path.exists('.ignore'):
self.s... |
def product_menu():
print("[0] Main menu")
print("[1] Print Products")
print("[2] Create/Add Products")
print("[3] Update Products")
print("[4] Delete a Product")
def get_from_database():
connection = connect_to_database()
cursor = connection.cursor();
cursor.execute(\
"""select * from products
... | The code displays a product management menu, repeatedly prompting the user for an option (1-4) to view products, add new products, update existing ones, or remove products. It uses a loop to keep showing the menu until the user selects option 0, with corresponding database operations triggered by each choice. | def show_products_menu():
product_menu()
option = int(input("Enter your option: "))
while option != 0:
if option == 1:
get_from_database()
print("Please see the selection of products")
#carry out option 1
elif option == 2:
new_product()
#carry ... |
def couriers_menu():
print("[0] Main menu")
print("[1] Print Couriers")
print("[2] Create/Add Couriers")
print("[3] Update Couriers")
print("[4] Delete a Courier")
def get_from_database():
connection = connect_to_database()
cursor = connection.cursor();
cursor.execute(\
"""select * from couriers... | The code displays a couriers management menu, allowing users to select options (1-4) to retrieve data, add new couriers, update existing ones, or remove couriers. It loops continuously, showing the menu and processing user input until option 0 is selected to exit. | def show_couriers_menu():
couriers_menu()
option = int(input("Enter your option: "))
while option != 0:
if option == 1:
get_from_database()
#carry out option 1
elif option == 2:
new_courier()
#carry out option 2
elif option == 3:
update_c... |
def orders_menu():
print("[0] Main menu")
print("[1] Print orders")
print("[2] Create/Add orders")
print("[3] Update order")
print("[4] Delete a order")
def get_from_database():
connection = connect_to_database()
cursor = connection.cursor();
cursor.execute(\
"""select * from orde... | This function displays an orders menu and processes user selections to either view orders, create a new order, update an existing order, or remove an order, looping until the user chooses to exit (option 0). | def show_orders_menu():
orders_menu()
option = int(input("Enter your option: "))
while option != 0:
if option == 1:
get_from_database()
print("Please see the selection of orders")
# carry out option 1
elif option == 2:
new_order()
# carry out optio... |
def welcome():
print(WELCOME)
def game():
global gamesWon, gamesPlayed
print(LINE_OF_STARS)
selected_number = computer_pick_number()
guess = user_guess(selected_number)
if selected_number == guess:
print(WIN)
gamesWon += 1
else:
print(LOSE)
gamesPlayed += 1
def pl... | The main task of the code is to execute a game loop by first welcoming the user, then running the game logic, and finally checking if the user wants to play again. The `main()` function orchestrates these steps sequentially, ensuring the game starts, plays, and offers replay functionality through the `welcome()`, `game... | def main():
welcome()
game()
play_again() |
def _initialize_agents(self):
self.agent_positions = {}
for agent_id in self.agents:
robots_placed = False
while not robots_placed:
x, y = (np.random.randint(0, self.grid_size - self.agent_size + 1),
np.random.randint(0, self.grid_size - se... | The code resets the environment by initializing a clean grid, randomly placing dirt, reinitializing agents, obstacles, and dirt, then returning the initial observation state for a simulation or reinforcement learning setup. | def reset(self):
self.cycle_count = 0
# Initialize a clean grid
self.grid = np.zeros((self.grid_size, self.grid_size))
# Reset the list of agents
self.agents = [f"agent_{i}" for i in range(self.num_agents)]
# Randomly place dirt
num_dirt_cells = int(self.grid_si... |
def _change_model(self, model_name: str):
if self.model is not None:
self.model.destroy()
self.model = [m for m in self.style_models if m.name == model_name][0]
self.model.load()
def _change_bg_model(self, model_name: str):
if self.bg_model is not None:
self.bg_mo... | This code runs a loop to process steps, optionally logging FPS if FPS_LOG_INTERVAL is set. It initializes models, tracks frame times, calculates and prints FPS at intervals, then cleans up resources with self.destroy(). | def run(self, update_queue):
self.updates = update_queue
self._change_model(DEFAULT_MODEL)
self._change_bg_model(DEFAULT_MODEL)
if FPS_LOG_INTERVAL > 0:
frame_times = []
last_time = time.monotonic()
while self.step():
new_time = time.... |
def check_required_fields(file_descriptor):
_, request_descriptor = _get_message_descriptor(file_descriptor, config.REQUESTS_MESSAGE_NAME)
request_fields = {field.name: field.number for field in request_descriptor.field}
_check_for_missing_fields(request_fields, config.REQUIRED_REQUEST_FIELDS)
_, respo... | The main task of the code is to generate RPC (Remote Procedure Call) definitions by processing protocol buffer descriptors. It compiles a definition file, extracts RPC sets from descriptors, retrieves request/response message paths, and constructs RPC content using these elements. The result is aggregated into a string... | def rpc(repo_path, tree_ish):
content = []
putils.compile_file(RPC_DEFINITION_FILE)
descriptor_set = putils.load_descriptor_set()
for descriptor in descriptor_set.file:
check_required_fields(descriptor)
matches, single_responses, single_requests = _get_rpc_sets_from_file_descriptor(descr... |
def darknet53(input_shape, n_filters_origin=32, blocks_repetitions=None, n_outputs=3):
"""Create darknet model.
Args:
input_shape: W x H x CH of input images,
n_filters_origin: number of filters in first conv layer,
blocks_repetitions: list of residual unit repetitions for each block (original darkn... | Your return
The code constructs a YOLOv3 model for object detection. It takes input shape, classes, anchors, and training flags to build the network. The DarkNet-53 backbone processes inputs, and YOLO branches generate outputs. If training, it returns raw outputs; otherwise, it processes them (e.g., decoding coordina... | def yolo_v3(input_shape, n_class, anchors=yolo_anchors, anchor_mask=yolo_anchor_masks, training=False, name="yolo_v3"):
"""Crete and return yolo v3 model.
Args:
input_shape: size of input images,
anchors: predefined anchors (np array of tuples [width, height]),
anchor_mask: anchor mask f... |
def check_for_royal_flush(color_list: list, value_list: list):
is_straight_flush, straight_highest_card = check_for_straight_flush(color_list, value_list)
return is_straight_flush and straight_highest_card == definitions.CARD_ACE
def check_for_straight_flush(color_list: list, value_list: list):
is_straight,... | This function evaluates a poker hand's rank by checking for specific card combinations in descending order of hierarchy, starting with the highest possible ranks (e.g., royal flush, straight flush) and proceeding to lower ones (e.g., pairs, high card), returning the corresponding predefined rank value based on the dete... | def calculate_hand_value(card_list: dict):
color_list = []
value_list = []
for card in card_list[definitions.DATA_CARDLIST]:
color_list.append(card[definitions.DATA_CARD_COLOR])
value_list.append(card[definitions.DATA_CARD_VALUE])
color_list.sort()
value_list.sort()
if check_fo... |
def get_sonar_readings(self, x, y, angle):
readings = []
"""
Instead of using a grid of boolean(ish) sensors, sonar readings
simply return N "distance" readings, one for each sonar
we're simulating. The distance is a count of the first non-zero
reading starting at the object. For instance, if the fifth sens... | This method updates the car's movement by setting velocity based on its angle, renders the game screen, checks for collisions using sonar readings, handles crashes by resetting the car's position, and increments the step counter. It also saves a screenshot on the first step and advances the physics simulation. | def frame_step(self):
driving_direction = Vec2d(1, 0).rotated(self.car_body.angle)
self.car_body.velocity = 100 * driving_direction
# Update the screen and stuff.
screen.fill(THECOLORS["black"])
draw(screen, self.space)
self.space.step(1./10)
if draw_screen:
pygame.display.flip()
if self.... |
def play(self):
response = requests.get(self.volumio_base_uri + "api/v1/commands/?cmd=play", timeout=7)
if self.is_success(response):
logging.info("start playing")
self.sync_state()
else:
logging.warning("could not start playing. Got " + response.text)
def sto... | The method toggles between playing and stopping based on the boolean input, triggering the corresponding action (play or stop) and notifying listeners of the state change via the on_playing_updated method. | def playing(self, playing: bool):
if playing:
self.play()
else:
self.stop()
self.on_playing_updated(playing) |
def play_function(window_to_close):
window_to_close.destroy()
pygame.quit()
snakelogic()
def reopen_first_window(window_to_close):
window_to_close.destroy()
pygame.quit()
first_window()
def quit_function(window_to_close):
window_to_close.destroy()
sys.exit() | This code creates a Tkinter GUI window titled "You lost" with centered buttons for "RETRY", "MENU", and "QUIT". Each button triggers specific functions (play_function, reopen_first_window, quit_function) when clicked. The interface uses a Roboto font, custom colors, and spacing to display options after a game loss. | def retry():
window = tk.Tk()
window.geometry("400x300")
window.config(bg=background)
window.title("You lost")
frame = tk.Frame(window)
frame.config(bg=background)
frame.pack()
frame.place(in_=window, anchor='c', relx=.5, rely=.5)
font0 = font.Font(size=30, family='Roboto')
re... |
def check_keydown_events(event, ai_setting, screen, ship, bullets):
# Key is pressed
if(event.key == pygame.K_RIGHT):
# Move ship right
ship.moving_right = True
elif(event.key == pygame.K_LEFT):
# Move ship left
ship.moving_left = True
elif(event.key == pygame.K_SPACE):
fire_bullet(ai_setting, screen, shi... | The function `check_event` processes Pygame events to handle user input, including quitting the game, keyboard actions (keydown/up for ship movement and shooting), and mouse clicks to trigger the play button. It delegates specific actions to helper functions, updating game state and initiating gameplay when the play bu... | def check_event(ai_setting, screen, stats, sb, play_button, ship, aliens, bullets):
# Keyboard action
for event in pygame.event.get():
if(event.type == pygame.QUIT):
sys.exit()
elif(event.type == pygame.KEYDOWN):
check_keydown_events(event, ai_setting, screen, ship, bullets)
elif(event.type == pygame.KEYU... |
def check_fleet_edges(ai_setting, aliens):
for alin in aliens.sprites():
if(alin.check_edges()):
change_fleet_direction(ai_setting, aliens)
break
def ship_hit(ai_setting, screen, stats, sb, ship, aliens, bullets):
if(stats.ships_left > 0):
# Reduce ship life by 1
stats.ships_left -= 1
# Update score
... | This function updates alien movement, checks for collisions between the ship and aliens, and detects if aliens reach the screen bottom. It triggers responses like handling ship collisions and alien bottom hits, managing game state changes accordingly. | def update_aliens(ai_setting, screen, stats, sb, ship, aliens, bullets):
check_fleet_edges(ai_setting, aliens)
aliens.update()
# Alien and ship collision
if(pygame.sprite.spritecollideany(ship, aliens)):
ship_hit(ai_setting, screen, stats, sb, ship, aliens, bullets)
# Aliens hit the bottom
check_aliens_bottom... |
def get_len(array):
length = 0
for item in array:
length += len(array[item])
return length
def printprogressbar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Author: Greenstick on StackOverflow
Source: https://stackoverflow.com/a/34325723
Edited to us... | The code generates unique hash values for all files in the provided 'contents' dictionary using the specified algorithm (default: SHA-1). It reads files in chunks, computes their hashes, skips problematic files (e.g., decoding/permission errors), and stores unique digests in a frozenset. Progress is tracked and display... | def get_hashes(contents, algorithm="sha1"):
hashes = []
ln = get_len(contents)
progress = 0
printprogressbar(0, ln, prefix='Progress:', suffix='Complete', length=50)
for key in contents:
for thing in contents[key]:
file = key + slash + thing
verbose_print("Hashing " +... |
def get_hash_type(algorithm="sha1"):
algorithm = algorithm.strip().lower()
for alg in hashlib.algorithms_guaranteed:
if algorithm == alg:
algorithm = eval(compile(f"hashlib.{algorithm}()", '<string>', 'eval'))
return algorithm
else:
verbose_print(f"Error: Invalid hash... | This code recursively compares file hashes in a directory tree against a baseline set, identifying files with new hashes using the specified algorithm (default: SHA1). It handles errors during file reading, skips problematic files, and returns a dictionary mapping paths to lists of files with non-matching hashes. | def compare_hashes(folder, baseline_hashes, algorithm="sha1"):
num_dirs = []
contents = {}
for (dirpath, dirnames, filenames) in walk(folder):
temp = []
for dirs in dirnames:
num_dirs.append(dirs)
for file in filenames:
rf = folder + slash + file
h... |
def make_dictionary(cos_or_stis):
"""Creates an ordered dictionary for all of the important info to be saved.
Parameters
----------
cos_or_stis : str
this is either 'cos' or 'stis' referring to if the reference is a cos
spectrum or a stis spectrum respectively.
Outputs
-------
... | The main task of the code is to cross-correlate specific wavelength windows of a dataset (e.g., COS spectra) with corresponding windows in a reference spectrum (e.g., STIS data), calculating parameters like wavelength shifts, correlation coefficients, centroids, and normalization factors. It processes FITS or .sav file... | def correlations(dataset, reference, wave_list=None, binsize=None, store_dic=None):
"""This is the main function that cross-correlates specific windows of
COS with the same windows for Reference.
Parameters
----------
dataset : str
name of file to be correlated to
reference : str
... |
def Execute_Go(user_input):
global janitorActive
if len(user_input)>1:
if user_input[1] in map.directions:
if player.current_room.Has_Exit(user_input[1]):
if not player.current_room.locked[user_input[1]]:
player.current_room = map.rooms[player.current_room... | The main task of the code is to process user commands in a text-based game. It directs actions like moving, taking, dropping, or using items via corresponding functions. If the "janitorActive" flag is true, it specifically checks for using a "cookie" item to deactivate the janitor, removing the cookie from the player's... | def Process_Command(user_input):
# call correct function
global janitorActive
if not janitorActive:
if user_input[0] in ["go", "move"]:
Execute_Go(user_input)
elif user_input[0] in ["drop"]:
Execute_Drop(user_input)
elif user_input[0] in ["take"]:
... |
def updateStatusIndicator(self, status):
"""Update the status indicator's text and background color based on the status."""
color_map = {
"OK": ("#909090", "black"), # Light green background, black text
"READY": ("#90EE90", "black"), # Light green background, black text
... | The code computes cosine similarity between image embeddings using a CLIP model, filters pairs based on user-defined difficulty ranges, and displays randomly selected similar image pairs in a GUI. It loads models, preprocesses images, normalizes embeddings, calculates similarities, and updates the interface with result... | def computeCosineSimilarity(self):
device = "cuda" if torch.cuda.is_available() else "cpu"
# Get and cap the min and max values from user input
# Load the selected model
self.updateStatusIndicator("RUNNING") # Update status to 'RUN'
QApplication.processEvents()
modelName... |
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def login():
clear_screen()
mobile_number = input("Enter mobile number: ")
pin = input("Enter PIN: ")
cursor.execute('SELECT * FROM users WHERE mobile_number=%s AND pin=%s', (mobile_number, pin))
user = cursor.fetchone()
i... | The main task of the code is to provide a menu-driven interface for user authentication and management. It continuously displays options for logging in, creating a new user, or exiting. Based on user input, it calls corresponding functions (`login()` or `create_user()`) and terminates the loop upon selecting "Exit," en... | def main():
while True:
clear_screen()
print("\n===== Welcome to the UPI App =====")
print("1. Login")
print("2. Create a new user")
print("3. Exit")
choice = input("Select an option: ")
if choice == '1':
login()
elif choice == '2':
... |
def permute_1(my_key):
hold = 0
perm_1_list = [57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
... | This code implements a DES-like encryption algorithm. It converts a hexadecimal key into an integer, generates 16 subkeys through permutations, and encrypts each 64-bit plaintext block in 16 rounds using these subkeys. The process involves initial permutation, round functions, left-right swapping, and inverse permutati... | def startEncryption(messageBlocks, key):
#convert key
key = int(key, base=16)
#generate list of subkeys
subkeys=[]
next_key = permute_1(key)
for i in range(16):
next_key=get_subkey(next_key,i)
subkeys.append(permute_2(next_key))
ciphertext = []
for message in messageBloc... |
def permute_1(my_key):
hold = 0
perm_1_list = [57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
... | This code decrypts ciphertext blocks using a DES-like algorithm. It converts the hexadecimal key into an integer, generates 16 subkeys via permutation functions, and applies 16 decryption rounds to each ciphertext block. Each round uses a subkey (in reverse order) with a DES function, swaps left/right halves, and appli... | def startDecrpyt(cipherBlocks, key):
#convert key
key = int(key, base=16)
subkeys=[]
next_key = permute_1(key)
for i in range(16):
next_key=get_subkey(next_key,i)
subkeys.append(permute_2(next_key))
unciphertext = []
for ciphertext in cipherBlocks:
print(f'ciphertext:... |
def newNorm2(X):
q = np.max(X) - np.min(X)
q1 = np.min(X)
a = [((x - q1)/(q+1e-60))+1e-60 for x in X]
#a = [(x + abs(q) + 1e-60) for x in X]
return a
def newNorm(X):
q = max(X) - min(X)
#print("q ",q)
a = [(x - min(X))/(q+1e-60) for x in X]
#print("a ",a)
return a
def discriminator_loss(real_output,... | The code defines a composite loss function for a neural network model, combining reconstruction errors (MSE), information-theoretic measures (Mutual Information, KL/JS divergence), and adversarial components. It calculates losses for source/target data encodings, applies PCA normalization, and weights these components ... | def loss(model, model2, original, test, Labels, lossType, alpha1, alpha2, beta1, beta2, gamma1, gamma2, delta1, delta2):
value1, value2 = model(original, test)
#print("Loss 1.0 value1", value1)
#print("Loss 1.0 original", original)
value1 = tf.cast(value1, dtype=tf.float64)
value2 = tf.cast(value2, dtype=tf.f... |
def chooseCourse(self, onlyThisTerm):
# Interactively choose a course from Canvas
strs, ids = self.listCourses(onlyThisTerm)
cli = Bullet("Choose course", strs, margin=3, return_index=True)
_, idx = cli.launch()
return ids[idx]
def chooseAssignment(self):
# Interactively choose ... | This code retrieves assignment overrides (section and student-specific due dates) from a course, separates them into two CSV files, and exports them. It selects a course and assignment, processes overrides to identify section/student-specific due dates, calculates date differences for sections, and saves dataframes as ... | def downloadAssignmentOverrides(self, onlyThisTerm = True):
# Downloads the "override" due dates from an assignment in a course
# Separate csv's are output for section overrides and student overrides
courseNum = self.chooseCourse(onlyThisTerm)
self.course = self.canvas.get_course(courseNu... |
def get_path(mangaTitle, chapterNum):
return LOCAL_PATH + mangaTitle + '/' + chapterNum + '/'
def released_or_not(mangaTitle, chapterNum):
manga_url = get_page_url(mangaTitle, chapterNum)
html = send_request(manga_url).text
return 'not released' in html
def get_page_url(mangaTitle, chapterNum, pageNum=... | The main task of the code is to download all images of a specified manga chapter by iterating through each page, checking if the chapter is released, parsing image URLs from HTML, and saving them to a designated path. It handles exceptions like unreleased chapters and failed requests, incrementing the page number until... | def download_chapter(mangaTitle, chapterNum):
current_page = INITIAL_PAGE
download_path = get_path(mangaTitle, chapterNum)
if released_or_not(mangaTitle, chapterNum): # handling exceptions
print('Not released yet')
return None
while True:
page_url = get_page_url(mangaTitle, cha... |
def process_prompt(prompt, tts_id='', idx=0, prompt_id='1', bits=0, prior_chars=0, bypass=False):
voice_alias, text = prompt
# print('Prompt:', prompt)
text = get_text_allowance(text, bits=bits, prior_chars=prior_chars, bypass=bypass)
if len(text) == 0:
return {}
voice_id = VOICE_ALIAS_2_VO... | The code processes multiple text-to-speech prompts by generating audio files for each, combining them into a single audio file, saving it with a timestamp and TTS ID, playing the sound, and returning the filename. | def process_prompts(prompts, tts_id='1', bits=None, bypass=False):
results = []
# process each pair of [<voice>, <text>]
for i, prompt in enumerate(prompts):
logging.debug('%s::::%s::::%s', tts_id, i, prompt)
result = process_prompt(prompt, tts_id=tts_id, idx=i, bits=bits, bypass=bypass)
... |
def remove_comment(self, lines):
"""remove comments and blank lines
Args:
lines (list): lines of a file
Returns:
list: processed lines
"""
tmp = []
comment = False
for line in lines:
if "/*" in line:
co... | The code scans source code files to extract struct definitions (names and fields) and type aliases (e.g., `type xxx string`), storing them in dictionaries (`objects` for structs, `type_def` for types). It skips excluded files and processes each line, parsing struct fields via `get_struct` and recording type mappings, t... | def scan_code(self):
""" scan struct and type definitions in codes
"""
# struct objects
objects = {}
# type_def: type xxx string
type_def = {}
for path in self.src_path:
for file in os.listdir(path):
if file in self.excluded or... |
def ram_address():
write_command(0x15)
write_data(0x00)
write_data(0x7f)
write_command(0x75)
write_data(0x00)
write_data(0x7f)
def write_command(cmd):
oled_cs(0)
oled_dc(0)
spi_writebyte([cmd])
oled_cs(1)
def oled_cs(x):
if x == 1:
GPIO.output(OLED_CS_PIN, GPIO.HIGH)
... | The code clears an OLED display by sending a command to fill its frame buffer with black pixels. It initializes the display, sets the RAM address, sends a clear command (0x5c), and writes a byte array of zeros across the screen's width for each row of the height, effectively erasing the display. | def clear_screen():
ram_address()
write_command(0x5c)
color_fill_byte = [0x00, 0x00] * SSD1351_WIDTH
oled_cs(0)
oled_dc(1)
for i in range(0, SSD1351_HEIGHT):
spi_writebyte(color_fill_byte)
oled_cs(1) |
def oled_cs(x):
if x == 1:
GPIO.output(OLED_CS_PIN, GPIO.HIGH)
elif x == 0:
GPIO.output(OLED_CS_PIN, GPIO.LOW)
def oled_rst(x):
if x == 1:
GPIO.output(OLED_RST_PIN, GPIO.HIGH)
elif x == 0:
GPIO.output(OLED_RST_PIN, GPIO.LOW)
def delay(x):
time.sleep(x / 1000.0)
def wr... | The code initializes an OLED display by configuring its settings, resetting the device, setting column/row addresses, adjusting display parameters (like remap, start line, offset), and enabling the display. It sends a series of commands and data to the OLED controller to prepare it for normal operation, including locki... | def device_init():
print('Initializing OLED...')
oled_cs(0)
oled_rst(0)
delay(500)
oled_rst(1)
delay(500)
write_command(0xfd) # command lock
write_data(0x12)
write_command(0xfd) # command lock
write_data(0xB1)
write_command(0xae) # display off
write_command(0xa4) # ... |
def compute_obj(self, pcovered, covered):
Yhat = np.zeros(int(self.N))
Yhat[pcovered] = 1
#rejection = self.paccept <= 0.5
Yhat[~covered] = self.Yb[~covered] # self.Y[~covered]#
numRejects = 0
#numRejects += sum(self.Yb[covered & rejection] != Yhat[covered & rejection])... | This code trains a rule-based model by iteratively optimizing rule sets (prules/nrules) to minimize an objective function balancing classification error, coverage, contradiction penalties, and interpretability. It uses simulated annealing, updating rule selections based on acceptance probabilities, and tracks performan... | def train(self, Niteration=5000, print_message=False, interpretability='size', T0=0.01):
self.maps = []
int_flag = int(interpretability == 'size')
T0 = T0
nprules = len(self.prules)
pnrules = len(self.nrules)
prs_curr = sample(list(range(nprules)), 3)
if self.forc... |
def objective(X):
return -np.log(np.linalg.det(X))
def constraints_barrier(X, a):
return -sum(np.log(-constraint(X, ai)) for ai in a)
def objective_gradient(X):
return -np.linalg.inv(X)
def constraints_barrier_gradient(X, a):
return np.sum(np.array([-1/constraint(X, ai) * constraint_gradient(ai) for ai ... | The code solves an optimization problem using a barrier method with gradient descent to find a matrix X, iteratively adjusting parameters until convergence. It initializes X with a scaled identity matrix, updates the objective function and gradient in each iteration, and refines X with additional iterations post-loop. ... | def solve(A: np.ndarray) -> np.ndarray:
m, dim = A.shape # Dimension of the matrix X
max_norm = np.max(np.linalg.norm(A, axis=1))
X = np.eye(dim) / (max_norm**2.01) # Initial guess for X
t = BARRIER_METHOD_T0
mu_factor = BARRIER_METHOD_MU_FACTOR
while m / t > SOLVER_TOLERANCE:
print(... |
def is_app(appdir):
if os.path.isdir(appdir) == False:
return False
appdir = os.path.realpath(appdir)
for mkname in VALID_MAKEFILE_NAMES:
mkfile_path = os.path.join(appdir, mkname)
if os.path.isfile(mkfile_path):
return True
return Fals... | This function builds a specified target for an application, validates the app directory, executes the build process, captures status details (success/failure, logs, time, ELF size), and returns the result along with a status dictionary containing build metadata. | def build_target(self, appdir, make_options="", target="clean", show_output=True, logfile=None, parallel=""):
if self.is_app(appdir) == False:
return False, None
build_status = dict()
ret, ticks = self.build_target_only(appdir, make_options, target, show_output, logfile, parallel)
... |
def wait_for_icontrol(timeout=None):
"""Blocks until the TMOS control plane iControl REST service is running"""
if not timeout:
timeout = ICONTROL_TIMEOUT
end_time = time.time() + timeout
while (end_time - time.time()) > 0:
if is_icontrol():
return True
LOG.debug('wai... | The code uninstalls an iControl LX extension by identifying the installed package matching the provided RPM file name, creating an uninstall task, waiting for its completion, and exiting with success or failure status. It logs progress and errors, ensuring the specified extension is removed if installed. | def uninstall_extension(rpm_file):
"""Uninstalls an iControl LX extension"""
wait_for_icontrol()
packages = get_installed_extensions()
for package in packages:
if rpm_file.startswith(package['packageName']):
LOG.info("creating iControl REST uninstall task for %s",
... |
def extract_hog(im):
# convert grey-scale image to double format and normalize
im = im.astype('float') / 255.0
# get x and y filter
filter_x, filter_y = get_differential_filter()
# get differentials
im_dx, im_dy = filter_image(im, filter_x), filter_image(im, filter_y)
# get magnitude and ang... | This code performs face recognition by sliding a template window over the target image, extracting HOG features for both, and computing normalized cross-correlation to detect matches above a threshold. It collects bounding boxes of potential faces, trims redundant data, and applies non-max suppression to refine detecti... | def face_recognition(I_target, I_template):
template_hog = extract_hog(I_template)
bounding_boxes = np.zeros((I_target.shape[0] * I_target.shape[1], 3))
k = 0
# how many steps from previous picture, larger number - faster performance (up to 50)
iterStep = 5
for i in range(0, I_target.shape[1] -... |
def scale_data(x, m=None, s=None):
if m is None:
m = x.mean(axis=0)
if s is None:
s = x.std(axis=0)
x = (x - m) / s
return x, m, s
def gradient_descent(w, iterations, eta, loss_grad):
# decided to use batch gradient descent
for i in range(0, iterations):
loss, grad = loss... | The main task of the code is to train a model using gradient descent by scaling input data, then iteratively updating model weights (self.w) to minimize a loss function that incorporates regularization. The process uses a specified learning rate (eta) and number of iterations to optimize parameters toward reducing pred... | def _train(self, x, y, reg, iterations, eta):
# Scale the data
x, self.m, self.s = scale_data(x)
self.w = gradient_descent(self.w, iterations, eta, create_loss_grad(x, y, reg)) |
def _is_module_header(self, statement):
if isinstance(statement, ImportFrom):
return statement.module == '__future__'
if isinstance(statement, Expr):
return isinstance(statement.value, Str)
return False
def _find_line_numbers(self, node, line_numbers):
""" Populat... | The code modifies a module's AST by wrapping its body in a `TryExcept` block that handles exceptions. It identifies and moves module headers to a new list, then constructs an `ExceptHandler` for the exception context. The original body is adjusted, line numbers are tracked and assigned, and the modified AST node is ret... | def visit_Module(self, node):
new_node = self.generic_visit(node)
try_body = new_node.body
if try_body:
new_body = []
while try_body and self._is_module_header(try_body[0]):
new_body.append(try_body.pop(0))
line_numbers = set()
self... |
def _wrap_slice(self, sliceNode, index_to_get=None):
""" Wrap a slice in calls to assignment index methods.
Also build a format string for the slice.
@param index_to_get: if this is None, wrap in add_assignment_index(),
otherwise, wrap in get_assignment_index(index_to_get).
... | This function generates a string representation of a subscript target in Python code, wrapping indexes with context methods. It handles different value types (Name, Subscript, Attribute), recursively processing nested subscripts and attributes. If the value is a Name, it uses the identifier; for Subscript, it recursive... | def _wrap_subscript_target(self, subscript, index_to_get=None):
""" Build string describing subscript target and wrap indexes.
For example, "x[{!r}]" for one index. Each index will be wrapped in a
call to context.add_assignment_index() or
context.get_assignment_index().
@param i... |
def _find_line_numbers(self, node, line_numbers):
""" Populates a set containing all line numbers used by the node and its
descendants.
line_numbers is a set that all the line numbers will be added to."""
line_number = getattr(node, 'lineno', None)
if line_number is not None:
... | This code instruments Python function definitions by inserting tracking code to record execution context, including start/end line numbers, parameter values, and exception handling. It creates a local context variable via globals(), adds frame start calls, traces non-self arguments, and appends try-except blocks for mo... | def visit_FunctionDef(self, node):
""" Instrument a function definition by creating a new report builder
for this stack frame and putting it in a local variable. The local
variable has the same name as the global variable so all calls can
use the same CONTEXT_NAME symbol, but it means th... |
def _find_line_numbers(self, node, line_numbers):
""" Populates a set containing all line numbers used by the node and its
descendants.
line_numbers is a set that all the line numbers will be added to."""
line_number = getattr(node, 'lineno', None)
if line_number is not None:
... | (The code instruments a lambda expression by tracing its argument values. It generates trace calls for each parameter (excluding 'self'), wraps them with the original expression in a tuple, and replaces the lambda's body with a subscript accessing the tuple's last element, effectively preserving the original logic whil... | def visit_Lambda(self, node):
""" Instrument a lambda expression by displaying the parameter values.
We create calls to trace assignment to each argument, then wrap them
all in a tuple together with the original expression, and pull the
original expression out of the tuple.
"""
... |
def start_assignment(self):
self.assignments.append(AssignmentReport())
def set_assignment_value(self, value):
self.assignments[-1].value = value
return value
def report_assignment(self, format_string, line_number):
assignment = self.assignments[-1]
try:
display = for... | The main task of the code is to handle a simple assignment by encapsulating the steps of initializing an assignment, setting its value, reporting the assignment with a formatted string, and finalizing the assignment. It ensures proper cleanup via a `finally` block and returns the assigned value. | def assign(self, name, value, line_number):
""" Convenience method for simple assignments.
Just wraps all the separate steps for a flexible assignment. """
self.start_assignment()
try:
self.set_assignment_value(value)
self.report_assignment('{} = {{!r}}'.format(... |
def _find_line_numbers(self, node, line_numbers):
""" Populates a set containing all line numbers used by the node and its
descendants.
line_numbers is a set that all the line numbers will be added to."""
line_number = getattr(node, 'lineno', None)
if line_number is not None:
... | The code modifies a 'for' loop node by inserting a context call to mark its block's start, tracking line numbers for analysis, and preserving assignments and original body structure. | def visit_For(self, node):
new_node = self.generic_visit(node)
line_numbers = set()
self._find_line_numbers(new_node, line_numbers)
args = [Num(n=min(line_numbers)),
Num(n=max(line_numbers))]
new_body = [self._create_context_call('start_block', args)]
new... |
def _find_line_numbers(self, node, line_numbers):
""" Populates a set containing all line numbers used by the node and its
descendants.
line_numbers is a set that all the line numbers will be added to."""
line_number = getattr(node, 'lineno', None)
if line_number is not None:
... | The code processes an augmented assignment node (AugAssign) by wrapping it in a try-finally block to instrument assignment operations. It generates context calls for tracking assignments, constructs format strings for variable names, and inserts monitoring logic for assignment values. The function ensures proper line n... | def visit_AugAssign(self, node):
read_target = deepcopy(node.target)
existing_node = self.generic_visit(node)
line_numbers = set()
self._find_line_numbers(existing_node, line_numbers)
first_line_number = min(line_numbers)
last_line_number = max(line_numbers)
new_n... |
def _find_line_numbers(self, node, line_numbers):
""" Populates a set containing all line numbers used by the node and its
descendants.
line_numbers is a set that all the line numbers will be added to."""
line_number = getattr(node, 'lineno', None)
if line_number is not None:
... | This code processes assignment nodes in an AST by wrapping them in context calls for tracking, checks for untraceable attributes, and structures a try-finally block to manage assignment contexts, adjusting line numbers for accurate source mapping. | def visit_Assign(self, node):
existing_node = self.generic_visit(node)
if any(map(self._is_untraceable_attribute, existing_node.targets)):
return existing_node
line_numbers = set()
self._find_line_numbers(existing_node, line_numbers)
first_line_number = min(line_numbe... |
def fill_profiles(self, cnt):
self.fill_users(cnt)
user_ids = list(
User.objects.values_list(
'id', flat=True
)
)
avatars_path = 'uploads/avatars/'
avatar_links = [f for f in listdir(avatars_path)
if isfile(join(ava... | The code generates and populates a database with sample data (users, questions, answers, tags, likes) based on specified sizes (small/medium/large). It creates base profiles, generates entities in batches, assigns tags dynamically, and updates ratings via likes. Time tracking is implemented for each step to measure per... | def handle(self, *args, **kwargs):
users_cnt = kwargs['users']
questions_cnt = kwargs['questions']
answers_cnt = kwargs['answers']
tags_cnt = kwargs['tags']
likes_cnt = kwargs['likes']
db_size = kwargs['db_size']
if db_size:
if db_size == 'small':
... |
def process_quick_reply(messaging_event):
quick_reply_payload = messaging_event["message"]["quick_reply"]["payload"]
if quick_reply_payload == "YESLIST":
messaging_event["message"]["text"] = "Link Kijiji"
process_string_message(messaging_event)
user = User.query.filter_by(fb_id=messagin... | This function processes incoming webhook events from a messaging platform, handling different message types (quick replies, text, images, stickers, locations) by routing them to specific processing functions. It logs data for testing, filters out unsupported stickers, and returns a success response. | def process_webhook():
# endpoint for processing incoming messaging events
data = request.get_json()
print("incoming msg " + str(data)) # you may not want to log every incoming message in production, but it's good for testing
if data["object"] == "page":
print(json.dumps(data, indent=4))
... |
def q16(st, position):
route.append("q16")
ch = st[position]
if "1" <= ch <= "9":
return q17(st, position + 1)
else:
return {"status": False, "position": position, "route": route}
def q19(st, position):
route.append("q19")
ch = st[position]
if "0" <= ch <= "9":
retu... | The function `q15` processes a string `st` at a given `position`, determining the next state based on the character value. It appends `"q15"` to a route tracker, checks the character at `position`, and transitions to `q16`, `q19`, or `q20` for `"0"`, `"1"–"8"`, or `"9"` respectively. If the character is invalid, it ret... | def q15(st, position):
route.append("q15")
ch = st[position]
if ch == "0":
return q16(st, position + 1)
elif "1" <= ch <= "8":
return q19(st, position + 1)
elif ch == "9":
return q20(st, position + 1)
else:
return {"status": False, "position": position, "route": ... |
def get_face_locations(img):
"""
Returns an array of bounding boxes of human faces in a image
"""
return face_detector(img, 0)
def get_face_landmarks(img, face_locations=None):
"""
Returns facial landmarks for all faces in the image
"""
if face_locations is None:
face_locatio... | The function `get_properties` extracts facial data from an image by detecting face locations, identifying facial landmarks, and generating face encodings, returning them as a tuple for analysis or recognition tasks. | def get_properties(img):
"""
Returns face locations, landmarks and encodings
"""
# print("lessgo")
locations = get_face_locations(img)
# print("location yes")
landmarks = get_face_landmarks(img, locations)
# print("landmark yes")
encodings = get_face_encodings(img, face_locations=loc... |
def predict(filePath):
"""
Load the classifier and make the prediction
:param filePath: fasta File contains the sequences
:return: print the prediction
"""
clf = load('clf.joblib')
records = []
for record in SeqIO.parse(filePath, 'fasta'):
records.append((str(record.name), str(re... | The code defines a protein subcellular localization predictor with three modes: prediction (1), training (2), and test-and-train (3). It uses command-line arguments to specify input data, kernel type, regularization, and kernel coefficient. In training mode, it processes datasets, extracts features, and trains a model ... | def main():
"""
protein subcellular localization predictor
Usage: locPred -m <Mode> -i input [Options]
Options:
-h, --help show this help message and exit
-i, --input SEQUENCE OR Path to FastA files
... |
def _stratify_range(x, eta=1):
return (1 - np.exp(eta*x)) / (1 - np.exp(eta))
def run_tests(datagen_func, decomp_func, decompLabels, nTest=100, haveShuffle=False):
rezDict = {k: [] for k in decompLabels}
for iTest in range(nTest):
x, y, z = datagen_func()
zEff = z if not haveShuffle else shu... | This function evaluates the effect of varying parameters (alpha) on statistical decomposition methods by generating synthetic data, running tests with and without shuffling, computing effect sizes, and visualizing results via violin plots (effect sizes) and bar plots (significance fractions) across multiple methods. It... | def run_plot_param_effect_test(datagen_func, decomp_func, decompLabels,
nStep=10, nTest=1000, alphaRange=(0, 1), valThrDict=None, fontsize=10):
# alphaLst = np.linspace(*alphaRange, nStep)
alphaLst = np.linspace(0, 1, nStep)
alphaLst = _stratify_range(alphaLst, eta=5)
alph... |
def run_tests(datagen_func, decomp_func, decompLabels, nTest=100, haveShuffle=False):
rezDict = {k: [] for k in decompLabels}
for iTest in range(nTest):
x, y, z = datagen_func()
zEff = z if not haveShuffle else shuffle(z)
rez = decomp_func(x, y, zEff)
for k in rezDict.keys():
... | This function evaluates the effect of a parameter (alpha) on decomposition methods by generating synthetic data, running tests with/without shuffling, calculating effect sizes, and plotting results. It compares method performance via violin plots of test outcomes and effect sizes on a log scale, assessing significance ... | def run_plot_param_effect_test_single(datagen_func, decomp_func, decompLabels, alpha, nTest=1000, valThrDict=None):
gen_data_eff = lambda: datagen_func(alpha)
rezDF = run_tests(gen_data_eff, decomp_func, decompLabels, nTest=nTest)
rezDFsh = run_tests(gen_data_eff, decomp_func, decompLabels, nTest=nTest, ... |
def run_tests(datagen_func, decomp_func, decompLabels, nTest=100, haveShuffle=False):
rezDict = {k: [] for k in decompLabels}
for iTest in range(nTest):
x, y, z = datagen_func()
zEff = z if not haveShuffle else shuffle(z)
rez = decomp_func(x, y, zEff)
for k in rezDict.keys():
... | This function evaluates the effect size and statistical significance of different data decomposition methods across varying data sizes. It generates synthetic data, runs tests with and without shuffling, computes effect sizes, and visualizes results using violin plots for effect sizes and bar plots for significance fra... | def run_plot_data_effect_test(datagen_func, decomp_func, decompLabels, nStep=10, nTest=1000, valThrDict=None):
nDataLst = (10 ** np.linspace(2, 5, nStep)).astype(int)
dfTrueDict = {}
dfRandDict = {}
dfEffDict = {}
for nData in nDataLst:
gen_data_eff = lambda: datagen_func(nData)
re... |
def isRedshiftClusterAvailable(redshift, config):
return (getStatusOfRedshiftCluster(redshift, config) == 'available')
def getStatusOfRedshiftCluster(redshift, config):
return getRedshiftClusterProperties(redshift, config)['ClusterStatus']
def describeRedshiftCluster(redshift, config):
try:
pd.set_o... | The function waits for an Amazon Redshift cluster to become available by periodically checking its status every 2 seconds. It prints progress updates every 30 seconds and finally saves the cluster's endpoint address into a configuration file once the cluster is ready. | def waitUntilRedshiftClusterIsAvailable(redshift,config):
time_passed = 0
print("5. Creating cluster:")
while not(isRedshiftClusterAvailable(redshift,config)):
time.sleep(2)
time_passed += 2
if time_passed % 30 == 0:
print("* ClusterStatus at ", time_passed, "s: ",
... |
def getEmptySections(config):
empty_sections = []
for section in config:
for (each_key, each_val) in config.items(section):
if not each_val and each_key != 'DWH_ENDPOINT':
print("Warning: ", each_key, " is empty in [", section, "]", sep="")
if section not in e... | The main task of the code is to configure and manage a Redshift cluster by reading AWS credentials, creating necessary clients, setting up IAM roles and policies, deploying the Redshift cluster, opening TCP ports, and subsequently cleaning up resources by deleting the cluster, detaching policies, and removing IAM roles... | def main():
"""
First, we read the parameters from the dwh.cfg file.
Second, we create the clients for EC2, S2, IAM and Redshift.
Third, we create the role and the policy for the DWH.
Fouth, we create the cluster in Redshift and wait until it is available.
Then, we open the incoming TCP port.
... |
def next_effect(self):
if self.brightness:
index = (self.current_effect_index + 1) % len(self.effect_list)
self.set_effect(str(self.effect_list[index].name))
def turn_on(self):
if self.brightness == 0:
while True:
if self.brightness + 10 > self.last_br... | This function processes incoming MQTT messages by decoding payloads and executing corresponding actions based on the message topic. It handles commands like turning devices on/off, toggling, adjusting brightness, setting effects, and parsing color values. Specific dimmer topics trigger tailored responses, including eff... | def _handle_message(self, mqttc, msg):
payload = str(msg.payload, 'utf-8')
if msg.topic == COMMAND_TOPIC:
if msg.payload.lower() == b"mode":
self.next_effect()
return
if msg.payload.lower() == b"on":
self.turn_on()
... |
def initMaze(self):
self.state = np.zeros((self.rows, self.cols), dtype=int)
self.state[self.start[0]][self.start[1]] = START
self.state[self.end[0]][self.end[1]] = END
def getCell(self, i, j):
if self.inBounds(i, j):
return self.state[i][j]
def setCell(self, i, j, cell):
... | The code generates a random maze by initializing it and setting a percentage of cells (based on the threshold) to 'BLOCKED', excluding the START and END cells. | def randMaze(self, threshold):
self.initMaze()
for i in range(self.rows):
for j in range(self.cols):
currCell = self.getCell(i, j)
if currCell != START and currCell != END and rand.random() < threshold:
self.setCell(i, j, BLOCKED) |
def _train_step(self, batch):
"""Train model one step."""
# parse batch
vqidx, aux, mel, prompt, y, xlens, prompt_lens = batch
vqidx = vqidx.to(self.device)
mel = mel.to(self.device)
aux = aux.to(self.device)
prompt = prompt.to(self.device)
vqvec = torch.c... | The main task of the code is to train a model for one epoch by iterating through batches, performing training steps, checking intervals for logging/evaluation/saving, updating epoch counters, and handling distributed training shuffling. It logs progress and exits early if training finishes, ensuring synchronization in ... | def _train_epoch(self):
"""Train model one epoch."""
for train_steps_per_epoch, batch in enumerate(self.data_loader["train"], 1):
# train one step
self._train_step(batch)
# check interval
if self.config["rank"] == 0:
self._check_log_interv... |
def get_crypto_price(self, symbol):
try:
time.sleep(self.exchange.rateLimit / 1000)
self.exchange = screener.get_exchange()
self.markets = self.exchange.load_markets()
except:
SUCCESS = False
while SUCCESS == False:
time.sleep(5... | This function processes a list of cryptocurrencies to buy by calculating trade details (price, size, commissions), generating transaction records, and authorizing each trade if the price is valid. It iterates through symbols, computes financial metrics, updates trade IDs, and maintains trade records while updating posi... | def buy_list_of_pairs(self):
self.trade_time = datetime.now()
for symbol in self.lst_crypto_to_buy:
id = self.nb_trades
self.nb_trades = self.nb_trades+1
time = self.trade_time
price = self.get_crypto_price(symbol)
trade_size = self.get_crypto_... |
def update_lst_crypto_for_buying(self):
if self.fdp:
df_crypto_symbols = screener.get_df_selected_data_from_fdp()
df_crypto_symbols = screener.filter_df_level(df_crypto_symbols, self.filter, config.RECOMMENDATION_ALL.copy())
list_reinforced = df_crypto_symbols['symbol'].to_li... | The code determines the next trading action based on the current position status. If no position exists, it updates crypto lists, ranks potential buys, and executes purchases. If a position exists, it updates positions, sells existing pairs, refreshes crypto lists, ranks new buys, and executes purchases, effectively ma... | def next_step(self):
if self.position == False:
self.update_lst_crypto_for_buying()
self.rank_list_of_crypto_to_buy()
self.buy_list_of_pairs()
else:
self.update_my_positions()
self.sell_list_of_pairs()
self.update_lst_crypto_for_buy... |
def copy_files(src_dir, dst_dir, pattern=None, filelist=None, file_suffix=None, prefix=None, suffix=None):
for filename in list_files(src_dir, pattern=pattern, filelist=filelist):
move_file(src_dir, dst_dir, filename, file_suffix=file_suffix, prefix=prefix, suffix=suffix)
def copy_src_platform_files(platfor... | The main task of the code is to generate platform-specific source and header files for Darwin-based systems (iOS, macOS, tvOS, watchOS). It copies common files, platform-specific source files, and builds aggregated headers that include all platform variants. The function conditionally handles each platform based on inp... | def generate_source_and_headers(
generate_osx=True,
generate_ios=True,
generate_tvos=True,
generate_watchos=True,
):
copy_files('src', 'darwin_common/src', pattern='*.c')
copy_files('include', 'darwin_common/include', pattern='*.h')
if generate_ios:
copy_src_platform_files(ios_simul... |
def loadData(self):
qry = db_session.query(purchases)
df = pd.read_sql(qry.statement, qry.session.bind)
# remove records whose prod_name contains 'spare' or 'service'
df['transaction_date'] = pd.to_datetime(df['transaction_date'])
df=df[df['prod_name'].str.lower().str.contains('s... | The code initializes a class by loading customer data, filtering to separate training and testing datasets, sorting client IDs, and initializing models with and without input features. | def __init__(self):
# get the inbox_table
df = self.loadData()
# apply filter to select customers in training dataset
self.train_client_ids = self.filters(df,1)
# get all customers
self.all_client_ids = list(set(list(df['cont_id'])))
# get customers in testing dat... |
def build(self,df):
# one-hot encoding for categorical columns
cateCols = {'prod_name'}
dfCate = pd.DataFrame(df,columns=cateCols)
dfCate = pd.get_dummies(dfCate)
dummCols = []
for i in list(dfCate.columns):
if i.find('_nan')==-1:
dummCols.appe... | The code recommends products to a client using k-nearest neighbors (KNN). It extracts the client's features, trains a model on historical data, finds similar clients via KNN, and suggests products preferred by those similar clients. Results are filtered, sorted, and returned as recommended products. | def recommend1(self, client_id):
dfCur = self.df.copy()
self.build(dfCur)
self.Training_data(dfCur)
row1 = self.data[self.data['cont_id']==str(client_id)]
x_test = np.array(row1).astype(np.float)
x_test = x_test[0][:-1]
x_train = self.train_x
y_train = se... |
def build(self,df):
# one-hot encoding for categorical columns
cateCols = {'prod_name'}
dfCate = pd.DataFrame(df,columns=cateCols)
dfCate = pd.get_dummies(dfCate)
dummCols = []
for i in list(dfCate.columns):
if i.find('_nan')==-1:
dummCols.appe... | The main task of the code is to recommend products to a client based on their transaction history using a k-nearest neighbors algorithm. It filters training data, extracts client-specific features, predicts similar items, and returns sorted recommendations from the dataset. | def recommend2(self, client_id):
#dfTrain=self.dfTrain[['CAT1', 'model_id', 'famille_intitule','sous_famille_intitule', 'modele_intitule']].drop_duplicates()
dfCur = self.df.copy()
dfCur=dfCur[(dfCur['transaction_id']!='suggestion')]
self.build(dfCur)
self.Training_data(dfCur)
... |
def gen_key(q):
key= secrets.SystemRandom.randint(cr, pow(10,20),q)
while gcd(q,key)!=1:
key=secrets.SystemRandom.randint(cr, pow(10,20),q)
return key
def power(a,b,c):
x=1
y=a
while b>0:
if b%2==0:
x=(x*y)%c
y=(y*y)%c
b=int(b/2)
return x%c
def enc... | The main task of the code is to demonstrate a cryptographic protocol involving key generation, encryption, and decryption. It uses large random primes (q, g) and a private key to generate a public key (h). The message is encrypted using the public key and decrypted with the private key, showcasing secure message transm... | def main():
msg=input("Enter message.")
q=secrets.SystemRandom.randint(cr, pow(10,20),pow(10,50))
g=secrets.SystemRandom.randint(cr, 2,q)
key=gen_key(q)
h=power(g,key,q)
print("g used=",g)
print("g^a used=",h)
ct,p=encryption(msg,q,h,g)
print("Original Message=",msg)
print("Encry... |
def main_message():
"""Display menu of options."""
print('\n\n*************==========================*****************')
print('\nGST Calculator version 0.5')
print('Created by Jeff Mitchell, 2019')
print('\nOptions:')
print('\n1. Help Menu')
print('2. Calculate from a GST-exclusive amount')... | This code implements a menu-driven GST calculation application. It allows users to calculate GST-exclusive/inclusive prices, view/set GST rates, and manage records via a looped interface. Input validation ensures valid selections between 0-8, with options for help, calculations, rate adjustments, and exit. Unimplemente... | def main():
# Initialise GST rate
gst_rate = 0.15
# Initialise records_dict
records_dict = {}
repeat = True
low = 0
high = 8
while repeat:
try_again = False
main_message()
try:
action = int(input('\nPlease enter the number for your '
... |
def reset(self):
"""Sets flags to default False values."""
self.head_played = False
self.doubles = False
self.head_forced = False
def count_points(self, s_index, t_index):
"""Returns sum of points occupied by a player between 2 indexes."""
return sum([point.stack[-1].colo... | This function determines valid moves in a backgammon game based on current board state, player color, and dice rolls. It checks for bearing-off conditions, blockages, and move validity across all positions, handling special cases for doubles and forced moves. It returns True if moves exist, False if no moves are availa... | def get_moves(self, rolls, player):
"""Gets available moves."""
if rolls == []:
self.reset()
return False
self.moves = {}
self.player = player
if self.board and self.count_points(0, 18) == 0:
self.player.bear_off = True
self.rotate(se... |
def get_all_combinaison(containers: List[Container], target_capacity: int) -> List[List[int]]:
return __get_all_combinaison(containers, Range(target_capacity, target_capacity))
def get_combinaison_prices(combinaisons: List[List[int]], containers: List[Container]):
def get_price(combinaison, containers):
... | The code computes the cheapest combination of containers that exactly meets a specified target capacity by generating all valid combinations, calculating their prices, and selecting the combination with the lowest cost. | def compute_cheapest_containers(containers: List[Container], target_capacity: int):
combinaisons = get_all_combinaison(containers, target_capacity)
prices = get_combinaison_prices(combinaisons, containers)
cheapest_price, cheapest_combinaison = get_cheapest_combinaison(prices, combinaisons)
return chea... |
def Check_KEYDOWN(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
if event.key == pygame.K_LEFT:
self.ship.moving_left = True
if event.key == pygame.K_UP :
self.ship.moving_top = True
if event.key == pygame.K_DOWN:
... | This function processes Pygame events: checks for quit requests, handles key presses/releases by calling respective methods, and detects mouse clicks to check if the play button is pressed. It updates game state based on user input, ensuring proper exit on quit events and triggering actions for keyboard and mouse inter... | def check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self.Check_KEYDOWN(event)
elif event.type == pygame.KEYUP:
self.Check_KEYUP(event)
... |
def check_fleet_edges(self):
# check if alien hit the edge
for alien in self.aliens.sprites():
if alien.check_edge():
self.change_fleet_direction()
break
def ship_hit(self):
if self.stats.ships_left > 0:
# Removes a life of a player
... | The main task of the code is to update alien movement, check for collisions between the ship and aliens, detect if aliens reach the screen's edge, and verify if any aliens have hit the bottom of the screen. It handles alien fleet behavior, collision detection, and game state responses like triggering "ship_hit()" when ... | def update_alien(self):
# Runs two functions the first one moves the fleet of alien and the second checks if the alien have hit and edge
self.aliens.update()
self.check_fleet_edges()
# Runs an if function to check for a collide between ship and alien
if pygame.sprite.spriteco... |
def check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self.Check_KEYDOWN(event)
elif event.type == pygame.KEYUP:
self.Check_KEYUP(event)
... | The code defines a game loop that continuously checks for events, updates game elements (ship, bullets, aliens) if the game is active, and refreshes the screen. It maintains gameplay by processing user input, moving objects, handling bullet behavior, alien movement, and rendering the updated game state in real-time. | def run_game(self):
while True:
self.check_event()
if self.stats.game_active:
self.ship.update()
self.bullets.update()
self.update_bullet()
self.update_alien()
self.update_screen() |
def stopping_condition(self, data:pd.DataFrame):
"""check whether to stop extending decision tree
Args:
data (pd.DataFrame): dataset
Returns:
Bool: stop or not
"""
assert len(data.columns.values) > 0, "Cannot find the label column"
if len(data.co... | The main task of the code is to recursively build a decision tree by partitioning the input dataset based on the best attribute split. It creates leaf nodes when stopping conditions are met, assigns class labels, and constructs internal nodes with child subtrees for each split condition. The function returns the root n... | def grow(self, data:pd.DataFrame):
"""recursion to grow tree
Args:
data (pd.DataFrame): dataset
Returns:
Node: root of the decision tree
"""
if self.stopping_condition(data):
# finnally we reach the leaf
leaf = Node()
... |
def state_1(self):
# -- CREATE UDP SOCKET
print(f"{bcolors.OKBLUE}Client started, listening for offer requests...{bcolors.RED}")
try:
UDP_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDP_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... | The code's main task is to initiate a client connection to a server by retrieving server details, attempting to connect, handling potential failures, and managing the TCP socket. It progresses through states (1-3) to establish and close the connection, with error handling for disconnections and socket closure issues, w... | def start_client(self):
server_ip, server_port, failed = self.state_1()
if failed:
return
print(f"{bcolors.OKBLUE}Received offer from " + server_ip + ", attempting to connect...")
failed = self.state_2(server_ip, server_port)
if failed:
return
sel... |
def header():
Information = []
response = requests.get('https://abcnews.go.com/International')
soup = BeautifulSoup(response.text, 'html.parser')
Article = soup.find('section', attrs={'class':'ContentRoll__Item'})
Article = Article.find("a").get("href")
link = Article
response = requests... | The main task of the code is to aggregate news data from multiple sources (header, Bing News, CNN, Washington Post, The Guardian) by calling their respective functions, compiling the results into a list, and returning it as a consolidated news collection. | def News():
info0 = header()
info1 = bingNews()
info2 = CNN()
info3 = WashingtonPost()
info4 = TheGuardian()
info = []
info.append(info0)
info.append(info1)
info.append(info2)
info.append(info3)
info.append(info4)
return info |
def ensure_loaded(data_file, data_directory):
if os.access(data_file, os.R_OK):
print("Cached file found, using it directly")
with open(data_file, "r") as f:
data = json.load(f)
else:
print("Cached file not found, parsing log files...")
data = load_all(data_directory)... | The main task of the code is to create an output directory, load data from a specified file, initialize a testbed environment, and generate visualizations for each experiment in the `EXPERIMENTS` list by calling `plot_all` with the loaded data and experiment parameters. The code handles potential directory creation err... | def main():
try:
os.mkdir(OUT_DIR)
except:
pass
data1 = ensure_loaded(DATA_FILE, DATA_DIRECTORY)
# data2 = ensure_loaded(DATA_FILE2, DATA_DIRECTORY2)
load_testbed()
for exp in EXPERIMENTS:
plot_all(data1, exp) |
def safe_mkdir(dirname):
try:
os.mkdir(dirname)
except:
pass
def ensure_loaded(data_file, data_directory):
if os.access(data_file, os.R_OK):
print("Cached file found, using it directly")
with open(data_file, "r") as f:
data = json.load(f)
else:
print("... | The main task of the code is to create directories, load data, and generate plots for network performance metrics. It first ensures the existence of output and testbed directories, loads dataset from a file, then iterates through experiments to plot packet delivery ratio (PDR), packet arrival rate (PAR), and queue loss... | def main():
safe_mkdir(OUT_DIR)
for local, remote in TESTBED_DIRS:
safe_mkdir(local)
safe_mkdir(remote)
data = ensure_loaded(DATA_FILE, DATA_DIRECTORY)
for exp in EXPERIMENTS:
plot_all_pdr(data, exp)
plot_all_par(data, exp)
plot_all_queue_losses(data, exp) |
def patient_distance(df, ax, gt_dict, fontsize=20):
df['gt_label_str'] = [gt_dict[str(i)] for i in df['label']]
df_2img = df[df['img_per_patient'] > 1]
for idx, label in enumerate(gt_dict.values()):
ax.plot(df_2img[df_2img['label'] == idx]['patient_mean'],
df_2img[df_2img['label'] ==... | The main task of the code is to generate and visualize multiple diagnostic plots (patient distance, 3-class distribution, ROC curves, and confusion matrix) from input data, using specified parameters and saving the combined visualization as an image file. It processes label mappings, extracts model predictions, calcula... | def plot_graphs(df, n_class, output_path, model_type, name, label_dict=None):
fig, ax = plt.subplots(1, 4)
fig.set_size_inches(32, 6)
if label_dict is not None:
gt_dict = json.load(open(label_dict, 'r'))
else:
gt_dict = {str(i): i for i in range(df['label'].max() + 1)}
patient_dista... |
def load_pred(df, colname='pred'):
return list(np.array([eval(str(j)) for j in df[colname]]))
def load_mc_pred(df, n_it=50):
mc_pred = []
for i in range(n_it):
col_name = "mc_epistemic_" + str(i)
mc_pred.append([eval(j) for j in df[col_name]])
return list(np.array(mc_pred).swapaxes(0, 1)... | This function generates visualizations from medical prediction data by reading and processing a CSV file, converting prediction formats, combining patient data, and plotting graphs based on model type, saving outputs to a specified path. | def generate_plots(output_path: str,
predfile_path: str,
label_colname: str,
image_colname: str,
patient_colname: str,
gt_dict_path: str,
name: str,
merge_per_patient: bool = True,
... |
def _get_num_samples_from_timestamps(audio_samplerate: int, start_timestamp: float, end_timestamp: float) -> int:
"""Function that returns the number of samples covered by a word, provided its
timestamps as strs.
Parameters
----------
start_timestamp: float
The starting timestamp from the a... | This function replaces a specified time segment in an audio array with a 1000Hz bleep sound. It calculates the required number of samples based on timestamps, generates a matching bleep signal, and replaces the original audio segment using a helper function. If the segment duration is zero, it returns the original audi... | def bleep_audio_segment(audio_ndarray: np.ndarray, audio_samplerate: int, start_timestamp: float, end_timestamp: float) -> np.ndarray:
"""Shortcut function to call without having to generate your own replacement
signal."""
num_samples = _get_num_samples_from_timestamps(audio_samplerate=audio_samplerate... |
def _spawn_gold(self):
"""Spawn gold on a random EMPTY tile."""
empty_coords = np.argwhere(self.map_disc == TileTypes.EMPTY)
if len(empty_coords) > 2:
gold_xy = empty_coords[random.randint(0, len(empty_coords) - 1)]
self.map_disc[tuple(gold_xy)] = TileTypes.GOLD
... | This code implements a reinforcement learning environment step function. It handles player movement, gold collection, enemy detection, and environment updates. The agent receives rewards for surviving, collecting gold, and defeating enemies. The function checks for game-ending conditions (e.g., player death, max steps)... | def step(self, action):
if np.sum(self.map_onehot[TileTypes.ENEMY]) != len(self._xys_to_enemies):
TT()
if len(self._xys_to_enemies) == 0 or self.map_onehot[TileTypes.ENEMY].sum() == 0:
self._n_tick_no_enemy += 1
else:
self._n_tick_no_enemy = 0
if self.... |
def _create_cells(self):
for i in range(self._num_cols):
cells_in_col = []
for j in range(self._num_rows):
cells_in_col.append(Cell(self._win))
self._cells.append(cells_in_col)
for i in range(self._num_cols):
for j in range(self... | This code initializes a maze structure with specified dimensions, creating cells and using recursive backtracking to break walls, forming a solvable path. It sets entrance/exit points, resets visited status, and applies a seed for reproducible randomness. | def __init__(self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None):
self._x1 = x1
self._y1 = y1
self._num_rows = num_rows
self._num_cols = num_cols
self._cell_size_x = cell_size_x
self._cell_size_y = cell_size_y
self._win = win
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.