dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def parse_metainfo(self,metainfo) -> dict:
decoder = bencodepy.Bencode(
encoding='utf-8'
)
with open(metainfo,"r") as torrent:
data = torrent.read()
# data = json.loads(data)
# print(data)
data = decoder.decode(data)
# print... | The main task of the code is to download a file via a BitTorrent-like protocol by parsing metadata, connecting to a tracker to find peers, downloading file pieces from available peers, and merging them into a complete file. It checks for existing pieces, manages piece storage, and handles peer communication to ensure f... | def download_file(self,metainfo_path):
metainfo = self.parse_metainfo(metainfo_path)
annouce = metainfo.get("announce")
annouce = annouce.split(":")
tracker_ip = annouce[0]
tracker_port = int(annouce[1])
file_path = metainfo.get("info").get("name").split(".")
file... |
def get_groups(path : str) -> pd.DataFrame:
'''
This method reads the groups file and returns a dataframe with the groups and their members.
pending : list
Parameters
----------
path : str
The path to the groups file.
Returns
-------
A dataframe with the groups ... | This code automates marking quizzes from SUNLearn by processing student responses, grouping data, applying a predefined scoring lookup table, calculating team averages, and generating scaled scores. It handles self-ratings, flags incomplete submissions, adjusts scores based on group performance, and outputs results wit... | def mark(args, self_rate: bool = True,settings: dict = {
"capped_mark": 1.1,
"correct_ids": True,
"create_file": True,
}, lookup:dict = {
'E': 100,
'V': 87.5,
'S': 75,
'O': 62.5,
'M': 50,
'D': 37.5,
'U': 25,
'F': 12.5,
'N': 0,
}):
'''
This script is designed to ta... |
def remove_nodes(super_adjacency, super_vertices, nodes_to_remove):
#Input original adjacency matrix and the vertices and nodes to remove
n_remove = len(nodes_to_remove)
n_super = len(super_adjacency)
sub_adjacency = np.delete(super_adjacency, nodes_to_remove, 0)
sub_adjacency = np.delete(sub_adjac... | The function generates all spanning trees of a subgraph formed by removing specified nodes from the original graph, then expands each spanning tree back to the original graph's size by re-adding the removed nodes, returning these expanded adjacency matrices as a list. | def adjacencies_with_nodes_removed(adjacency_mat, vertices, comb_to_remove):
sub_adjacency, sub_vertices, sub_to_super_node_mapping, super_to_sub_node_mapping, super_coord_sub_vertices = \
remove_nodes(adjacency_mat, vertices, comb_to_remove)
sub_spanning_trees = find_all_spanning_trees(sub_adjacency, ... |
def complete_task(contact_id, task_id):
form = TaskForm()
contact = Contacts.query.filter_by(contact_id=contact_id, team_id=g.team_id).first()
tasks = "Not None"
google_token = session.get("google_token")
task_list = get_task_list(contact)
task = google.get(url=f"https://tasks.googleapis.com/tas... | The function `tasks_activity` manages contact tasks by handling task completion, adding new tasks via a form, and updating UI elements. It uses Google authentication; if unauthenticated, it redirects to authorization. It categorizes tasks into upcoming, past due, and completed, streams updates to the activity box if su... | def tasks_activity(contact_id, google_token, contact, complete="false"):
form = TaskForm()
upcoming_tasks, past_due_tasks, completed_tasks = None, None, None
tasks = None
if google_token != None:
if complete != "false":
complete_task(contact_id, complete)
timestamp = date... |
def send_email(subject, message, from_email, to_email, reply=None):
"""Function to send an email with an oAuth authenticated google account."""
message = MIMEText(message)
message["from"] = from_email
message["to"] = to_email
if reply != None:
# reply[0] is the message_id we wish to reply to... | The function handles email activities on a contacts page by sending emails via Google's API if authorized, validating forms, logging activities, fetching user emails, and updating the page with Turbo streaming or full rendering based on authentication status and form submission outcomes. | def email_activity(google_token, form, google_email, contact_id, contact, reply):
"""Function for the email activity on the contacts page."""
# Make sure user has authorized their google.
if google_token != None:
# If the user's submitted a valid email, send the email on their behalf... |
def email_activity(google_token, form, google_email, contact_id, contact, reply):
"""Function for the email activity on the contacts page."""
# Make sure user has authorized their google.
if google_token != None:
# If the user's submitted a valid email, send the email on their behalf... | This function handles contact-specific activities by routing requests to appropriate functions based on the 'activity' parameter. It retrieves contact data, processes forms, and delegates tasks like emails, notes, meetings, or tasks to dedicated functions, using Google authentication tokens and contact details. The 'co... | def contact(contact_id, activity, reply, complete):
"""contact =
This is the route for the contact page i.e. an individual contact, not the list.
Calls the relevant function depending on user selection.
<activity>
----------
emails -- Sending and viewing emails to and from the contact.
note... |
def output_json(self) -> Tuple[str, str]:
"""Method to output json output
Returns:
Tuple[str, str]: returns test_name and json output
"""
_, change_points_by_metric = self._analyze()
dataframe_json = self.dataframe.to_json(orient="records")
dataframe_json = j... | The method selects and returns the appropriate output method based on the specified format (JSON, TEXT, JUNIT). If the format is unsupported, it raises a ValueError. | def output(self, output_format) -> Union[Any,None]:
"""Method to select output method
Args:
output_format (str): format of the output
Raises:
ValueError: In case of unmatched output
Returns:
method: return method to be used
"""
if ou... |
def smooth_shape(self, shape_x: Shape, shape_y: Shape):
k_x = self.k
self.vert_x_smooth = torch.mm(shape_x.evecs[:, :k_x], shape_x.xi[:k_x, :])
weights, k_y = self._smooth_shell_weights(k_x)
self.vert_y_smooth = torch.mm(shape_y.evecs[:, :k_y], weights * shape_y.xi[:k_y, :])
def compute... | The function `hierarchical_matching` iteratively matches two shapes (shape_x and shape_y) by varying a parameter `k` over `self.param.k_array`. For each `k`, it smooths the shapes, computes deformation and correspondences, calculates the mean error, and accumulates the weighted average error. If logging is enabled, it ... | def hierarchical_matching(self, shape_x: Shape, shape_y: Shape):
tot_error = 0
for k in self.param.k_array:
self.k = k
self.smooth_shape(shape_x, shape_y)
self.compute_deformation(shape_x, shape_y)
self.compute_correspondences(shape_x, shape_y)
... |
def parse_categories(self):
return ["anime"]
def menu_items(self):
return (item for item in self.__menu_items())
def load_config(self):
if not os.path.isfile(self.config_path):
return
try:
with open(self.config_path, "r", encoding = "utf-8") as file:
self.config = json.loads(file.read())
except:
... | This code initializes a wallpaper downloader/upscaler application by setting up a requests session, handling categories, configuring a download folder, checking an image upscaler's readiness, creating directories, loading a configuration, and initializing a system tray icon for the application. | def __init__(self, categories = [], download_folder = "wallpapers", image_upscaler_object = None):
print("[Init] Starting...")
self.session = requests.Session()
self.session.headers = RANDOM_WALLPAPER_SESSION_HEADERS
self.session.get(WALLPAPERCAVE_HOST) # get cookies
print("[Session] Cookies:", self.session.c... |
def get_random_wallpaper(self, cat = None):
if cat is None:
cat = self.get_random_category()
theme = self.get_random_theme_in_category(cat)
wallpaper = self.get_random_wallpaper_in_theme(theme)
wallpaper_path = self.download_wallpaper(wallpaper)
return [wallpaper_path, wallpaper]
def set_wallpaper(self, w... | This function sets a random wallpaper by searching a category (from query or default), handling retries on failures, and displaying alerts. It uses `get_random_wallpaper` to fetch the image, sets it via `set_wallpaper`, and updates the icon title during processing. If errors occur, it retries or alerts the user, ensuri... | def set_random_wallpaper(self, icon = None, query = None):
self.icon.title = "Searching for Random Wallpaper"
cat = ""
try:
if query:
cat = str(query).strip().lower()
if cat != "set random wallpaper":
cat = WALLPAPERCAVE_HOST + "/categories/" + cat
else:
cat = None
retries = 5
wal... |
def _provision_builddir(self):
if os.path.exists(self.builddir):
shutil.rmtree(self.builddir)
dst = os.path.join(self.builddir, 'src')
source_subdir = getattr(self.options, 'source_subdir', None)
if source_subdir:
sourcedir = os.path.join(self.sourcedir, source_s... | The code's main task is to build a ROS environment by checking the source directory, provisioning a build directory if needed, fixing hardcoded paths in CMake files, managing package dependencies, and modifying the shebang line in a setup script for portability. | def build(self):
if os.path.exists(os.path.join(self.sourcedir, 'src')):
super().build()
else:
self._provision_builddir()
# Fixup ROS Cmake files that have hardcoded paths in them
self.run([
'find', self.rosdir, '-name', '*.cmake',
'-exec'... |
def build_snap(self, project_dir):
# To measure coverage, a wrapper for the snapcraft binary might be set
# in the environment variable.
snapcraft_bin = os.getenv('SNAPCRAFT', 'snapcraft')
snapcraft = os.path.join(os.getcwd(), 'bin', snapcraft_bin)
subprocess.check_call([snapcraf... | This test method verifies a snap's functionality by building it from an example directory, installing required snaps, and executing both internal and external test commands to ensure outputs match expected results. It handles filtering, setup, installation, and cleanup, raising exceptions on errors while using subtests... | def test_example(self):
filter_ = config.get('filter', False)
if filter_:
if not re.match(filter_, self.dir):
self.skipTest(
'{} does not match the filter {}'.format(
self.dir, filter_))
example_dir = os.path.join('examples... |
def construct_raw_PAM_matrix_and_get_alignment_mutation(self):
# initialize the raw PAM matrix
full_mutated_amino_acid = {'A': {}, 'R': {}, 'N': {}, 'D': {}, 'C': {}, 'Q': {}, 'E': {}, 'G': {}, 'H': {}, 'I': {},
'L': {}, 'K': {}, 'M': {}, 'F': {}, 'P': {}, 'S': {}, 'T': {}, 'W': {}, ... | The code constructs the JTT substitution matrix by initializing a 20x20 matrix, populating it using a normalized PAM matrix and relative mutability values, then adjusting entries with a proportionality constant to ensure row sums equal 1, resulting in a symmetric, mutation-rate-based amino acid substitution model. | def construct_JTT_matrix(self):
# initialize the raw JTT matrix
jtt_matrix = {'A': {}, 'R': {}, 'N': {}, 'D': {}, 'C': {}, 'Q': {}, 'E': {}, 'G': {}, 'H': {}, 'I': {},
'L': {}, 'K': {}, 'M': {}, 'F': {}, 'P': {}, 'S': {}, 'T': {}, 'W': {}, 'Y': {}, 'V': {}}
for amino_acid in ... |
def construct_JTT_matrix(self):
# initialize the raw JTT matrix
jtt_matrix = {'A': {}, 'R': {}, 'N': {}, 'D': {}, 'C': {}, 'Q': {}, 'E': {}, 'G': {}, 'H': {}, 'I': {},
'L': {}, 'K': {}, 'M': {}, 'F': {}, 'P': {}, 'S': {}, 'T': {}, 'W': {}, 'Y': {}, 'V': {}}
for amino_acid in ... | The main task of the code is to construct a normalized relatedness odd matrix by dividing each entry of a JTT matrix by the normalized frequency of the target amino acid. This adjusts substitution probabilities to account for amino acid mutation frequencies, creating a matrix that reflects relative substitution odds we... | def construct_relatedness_odd_matrix(self):
new_matrix = self.construct_JTT_matrix()
normalized_frequency = self.get_normalized_frequency(self.get_total_exposure_of_amino_acid_to_mutation())
for amino_acid in self.amino_acid_list:
for another_amino_acid in self.amino_acid_list:
... |
def log(msg):
print(msg, file=sys.stderr)
sys.stderr.flush()
def WaitOnIOActivity():
global activity_event
if LOG_FINER:
log("activity_event.wait()")
activity_event.wait()
if LOG_FINER:
log("activity_event.clear()")
activity_event.clear()
def process_command(json_command):
... | The code implements a PTY (pseudo-terminal) server that monitors and manages multiple PTY processes. It reads input from stdin, processes commands, captures output from active PTYs, sends data to a controller, and handles terminated PTYs by updating the list and notifying the controller. The loop runs until stdin EOF o... | def main():
global pty_list
running = True
if LOG_FINE:
log("pty server process starting up")
stdin_reader = NonblockingLineReader(sys.stdin)
while running:
if LOG_FINER:
log("pty server thread active count: " + str(threading.active_count()))
WaitOnIOAct... |
def _create_temp_files(self):
new_key_file = open(f'{self._key_filename()}.tmp', 'a+')
new_value_file = open(f'{self._value_filename()}.tmp', 'ba+')
new_key_file.truncate()
new_value_file.truncate()
return new_key_file, new_value_file
def _read_value(self, ptr: ValuePointer, deco... | The code reclaims storage by removing expired entries from a key-value table. It creates temporary files, iterates through existing entries, writes non-expired data to new files with updated pointers and checksums, swaps old files with new ones, and deletes expired keys from the table. | def _reclaim(self):
new_key_file, new_value_file = self._create_temp_files()
expired_keys = []
for key, ptr in self._table.items():
if ptr.is_expired():
expired_keys.append(key)
continue
offset = new_value_file.tell()
value = ... |
def _create_temp_files(self):
new_key_file = open(f'{self._key_filename()}.tmp', 'a+')
new_value_file = open(f'{self._value_filename()}.tmp', 'ba+')
new_key_file.truncate()
new_value_file.truncate()
return new_key_file, new_value_file
def _read_value(self, ptr: ValuePointer, deco... | This function repairs a database by validating each entry's checksum. It creates temporary files, reads entries from the original key file, verifies their integrity, and writes valid entries to new files. If a checksum mismatch occurs or an error is encountered, the process stops. Finally, it replaces the original file... | def _repair_db(self):
new_key_file, new_value_file = self._create_temp_files()
self._key_file.seek(0)
json_entry = self._key_file.readline()
while json_entry.strip() != '':
try:
entry = json.loads(json_entry)
encoded_value = None
... |
def _open_files(self):
self._key_file = open(self._key_filename(), 'a+')
self._value_file = open(self._value_filename(), 'ba+')
def _check_db_open(self) -> bool:
db_open_filename = self._open_filename()
is_open = os.path.exists(db_open_filename)
if not is_open:
with o... | The main task of the code is to initialize a database by creating a directory, opening files, repairing the database if necessary, and populating a table with entries from a key file. It reads JSON entries, processes 'set' type entries by storing non-expired pointers, and deletes entries of other types. This ensures th... | def _init_db(self):
os.makedirs(self._path, exist_ok=True)
self._open_files()
if self._check_db_open():
self._repair_db()
self._key_file.seek(0)
json_entry = self._key_file.readline()
while json_entry.strip() != '':
entry = json.loads(json_entry... |
def foul_action(self, shots):
self.oob()
pts = 0
for shot in range(shots):
pts_now = self.o_team.players[self.ball].free_throws()
self.o_team.box_score["points"] += pts_now
pts += pts_now
statement = f"{self.ball} is fouled and s... | This code handles a pass action in a sports simulation. If a foul occurs, it increments the defense team's pass foul count and triggers a foul action if exceeding 4 fouls. If no foul, it calculates turnover probability; if a turnover happens, it may result in an out-of-bounds or turnover event. Otherwise, it selects a ... | def pass_action(self, fouled):
# Successful pass, turnover
if fouled:
self.d_team.pass_fouls += 1
if self.d_team.pass_fouls > 4:
self.foul_action(2)
else:
to_probs = redist([self.o_team.players[self.ball].pass_success, self.d_team.rost... |
def oob(self):
self.o_team.recompute_roster()
self.d_team.recompute_roster()
statement = f"Roster changes, {self.o_team.name} subs in {self.o_team.on_field}\n"
statement += f"Roster changes, {self.d_team.name} subs in {self.d_team.on_field}"
if self.verbose:
print(sta... | This code simulates a basketball shot action, handling scoring, fouls, and possession changes. It calculates points based on shot type and fouls, updates the team's box score, and prints outcomes if verbose. It also handles blocking scenarios, rebound assignments, and possession transitions depending on whether the sho... | def shot_action(self, shot_val, fouled):
discount = 0
if fouled:
discount = .3
pts_shot = self.o_team.players[self.ball].shoot(score_type=shot_val, discount=discount)
self.o_team.box_score["points"] += pts_shot
if pts_shot == 0:
... |
def jump_ball(self):
self.possession = 1 if flip() else 2
self.first_possession = self.possession
self.init_possession()
def action(self):
# Actions:
# -1: turnover
# 0: pass
# 2: 2p fga
# 3: 3p fga
time = self.possession_incremen... | The code simulates a basketball game by initializing team rosters, tracking game state variables (clocks, possession), and processing actions (turnovers, passes, shots) in a loop until the total clock expires. It manages quarters, possession changes, and updates team scores, with methods handling game events and state ... | def play_game(self, verbose=False):
self.verbose = verbose
self.team_1.box_score["points"] = 0
self.team_2.box_score["points"] = 0
self.team_1.init_roster()
self.team_2.init_roster()
self.possession = None
self.o_team = None
self.d_team =... |
def opendcm(self):
fname = QtWidgets.QFileDialog.getExistingDirectory(self,"Open a folder",os.path.expanduser("~"),QtWidgets.QFileDialog.ShowDirsOnly)
self.path=fname.split("/")[-1]
print(fname)
print(self.path)
self.mode()
def mode(self):
if self.ui.comboBox.currentText... | The code initializes a GUI application by setting up UI components, connecting sliders and labels to event handlers for dynamic updates, and hiding specific UI elements. It configures default values for sliders and labels, links menu actions and combo box changes to functions, and establishes signal-slot connections fo... | def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.verticalSlider.setValue(100)
self.ui.verticalSlider_2.setValue(50)
self.ui.verticalSlider_3.setValue(30)
self.ui.label_6.setText("1")
self.ui.label_7.setText("0.... |
def play():
telnet_write("play")
def pause():
telnet_write("pause")
def stop():
telnet_write("stop")
def next():
telnet_write("next")
def prev():
telnet_write("prev")
def getInfo():
global title, songfile
global volume
global active
if isPlaying():
title = __getTitle()
... | This code processes a query string to execute media control commands like play, pause, stop, next, prev, queue, and volume. It splits the input into a command and optional argument, then triggers corresponding functions. For example, "play" initiates playback, "volume 50" adjusts volume, and "queue song.mp3" adds a tra... | def exec(query):
print("====> VLCQUERY " + query)
l = query.split()
command = l[0]
if len(l) > 1 :
arg = l[1]
print(command)
print(arg)
if command == "play":
print("=========> PLAY")
play()
if command == "pause":
pause()
if command == "stop":... |
def _reset_hands(self) -> None:
self.dealer.new_hand()
self.player.new_hand()
self.player.reset_played_hands()
self.player.split_count = 0
def _deal_the_cards(self) -> None:
"""
Deal the cards at the beginning of the round.
"""
players_hand: Hand = self.pl... | The main task of the code is to initiate a new game by handling betting, dealing cards, processing player and dealer turns, and evaluating outcomes. It returns True if the player successfully bets the minimum amount and the game proceeds, otherwise False if the bet fails. | def _new_game(self) -> bool:
print("------------NewGame------------")
if self.player.make_bet(bet=Game.MIN_BET):
self._reset_hands()
self._deal_the_cards()
self._players_turn(player=self.player)
self._dealers_turn()
dealers_hand: Hand = self.... |
def _deck_below_threshold(self) -> bool:
THRESHOLD = 0.2
init_deck_cards_count = self.DECKS * 52
deck_below_threshold = (
len(self.deck) / init_deck_cards_count
) < THRESHOLD
if deck_below_threshold:
print(f"Deck has less than {THRESHOLD:.0%}, last game.")... | The code simulates a series of games, continuing while the player's balance exceeds a minimum bet and the game count is under 1000. It manages game rounds, resets the deck, tracks outcomes (wins/losses/draws), and prints statistical results including win/loss ratios against the house. The process ends when the balance ... | def play_game(self):
while self.player.balance > self.MIN_BET and self.game_count < 1000:
while not self._deck_below_threshold():
if not self._new_game():
break
self.game_count += 1
self._print_summary()
self.deck = Deck(dec... |
def show_books():
mycursor.execute("SELECT book_name, details, author FROM book;") #retreive relevant information from book table
books = mycursor.fetchall()
for book in books: #print retreived information from book table
print("Book Name: {}".format(book[0]))
print("Details: {}".format(book... | The code displays a menu with four options (View Books, View Store Locations, My Account, Exit) and loops until the user selects "Exit." It processes user input to call corresponding functions: show_books(), show_locations(), or show_account_menu() after validating the user. Invalid choices prompt retries, ensuring the... | def show_menu():
go = 1 #true
while go == 1:
print("""1. View Books\n2. View Store Locations\n3. My Account\n4. Exit Program""")
user_choice = input("Please choose one of the available options: ")
user_choice = int(user_choice) #make same type
if user_choice == 1:
sho... |
def input2projectogon(single_input, radius):
projectogon = []
for i in range(0, len(single_input), 2):
sub_input = single_input[i: i + 2]
input_box = get_box(sub_input, radius)
projectogon.append(input_box)
return projectogon
def forward_to_hidden_projectogon(projectogon, affine):
... | This code verifies the robustness of a neural network against adversarial perturbations within a specified radius. It transforms the input into a "projectogon" representation, propagates it through each linear layer (excluding the last), applies label-specific projection on the final layer, and checks if the projected ... | def verify(single_input, single_label, linear_layers, radius=epsilon):
projectogon = input2projectogon(single_input, radius)
for layer in linear_layers[:-1]:
projectogon = forward_to_hidden_projectogon(projectogon, layer)
# print('done with one layer')
projectogon = forward_to_logit_projecto... |
def otool(s):
o = subprocess.Popen(['/usr/bin/otool', '-L', s], stdout=subprocess.PIPE)
for line in map(lambda s: s.decode('ascii'), o.stdout):
if line[0] == '\t':
yield line.split(' ', 1)[0][1:]
def change_non_system_libraries_path(libraries, relative_path, binary):
for lib in libraries... | This function recursively copies all non-system libraries required by a binary and its dependencies into a specified directory, adjusting their paths to be relative to the target location. It ensures proper linking by resolving dependencies, copying missing files, and updating library paths to avoid system dependencies... | def copy_dependencies(binary_path, lib_path, gst_lib_dir):
relative_path = path.relpath(lib_path, path.dirname(binary_path)) + "/"
# Update binary libraries
binary_dependencies = set(otool(binary_path))
change_non_system_libraries_path(binary_dependencies, relative_path, binary_path)
# Update depe... |
def Show_scoreboard(self,text_x=180,text_y = 45,number=1):
with self.Scoreboard_path.open("r") as scoreboard_txt:
content = json.load(scoreboard_txt)
font = pygame.font.Font(None, 45)
users_dict = sorted(content, key=lambda x: x['score'], reverse=True)
for user in users_dic... | This code implements a menu system for a Pac-Man game using Pygame, handling user interactions to switch between the main menu, scoreboard, options, and map selection screens. It initializes buttons, manages game states, and updates the display based on user input, such as clicking buttons to start the game, view score... | def Menu(self):
clock = pygame.time.Clock ( )
pygame.init()
self.screen = pygame.display.set_mode ((self.width_menu, self.height_menu))
pygame.display.set_caption ('Pac-Man')
button_start_game = Button (pygame.image.load ("buttons/Button_start_game.png"), (240, 280), self.screen)... |
def generate_tsne(self, data, d, file_2d):
dim_two = TSNE(n_components=d, random_state=1971, init='random').fit_transform(data)
mystr = ""
data_len = len(dim_two)
for i in range(data_len):
for n in range(d):
mystr += str(round(dim_two[i][n], 6))
... | The code initializes an object for data analysis, validating and preprocessing training/test data (converting to contiguous NumPy arrays), handling t-SNE dimensionality reduction if needed, and setting up structures for clustering (e.g., DenMune). It checks data consistency, ensures labels are provided, and prepares at... | def __init__(
self,
train_data=None,
test_data=None,
train_truth=None, test_truth=None,
file_2d=None, k_nearest=1,
rgn_tsne=False, prop_step=0,
):
"""Initiate object in Null-state. User should ... |
def run(command):
return os.system(command) == 0
def zenity(command):
x = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
(stdout,error) = x.communicate()
res = str(stdout)[2:-3].strip() # slicing to get rid of quotes and new line character
return res
def doit(comm... | The main task of the code is to capture user input via a GUI dialog using `zenity`, split the input into a command and arguments, store the arguments in the global `rest` variable, and execute the command using the `doit()` function if a command is provided. | def gui():
global rest
if run('killall zenity'):
return
output = zenity("zenity --title='Shelp' --entry --text='Enter a shelp command:'")
output = output.split(" ")
command = output[0]
rest = " ".join(output[1:])
if command: doit(command) |
def get_most_used_colors(self, number_of_colors=COLOR_PALETTE):
image_buffer = self.convert_string_to_image_buffer(self.icon_string)
try:
colorthief = ColorThief(image_buffer)
return colorthief.get_palette(number_of_colors)
except Exception as e:
return None
... | This code initializes an object with icon data, validates the icon by downloading its content, extracts dominant colors, converts them to hex format, and saves the result to disk. It handles download errors by marking the icon as invalid. | def __init__(self, icon, orig_url):
self.icon = icon
self.orig_url = orig_url
self.valid = True
self.width = icon.width
self.height = icon.height
self.format = icon.format
try:
self.icon_string = requests.get(self.icon.url, timeout=5).content
... |
def FTIR():
thick_film_2 = 0.005
thick_film_data = 0.00005 # * Dont change unless data changes * thickness of film used for ftir data [m]
path = r"D:\Masters related\Python Code\FTIR data\csv_files\Edit-coldtubeT.csv"
file = open(path, newline='')
reader = csv.reader(file)
trans = []
... | This Python function simulates heat transfer in a building panel system, calculating thermal performance metrics like heat gain, surface temperatures, and comfort indices (MRT, PMV). It uses TRNSYS inputs for environmental conditions, computes radiative/convective heat exchange, and outputs values for energy modeling. ... | def PythonFunction():
#model performance
deltaT = 0.5
orientation = 0 #0 for vertical panel, 1 for horizontal
#Variables for multiple modes of heat transfer
panel_height = 18 #[m]
panel_width = 10 #[m]
insulation_thicknes = 0.15 #[m]
A_cs = panel_height*p... |
def create_bounding_rectangle(tf_details: pd.DataFrame, temp_cropped_df: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
"""
Create 2 lists of coordinates according to the zoom, the coordinates and the color that appear in
"tf_details" dataframe and save those in the temporary df sent, then returns the list... | The function generates a Pandas DataFrame where each row represents a cropped image of suspicious traffic light (TL) points, including metadata like coordinates (x0, x1, y0, y1), color, path, and flags (is_true, is_ignore). It processes image data, calculates bounding rectangles for TLs, labels cropped regions, and agg... | def create_pandas_cropped_images():
"""
Create a dataframe Pandas where each row represent a cropped rectangle image of suspicious TL point
as below:
seq is_true is_ignore path x0 x1 y0 y1 col(or)
0 0 False False aachen_000001... |
def get_error(self,idx):
if 0 < self.multipliers[idx] < self.C:
return self.error_cache[idx]
else:
return self.predict(self.X[idx]) - self.y[idx]
def non_bound_index(self):
lst = []
for i in range(self.m):
if 0 < self.multipliers[i] and self.multiplier... | The main task of the code is to find an optimal second multiplier (i1) for coordinate descent with a given first multiplier (i2), checking non-bound multipliers first to maximize |E1 - E2|. If no improvement is found, it randomly samples other multipliers. It returns 1 if any improvement occurs during coordinate descen... | def examineExample(self, i2):
'''
Takes a multiplier, searches for an optimal second multiplier to then
perform coordinate descent and informs the calling function whether
the multipliers have been improved or not
:param i2: index of the first chosen multiplier
:return:... |
def check_data(self):
if not self.ready:
raise Exception("Missing Data Input")
def examineExample(self, i2):
'''
Takes a multiplier, searches for an optimal second multiplier to then
perform coordinate descent and informs the calling function whether
the multipliers ... | (This code trains a Support Vector Machine (SVM) using the Sequential Minimal Optimization (SMO) algorithm. It iteratively adjusts Lagrange multipliers to satisfy KKT conditions by examining all or non-bound multipliers, updating them until convergence. The loop alternates between full-set and non-bound-index checks ba... | def train(self):
'''
Trains the SVM
:Pre-Condition: data and hyperparameters have to be already set
:return: None
'''
self.check_data()
numChanged = 0
examineAll = True
# modify multiplier pairs until the entire set
# of multipliers sa... |
def save_logs(self):
print('___________________________saving logs_______________________')
np.save(f'{self.log_save_path}/M_x_log', self.M_x_log)
np.save(f'{self.log_save_path}/M_y_log', self.M_y_log)
np.save(f'{self.log_save_path}/M_z_log', self.M_z_log)
np.save(f'{self.log_sav... | The main task of the code is to reset the environment's state variables (duration, done, success, reward), record the last action, set a new goal based on the current angle (theta), and immediately execute a step with the provided action. This prepares the environment for a new episode or action sequence while logging ... | def reset(self, action):
self.save_logs()
self.duration = 0
self.done = 0
self.success = 0
self.reward = 0
if self.verbose: print('taking observation')
self.take_observation()
if self.verbose: print('successfully took observation')
self.goal = self... |
def update(state_batch, action_batch, reward_batch, next_state_batch, done_batch, pi_model, q1_model, q2_model, target_q1, target_q2):
global alpha
critic_optimizer = tf.keras.optimizers.Adam(CRITIC_LR)
actor_optimizer = tf.keras.optimizers.Adam(ACTOR_LR)
_,action_next,logp_action_next = poli... | This function performs a learning step in a Soft Actor-Critic (SAC) algorithm by updating Q-networks, policy, and entropy temperature parameter using collected experience batches. It calculates Q-losses, policy loss, and entropy, updates target networks via soft updates, and returns all loss values and entropy for moni... | def learn(state_batch, action_batch, reward_batch, next_state_batch, done_batch, pi_model, q1_model, q2_model, target_q1, target_q2, log_alpha, minibatches):
#print('learn function called')
q1_loss, q2_loss, pi_loss = update(state_batch, action_batch, reward_batch, next_state_batch, done_batch, pi_model, q1_... |
def parse_args() -> Optional[str]:
args = sys.argv[1:]
argc = len(args)
for arg in args:
if arg in ('/h', '-h'):
print_usage()
sys.exit(0)
if argc > 1:
abort(reason="Invalid number of arguments. Abort.", return_code=2, usage=True)
return None if argc == 0 e... | This function initializes and manages a camera process using Vimba, handling frame acquisition and processing. It parses camera arguments, sets up the camera, creates a Handler to process frames via queues (frame_q, frame_request_q), starts streaming with a buffer, waits for shutdown, and handles errors by signaling ab... | def camera_process(frame_q, frame_request_q, abort_q):
try:
print('camera process id:', os.getpid())
cam_id = parse_args()
with Vimba.get_instance():
with get_camera(cam_id) as cam:
setup_camera(cam)
handler = Handler(frame_q, frame_reque... |
def get_conv_actor(state_shape, NUM_ACTIONS):
print(f'generating a CNN with state shape {state_shape} and {NUM_ACTIONS} actions')
last_init = tf.random_uniform_initializer(minval=-0.0003, maxval=0.0003)
inputs = layers.Input(shape=(state_shape), dtype = tf.float32)
out = layers.Conv2D(16, (3,3), ac... | The main task of the code is to perform reinforcement learning training using a learner process. It initializes neural networks (policy and Q-value models), processes incoming minibatches from a queue, computes losses via the `learn` function, logs training metrics, and periodically saves model checkpoints. The process... | def learner_process(minibatch_q, training_logs_q, done_q, begin_q, learner_device_ID, new_pi_q, abort_q, reset_q, model_save_q):
tf.random.set_seed(time.time())
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
# Currently, memory growth needs to be the same across... |
def final_destination_unreachable(location):
surrounding_locations = list(get_surrounding_locations(location[0], location[1]).values())
surrounding_locations = [surr for surr in surrounding_locations if surr is not None]
is_unreachable = False
for surrounding_location in surrounding_locations:
... | This function performs a breadth-first search (BFS) to find the shortest path from a start node to a specified end node in a grid. It checks if the end node is unreachable, processes nodes by dequeuing them, explores adjacent movable locations, and enqueues unvisited nodes. If the destination is reached, it returns the... | def bfs(end, cost=0, enqueued=[]):
visited = []
visited_normal = []
if final_destination_unreachable(end):
print("Final destination" + str(end) + "unreachable from all sides, aborting")
return "FAIL", []
while 1:
if len(enqueued) == 0:
print("Nothing to expand for en... |
def final_destination_unreachable(location):
surrounding_locations = list(get_surrounding_locations(location[0], location[1]).values())
surrounding_locations = [surr for surr in surrounding_locations if surr is not None]
is_unreachable = False
for surrounding_location in surrounding_locations:
... | This function implements a search algorithm (likely BFS or UCS) to find the shortest path to a destination node. It explores nodes from a queue, tracks visited nodes, and returns the path cost and visited nodes if the end is reached. If the queue is empty or the destination is unreachable, it returns "FAIL". The algori... | def ucs(end, visited=[], cost=0, enqueued=[]):
if final_destination_unreachable(end):
print("Final destination unreachable, aborting")
return "FAIL", []
while 1:
if len(enqueued) <= 0:
return "FAIL", []
node = enqueued.pop(0)
cost = cost+1
... |
def calculate_momentum(elevation_change):
if elevation_change <= 0:
return 0
elif elevation_change > 0:
return max(0, elevation_change)
else:
raise Exception("Whoops! This wasn't supposed to happen")
def get_movable_locations(position, random_order=False, momentum=None):
x_cord, ... | This function implements the A* algorithm to find the shortest path from a start node to a destination node, considering elevation-based momentum adjustments. It processes nodes from a queue, calculates movement costs, and explores reachable locations while avoiding revisits. If the destination is reached, it returns t... | def a_star(end, enqueued=[]):
visited = []
momentum = 0
while 1:
if len(enqueued) <= 0:
return "FAIL", []
node = enqueued.pop(0)
cost = node.cost
previous_node = node.parent
if previous_node is not None:
elevation_change = abs(previous_n... |
def create_cycle_graph(n_agents) -> nx.Graph:
"""
Create an undirected cycle graph of `n_agents`.
returns a nx.Graph structure representing the overall connectivity
at gossip-layer of the agents.
Sets the 'pos' attribute on the nodes accroding to the circular layout
"""
# 1. create nx cycl... | The code simulates a distributed knowledge exchange system where agents (nodes) share information (facts) through a cycle network. It initializes a knowledge base with injected facts, applies rule-based inference, and iteratively propagates knowledge via symmetric gossip (information exchange) across edges. The system ... | def run_demo(n_agents,
inject_0: Set[Expr],
k_rule_factories=None,
check_properties=None,
do_yield=False,
verbose=True,
):
# create the net
gossip_net = create_cycle_graph(n_agents)
# inject initial fact
gossip_net.nodes[0]['k... |
def load_tracker(self):
"""Load the tracking table with the source assemblies for this taxonomy. Will not load anything if jobs in
the tracker already exist for this taxonomy/target assembly pair."""
header_to_print = (
'Sources', 'Taxonomy', 'Scientific Name', 'Assembly', 'Target As... | The main task of the code is to execute a series of predefined operations based on the `tasks` input. It conditionally runs `load_tracker()`, `run_remapping_and_clustering()`, and `update_dbs()` methods if their corresponding keys are present in the `tasks` dictionary, allowing selective execution of data processing st... | def run_all(self, tasks, instance, source_of_assembly, resume):
if 'load_tracker' in tasks:
self.load_tracker()
if 'remap_cluster' in tasks:
self.run_remapping_and_clustering(instance, resume)
if 'update_dbs' in tasks:
self.update_dbs(source_of_assembly) |
def do_parse_args(config):
"""Parse args and return a config dict"""
parser = argparse.ArgumentParser(description="Generate accounting records for OpenStack instances", epilog="-D and -A are mutually exclusive")
parser.add_argument("-v", "--verbose", help="output debugging information", action="store_true")... | The main task of the code is to configure logging, retrieve data, and save it as a timestamped JSON file in the specified output directory if the data is determined to be new. | def main():
"""the main function"""
config = {}
do_parse_args(config)
do_read_config(config)
logging.basicConfig(format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=config["loglevel"])
data = get_data(config)
if is_new_data(config, data):
nowtime ... |
def do_parse_args(config):
"""Parse args and return a config dict"""
parser = argparse.ArgumentParser(description="Generate accounting records for OpenStack instances", epilog="-D and -A are mutually exclusive")
parser.add_argument("-v", "--verbose", help="output debugging information", action="store_true")... | The main task of the code is to collect and process OpenStack compute and volume events from a specified cloud, merge them with cached data, and output structured JSON files for daily event tracking. It maintains cluster state records, updates timestamps, and generates hierarchy data, ensuring consistent event logging ... | def main():
"""The main function"""
config = {}
do_parse_args(config)
do_read_config(config)
script_datetime = datetime.datetime.fromisoformat(config["end"])
if "cloud" in config:
openstack_conn = openstack.connect(cloud=config["cloud"])
else:
print("Please specify an OpenS... |
def get_scoring_artifacts(docs, metric):
# Get sentence transformer model
model = SentenceTransformer("bert-large-nli-stsb-mean-tokens")
# Word and sentence tokenization
sent_info_dic, _, sents_weights = parse_documents(docs, None, metric)
all_token_vecs, all_tokens = get_all_token_vecs(model, sent... | This function computes similarity scores between generated summaries and pseudo-references using a specified metric (default: F1). It extracts vector representations of documents/summaries, then calculates pairwise similarity scores to evaluate alignment between system outputs and reference material. | def get_rewards(docs, summaries, ref_metric, sim_metric="f1"):
model, ref_idxs, all_token_vecs, all_tokens = get_scoring_artifacts(
docs, ref_metric
)
# Get vectors and tokens of the pseudo reference and the summaries
ref_vecs, ref_tokens = get_vecs_tokens(ref_idxs, all_token_vecs, all_tokens)
... |
def get_scoring_artifacts(docs, metric):
# Get sentence transformer model
model = SentenceTransformer("bert-large-nli-stsb-mean-tokens")
# Word and sentence tokenization
sent_info_dic, _, sents_weights = parse_documents(docs, None, metric)
all_token_vecs, all_tokens = get_all_token_vecs(model, sent... | This function computes similarity scores between system-generated summaries and a pseudo-reference using SBERT embeddings. It processes documents and summaries to extract token vectors, calculates similarity metrics (default: F1), and returns scores (and optionally summary vectors) to evaluate summary quality against r... | def get_sbert_score_metrics(
docs, summaries, ref_metric, sim_metric="f1", return_summary_vectors=False
):
model, ref_idxs, all_token_vecs, all_tokens = get_scoring_artifacts(
docs, ref_metric
)
# Get vecs and tokens of the pseudo reference
ref_vecs, ref_tokens = get_vecs_tokens(ref_idxs, a... |
def cancel_targets():
CancelWaitTarget()
if TargetPresent():
CancelTarget()
def check_and_equip_tool():
if not ObjAtLayer(LhandLayer()):
UOSay("[armtool 1")
Wait(500)
def check_elemental():
if FindType(ELEMENTAL, Ground()):
_enemy = FindItem()
telegram_message(f"... | The code automates tree-cutting in a game by iterating through sorted tree coordinates, checking for valid positions, equipping tools, managing inventory weight, and using the axe. It handles dead character detection, skips problematic tiles, logs messages, and avoids bad points while ensuring proper movement and inter... | def lumberjacking(sorted_trees):
for _t, _x, _y, _z in sorted_trees:
if ([_x, _y] not in BAD_POINTS) and NewMoveXY(_x, _y, True, 1, True):
if Dead():
newMoveXY(INSIDE_GATE[0], INSIDE_GATE[1], True, 0, True)
SetWarMode(True)
print(f"Character dead X... |
def initWordsFromFile(corpus):
corpusArray = []
punc = ['?', '!', ';', '.', ',']
for line in corpus:
for word in line.split():
endsWithPunc = ""
print(word)
#Checks if word ends with punctuation
for j in punc:
if(word[len(word) - 1... | The code generates n-grams from a text corpus and predicts the next word in a sequence. It reads a text file, processes it into n-gram structures, and uses these to determine the most probable next word after a given input, testing with the example input 'the'. | def main():
#testing data
NGRAMS = 4
nGramsArray = []
corpusFile = open("Data/rahul_flirty.txt", "r")
corpusArray = initWordsFromFile(corpusFile)
nGramsArrayFreq = [None] * NGRAMS
for i in range(NGRAMS):
nGramsArrayFreq[i] = [None] * (len(corpusArray) - i)
print("Mak... |
def check_block_validity(block: ib.IdentityBlock) -> bool:
"""
Returns true if block is valid, false otherwise
Currenty only checks prev hash and sequencer signature, not state transition
"""
if not block_check_chain_tip(block):
if cfg.show_sync:
print("prev hash does not match")... | The function processes a received block by deserializing it and validating its authenticity. If valid and extending the current chain tip, it processes the block; otherwise, it decrements the index, clears cached blocks, and initiates a chain resync. Errors trigger similar resync steps, ensuring consistency by adjustin... | def load_block(serialized_block: bytes) -> None:
"""
called when client is ready to process a received block
process the block if it builds on the chain tip
resync the chain if it does not build on the chain tip
"""
index = Index(cfg.db.misc_values.get(b"identity_bc_index"))
try:
new... |
def initial(self):
self.employDict = {}
self.employDict[Employee()] = self.employDict
self.filename = 'people.txt'
def employeeList(self):
self.employDict.clear()
try:
with open(self.filename, 'r+') as f:
# Tries to read lines from file
... | The code initializes an object by executing the initial setup, creating an employee list, generating a menu, and saving data, typically part of a program's startup process to configure and persist essential information. | def __init__(self):
self.initial()
self.employeeList()
self.createMenu()
self.save() |
def build_chow_liu_tree(self, n):
"""
Build a Chow-Liu tree from the data, X. n is the number of features. The weight on each edge is
the negative of the mutual information between those features. The tree is returned as a networkx
object.
"""
G = nx.Graph()
for v... | The code initializes a class to set up a structured prediction model using a Chow-Liu tree. It stores input data, labels, and weights, constructs the tree based on feature dimensions, computes label node degrees, extracts neighboring nodes, initializes a cache, and calculates the initial error rate for optimization tas... | def __init__(self, data, label, weight):
self.X = data
self.label = label
self.weight = weight
self.lb_margin = {}
self.lb_nb_pair_margin = {}
self.tree = self.build_chow_liu_tree(len(self.X[0]))
self.lb_degree = self.tree.degree(label)
self.extract_neighb... |
def usage():
print ("train_multinomial_logistic_regression.py ")
print ("train_data_folder: where the state assignment and of training data are stored for all cell types. Each cell type has its own file")
print ("all_ct_segment_folder: where segmentation data of all cell types are stored, for the entire genome, so t... | The main task of the code is to train a multinomial logistic regression model using genome-wide segmentation data from multiple cell types as predictors, then apply it to predict the segmentation of a specified response cell type across the genome. It validates inputs, loads training data, trains the model, and outputs... | def main():
num_mandatory_args = 7
if len(sys.argv)!= num_mandatory_args:
usage()
train_data_folder = sys.argv[1]
helper.check_dir_exist(train_data_folder)
all_ct_segment_folder = sys.argv[2] # where the genome-wide segmentation data of all cell types are combined, and stored in files corresponding to different... |
def createTable(self, table):
if self.sqlConnection:
try:
self.connectDatabase()
self.lock.acquire(True)
query = "CREATE TABLE IF NOT EXISTS " +table+ " (id INT, dept TEXT, title TEXT, number TEXT, score INT);"
self.mycursor.execute(que... | The main task of the code is to initialize a SQLite database by creating multiple tables (e.g., `selectClass`, `describeClass`, `userFeedback`, etc.) and handling exceptions during initialization. It sets the database path, calls table-creation methods, and prints errors if initialization fails. | def initDatabase(self):
try:
self.path = './data/sql.db'
self.createTable('selectClass')
self.createTable('describeClass')
self.createMajorTable('describeMajor')
self.createTable('userFeedback')
self.createTable('classlist')
sel... |
def connectDatabase(self):
try:
self.sqlConnection = sqlite3.connect(self.path, check_same_thread=False)
cursor = self.sqlConnection.cursor()
self.mycursor = cursor
print('SQL Connection Open')
except sqlite3.Error as error:
print('Error occur... | The code's main task is to insert course data into a database table, ensuring thread safety via a lock, handling potential SQL errors, and managing database connections. It checks if courses exist in the specified table, iterates through each course, and closes the connection afterward. If no connection exists, it atte... | def insertClass(self, courses, table):
if self.sqlConnection:
try:
self.lock.acquire(True)
self.connectDatabase()
for course in courses:
self.courseExists(course, table)
except sqlite3.Error as error:
pri... |
def create(item):
checklist.append(item)
def user_input(prompt):
user_input = raw_input(prompt)
return str(user_input)
def select(theString):
# Create item
if theString.lower() == "a":
input_item = user_input("What item would you like to add?:")
create(input_item)
unused_vari... | The code defines a function `test()` that manages a command-line interface for a list. It initializes the list with "purple sox" and loops to accept user commands: add (A), read (R), display (P), update (U), destroy (D), check (C), or quit (Q). Each command triggers a corresponding action via the `select()` function, w... | def test():
create("purple sox")
running = True
while running:
selection = user_input(CGREEN+"Press A to add to list, R to Read from list, P to display list, U to update, D to destroy,C to check, and Q to quit\nEnter:"+CEND)
running = select(selection) |
def startHunt():
pg.click(700,100)
#pg.press("w")
while True:
if LocateObject("hunt.png") or LocateObject("20nrg.png"):
pg.press("w")
if LocateObject("nrg.png"):
pg.press("r")
time.sleep(10)
def inShop():
# take a screenshot to locate objects on
sc... | The main task of the code is to automate in-game purchases using skystones and gold, tracking resource usage, spin times, and item counts. It processes user input, initializes variables, and enters a loop to buy items (bookmark/mystic) while conditions allow, scrolls/refreshes the shop, and logs progress. On interrupti... | def main():
global skystones,gold, num_mystic,num_book,bookFlag,mystFlag,huntFlag,bookmark,mystic,start,end
getUsr = input("enter ints sep by spaces (skystones gold bookmark mystics): ").split()
if len(getUsr) <= 3:
for i in range(4):
getUsr.append(0)
if getUsr[... |
def buildProbParseTree(fpexp):
""" This Function constructs a binary logic tree utilizing the binary tree class and stack class
The combination of classes functions as structure and navigation for the tree.
The logical expression use 4 inputs (T:True, F:False, U_x:Unlikely, L_x:Likely) and two operator
... | The main task of the code is to test probabilistic logic expression parsing and evaluation. It builds parse trees from two input strings representing logical formulas with probability values, evaluates their results, and prints both the parsed expressions and evaluation outcomes to validate correctness. | def main():
""" Testing two possible inputs and there function results """
input_str = "( U_0.5 OR ( L_0.8 AND T ) )"
pt = buildProbParseTree(input_str)
print("Evaluating parse tree...", evaluateProbLogicParseTree(pt))
print(printProbLogicExpression(pt))
input_str2 = "( ( ( L_0.8 AND T ) OR U_0.... |
def resource_image(name):
"""
Loads resourse image
"""
return resource_path(os.path.join("images", name))
def load_status_icons(self):
"""
Loads icons from resourses
"""
for (name, code) in self.STATUS.items():
self.STATUS_QICONS[code] = QIcon(resource_image(n... | This code initializes a network monitoring application by reading configuration settings, setting up GUI components (QApplication, system tray icon, main window), configuring ping thresholds, and preparing a thread for periodic connectivity checks. It loads status icons/sounds, initializes variables for tracking networ... | def __init__(self):
self.config.read('conntester.ini')
self.host = self.config.get('MAIN', 'host')
self.timeout = int(self.config.get('MAIN', 'timeout'))
self.interval = int(self.config.get('MAIN', 'interval'))
self.history = int(self.config.get('MAIN', 'history'))
self.h... |
def get_loss_status(self):
"""
Loss status
"""
loss = self.get_loss_ping()
if loss > self.loss_tresh_lost:
return self.STATUS['LOST']
if loss > self.loss_tresh:
return self.STATUS['BAD']
return self.STATUS['GOOD']
def get_ping_status(self)... | The code determines the overall system status by comparing the maximum value of loss and ping statuses. If the new status differs from the current one, it triggers a status change process and updates the current status. Finally, it returns the updated or unchanged current status. | def get_overall_status(self):
"""
Overall status
"""
new_status = max([
self.get_loss_status(),
self.get_ping_status(),
])
if self.current_status != new_status:
self.process_status_change(self.current_status, new_status)
sel... |
def get_mean_ping(self):
"""
Calculate mean ping time in ms
"""
responses = self.get_responses()
if len(responses) == 0:
return None
m_ping = mean([r["time"] for r in responses])
return int(round(m_ping, 0))
def get_last_ping(self):
"""
... | The main task of the code is to update the application's UI with network results by setting tooltips, labels, and data series. It compiles mean/last ping and loss metrics into a status string, updates the system tray tooltip, calls status checks, and syncs UI elements like labels and charts with the latest ping data fo... | def process_results(self):
"""
Update state based on results
"""
info = "\n".join([
f"Mean {self.get_mean_ping()} ms",
f"Last {self.get_last_ping()} ms",
f"Loss {self.get_loss_ping()} %",
])
self.tray.setToolTip(info)
self.get_o... |
def trainTestSplitData(self, iTrainSplit = 0.80):
# Train Test Split Stage
print("\nStarted Spliting Training and Test Data:\n")
# iTrainSplit of 0.80 means the data is split into 80% Training and 20% Test by default
self.xTrain = []
self.yTrain = []
self.xTest = []
... | The main task of the code is to generate performance logs of a neural network model across various hyperparameters (activation functions, learning rates, hidden neurons, etc.) by training and testing the model with different configurations. It calculates metrics like MSE, RMSE, MAE, and R² for both training and test se... | def generateLogs(self):
#----------------------------Initialize the Lists------------------------------#
# Declaring lists to store required results
trainMSEList = []
testMSEList = []
trainRMSEList = []
testRMSEList = []
trainMAEList = []
testMAEList = []
... |
def draw_clean_board(self):
# pygame.draw.rect(self.display, (255, 255, 255), (0, 0, 5000, 5000))
color = self.board_color
for corner in self.squares:
if (corner[0] + corner[1]) % 2 == 0:
pygame.draw.rect(self.display, self.light[color],
... | This function handles mouse clicks on a game board by updating the visual state: it cleans the board, highlights the clicked square and possible moves, redraws pieces excluding the clicked one, and centers the clicked piece on the cursor when a valid piece is selected. If no piece is clicked, it still highlights moves ... | def mouse_press_handler(self, clicked_piece=None):
if self.mode == 'default_game_board':
if self.mouse_button == 1:
if clicked_piece != ' ':
# pygame.mouse.set_visible(0)
self.draw_clean_board()
self.highlight_square(self.cl... |
def draw_clean_board(self):
# pygame.draw.rect(self.display, (255, 255, 255), (0, 0, 5000, 5000))
color = self.board_color
for corner in self.squares:
if (corner[0] + corner[1]) % 2 == 0:
pygame.draw.rect(self.display, self.light[color],
... | This function handles chess piece movement and promotion logic. It determines the promotion row based on the current player, processes pawn promotions by showing a menu, moves pieces on the board (with board flipping for black's turn), and updates the UI by redrawing the board and highlighting squares. It checks if the... | def drop_handler(self):
# pygame.mouse.set_visible(1)
if self.abstract_board.current_white == self.abstract_board.current_white_turn:
promotion_row = 0
else:
promotion_row = 7
if self.mode == 'default_game_board':
if self.release_square not in self.hig... |
def get_current_color(self):
if self.current_white:
return 'w'
else:
return 'b'
def find_pawn_moves(self, color, position, omit_pawn_forward=False):
results = []
move_squares = [(position[0], position[1] - 1)]
if position[1] == 6 and not omit_pawn_forward:... | This function generates all possible moves for the current player's pieces on a chessboard. It iterates through each position, identifies pieces of the current color, and uses specialized methods to find valid moves for pawns, rooks, knights, bishops, queens, and kings. Pawns reaching the 0th rank trigger promotion opt... | def find_all_moves(self, omit_castle=False):
# creates list of all possible moves from board perspective
color = self.get_current_color()
results = []
for position in self.game_board:
if self.game_board[position][0] == color:
if self.game_board[position][1] ==... |
def computer_make_move(self):
flip = False
if self.abstract_board.current_white != self.abstract_board.current_white_turn:
self.abstract_board.flip_board()
flip = True
move = self.abstract_board.find_best_move()
if move:
self.abstract_board.move_piece(... | The code defines a game loop for a Pygame-based application, handling user inputs (keyboard/mouse), game state updates (e.g., move execution, undo/redo, promotion selection), and rendering. It processes events like quitting, key presses (e.g., ESC, arrow keys, 'C' for timed moves), mouse clicks/drags for piece interact... | def game_loop(self):
while True:
self.clock.tick(60)
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ES... |
def draw_clean_board(self):
# pygame.draw.rect(self.display, (255, 255, 255), (0, 0, 5000, 5000))
color = self.board_color
for corner in self.squares:
if (corner[0] + corner[1]) % 2 == 0:
pygame.draw.rect(self.display, self.light[color],
... | The main task of the code is to initialize a chess game interface using Pygame, setting up a graphical board with piece rendering, mouse interaction tracking (clicks, releases, selections), and launching the game loop to handle gameplay mechanics like piece movement, promotions, and state management. | def __init__(self, load_game=False):
self.abstract_board = Board()
self.square_size = 70
self.board_color = 4
icon = pygame.image.load('icon.png')
super().__init__(self.square_size * 8, self.square_size * 8, 'chess', icon, pygame.DOUBLEBUF)
self.draw_clean_board()
... |
def ReadComments(input_files, input_format, font_size=25.0, progress_callback=None):
if isinstance(input_files, bytes):
input_files = str(bytes(input_files).decode('utf-8', 'replace'))
if isinstance(input_files, str):
input_files = [input_files]
else:
input_files = list(input_files)
... | The function converts danmaku (subtitle) comments from input files into ASS format, applying customizable filters, font settings, and positioning parameters. It reads comments, processes them with specified styles and filters, and writes the result to an output file or stdout, handling encoding, regex validation, and r... | def Danmaku2ASS(input_files, input_format, output_file, stage_width, stage_height, reserve_blank=0, font_face=_('(FONT) sans-serif')[7:], font_size=25.0, text_opacity=1.0, duration_marquee=5.0, duration_still=5.0, comment_filter=None, comment_filters_file=None, is_reduce_comments=False, progress_callback=None):
com... |
def nan_helper(self, y, mode=1):
if mode == 1:
return np.isnan(y), lambda z: z.nonzero()[0]
elif mode == 2:
return np.isinf(y), lambda z: z.nonzero()[0]
def segmentation(self, blocks):
new_blocks = []
changed = False
for block in blocks:
segmen... | The code processes a distance array (`l`) to identify and segment obstacles in a robotic environment. It handles missing/infinite values in `l` by either filling with a constant, interpolating, or filtering them out. It converts polar coordinates (distance, angle) to Cartesian coordinates, applies rotation based on the... | def get_obstacles(self, l, rng=360, fillna="else", state=np.array([2, 2, np.pi])):
state_coord = state[:2].reshape(-1, 1)
state_angle = state[2]
rot_mat = np.array(
[
[np.cos(state_angle), -np.sin(state_angle)],
[np.sin(state_angle), np.cos(state_angle... |
def choose_room_reward(self):
self.window.withdraw()
self.room_window = tk.Toplevel(self.window)
self.room_window.geometry(f'600x800+{self.screen_width // 2 - 300}+{self.screen_height // 2 - 400}')
self.room_window.configure(bg=config.BG)
self.room_window.grid_rowconfigure(0, wei... | This function handles enemy death by healing the player, removing defeated enemies, advancing to the next enemy or room reward, and checking game progression. It transitions to the next enemy or triggers rewards/floor progression, generating new enemies or initiating a boss fight when conditions are met. If the player ... | def enemy_death(self):
self.player.heal(self.player.hp / 4)
if len(self.enemies) > 1:
self.enemies.pop(0)
self.current_enemy = self.enemies[0]
self.window.after(2000, self.enemy_turn)
else:
self.choose_room_reward()
self.room += 1
... |
def responseLine(self, request, statusCode):
return "{} {} {}\r\n".format(request.version, statusCode, self.status_codes[statusCode])
def errorHeaders(self, responseLine, error):
headers = self.allHeaders()
headers += "\r\n"
responseBody = "<head><title>{} {}</title></head><body><h1>{} {}</h1><p>Your browser se... | This code receives and processes an HTTP request from a client by reading data, parsing headers to determine content length, handling different HTTP methods (GET, POST, etc.), and generating appropriate responses. It ensures complete data reception, validates the request URI, and delegates processing to method-specific... | def receiveRequest(self, client, clientAddress):
self.client = client
self.clientAddress = clientAddress[0]
data = b''
flag = 1
length = 0
c = 0
i = 0
while True:
p = self.client.recv(SIZE) # considering sum of the request line and ALL header fields is <= SIZE
data += p
if(b'Content-Length: ' i... |
def get_key(self, num):
if not self.keys:
self.generate_new_keys()
key = self.keys[num]
return key
def check_if_shift_down(self, mod):
if mod & pygame.KMOD_LSHIFT or mod & pygame.KMOD_RSHIFT:
return True
return False
def check_if_shift_released(self, key):... | The function checks if a key corresponds to a specific uppercase key (self.get_key(0) + 32). If true, it verifies if the shift key is pressed using `check_if_shift_down(mod)`. Otherwise, it checks if the shift key is released via `check_if_shift_released(key)`, likely handling keyboard input logic for uppercase letters... | def check_upper_keys(self, key, mod):
if key == self.get_key(0) + 32:
return self.check_if_shift_down(mod)
else:
return self.check_if_shift_released(key) |
def restart(self, mode):
self.finished = False
self.set_gameover(False)
self.set_mode(mode)
self.generate_new_keys()
self.total_time = 0
self.points = 0
self.first = True
self.gui.update_board()
def get_gameover(self):
return self.gameover
def chec... | This code defines a game loop that processes Pygame events, checks for user input to control game states (restart, exit), updates the game board, and renders the GUI based on whether the game is active, finished, or over. It handles key presses for restarting in different modes, exiting, and updating the display accord... | def game_loop(self):
running = True
while running:
for event in pygame.event.get():
if self.finished:
if event.type == pygame.KEYUP:
if event.key == ord('1'):
self.restart(Modes.lower)
... |
def get_key(self, num):
if not self.keys:
self.generate_new_keys()
key = self.keys[num]
return key
def check_upper_keys(self, key, mod):
if key == self.get_key(0) + 32:
return self.check_if_shift_down(mod)
else:
return self.check_if_shift_rele... | The function determines whether to check uppercase or lowercase keys by evaluating the ASCII value of the first key. If the first key is an uppercase letter (ASCII 65–90), it calls `check_upper_keys` with the provided key and modulus. Otherwise, it calls `check_lower_keys` with just the key, handling lowercase letters ... | def check_if_correct_key(self, key, mod):
if self.get_key(0) >= 65 and self.get_key(0) <= 90:
return self.check_upper_keys(key, mod)
else:
return self.check_lower_keys(key) |
def generateOldMirCommands(expID, peers, clients):
output("#========================================")
output("# {0} (Old Mir)".format(expID))
output("#========================================")
output("\n")
# both peers and clients are dictionaries with slave tags as keys
# and the assigned c... | This code parses command-line tokens to configure and run experiments, handling ID generation, existing directories, user input for skipping/canceling, and generating commands based on deployment type (local/cloud) or legacy "oldmir" mode. It processes tokens to set config, bandwidth, peers/clients, validates config fi... | def run(expID, tokens):
global lastFinished
global idOffset
global experimentIdDigits
global skipAllExisting
runOldMir = False
# If oldmir is the first token, run old mir
if tokens[0] == "oldmir":
runOldMir = True
tokens = tokens[1:]
# If special value "next" is specifi... |
def reading_marc(filename):
"""Reads the whole MARC file"""
try:
with open(filename, 'rb') as fh:
reader = MARCReader(fh, to_unicode=True, force_utf8=True)
for record in reader:
if record is None:
sys.exit("Problem with MARC file. Record is 'No... | The function processes MARC records from a file, filtering and yielding results based on a specified type (e.g., 'sh', 'fd', etc.). It checks the LCCN prefix, verifies specific MARC fields (e.g., 185, 150), and calls fetch_results if conditions match. The global reccounter tracks processed records, and results are yiel... | def processrecord(filename, type, keyword):
"""processes records in file based on type, whch is [sh | fd | gd | dg | gf | sj | mp] """
global reccounter
marc_gen = reading_marc(filename)
for record in marc_gen:
reccounter = reccounter + 1
result = None
lccn = lccnno(record)
... |
def load_mimic_iii_admissions_with_icd_codes(data_dir: Path):
mimiciii_dir = data_dir / 'mimiciii'
adm = pd.read_csv(mimiciii_dir / 'ADMISSIONS.csv', parse_dates=list(map(str.upper, TIME_COLUMNS)))
dia = pd.read_csv(mimiciii_dir / 'DIAGNOSES_ICD.csv', dtype={'ICD9_CODE': str}, usecols=['HADM_ID', 'SUBJECT_... | The function matches admissions data with MIMIC-III data by aligning ICD-9 diagnosis/procedure codes and time intervals, filtering out ICD-10 entries, then returning rows where both code sets match between datasets. | def get_matching_admissions(data_dir: Path, admissions: pd.DataFrame, dia_codes: pd.DataFrame, pro_codes: pd.DataFrame):
iii_adm = load_mimic_iii_admissions_with_icd_codes(data_dir)
admissions = add_required_columns(admissions, dia_codes, pro_codes)
admissions_9 = admissions[(admissions.dia_version != 10) &... |
def load_input(path):
with open(path) as f:
all_digits = []
all_segments = []
for line in f.readlines():
segments, digits = line.split(' | ')
all_digits.append([digit.strip() for digit in digits.split(' ')])
all_segments.append([seg.strip() for seg in segm... | The main task of the code is to load input data, calculate the count of unique digits in part1, decode the segment data in part2, sum the decoded values, and print both results. It processes input segments and digits, applies specific functions to analyze and compute values, then outputs the findings for two parts of a... | def main():
segments, digits = load_input('Input')
print(F'Part1 : {find_unique_count(digits)}')
print(F'Part2 : {sum(decode_data(segments, digits))}') |
def get_imgs_and_locations(display=False):
images = []
for img in range(4900):
hdr_img = cv2.imread(f'C:\Data\HDR\Level_0_{img}.hdr')
hdr_img = cv2.cvtColor(hdr_img, cv2.COLOR_BGR2RGB)
if display:
# Optionally display the HDR image
cv2.imshow('HDR Image', hdr_im... | The main task of the code is to generate bilinear interpolated images using Delaunay triangulation from a set of input images and their corresponding locations. It retrieves images and locations, computes triangular meshes, and applies bilinear interpolation to each image based on the triangulated coordinates, returnin... | def get_data():
all_imgs, locations = get_imgs_and_locations(False)
# List of triangles and their coordinates
triangles, img_indexes = get_Delaunay_triangles(locations)
bi_linear_imgs = []
for i in tqdm.tqdm(range(len(all_imgs))):
bi_linear_imgs.append(create_bi_linear_img(locations[i], ... |
def transpose(board):
"""
returns: the transpose of the input board
ie. all columns and rows are "flipped" accross the diagonal
note: requires square board
"""
outputBoard = [[0 for col in range(c.NUM_CELLS)] for row in range(c.NUM_CELLS)]
for row in range(c.NUM_CELLS):
for col in ... | The code performs a rightward move on a game board by transposing the board, reversing columns, simulating an upward move, reversing columns again, and transposing back. It returns the updated board and a boolean indicating if any changes occurred during the move. | def moveRight(board):
"""
performs rightward move
returns: updated board,
bool of if there were any changes to the board
"""
outputBoard = transpose(board)
outputBoard = reverseColumns(outputBoard)
outputBoard = moveUp(outputBoard)[0]
outputBoard = reverseColumns(outputBoar... |
def get_db_connection():
engine = create_engine('postgresql://'+credential['username']+':'+credential['password']+'@'+credential['host']+':5432/' + credential['db'])
connection = engine.raw_connection()
return engine,connection
def cleanHTMLAndMarkupCampoDict(campoDict):
results = {}
for key,campo in campoDict.... | The code retrieves and processes data from a database for a web application, handling pagination, sorting, and filtering. It fetches campaign and idea records, cleans HTML content, parses JSON, and applies search/tag filters. Pagination parameters are managed, and results are rendered in a template with dynamic sorting... | def index( pagination="1", orderby= "voteCount",orderdir="desc",tag="",search=""):
swLocalRun = environ["LOCAL RUN"] == "True"
engine,connection = get_db_connection()
cur = connection.cursor()
cur.execute('SELECT nombre,"nombreSQL" FROM "mostrarTabla" WHERE id = 1')
proyecto = cur.fetchone()
nombreProyecto = p... |
def get_db_connection():
engine = create_engine('postgresql://'+credential['username']+':'+credential['password']+'@'+credential['host']+':5432/' + credential['db'])
connection = engine.raw_connection()
return engine,connection
def cleanHTMLAndMarkupCampoDict(campoDict):
results = {}
for key,campo in campoDict.... | The main task of the code is to retrieve and process data for a specific campaign, including its details, associated ideas, and pagination information. It connects to a database, fetches campaign and idea records, cleans HTML/JSON fields, calculates pagination parameters, and renders a campaign page template with the s... | def campaign(campaign_id,pagination="1",orderby= "voteCount",orderdir="desc"):
print ("campaign: %s " %campaign_id)
engine,connection = get_db_connection()
cur = connection.cursor()
cur.execute('SELECT nombre,"nombreSQL" FROM "mostrarTabla" WHERE id = 1')
proyecto = cur.fetchone()
nombreProyecto = proyecto[0]
... |
def get_db_connection():
engine = create_engine('postgresql://'+credential['username']+':'+credential['password']+'@'+credential['host']+':5432/' + credential['db'])
connection = engine.raw_connection()
return engine,connection
def cleanHTMLAndMarkupCampoDict(campoDict):
results = {}
for key,campo in campoDict.... | The function retrieves and processes campaign data from a database table, cleans HTML/JSON content, and renders a template with project details, all campaigns, and specific campaign information for display. | def campaign_acerca(campaign_id):
print ("campaign: %s " %campaign_id)
engine,connection = get_db_connection()
cur = connection.cursor()
cur.execute('SELECT nombre,"nombreSQL" FROM "mostrarTabla" WHERE id = 1')
proyecto = cur.fetchone()
nombreProyecto = proyecto[0]
nombreTablas = proyecto[1]
cur.execute('SEL... |
def get_db_connection():
engine = create_engine('postgresql://'+credential['username']+':'+credential['password']+'@'+credential['host']+':5432/' + credential['db'])
connection = engine.raw_connection()
return engine,connection
def cleanHTMLAndMarkupCampoDict(campoDict):
results = {}
for key,campo in campoDict.... | The main task of the code is to retrieve and process an idea along with its associated campaign data from a database. It fetches the idea's details, cleans HTML/JSON fields, retrieves related campaigns, and prepares data for rendering in a template. The function handles database connections, error checks (e.g., 404 for... | def idea(idea_id):
print ("idea: %s " %idea_id)
engine,connection = get_db_connection()
cur = connection.cursor()
cur.execute('SELECT nombre,"nombreSQL" FROM "mostrarTabla" WHERE id = 1')
proyecto = cur.fetchone()
nombreProyecto = proyecto[0]
nombreTablas = proyecto[1]
cur.execute('SELECT %s FROM ideas_esp_%... |
def XORLS_MASK(DEST,OP):
"""
Performs addition of the unmaksed value OP
with the shared DEST
"""
DEST[0,:] ^= OP[0];
DEST[1*D,:] ^= OP[1];
DEST[2*D,:] ^= OP[2];
DEST[3*D,:] ^= OP[3];
def sbox_layer_masked(a,b,c,d,refresh_flag=0):
"""
Applies inplace sbox to the inputs... | This function encrypts multiple plaintexts using masked keys and tweaks via the Clyde128 algorithm, applying Nr rounds of S-box/L-box transformations, LFSR updates, and XOR operations. It returns the masked state matrix after specified steps, incorporating PRNG seeding and parallel processing of Nc executions with mask... | def clyde128_encrypt_masked(state,t,key,seed,Nr=6,step=2):
"""
This function simulates the behavior of
multiple executions of Nc masked clyde128
inputs:
- state (4,Nc) matrix with each column being a plaintext of an execution
- t (4,Nc) matrix with each column being ... |
def tweakey(key, tweak):
tx = (tweak[0]^tweak[2], tweak[1]^tweak[3])
tk = [tweak, (*tx , tweak[0], tweak[1]), (tweak[2], tweak[3], *tx)]
return [list(k^t for k, t in zip(key, tk_r)) for tk_r in tk]
def xor_states(x, y):
return list(xr ^ yr for xr, yr in zip(x, y))
def sbox_layer(x):
y1 = (x[0] & x[1... | The main task of the code is to perform symmetric encryption using a tweakable block cipher. It initializes a state with the message and tweak key, then applies multiple rounds of substitution (sbox_layer), linear transformation (lbox_layer), and round constant addition (add_rc), interleaved with XOR operations using t... | def clyde_encrypt(m, t, k):
tk = tweakey(k, t)
x = xor_states(m, tk[0])
for s in range(N_STEPS):
for rho in range(2):
r = 2*s+rho
x = sbox_layer(x)
x = lbox_layer(x)
x = add_rc(x, r)
x = xor_states(x, tk[(s+1)%3])
return x |
def lbox_layer(x):
return [*lbox(x[0], x[1]), *lbox(x[2], x[3])]
def sbox_layer(x):
y1 = (x[0] & x[1]) ^ x[2]
y0 = (x[3] & x[0]) ^ x[1]
y3 = (y1 & x[3]) ^ x[0]
y2 = (y0 & y1) ^ x[3]
return [y0, y1, y2, y3]
def update_lfsr(lfsr):
return ((lfsr << 1) & 0xffffffff) ^ (CST_LFSR_POLY_MASK if lfsr... | The code performs a cryptographic transformation on input data 'x' using a combination of substitution (sbox), linear (lbox), and dynamic (dbox) layers. It iterates for N_STEPS, applying these layers while dynamically modifying specific data elements via an LFSR (Linear Feedback Shift Register) for key mixing. The LFSR... | def shadow(x):
lfsr = CST_LFSR_INIT_VALUE
for s in range(N_STEPS):
x = [lbox_layer(sbox_layer(xi)) for xi in x]
for xi in x:
xi[SHADOW_RA_CST_ROW] ^= lfsr
lfsr = update_lfsr(lfsr)
x = [sbox_layer(xi) for xi in x]
x = dbox(x)
for i in range(len(x[0]... |
def tweakey(key, tweak):
tx = (tweak[0]^tweak[2], tweak[1]^tweak[3])
tk = [tweak, (*tx , tweak[0], tweak[1]), (tweak[2], tweak[3], *tx)]
return [list(k^t for k, t in zip(key, tk_r)) for tk_r in tk]
def xor_states(x, y):
return list(xr ^ yr for xr, yr in zip(x, y))
def add_rc(x, r):
return list(row ^... | The function decrypts ciphertext 'c' using a tweakable block cipher. It applies inverse operations (lbox_layer_inv, sbox_layer_inv) and round constants (add_rc) in reversed steps, combined with tweak keys derived from 'k' and 't'. The process uses XOR operations with tweak keys and reverses encryption rounds to recover... | def clyde_decrypt(c, t, k):
tk = tweakey(k, t)
x = c
for s in reversed(range(N_STEPS)):
x = xor_states(x, tk[(s+1)%3])
for rho in reversed(range(2)):
r = 2*s+rho
x = add_rc(x, r)
x = lbox_layer_inv(x)
x = sbox_layer_inv(x)
x = xor_states(x,... |
def bytes2state(x):
return list(x[4*i] | x[4*i+1] << 8 | x[4*i+2] << 16 | x[4*i+3] << 24 for i in range(4))
def clyde_encrypt(m, t, k):
tk = tweakey(k, t)
x = xor_states(m, tk[0])
for s in range(N_STEPS):
for rho in range(2):
r = 2*s+rho
x = sbox_layer(x)
x = ... | The function initializes a sponge state for cryptographic processing by processing the key `k` and nonce `n`. If `k` is 32 bytes, it modifies the last byte and converts it to a state; otherwise, it uses a default zero state. It converts `n` to a state, encrypts using `clyde_encrypt`, and constructs a list `x` with encr... | def init_sponge_state(k, n):
if len(k) == 32:
# mu variant
p = bytearray(k[16:])
p[-1] &= 0x7F
p[-1] |= 0x40
p = bytes2state(p)
else:
assert len(k) == 16
p = (0, 0, 0, 0)
n = bytes2state(n)
b = clyde_encrypt(n, p, bytes2state(k))
if SMALL_PERM:... |
def compress_block(x, block, mode, nbytes,pad):
xb = state2bytes(x[0])
if not SMALL_PERM:
xb = xb + state2bytes(x[1])
res = bytes(a ^ b for a, b in zip(xb, block))
if mode == 'ENC':
x_bytes = res
elif mode == 'DEC':
x_bytes = bytearray(xb)
for i, b in enumerate(block[... | This function compresses or encrypts input data in fixed-size blocks using a block cipher. It processes data iteratively, padding the final block if necessary, and returns the transformed state 'x' along with the compressed result 'res'. | def compress_data(x, data, mode='ENC'):
res = b''
while len(data) >= BLOCK_SIZE():
x, r = compress_block(x, data[:BLOCK_SIZE()], mode, BLOCK_SIZE(), False)
res = res+r
data = data[BLOCK_SIZE():]
x = shadow(x)
if data:
pb = pad_bytes(data + b'\x01', n=BLOCK_SIZE())
... |
def init_sponge_state(k, n):
if len(k) == 32:
# mu variant
p = bytearray(k[16:])
p[-1] &= 0x7F
p[-1] |= 0x40
p = bytes2state(p)
else:
assert len(k) == 16
p = (0, 0, 0, 0)
n = bytes2state(n)
b = clyde_encrypt(n, p, bytes2state(k))
if SMALL_PERM:... | The function implements a cryptographic sponge-based encryption scheme. It initializes a sponge state with a key and parameters, compresses associated data (ad), and conditionally processes message data (m) with a bit toggle. It then generates an authentication tag using the sponge state and key, combining ciphertext a... | def spook_encrypt(ad, m, k, n):
x = init_sponge_state(k, n)
x, _ = compress_data(x, ad)
if m:
x[-2][0] ^= 0x1
x, c = compress_data(x, m)
else:
c = b''
x[1][3] |= 0x80000000
tag = state2bytes(clyde_encrypt(x[0], x[1], bytes2state(k)))
return c+tag |
def init_sponge_state(k, n):
if len(k) == 32:
# mu variant
p = bytearray(k[16:])
p[-1] &= 0x7F
p[-1] |= 0x40
p = bytes2state(p)
else:
assert len(k) == 16
p = (0, 0, 0, 0)
n = bytes2state(n)
b = clyde_encrypt(n, p, bytes2state(k))
if SMALL_PERM:... | This function decrypts ciphertext 'c' using a sponge-based encryption scheme with key 'k' and additional data 'ad'. It initializes a sponge state, compresses data, and verifies a tag derived from the ciphertext's last segment. If the tag matches, it returns the decrypted message; otherwise, it returns None. | def spook_decrypt(ad, c, k, n):
x = init_sponge_state(k, n)
x, _ = compress_data(x, ad)
if len(c) > LS_SIZE:
x[-2][0] ^= 0x1
x, m = compress_data(x, c[:-LS_SIZE], mode='DEC')
else:
m = b''
x[1][3] |= 0x80000000
# NOTE: We do forward tag verification. In leveled implementa... |
def embedding_layer(self):
with tf.name_scope("embedding"):
embedding_mat = tf.Variable(tf.truncated_normal((self.vocab_size, self.embedding_size)))
word_embedded = tf.nn.embedding_lookup(embedding_mat, self.input_x)
self.embedding_layer = word_embedded
def sentence_layer(self):
... | The code defines a document classification model by constructing embedding, sentence, and document layers. It applies a fully connected layer to the document vector (`self.doc_vec`) to generate logits for classification, then computes the predicted class labels using `tf.argmax` on the logits. | def build_model(self):
self.embedding_layer()
self.sentence_layer()
self.doc_layer()
with tf.name_scope('doc_classification'):
out = layers.fully_connected(inputs=self.doc_vec, num_outputs=self.classes, activation_fn=None)
self.logits = out
self.prediction = ... |
def valid_route(self, route):
len_actions = len(route.actions)
len_command = len(self.commands)
if len_actions > len_command:
route.is_valid = False
else:
index = 0
route.validity += 1
for action in route.actions:
if route.i... | The code identifies valid routes by checking each route's validity, filters them, compares validity scores if valid routes exist, or executes a specific route with empty action and non-empty expected if no valid routes are found, otherwise exiting with an error message. | def find_route(self):
possibles = []
for route in self.routes:
possibles.append(self.valid_route(route))
possibles = [possible for possible in possibles if possible.is_valid]
if len(possibles) >= 1:
self.compare_validity_scores(possibles)
else:
... |
def build_help_content(self, definition):
if not isinstance(definition, str):
if isinstance(
definition[0], list) or isinstance(
definition[0], tuple):
self.help_content += "|"
for i in definition[0]:
if i == "" ... | The code processes route definitions to build routing logic and CLI help content. It initializes routes, constructs help text from definitions, determines command-line arguments, and identifies the appropriate route to execute. | def route(self, *definitions):
self.routes = []
self.help_content = (
"| ============================= CLI options"
" =============================\n"
)
for definition in definitions:
self.build_help_content(definition)
self.buil... |
def download_files(self):
for package in self.packages:
dest = os.path.join(self.destdir, self.package_destination(package[1], package[2]))
if os.path.isfile(dest):
print('Skipping download of {dest}'.format(dest=dest))
else:
url = self.package... | The main task of the code is to download required files, trigger completion handling, check for missing JAR dependencies, and raise a runtime error with a warning message if any JARs are missing. | def download_and_check(self):
self.download_files()
self.on_completion()
missing_jars = self.missing_jars()
if len(missing_jars) > 0:
raise RuntimeError(self.warning_string(missing_jars)) |
def loss_function(self, X, y):
'''
This function implements the logistic loss at the current self.params
:param X: d by m sparse (csc_array) matrix
:param y: m dimensional vector (numpy.array) of true labels
:return: a scalar, which denotes the mean of the loss functions on the... | The function `train_gd` performs Gradient Descent for `niter` iterations to update a model's parameters using training data (`train_sentences` and `train_labels`). It handles both raw text and preprocessed features based on the `RAW_TEXT` flag. For each iteration, it computes the gradient of the loss function, updates ... | def train_gd(self, train_sentences, train_labels, niter, lr=0.01, RAW_TEXT=True):
'''
The function should updates the parameters of the model for niter iterations using Gradient Descent
It returns the sequence of loss functions and the sequence of training error for each iteration.
By d... |
def loss_function(self, X, y):
'''
This function implements the logistic loss at the current self.params
:param X: d by m sparse (csc_array) matrix
:param y: m dimensional vector (numpy.array) of true labels
:return: a scalar, which denotes the mean of the loss functions on the... | The main task of the code is to train a model using **Stochastic Gradient Descent (SGD)** by iteratively updating its parameters. For each epoch, it randomly selects individual data points (without minibatches), computes their gradients, and adjusts the model's parameters using the specified learning rate. The function... | def train_sgd(self, train_sentences, train_labels, nepoch, lr=0.001, RAW_TEXT=True):
'''
The function should updates the parameters of the model for using Stochastic Gradient Descent.
(random sample in every iteration, without minibatches,
pls follow the algorithm from the lecture which ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.