dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getQueryRefCombinations(filename):
print("header from delta file:")
try:
f = gzip.open(filename, 'rt')
print(f.readline().strip())
except:
f = open(filename, 'r')
print(f.readline().strip())
# Ignore the first two lines for now
print(f.readline().strip())
linecounter = 0
current_query_name = ""
... | This code processes a delta file to filter alignments based on unique anchor sequences, generating a filtered delta file and coordinate data for visualization. It reads query-reference combinations, identifies unique alignments, writes the filtered results, and creates an index for dot plot generation. | def run(args):
filename = args.delta
unique_length = args.unique_length
output_filename = args.out
keep_small_uniques = True
max_overview_alignments = args.overview
# Read through the file and store information indexed by Query sequence names
header_lines_by_query, lines_by_query = getQueryRefCombinations(filen... |
def depth_blur(self,img):
(winW, winH) = (self.winsize, self.winsize)
alpha = self.attenuation
for (x, y, window) in utils.sliding_window(img, stepSize=self.winsize-6,
windowSize=(winW, winH)):
if window.shape[0] != winH or window.sh... | This code processes incoming RGB images by converting them from ROS messages, applying resizing, blur, style transfer, and light effects based on predefined parameters, then publishing the modified image as a ROS message. | def img_callback(self,msg):
cv_img = self.bridge.imgmsg_to_cv2(msg, desired_encoding="rgb8")
cv2.imwrite('/home/olaya/catkin_ws/src/uw_img_sim/nodes/rgb_panel.jpg',cv_img)
if self.scale is not None:
cv_img = cv2.resize(cv_img,
dsize = (int(cv_img.shap... |
def depth_callback(self,msg):
cv_img = self.bridge.imgmsg_to_cv2(msg, desired_encoding="16UC1")
cv_img = np.where(cv_img!=0, cv_img, 200)
cv2.imwrite('/home/olaya/catkin_ws/src/uw_img_sim/nodes/depth_panel.jpg',cv_img)
if self.scale is not None:
cv_img = cv2.resize(cv_img,
... | This code processes a ROS bag file by reading messages from a specified topic, converting image messages to OpenCV format, applying scaling, depth blur, style transfer, and light effects, then writing the modified images to a new bag file while preserving other topics. It also handles depth topic callbacks and timestam... | def bag_read(self, filein, topicin, fileout):
print('Reading bag file '+ filein + ' topic ' + topicin)
readbag = rosbag.Bag(filein,'r')
with rosbag.Bag(fileout,'w') as outbag:
for topic, msg, dtime in readbag.read_messages():
if topic == self.depth_topic:
... |
def extract_dark_channel_features(img_npy):
darkchannel = get_dark_channel(img_npy, 15)
feature_matrix = np.zeros((10, 10))
for i, j in np.ndindex(feature_matrix.shape):
feature_matrix[i, j] = np.median(darkchannel[i:(i+1)*50, j:(j+1)*50])
return feature_matrix.ravel(), darkchannel
def extract_atmosphere_features... | The code extracts multiple image features including dark channel, atmosphere, transmission, power spectrum, saturation histogram, and contrast from an input image. It resizes the image, processes it to obtain these features using specialized functions, and concatenates them into a single feature vector for further anal... | def extract_features_from_image(path_to_input_image):
img_npy = cv2.imread(path_to_input_image)
img_npy = skimage.transform.resize(img_npy,(500,500,3))
img_npy = np.array(img_npy).astype(np.float64)
dark_channel_features, darkchannel = extract_dark_channel_features(img_npy)
atmosphere_features, A_ =... |
def extract_dark_channel_features(img_npy):
darkchannel = get_dark_channel(img_npy, 15)
feature_matrix = np.zeros((10, 10))
for i, j in np.ndindex(feature_matrix.shape):
feature_matrix[i, j] = np.median(darkchannel[i:(i+1)*50, j:(j+1)*50])
return feature_matrix.ravel(), darkchannel
def extract_atmosphere_features... | The code extracts multiple image features (dark channel, atmosphere, transmission, power spectrum, saturation, contrast) from a resized input image, converts them to float32, and concatenates them into a single feature vector for analysis or machine learning tasks. | def extract_features_from_fullimage(img):
img_npy = skimage.transform.resize(img,(500,500,3))
img_npy = np.array(img_npy).astype(np.float64)
dark_channel_features, darkchannel = extract_dark_channel_features(img_npy)
atmosphere_features, A_ = extract_atmosphere_features(img_npy, darkchannel)
transmi... |
def hasElement(node, element):
"""Check if exlement existing in a tag."""
if node.getElementsByTagName(element).length > 0:
return True
else:
return False
def getInertia(node):
"""Parse inertia of a link."""
inertia = Inertia()
inertialElement = node.getElementsByTagName('inertia... | The function `getLink` parses a link element from an XML node, populating its properties such as name, inertia, visual, and collision data. It checks for the presence of these sub-elements and delegates parsing to helper functions. If no inertial, visual, or collision elements exist, it explicitly sets the inertia mass... | def getLink(node, path, outputDirectory):
"""Parse a link."""
link = Link()
link.name = node.getAttribute('name')
if hasElement(node, 'inertial'):
link.inertia = getInertia(node)
if hasElement(node, 'visual'):
getVisual(link, node, path, outputDirectory)
if hasElement(node, 'coll... |
def get_square_occupant(self, square):
"""
Takes as a parameter a square in algebraic notation.
Returns "BLACK", "RED", or "NONE" corresponding to a black, red, or no piece, respectively, in the square.
"""
row, col = self._square_to_indexes(square)
square_occupant = self... | This function checks if a chess-like move is legal by verifying the moving piece belongs to the active player, ensuring the move isn't to the same square, confirming the move is straight (same row or column), checking the target square is unoccupied, and validating the path between squares is clear of other pieces. | def _legal_move(self, square_moved_from, square_moved_to):
"""
Takes as parameters the squares a player is attempting to move from and to, respectively, in algebraic notation.
Returns True if the move is legal, else returns False.
"""
if self.get_square_occupant(square_moved_from... |
def _directions_to_check_for_non_corner_capture(self, square_moved_from, square_moved_to):
"""
Takes as parameters the squares the active player moved from and to, respectively, in algebraic notation.
Returns a dictionary containing the squares to check for captures in each applicable direction.... | This function identifies and returns the active player's non-corner captures after a move by checking squares along specific directions. It iterates through potential paths, collects opponent pieces until encountering a friendly piece or empty square, and aggregates valid captures for the active player. | def _non_corner_capture(self, square_moved_from, square_moved_to):
"""
Takes as parameters the squares the active player moved from and to, respectively, in algebraic notation.
Returns the active player's non-corner captures, if applicable.
"""
non_corner_captures = []
d... |
def _corner_capture(self, square_moved_to):
"""
Takes as a parameter the square the active player moved to, in algebraic notation.
Returns the active player's corner capture, if applicable.
"""
corners_and_capture_locations = {"a1": ("a2", "b1"), "a9": ("a8", "b9"), "i1": ("h1", ... | This function identifies and removes opponent pieces captured by a legal move from 'square_moved_from' to 'square_moved_to'. It checks for captures in corners and non-corners, collects captured squares, updates the active player's captured piece count, and removes captured pieces from the board. | def _capture_pieces(self, square_moved_from, square_moved_to):
"""
Takes as parameters the squares the active player moved from and to, respectively, in algebraic notation.
Determines whether any of the opponents pieces were captured following the legal move.
If so, clears the pieces fro... |
def _legal_move(self, square_moved_from, square_moved_to):
"""
Takes as parameters the squares a player is attempting to move from and to, respectively, in algebraic notation.
Returns True if the move is legal, else returns False.
"""
if self.get_square_occupant(square_moved_from... | The code validates and executes a player's move in a game. It checks if the game is unfinished and if the move is legal. If valid, it updates the board by removing the piece from the original square and adding it to the new square, captures any affected pieces, updates the game state, switches the active player, and re... | def make_move(self, square_moved_from, square_moved_to):
"""
Takes as parameters the squares a player is attempting to move from and to, respectively, in algebraic notation.
Determines if the move is valid and legal.
If it is not, returns False.
If it is, moves the player, captur... |
def valid_move(self, coordinate):
return self.board[coordinate] == 0
def checkwin(self):
# Checks rows
for row in range(3):
if np.all(self.board[row] == self.board[row][0]) and self.board[row][0] != 0:
return self.board[row][0], True
# Checks columns
f... | This code handles a turn in a game (likely Tic-Tac-Toe) by validating a player's move at a given position, updating the board with the agent's symbol, checking for a win, and if the game continues, letting the computer make a move and check again. It returns the reward and game state (done) after processing both moves. | def play(self, position):
coordinate = (position//3, position % 3)
if not self.valid_move(coordinate):
return -10, False
self.board[coordinate] = self.agent_symbol
reward, done = self.checkwin()
if not done:
position = self.computer_move()
... |
def display_board(self):
print(self.board)
def checkwin(self):
# Checks rows
for row in range(3):
if np.all(self.board[row] == self.board[row][0]) and self.board[row][0] != 0:
return self.board[row][0], True
# Checks columns
for col in range(3):
... | This function enables a human player to interactively play a turn-based game (likely Tic-Tac-Toe) against a computer opponent. It alternates between taking human input to update the game board, checking for a win, letting the computer make a move, and repeating until the game concludes. The loop displays the board afte... | def human_play(self):
done = False
result = None
self.display_board()
while not done:
i = input()
self.board[int(i) // 3, int(i) % 3] = self.agent_symbol
self.display_board()
result, done = self.checkwin()
if done:
... |
def yesClicked(self):
self.browser.append("<i>Me</i>: Yes")
self.fever.setEnabled(True)
self.headache.setEnabled(True)
self.diarrhea.setEnabled(True)
self.sneezing.setEnabled(True)
self.vomiting.setEnabled(True)
self.heartburn.setEnabled(True)
sel... | This code configures a UI by enabling/disabling buttons for symptom selection, connecting button clicks to corresponding methods (e.g., adding symptoms to a list), and hiding the back button. It sets up event handlers for user interactions like symptom selection, yes/no responses, and navigation, likely for a medical t... | def handle_UI(self):
self.yes.setEnabled(False)
self.no.setEnabled(False)
self.fever.setEnabled(True)
self.headache.setEnabled(True)
self.diarrhea.setEnabled(True)
# self.breathing_difficulty.setEnabled(True)
self.vomiting.setEnabled(True)
self.heartburn.... |
def validate_chain(n: PosNetwork):
if len(n.blockchain) <= 1:
return None
curr_block_idx = len(n.blockchain) - 1
prev_block_idx = len(n.blockchain) - 2
while prev_block_idx >= 0:
curr_block = n.blockchain[curr_block_idx]
prev_block = n.blockchain[prev_block_idx]
if curr... | The function creates a new block for a node in a blockchain network. It first validates the existing blockchain; if invalid, it penalizes the node's stake and returns validation results. If valid, it generates a new block with current timestamp, previous hash, and node address. It then validates the new block candidate... | def create_block(_node: Node, n: PosNetwork):
# penalize node if blockchain has changed
is_validated = validate_chain(n)
if is_validated is not None:
_node.stake -= 10
return n.blockchain, n.blockchain_head, is_validated
currentTime = str(datetime.now())
newBlock = Block(
tim... |
def new_hash(_data: str) -> str:
h = hashlib.sha256()
h.update(_data.encode('utf-8'))
hashed = h.digest()
return hashed.hex()
def new_node(n: PosNetwork, stake: int):
new_node = Node(stake=stake, address=random_address())
n.validators.append(new_node)
return n.validators
def select_winner(n:... | The main task of the code is to simulate a Proof-of-Stake (PoS) blockchain network by initializing a blockchain with a genesis block, adding validator nodes, and executing five rounds of block creation. In each round, a validator is selected as the winner, their stake is incremented, and a new block is generated. The p... | def main():
# set random seed
random.seed(str(datetime.now()))
genesis_time = str(datetime.now())
_blockchain = [Block(timestamp=genesis_time, prev_hash="", hsh=new_hash(genesis_time), validator_addr="")]
pos = PosNetwork(blockchain=_blockchain, blockchain_head=Block(), validators=[])
pos.block... |
def _check_envs(self):
if not ENGINE_IP:
raise QueryException('Invalid ENGINE_IP: Please set the environment.')
if not QUERY_INPUT_TYPE:
raise QueryException('Invalid QUERY_INPUT_TYPE: Please set the environment.')
if not INPUT_CSV_PATH:
raise QueryException('... | (The main task of the code is to initialize a class that tracks query execution metrics (success/failure counts, timestamps), establishes database connections, executes queries from a CSV file, generates reports, and raises exceptions on query failures to notify Jenkins of build failures. It includes environment checks... | def __init__(self):
self.execution_start_time = datetime.datetime.now()
self.total_number_of_queries = 0
self.total_number_of_queries_successful = 0
self.total_number_of_queries_failed = 0
self.failed_query_alias = []
self.db_list = list()
self.e6x_connection = ... |
def _check_envs(self):
if not QUERY_INPUT_TYPE:
raise QueryException('Invalid QUERY_INPUT_TYPE: Please set the environment.')
if not INPUT_CSV_PATH:
raise QueryException('Invalid INPUT_CSV_PATH: Please set the environment.')
if not DB_NAME:
raise QueryExceptio... | (The main task of this code is to initialize a class instance for tracking query execution metrics, establishing database connections, and processing CSV-based queries. It sets up counters for total, successful, and failed queries, initializes environment checks, executes queries via `_perform_query_from_csv()`, genera... | def __init__(self):
self.execution_start_time = datetime.datetime.now()
self.total_number_of_queries = 0
self.total_number_of_queries_successful = 0
self.total_number_of_queries_failed = 0
self.failed_query_alias = []
self.db_list = list()
self.athena_connection... |
def _create_data_directory(save_path):
if save_path is None:
save_path = DATA_PATH
os.makedirs(save_path, exist_ok=True)
return save_path
def get_files(self, start_year, end_year, districts, file_types, months=None):
"""Return a list of available files for specific query."""
... | The main task of the code is to download specified text files based on user-defined parameters (years, districts, file types, months) while avoiding re-downloading existing files. It creates a directory, filters new files, downloads them with delays, tracks progress, and saves metadata in a CSV. The function logs downl... | def download_files(self, start_year, end_year, districts, file_types, months, save_path=None):
"""Download all text files for user's query."""
# Create data directory
save_path = self._create_data_directory(save_path=save_path)
# Get files to download
files_to_download = self.ge... |
def get_train_dataset(cfg, root_dataset_path, train_dataset_name, eval_binary_path):
# We only create the train dataset if we need PCA or whitening training.
# Otherwise not.
if cfg.IMG_RETRIEVAL.TRAIN_PCA_WHITENING:
train_data_path = f"{root_dataset_path}/{train_dataset_name}"
assert g_pat... | The function performs instance retrieval by extracting features from training and evaluation datasets, applying PCA/whitening, computing similarity scores (cosine/L2), and saving rankings/metrics. It uses a pre-trained model for feature extraction, handles GPU requirements, and outputs results based on configuration pa... | def instance_retrieval_test(args, cfg):
# We require 1-gpu for feature extraction. Hence check CUDA is available.
assert torch.cuda.is_available(), "CUDA not available, Exit!"
train_dataset_name = cfg.IMG_RETRIEVAL.TRAIN_DATASET_NAME
eval_dataset_name = cfg.IMG_RETRIEVAL.EVAL_DATASET_NAME
spatial_l... |
def drawTileMenuLabels(self):
title = tk.Label(
self.master, text="Tile Selection", font=("Arial", 16))
title.grid(row=3, column=0, columnspan=3)
active_title = tk.Label(
self.master, text="Current:", font=("Arial", 12)
)
active_title.grid(row=4, column=0, columnspan=2)
def drawActiveTil... | The main task of the code is to generate a tile menu interface by calling three methods: drawing tile labels, rendering the active tile, and displaying all tiles. This function orchestrates the visual setup of a tile-based menu system, likely for a graphical application or game, ensuring labels, active states, and tile... | def createTileMenu(self):
self.drawTileMenuLabels()
self.drawActiveTile()
self.drawAllTiles() |
def build_priority_queue(freq_dict):
""" Function to build priority queue using a min heap data structure
INPUT: Dictionary containing frequencies of each character in message
OUTPUT: Priority Queue (heapq)
"""
#Create a lit and populate the heap
heap_pq = []
for key, value in freq_d... | The code implements Huffman encoding by building a priority queue of character frequencies, constructing a Huffman tree by repeatedly combining the two lowest-frequency nodes, and generating an encoded string using depth-first traversal of the tree. Special handling occurs when only one character exists, producing a st... | def huffman_encoding(message):
test_heap = build_priority_queue(determine_frequency(message))
h_tree = huffman_tree()
if(len(test_heap) == 1):
h_tree.set_root(heapq.heappop(test_heap))
[freq, char] = h_tree.get_root().get_value()
encoded_str = ''
for i in range(0, freq+1):
... |
def predict_class(sentence):
bow=bag_of_words(sentence)
res=model.predict(np.array([bow]))[0]
ERROR_THRESHOLD=0.25
results=[[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
results.sort(key=lambda x:x[1],reverse=True)
return_list=[]
for r in results:
return_list.append({'intent':classes[r[0]],'pr... | The main task of the code is to process user input by predicting intent, validate confidence levels (probability > 0.7), update a JSON with detected intents, generate responses, and return either a valid response or an error message for invalid inputs. | def chatbotextention(message):
print(message)
i=0
ints=predict_class(message)
for i in ints:
print(i)
if i['probability']>0.7:
updatejson(i['intent'],message)
res=get_response(ints,intents)
i=0
break
else:
i=1
if i==1:
res="please enter valid input"
return... |
def constructBaseUrl(self):
base_url = "https://{}:{}@{}".format(self.username, self.password, self.grafana_url)
return base_url
def constructPayload(self):
data = {
"name": self.uname,
"email": self.email,
"login": self.uname,
"password": self.pwo... | The main task of the code is to create a user via an API POST request, validate the response, log success or errors, and initiate a time-series write if the user creation is confirmed. It constructs the request URL and payload, sends the request, checks for a 'User created' message, logs success, and returns the respon... | def createUser(self):
try:
resp = requests.post(self.constructBaseUrl() + "/api/admin/users", json=self.constructPayload(),
verify=False)
data = resp.json()
if 'message' in data and data['message'] == 'User created':
self.write... |
def move(self, delta_x):
if self.in_game and not self.pause:
next_x = self.c_piece_x + delta_x
if next_x < 0:
next_x = 0
if next_x > 10 - len(self.c_piece[0]):
next_x = 10 - len(self.c_piece[0])
if not self.collision(self.c_piece, (... | The code defines a game loop for a Tetris-like game, handling keyboard inputs for movement, rotation, and actions like dropping or pausing. It renders the game state, manages game over/pause screens, and integrates AI for automated piece positioning. The loop processes events, updates the display, and uses a clock to m... | def run(self):
key_actions = {
'ESCAPE': sys.exit,
'LEFT': lambda: self.move(-1),
'RIGHT': lambda: self.move(+1),
'DOWN': lambda: self.drop(soft_drop=True),
'UP': self.rotate_piece,
'SPACE': self.hard_drop,
'p': self.toggle_paus... |
def reset(self):
self.kn_pos = self.ori_pos
for i in range(8):
self.board[i] = [0]*8
self.board[self.kn_pos[0]][self.kn_pos[1]] = 1
def move(self, enc_mv): # Tries to move the knight and returns True if move is valid
mv = self.decodeMove(enc_mv)
if mv == 0:
... | This function processes a list of 3D move tuples, attempting to apply each move. If a move fails, it tries to repair the state using `tryRepair`. It counts and returns the number of successfully applied moves before any failure occurs. | def getValidMoves(self, mv_list):
self.reset()
num_mvs = len(mv_list)//3
assert len(mv_list) % 3 == 0
count = 0
for i in range(num_mvs):
if not (self.move(mv_list[i*3:(i+1)*3])):
if not (self.tryRepair(mv_list, i)):
break
... |
def print_maps(self, treasure=False, clear=True):
if clear:
os.system('cls' if os.name == 'nt' else 'clear')
if treasure:
print('>> Map With Treasure <<')
else:
print('>> Map <<')
for rows in range(len(self.map_data)):
output = ''... | The code presents a menu of options to the user, clears the console, and processes the selected input by invoking corresponding methods like printing maps, displaying treasure positions, or starting the game. It recursively loops back to the menu after each action, allowing continuous interaction until the user exits. | def pick_option(self):
os.system('cls' if os.name == 'nt' else 'clear')
for op in self.option.keys():
print(str(op) + ' : ' + self.option[op])
input_option = int(input('Option :'))
if input_option == 1:
self.print_maps(treasure=False)
if input_option ==... |
def load_coordinate(self):
# get set of position of user and possible road
for row in range(len(self.map_data)):
for column in range(len(self.map_data[row])):
if self.map_data[row][column] == 'X':
self.pos_user.append([row,column])
if self.... | The code initializes a game by setting the treasure count, loading coordinates, loading treasures based on the specified number, and prompting the player to pick an option. It prepares the game environment for interaction. | def load_game(self, treasure_num=1):
self.treasure_num = treasure_num
self.load_coordinate()
self.load_treasure(treasure_num)
self.pick_option() |
def authenticate(self):
"""
Sends messages containing the bot's username and OAuth password to
Twitch's IRC client.
"""
self._socket.send(bytes("PASS " + self.__password + "\r\n", "utf-8"))
self._socket.send(bytes("NICK " + self.username + "\r\n", "utf-8"))
def join_chann... | The code connects to Twitch's IRC server, authenticates the bot, joins specified channels, and listens for server responses until the "End of /NAMES list" message is received, then continues listening for further interactions. | def connect(self):
"""
Connects to Twitch's IRC client.
References
----------
https://dev.twitch.tv/docs/irc/guide#connecting-to-twitch-irc
"""
# Connects to Twitch's IRC client.
self._socket.connect((self.IRC_CLIENT, self.IRC_PORT))
# Authentic... |
def step_values(self, cnfg):
calc = []
for i in range(0, cnfg["steps"] +1):
val = (i * cnfg["speed"]) + cnfg["minimum"]
if cnfg.has_key("decimal_places"):
val = round(val, cnfg["decimal_places"])
calc.append(val)
if "reverse_mode" in cnfg and cnfg["reverse_mode"] is True:
calc = list(reversed(calc... | This code processes a configuration to adjust a controller's parameters by retrieving current values, validating ranges, calculating step-based mappings, and updating the system based on control type (absolute/relative/on/off). It handles user-defined min/max bounds, snaps out-of-range values, and applies decisions via... | def val_brain(self, cnfg):
try:
cnfg["current_position"] = getattr(eval(cnfg["module"]), cnfg["element"])
except:
self.show_message("This control does not exist in your session")
return
self._parameter_to_map_to = eval(cnfg["module"])
if cnfg["ctrl_type"] != "on/off" and hasattr(self._parameter_to_map... |
def feedback_on_off(self, feedback_to):
param = eval(feedback_to["module"])
ctrl_on = self.feedback_which_ctrl_on_off(feedback_to, "on")
ctrl_off = self.feedback_which_ctrl_on_off(feedback_to, "off")
param_value = round(param.value,2)
mapping_type = str(feedback_to["mapping_type"])
if feedback_to.has_k... | This code maps a parameter's value to a control range based on the specified control type (on/off, increment, decrement), minimum/maximum values, and reverse mode. It calculates a scaled percentage of the control range, adjusts for reversal if needed, and passes the result to a feedback handler for further processing. | def feedback_range(self, feedback_to):
if feedback_to['ctrl_type'] == "on/off":
self.feedback_on_off(feedback_to)
elif feedback_to['ctrl_type'] == "increment":
self.feedback_increment(feedback_to)
elif feedback_to['ctrl_type'] == "decrement":
self.feedback_decrement(feedback_to)
control = eval("self."... |
def selected_track_idx(self):
self._track = self.song().view.selected_track
self._track_num = self.tuple_index(self.song().tracks, self._track)
self._track_num = self._track_num + 1
return self._track_num
def selected_scene_idx(self):
self._scene = self.song().view.selected_scene
self._scene_num = self.tupl... | This method determines the current track or scene index and total count based on the 'feedback_to' input, then calls 'sess_highlight_banking_calculate' to handle highlighting or banking logic with these values. | def feedback_highlight_nav(self, feedback_to):
tracks_or_scenes = feedback_to["tracks_scenes"]
if tracks_or_scenes == "tracks":
offset_is_at = int(self.selected_track_idx()) - 1
num_of_tracks_scenes = int(len(self.song().tracks)) - 1
elif tracks_or_scenes == "scenes":
offset_is_at = int(self.selected_sce... |
def log(self, msg):
if self.debug_on is True:
self.log_message("csslog:" + str(msg))
def track_feedback(self, mode_id=None):
if (mode_id == None):
global active_mode
mode_id = active_mode
config_map = "mode_" + str(mode_id) + "_configs_map"
config_map = getattr(self, config_map)
selected_track = self... | This function handles changes in the selected track by updating LED listeners and feedback. It removes the current mode's LED listeners, adds the new mode's listeners, updates track/device feedback, and refreshes the state. The method uses dynamic method calls based on the active mode, ensuring UI elements reflect the ... | def _on_selected_track_changed(self):
global active_mode, prev_active_mode, modes
self.log("selected track changed")
mode_to_call = getattr(self, "_remove_mode" + active_mode + "_led_listeners")
mode_to_call()
mode_to_call = getattr(self, "_mode" + active_mode + "_led_listeners")
mode_to_call()
self.track... |
def val_brain(self, cnfg):
try:
cnfg["current_position"] = getattr(eval(cnfg["module"]), cnfg["element"])
except:
self.show_message("This control does not exist in your session")
return
self._parameter_to_map_to = eval(cnfg["module"])
if cnfg["ctrl_type"] != "on/off" and hasattr(self._parameter_to_map... | The main task of the code is to route the input configuration object to different processing methods based on its "output_type" value. It copies the configuration, then calls either `val_brain`, `func_brain`, or `bool_brain` methods depending on whether the output type is "val", "func", or "bool", respectively, to hand... | def pick_brain(self, obj):
cnfg = obj.copy()
if cnfg["output_type"] == "val":
self.val_brain(cnfg)
elif cnfg["output_type"] == "func":
self.func_brain(cnfg)
elif cnfg["output_type"] == "bool":
self.bool_brain(cnfg) |
def has_next_token(self):
return self.end > self.idx
def qstring(self):
self.idx += 1
s = self.string()
s.token_type = Token.STR
self.idx += 1
return s
def string(self):
cur = self.text[self.idx] if self.has_next_token() else ''
if cur in string.ascii_let... | The main task of the code is to parse and return the next token from a text stream. It handles special characters (parentheses, brackets, commas, etc.) by creating tokens, processes quoted strings via `qstring()`, skips whitespace recursively, and handles regular strings via `string()`. The function advances the index ... | def next_token(self):
if not self.has_next_token():
return None
self.idx = self.start
cur = self.text[self.idx]
match cur:
case '(' | ')' | '[' | ']' | '{' | '}' | ',' | ':':
self.idx += 1
self.start = self.idx
retu... |
def eat(self, token_type: str) -> str:
if self.lookahead is None:
raise ParseError(f"unexpected end of input")
if self.lookahead.token_type != token_type:
self.fail()
value = self.lookahead.value
self.advance()
return value
def type(self) -> Node:
... | This function parses a frame declaration, constructing an AST node (Node) representing the frame. It adds the frame's type, name, superclasses (if present), and slots (if present) as child nodes, returning the fully built Node structure. | def add_frame(self) -> Node:
self.eat(Token.ADD)
add_class = Node(Node.ADD_FRAME)
frame_type = self.type()
add_class.add_child(frame_type)
frame_name = self.literal()
add_class.add_child(frame_name)
if not self.EOF() and self.lookahead.token_type == Token.OP_C... |
def literal(self) -> Node:
return Node(Node.LITERAL, self.eat(Token.STR))
def eat(self, token_type: str) -> str:
if self.lookahead is None:
raise ParseError(f"unexpected end of input")
if self.lookahead.token_type != token_type:
self.fail()
value = self.lookahead.... | This code parses a slot element by creating a Node, adding its name, optional value, and facets based on token types, then returns the constructed slot node. | def slot(self):
slot = Node(Node.SLOT)
slot_name = self.literal()
slot.add_child(slot_name)
self.eat(Token.COLON)
if self.lookahead.token_type != Token.CL_SQUARE and self.lookahead.token_type != Token.OP_CURLY and \
self.lookahead.token_type != Token.COMMA:
... |
def eat(self, token_type: str) -> str:
if self.lookahead is None:
raise ParseError(f"unexpected end of input")
if self.lookahead.token_type != token_type:
self.fail()
value = self.lookahead.value
self.advance()
return value
def literal(self) -> Node:
... | The `update_slot` method parses token sequences to construct AST nodes representing slot operations. It identifies tokens like `ADD`, `DELETE`, `ADD_VALUE`, `DELETE_VALUE`, or `COLON`, consumes relevant tokens, and returns a `Node` with the corresponding operation type and a literal value. This function handles differe... | def update_slot(self):
tok_type = self.lookahead.token_type
if tok_type == Token.ADD:
self.eat(Token.ADD)
self.eat(Token.FACET)
return Node(Node.ADD_FACET, None, [self.literal()])
elif tok_type == Token.DELETE:
self.eat(Token.DELETE)
se... |
def eat(self, token_type: str) -> str:
if self.lookahead is None:
raise ParseError(f"unexpected end of input")
if self.lookahead.token_type != token_type:
self.fail()
value = self.lookahead.value
self.advance()
return value
def literal(self) -> Node:
... | This function parses tokens to construct AST nodes for adding or deleting 'super' or 'slot' elements. It checks the current token type (ADD/DELETE), consumes the token, validates the next token (SUPER/SLOT), and returns a Node with the corresponding operation type (ADD_SUPER, ADD_SLOT, DELETE_SUPER, DELETE_SLOT) and as... | def add_or_delete_super_or_slot(self):
tok_type = self.lookahead.token_type
if tok_type == Token.ADD:
self.eat(Token.ADD)
tok_type = self.lookahead.token_type
if tok_type == Token.SUPER:
self.eat(Token.SUPER)
return Node(Node.ADD_SUPER,... |
def eat(self, token_type: str) -> str:
if self.lookahead is None:
raise ParseError(f"unexpected end of input")
if self.lookahead.token_type != token_type:
self.fail()
value = self.lookahead.value
self.advance()
return value
def literal(self) -> Node:
... | This code parses an "update" command in a syntax tree, creating a Node representing an update operation. It handles four cases: updating a name, updating a type, adding/deleting elements, or updating a slot. It consumes tokens, constructs child nodes with relevant data, and returns a parent Node encapsulating the updat... | def update_frame(self) -> Node:
self.eat(Token.UPDATE)
tk_name = self.literal()
lookahead = self.lookahead
children = []
# print(lookahead.token_type)
match lookahead.token_type:
case Token.NAME:
self.eat(Token.NAME)
self.eat(T... |
def advance(self):
self.lookahead = self.tokenizer.next_token()
def add_frame(self) -> Node:
self.eat(Token.ADD)
add_class = Node(Node.ADD_FRAME)
frame_type = self.type()
add_class.add_child(frame_type)
frame_name = self.literal()
add_class.add_child(frame_name... | The main task of the code is to parse a "TELL" statement by creating a TELL node and adding a child node based on the lookahead token type (ADD, UPDATE, or DELETE). It advances the parser, checks the token, executes the corresponding frame operation (add, update, delete), and returns the constructed TELL node with its ... | def tell(self) -> Node:
self.advance()
tell = Node(Node.TELL)
match self.lookahead.token_type:
case Token.ADD:
tell.add_child(self.add_frame())
case Token.UPDATE:
tell.add_child(self.update_frame())
case Token.DELETE:
... |
def get_phi(self, min, max):
p1 = self.generate_prime(min,max)
p2 = self.generate_prime(min,max)
self.n = p1*p2
return (p1-1)*(p2-1)
def get_public(self):
e = random.randint(3, self.phi-1)
while math.gcd(e,self.phi) != 1:
e = random.randint(3, self.phi-1)
... | The code initializes an RSA key generation process by calculating Euler's totient function (phi) for a given range, selecting a public exponent (e), computing the private exponent (d) using the extended Euclidean algorithm, and storing these cryptographic parameters in a JSON file. The main task involves generating RSA... | def __init__(self):
self.n = None
self.phi = self.get_phi(10000,15000)
self.e = self.get_public()
gcd, self.d, y = self.euclid_extended(self.e, self.phi)
self.write_to_json() |
def initial_population(pop_size=20):
population = np.random.randint(high=7, low=0, size=(pop_size, 8))
return population
def fitness_function(population):
solved = False
solution = None
best = None
best_fitness = 0
pop_num_collisions = collisions(population)
fitness_scores = [(28-collis... | This code implements an evolutionary algorithm to optimize a problem by evolving a population of individuals through generations. It tracks the best solution, adjusts mutation rates to preserve useful traits, introduces diversity when convergence stalls, and terminates when the target fitness is achieved or after 2500 ... | def run():
#Initialize
initial_pop_size = 50
mutation_rate = 0.05 #Mutation=0 causes the generations to get stuck until variation is introduced
gen = 0
best_fitness = 0
best = None
avg_fitness = 0
pop = initial_population(pop_size=initial_pop_size)
#Loop through the generations
... |
def connect_with_node(self, host, port, reconnect=False):
if host == self.host and port == self.port:
print("connect_with_node: Cannot connect with yourself!!")
return False
for node in self.nodes_outbound:
if node.host == host and node.port == port:
... | The code processes incoming messages from nodes in a distributed system, handling heartbeat signals to manage connections and determine the coordinator, appending transactions, validating blocks, and synchronizing blockchain data across nodes through query-response mechanisms. | def node_message(self, node, data):
message = decode_message(data)
if message.type == MessageType.HEARTBEAT:
# print(f"node_message received ({self.id}) from {node.host}:{node.port}: data - {str(message.data)}")
connections = self.node_data_manager.connections
inacti... |
def read_puzzle(self):
puzzle = []
for i in range(self.size):
row = input().split(" ")
puzzle.append(row)
return puzzle
def calc_f_score(self, start, goal):
f_score = self.calc_h_score(start.data, goal) + start.level
return f_score
def calc_h_score(self, s... | The code implements an A* algorithm to solve a puzzle by iteratively expanding nodes from the open list, calculating f-scores, checking for the goal state, and managing node exploration. It reads initial and goal states, generates child nodes, avoids redundant paths, and sorts nodes by f-score for optimal search progre... | def process(self):
print("Enter the Initial State Puzzle :")
start = self.read_puzzle()
print("\nEnter the Goal State Puzzle :")
goal = self.read_puzzle()
start = Node(start, 0, 0)
start.f_score = self.calc_f_score(start, goal)
self.open.append(start)
pri... |
def parseCode(self, code_line):
point1 = code_line.find(' ')
if point1 == -1:
self.opcode.opCode_name = code_line.strip()
return
self.opcode.opCode_name = code_line[:point1].strip()
rest = code_line[point1 + 1:]
point2 = rest.find(",")
if point2 ==... | The code assembles machine code from an instruction line by parsing operands, determining the opcode type (single, two-operand, or single-operand), applying address size prefixes (66h, 67h), and returning the formatted assembly string. It handles operand types, sets appropriate prefixes based on operation size and addr... | def assemble(self, code_line): # Done
self.operand1: Union[Memory, Register]
self.operand2: Union[Memory, Register]
self.parseCode(code_line)
if self.opcode.opCode_name in single_commands:
return single_commands[self.opcode.opCode_name]
elif self.opcode.opCode_name i... |
def denoise_image(filename, initialization='rand', logfile=None, DUMB_SAMPLE=0):
'''
Do Gibbs sampling on the image and return the denoised one and frequencyZ
'''
posterior, Y, frequencyZ = \
get_posterior_by_sampling(
filename, initialization, logfile=logfile, DUMB_SAMPLE=DUMB_SAMPLE)
N, M =... | The main task of the code is to apply the denoise_image function to images with 10% and 20% noise, compare the denoised results with the original image, calculate restoration errors as pixel mismatch ratios, and save the original and denoised images as PNG files for analysis. | def perform_part_d():
'''
Run denoise_image function with different noise levels of 10% and 20%, and
report the errors between denoised images and original image
'''
global denoised_10, frequencyZ_10
denoised_10, frequencyZ_10 = denoise_image("noisy_10.txt",
init... |
def read_txt_file(filename):
'''
filename: image filename in txt
return: 2-d array image
'''
f = open(filename, "r")
lines = f.readlines()
height = int(lines[0].split()[1].split("=")[1])
width = int(lines[0].split()[2].split("=")[1])
Y = [[0]*(width+2) for i in range(height+2)]
for line in lines[2... | The main task of the code is to denoise images corrupted with 10% and 20% noise using a dumb sampling approach. It reads an original image, applies the denoise_image function to two noisy versions, saves the denoised outputs as PNGs, and calculates restoration errors by comparing edge-excluded regions of the denoised i... | def perform_part_e():
'''
Run denoise_image function using dumb sampling with different noise levels of
10% and 20%.
'''
orig_img = read_txt_file("orig.txt")
orig_img = .5 * (1 - orig_img)
denoised_dumb_10, _ = denoise_image("noisy_10.txt", initialization='same',
log... |
def read_txt_file(filename):
'''
filename: image filename in txt
return: 2-d array image
'''
f = open(filename, "r")
lines = f.readlines()
height = int(lines[0].split()[1].split("=")[1])
width = int(lines[0].split()[2].split("=")[1])
Y = [[0]*(width+2) for i in range(height+2)]
print(np.shape(Y))... | The function `denoise_image` performs Gibbs sampling to denoise an image by estimating the posterior probability of each pixel being 0 or 1. It initializes the image using specified methods, runs burn-in iterations to stabilize the sampler, then collects samples to compute a posterior matrix. The denoised image is deri... | def denoise_image(filename, initialization='rand', logfile=None):
'''
TODO
Do Gibbs sampling and compute the energy of each assignment for the image
specified in filename.
It should run MAX_BURNS iterations of burn in and then
MAX_SAMPLES iterations for collecting samples.
It is highly recommended ... |
def denoise_image(filename, initialization='rand', logfile=None):
'''
TODO
Do Gibbs sampling and compute the energy of each assignment for the image
specified in filename.
It should run MAX_BURNS iterations of burn in and then
MAX_SAMPLES iterations for collecting samples.
It is highly recommended ... | The code denoises two noisy images using the denoise_image function, compares the resulting denoised images with their original counterparts, calculates restoration errors by measuring pixel differences, and saves all images as PNG files. It reports the error rates for both images, excluding edge pixels, to assess deno... | def run_q3():
'''
Run denoise_image function with two different pics, and
report the errors between denoised images and original image
'''
global denoised_b
denoised_b = denoise_image("b_noise10.png.txt",initialization='same',logfile=None)
orig_img_a = read_txt_file("a.png.txt")
orig_img_a = .5 * (1 - ... |
def _get_chaptcha_chars(self, img_base64: str) -> Tuple[list, list]:
image_bytes = base64.b64decode(img_base64)
img = Image.open(BytesIO(image_bytes))
poses = self._detector_predict(img)
chars = []
centre = []
for box in poses:
x1, y1, x2, y2 = box
... | The code processes a base64-encoded image to identify and match characters from a given word list. It extracts captcha characters, preprocesses them and target words using a Siamese network, computes pairwise similarity scores, and employs the Hungarian algorithm to find optimal character matches. The function returns ... | def __call__(
self,
img_base64: str,
words: list,
**kwargs,
) -> list:
words_len = len(words)
chaptcha_chars, points = self._get_chaptcha_chars(img_base64)
if len(chaptcha_chars) < words_len:
return []
target_chars = [self._get_chinese_char... |
def login(
username: Optional[str] = None,
passwd: Optional[str] = None,
acc_type: Optional[AccountType] = None,
) -> dict:
if username is None or passwd is None or acc_type is None:
return asyncio.run(login_manual())
else:
while True:
try:
if acc_type == ... | This code handles user confirmation, logs in with a key, schedules execution, authenticates a main account, interacts with a buddy account, selects CDD, reserves resources, and exits, ensuring proper account setup and timing for task execution. | def __call__(self):
self._logger.info("Hello, dear DDL!")
self._logger.info("Config: \n%s", self._conf)
self._logger.info(
"CAUTION: You need to ensure that you have MANUALLY added the buddy account to the main account."
)
while True:
confirm = input("Are ... |
def _get_color_variations(self, hex_color, variation_count=6, alpha=20):
base_color = pygame.Color(hex_color)
variations = []
for i in range(variation_count):
variation = pygame.Color(
max(0, min(255, base_color.r + random.randint(-15, 15))),
max(0, m... | The function generates a randomized plant structure using L-system rules, creating branching patterns, leaves, fruits, and flowers with varied colors and sizes. It initializes parameters, applies transformation rules, tracks positions and angles, and adjusts UI sliders for iterations and growth factors, returning a cal... | def _generate_plant(self):
self.preset_index = random.randint(0, len(_PRESETS) - 1)
self._axiom = _PRESETS[self.preset_index]['axiom']
self._rules = _PRESETS[self.preset_index]['rules']
self.growth_factor = 7
self.iterations = 4
self._sentence = []
self._angles... |
def _apply_rules(self):
cur = self._axiom
for _ in range(self.iterations):
cur = self._apply_rules_to_sentence(cur)
self._sentence = cur
def get_varied_color(self, base_hex_color, variation_range=12):
base_color = pygame.Color(base_hex_color)
r = max(0, min(255, base... | This function processes a generated plant structure by applying rules to modify its geometry. It initializes parameters for angles, leaf/fruits/flower sizes, and colors, then iterates through a command string to build the plant's segments. It handles branching with a stack, randomizes angles and sizes for variation, an... | def _modify_plant(self):
self._sentence = []
self._apply_rules()
self._angles = []
self._leaf_angles = []
self._leaf_size = []
self._fruit_size = []
self._flower_size = []
self._fruit_angles = []
self.leaf_colors_variated = []
self.flower_... |
def mat_color_items(self, context):
colors = ("custom", *BASE_MATERIAL_COLORS[self.mat_base.lower()].keys())
return tuple(zip((name.upper() for name in colors), colors, ("",) * len(colors)))
def update_props(self, context):
if not self.mat_color:
self.mat_color = self.mat_color_items... | This code initializes a shader node tree for a material, combining color, texture strength, scratches, and normal maps. It sets up interconnected nodes to generate a principled BSDF shader with adjustable parameters like metallic, roughness, and normal maps, using math operations and noise/scratch textures for realisti... | def init(self, context):
inputs = {
"Color": ("NodeSocketColor", {"default_value": (0.5, 0.5, 0.5, 1.0)}),
"Texture Strength": ("NodeSocketFloat", {"default_value": 0.5}),
"Scratches": ("NodeSocketFloat", {"default_value": 0.5}),
"Normal": ("NodeSocketVector", {"h... |
def isCheckExists(self, checkid):
query = "SELECT * FROM `akp_checks` WHERE check_id = %s LIMIT 1"
values = (checkid,)
self.reconnect()
cursor = self.db.cursor(buffered=True)
cursor.execute(query, values)
if cursor.rowcount > 0:
cursor.close()
ret... | The main task of the code is to update a check's result, duration, and status in a database table (`akp_checks`) based on the provided `checkid`. It verifies if the check exists, retrieves missing status if unspecified, executes the SQL update, and returns a success response with the updated check data or a 404 error i... | def updateCheckResult(self, checkid, check_result, check_taken_time = None, check_status = None):
if self.isCheckExists(checkid) is False:
return {
'error' : False,
'code' : 404,
'message' : "No check founed with this id"
}, 404
... |
def isCheckExists(self, checkid):
query = "SELECT * FROM `akp_checks` WHERE check_id = %s LIMIT 1"
values = (checkid,)
self.reconnect()
cursor = self.db.cursor(buffered=True)
cursor.execute(query, values)
if cursor.rowcount > 0:
cursor.close()
ret... | This function updates a check's name in the database if it exists. It first verifies the check's existence by ID. If not found, it returns a 404 error. If found, it executes an SQL UPDATE query to modify the check name, commits the transaction, and returns a success response with the updated check data. The function ha... | def updateCheck(self, checkid, checkname):
if self.isCheckExists(checkid) is False:
return {
'error' : False,
'code' : 404,
'message' : "No check founed with this id"
}, 404
query = "UPDATE `akp_checks` SET `check_name` = %s WHERE `... |
def updateCheckResult(self, checkid, check_result, check_taken_time = None, check_status = None):
if self.isCheckExists(checkid) is False:
return {
'error' : False,
'code' : 404,
'message' : "No check founed with this id"
}, 404
... | The code modifies a check result by converting keys/values into a JSON-formatted dictionary, updates the check status to "Modified", stores the analysis using an external method, and returns a success response with the updated check data. | def modifyCheckResult(self, check_id, keys, values):
check_result = {
"keys" : keys,
"values" : values,
"analysis" : ""
}
import json
check_result = json.dumps(check_result)
self.updateCheckResult(check_id, check_result, check_status= ... |
def main_Q1():
user_str = input("Please enter a string letters: ")
user_str = check_string(user_str)
print("The user string is:", user_str)
sorted_list = quicksort_list(user_str)
sorted_str = quicksort_str(sorted_list)
print("The sorted string is:", sorted_str)
return sorted_str
def rem... | The main task of the code is to generate all unique permutations of a sorted string with duplicates removed. It first retrieves a sorted string from `main_Q1()`, eliminates duplicate characters using `remove_duplicates()`, computes permutations via `str_permutation()`, and prints the resulting list of permutations. | def main_Q2():
sorted_str = main_Q1()
new_str = remove_duplicates(sorted_str)
perm_list = str_permutation(new_str)
print("The permutations of this string:", perm_list, sep = "\n") |
def handle_create(event, context):
logging.info("**Received create request")
resource_config = event["ResourceProperties"]
logging.info("**Setting up user")
result = create_user_setup(resource_config)
cfnresponse.send(
event,
context,
cfnresponse.SUCCESS,
{ "UserProfi... | The code defines a Lambda function handling AWS CloudFormation custom resource operations. It processes "Create," "Update," or "Delete" requests by invoking corresponding helper functions. For unsupported request types or uncaught exceptions, it sends a failure response with an error message, logs the exception, and re... | def lambda_handler(event, context):
try:
request_type = event["RequestType"]
if request_type == "Create":
handle_create(event, context)
elif request_type == "Update":
handle_update(event, context)
elif request_type == "Delete":
handle_delete(event,... |
def minimax_tracking(self, depth, currBoardIdx, isMax, path):
"""
Improved version of minimax. It keeps the tracking
"""
pathkeeping = path.copy()
value = 0
if depth == 0 or self.is_terminal_node(currBoardIdx) == True:
return (self.evaluatePredifined(not isMa... | The function simulates a game between the agent and a predefined offensive agent using minimax algorithms. It alternates turns, tracks best moves, game boards, and expanded nodes, determining the winner (1 for maxPlayer, -1 for minPlayer, 0 for tie) by evaluating board states after each move. | def playGameYourAgent(self):
"""
This function implements the processes of the game of your own agent vs predifined offensive agent.
input args:
output:
bestMove(list of tuple): list of bestMove coordinates at each step
gameBoards(list of 2d lists): list of game board pos... |
def minimax_tracking_designed(self, depth, currBoardIdx, isMax, path):
"""
Improved version of minimax. It keeps the tracking
"""
pathkeeping = path.copy()
value = 0
if depth == 0 or self.is_terminal_node(currBoardIdx) == True:
return (self.evaluateDesigned(n... | The main task of the code is to simulate a turn-based game between an AI agent and a human player. The AI uses the minimax algorithm to determine optimal moves, while the human inputs their moves. The function tracks the game's progression by recording each move's coordinates, the board state after each move, and deter... | def playGameHuman(self):
"""
This function implements the processes of the game of your own agent vs a human.
output:
bestMove(list of tuple): list of bestMove coordinates at each step
gameBoards(list of 2d lists): list of game board positions at each move
winner(int): 1 ... |
def minimax_tracking_designed(self, depth, currBoardIdx, isMax, path):
"""
Improved version of minimax. It keeps the tracking
"""
pathkeeping = path.copy()
value = 0
if depth == 0 or self.is_terminal_node(currBoardIdx):
return (self.evaluateDesigned(not isMax)... | This function simulates a game between the user's agent and a predefined offensive agent using a minimax algorithm. It alternates turns, tracks best moves, game boards, and expanded nodes, determines the winner (1 for maxPlayer, -1 for minPlayer, 0 for tie), and returns the game states and outcomes. The agent uses mini... | def playGameYourAgent(self):
"""
This function implements the processes of the game of your own agent vs predifined offensive agent.
input args:
output:
bestMove(list of tuple): list of bestMove coordinates at each step
gameBoards(list of 2d lists): list of game board pos... |
def minimax_tracking(self, depth, currBoardIdx, isMax, path):
"""
Improved version of minimax. It keeps the tracking
"""
pathkeeping = path.copy()
value = 0
if depth == 0 or self.is_terminal_node(currBoardIdx) == True:
return (self.evaluatePredifined(not isMa... | This function simulates a game between predefined offensive and defensive agents using minimax or alpha-beta pruning. It alternates moves based on 'maxFirst', tracks best moves, values, expanded nodes, and game boards, and determines the winner. The output includes move sequences, evaluation values, node counts, board ... | def playGamePredifinedAgent(self,maxFirst,isMinimaxOffensive,isMinimaxDefensive):
"""
This function implements the processes of the game of predifined offensive agent vs defensive agent.
input args:
maxFirst(bool): boolean variable indicates whether maxPlayer or minPlayer plays first.
... |
def log(data, key=None, adminput=False):
global logQ
if adminput:
text = ""
elif key is None:
text = "SERVER: "
else:
text = f"Player{key}: "
if data is not None:
text += data
if not adminput:
print(text)
def write(sock, msg):
if msg:
... | This function initializes a new player connection by checking server status (busy/locked), assigning a unique key if possible, and managing player sessions. It increments connection counters, handles rejection messages, and cleans up resources after the player disconnects, ensuring concurrency limits and proper socket ... | def initPlayerThread(sock):
global players, total, totalsuccess
log("New client is attempting to connect.")
total += 1
if len(players) >= 10:
log("Server is busy, closing new connections.")
write(sock, "errBusy")
elif lock:
log("SERVER: Server is locked, closin... |
def get_period_first_difference(x, y):
if x != 2 or y < 5:
return ["No period exists."]
n = 100
while True:
seq = ulam_2(y, n)
even_index = find_even(seq, 2)
seq_diff = format_sequence(seq)[even_index + 1:]
p = period(seq_diff)
if p:
return p, se... | The function `get_ulam_2` computes and returns three components for a given input `y`: the period (`p`), the first difference of the sequence (`first_difference`), and the repeated sequence (`repeated_seq`). It relies on helper functions to extract the period and sequence, generate the repeated pattern, and calculate t... | def get_ulam_2(y):
p, seq = get_period_first_difference(2, y)
repeated_seq = get_repeated_sequence(p, seq)
first_difference = get_first_difference(p, seq)
return p, first_difference, repeated_seq |
def docstring_comment(lines: List[str]) -> List[str]:
if len(lines) == 0:
return []
if len(lines) == 1:
return [f'"""{escape_escapes(lines[0])}"""']
result = ['"""' + escape_escapes(lines[0])]
result += [escape_escapes(line) for line in lines[1:]]
result += ['"""']
return result
... | The function generates Python code defining a data type based on its structure. It handles enums by creating variables or Enum classes with acceptable values, primitives by assigning direct types, and custom classes like `ImplicitDict` by defining fields and docstrings. Docstrings are added for descriptions and enum ke... | def data_type(d_type: DataType) -> List[str]:
"""Generate Python code defining the provided data type.
:param d_type: Parsed API data type to render into Python code
:return: Lines of Python code defining the provided data type
"""
docstring_lines = docstring_comment(
d_type.description.spl... |
def macro_accuracy(yhat, y):
num = intersect_size(yhat, y, 0) / (union_size(yhat, y, 0) + 1e-10)
return np.mean(num)
def macro_recall(yhat, y):
num = intersect_size(yhat, y, 0) / (y.sum(axis=0) + 1e-10)
return np.mean(num)
def macro_precision(yhat, y):
num = intersect_size(yhat, y, 0) / (yhat.sum(ax... | The code evaluates a trained model on a dataset, computing performance metrics. It processes batches, calculates loss, and collects predictions/targets. It computes macro/micro accuracy, precision, recall, F1, AUC, and precision@k metrics, then prints/results returns them. The function disables gradients, handles data ... | def evaluate(model, device, data_loader, criterion, print_freq=10, verbose=True):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
y_hats = []
y_all = []
yhat_raws = []
model.eval()
with torch.no_grad():
end = time.time()
for i, (input, ta... |
def inst_f1(yhat, y):
prec = inst_precision(yhat, y)
rec = inst_recall(yhat, y)
f1 = 2 * (prec * rec) / (prec + rec)
return f1
def macro_accuracy(yhat, y):
num = intersect_size(yhat, y, 0) / (union_size(yhat, y, 0) + 1e-10)
return np.mean(num)
def macro_recall(yhat, y):
num = intersect_size(... | The code trains a neural network model on a dataset, computes loss and performance metrics (e.g., F1, accuracy, precision, recall, AUC) during training, and returns averaged loss and metrics for the epoch. It handles data loading, device placement, backpropagation, and logs training progress with detailed statistics. T... | def train(model, device, data_loader, criterion, optimizer, epoch, print_freq=10, verbose=True):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
y_hats = []
y_all = []
yhat_raws = []
model.train()
end = time.time()
for i, (input, target) in enumerate... |
def shuffleDeck():
import random
suits = {'\u2660', '\u2661', '\u2662', '\u2663'}
ranks = {'2','3','4','5','6','7','8','9','T','J','Q','K','A'}
deck = []
for suit in suits:
for rank in ranks:
card = rank+' '+suit
deck.append(card)
random.shuffle(deck)
return... | The code simulates a card game of "War" between two players. It initializes and shuffles a deck, deals cards to two players, and runs a loop to process turns. Each turn updates game stats (e.g., battles, turns), checks for empty decks, and determines the winner based on remaining cards. The function returns final stati... | def war():
deck = shuffleDeck()
player1=[]
player2=[]
deal(deck,player1,player2)
count = 0
battle = 0
doubleBattle = 0
playSignal = 1
p1Win = 0
p2Win = 0
stats = [count,battle,doubleBattle,playSignal,p1Win,p2Win]
while stats[3] == 1:
stats[0]+=1
... |
def CheckWord(w):
print("-----------------------cw")
st = models.RhymeWords.objects.filter(word=w).first()
if st==None:
return False
else:
return True
def GetRhymes(w):
print("-----------------------gr")
rhymingId = models.RhymeWords.objects.filter(word=w).first().rhymingGroup
... | The code processes a request to find rhyming words. It retrieves a word from the GET parameters, validates it using `CheckWord`, and returns JSON with rhymes via `GetRhymes` if valid. If invalid, it logs the request with `AddRequest` and returns an empty response. | def RhymesRequest(request):
# w = request.word
w = request.GET["word"]
print("-----------------------rr", w)
if CheckWord(w)==True:
print("-----------------------word found")
return HttpResponse(json.dumps(GetRhymes(w)))
else:
print("-----------------------word not found")
... |
def read_input(path: str) -> list:
with open(path, 'r') as input_file:
contents = input_file.read().split('\n')
return contents
def sum_of_possible_games(data: list, repartition: dict) -> int:
sum_of_ok_games = 0
for game in data:
game_idx = int(game.split(':')[0].split(' ')[1])
... | The main task of the code is to process game data from 'data.txt', calculate the sum of IDs for games possible under given cube limits (red:12, green:13, blue:14), and compute the sum of the "power" of minimum cube sets required for each game. The results are printed as outputs. | def main():
data = read_input('data.txt')
first_repartition = {'red': 12, 'green': 13, 'blue': 14}
print(f"Sum of possible games: {sum_of_possible_games(data, first_repartition)}")
print(f"Sum of power of min sets: {power_of_min_sets(data)}") |
def read_input(path: str) -> list:
with open(path, 'r') as input_file:
contents = input_file.read().split('\n')
return contents
def format_data(data: list) -> list:
f_data = []
for d in data:
f_data.append([int(x) for x in d.split(' ')])
return f_data
def sum_of_extrapolations(d... | The main task of the code is to read and format data from 'data.txt', compute the sum of extrapolated values and the sum of extrapolated first values, then print both results. It processes input data through formatting functions and applies extrapolation methods to generate and sum predicted values, showcasing two dist... | def main():
data = read_input('data.txt')
data = format_data(data)
print(f'Sum of extrapolated values: {sum_of_extrapolations(data)}')
print(f'Sum of extrapolated first values: {sum_of_extrapolations_first(data)}') |
def menu():
print("1. Create an account")
print("2. Log into account")
print("0. Exit")
def create_account():
card_number = []
card_number.insert(0, 4)
for i in range(1, 6):
card_number.insert(i, 0)
for i in range(6, 15):
card_number.insert(i, random.randrange(0, 9))
car... | The main task of the code is to implement a menu-driven banking application that allows users to create accounts, log in, and manage a database. It handles user input to either exit, create a new user with a card and PIN, log in, or delete/drop the 'card' table. The code interacts with a database, storing user details ... | def main():
menu()
value = int(input())
if value == 0:
print("\nBye!")
exit()
elif value == 1:
global user1
user1 = User(create_account(), create_pin())
print("\nYour card has been created")
print("Your card number:")
print(user1.number)
... |
def naslov():
print("Hotel Servis")
print("-------------")
def recepcioner_meni():
print("1. Rezervacija")
print("2. Pretraga soba")
print("3. Pretraga rezervacija")
print("4. Izvestaj")
print("5. Odjava")
def rezervacija():
print("Rezervacija")
otvori = open("rezervacija.txt", "a")
sifra = input("Unesite sif... | The main task of the code is to run a receptionist menu loop, allowing users to select options for making reservations, searching rooms, checking reservations, generating reports, or logging out. It repeatedly displays the menu, processes user input, and executes corresponding functions until the logout option is chose... | def main():
naslov()
while True:
recepcioner_meni()
opcija = input('>>>')
if opcija == '1':
rezervacija()
elif opcija == '2':
pretragaSoba()
elif opcija == '3':
pretragaRezervacija()
elif opcija == '4':
izvestaj()
elif opcija == '5':
odjava()
else:
print("Opcija nije prepoznata.") |
def Get_All_Contours_From_Image(img):
# Image Processing involving Threshold
img = np.array(img, np.uint8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Ret, Threshold = cv2.threshold(gray, 127, 255, 0)
# Find all contours
Contours, Hierarchy = cv2.findContours(Threshold, cv2.RETR_TREE, cv2.CHA... | The main task of the code is to convert a flowchart image into a Python code representation by identifying shapes, tracking connections between them, handling conditional branches (if/else), and validating the flowchart structure. It extracts instructions from shapes, stores them in a list, checks for proper start/end ... | def main():
# Input Parameter (Image Path) from the Terminal
argv = sys.argv
image_path = argv[1]
# Read the Input Image using cv2
Flowchart_Image = cv2.imread(image_path)
# Execute the Image Processing Algorithm and output results in case of no errors
try:
# Get all Contours fro... |
def readNewData(f):
"""
A utility function that creates a pandas dataframe given a filepath. This is the function
used to read in the data from Flueckiger et al.'s dataset from the University of Basel.
*parameters*
f: a filepath
"""
filename = f
df = pd.read_csv(filename, engine='c')
... | The main task of the code is to process and prepare two datasets (Basel and Dartmouth) for analysis. It binarizes sleep quality data, cleans LGA values, merges Dartmouth data, imputes missing values using predictive modeling, and exports the processed datasets to CSV files for further analysis or storage. | def main():
"""
Implemented for testing purposes.
"""
f = "/Users/jonathoncarl/s22/cs379/project/BaselData/academicSleep.csv"
df = readNewData(f)
# convert sleep quality from multinomial to binary
df['SQ'] = (df['SQ'] > df['SQ'].median())*1
# round LGA values up
df['LGA'] = df['LGA'... |
def get_stacking_regressor(reg_names, X, y):
reg_list = []
for r in reg_names:
if r in ["xgb", "rf", "knn", "mlp"]:
reg = get_optimized_regressor(X, y, regressor=r)
elif r == "dummy":
reg = DummyRegressor(strategy="mean")
elif r == "linreg":
reg = Lin... | The main task of the code is to fit an outcome regression model using stacking regressors (XGB, RF, linreg, dummy) on medical data, evaluate its performance with R² score, and optionally perform bootstrap analysis. It loads parameters, processes data, handles missing values, and saves the regression model, coefficients... | def main():
params_path = os.path.join(os.path.dirname(__file__),"..","params.yaml")
analysis = yaml.load(open(params_path), Loader=yaml.FullLoader)["analysis"]
registry = analysis.get("registry","pancreas")
setting = analysis[registry].get("setting", "palliative")
data_dir = os.path.join(os.path.... |
def readcsv(filename, nrHeaderLines):
f = open(filename)
header = f.readline()
header = header.strip().split(',')
if nrHeaderLines > 1: # it is either 1 or 2
f.readline()
content = f.readlines()
data = {}
for line in content:
line = split(line.strip())
for i in range(... | The main task of the code is to generate a netCDF file from CSV data, incorporating metadata and variable definitions. It reads input CSVs, maps variables to netCDF dimensions/attributes, assigns metadata like units and definitions, and writes time-series data with specified formats, adhering to STEMMUS-SCOPE standards... | def generateNetCdf(lat, lon, nctime, output_dir, csvfiles_path, variables_filename, duration_size):
# Renamed radiation.dat to radiation.csv
# Renamed LEtot to lEtot
# Split AResist into AResist_rac and AResist_ras
# Renamed the 2nd occurence of SWdown and LWdown to SWdown_ec and LWdown_ex
# Note th... |
def handle_server_commands(client_socket):
while True:
try:
command = client_socket.recv(1024).decode('utf-8').strip()
if not command:
continue
if command.startswith("message:"):
# Display a message to the user
show_message(... | The main task of the code is to establish a connection to a server, handle incoming commands via a socket, ensure the client runs at startup, and gracefully enter standby mode if connection fails. | def client_program():
client_socket = socket.socket()
try:
client_socket.connect((server_host, server_port))
handle_server_commands(client_socket)
add_to_startup()
except Exception as e:
print(f"Failed to connect to server: {e}")
go_into_standby_mode() |
def fxn(file):
segments = vad(file)
segments = np.asarray(segments)
dummy = 0.01*np.where(segments[:-1] != segments[1:])[0] +.01
if len(dummy)%2==0:
dummy = dummy
else:
dummy = np.delete(dummy, len(dummy)-1)
voice = dummy.reshape(int(len(dummy)/2),2)
return voice
def multi_segmentation(file_p... | The code performs speaker diarization on an audio file by segmenting it, grouping intervals, clustering embeddings to identify speakers, and generating a hypothesis of speaker turns with start/end timestamps. It returns segmented data, number of speakers, and labeled intervals. | def diarization(audiofile):
voice = fxn(audiofile)
segmented = multi_segmentation(audiofile)
print("segmentation done")
gp = group_intervals(voice)
splt = spliting(segmented,gp)
print("Splitting done")
resegmented = final_reseg(splt)
print("Resegmentation Part Done")
embeddings = emb... |
def find_market_clearing_price(self):
"""
Determines the market clearing price for goods in the exchange economy
Args:
initial_price_guess (float): An initial guess for the price to start the optimization process.
Returns:
float: The market clearing price, at wh... | This function determines the market equilibrium allocation of goods by first finding the equilibrium price using `find_market_clearing_price`, then calculating each consumer's demand at that price. It returns the equilibrium quantities allocated to consumers A and B. | def find_market_equilibrium_allocation(self):
"""
Finds the market equilibrium allocation of goods.
Returns:
tuple: The equilibrium allocations for consumers A and B.
"""
# Use the find_market_clearing_price method to find the equilibrium price
p1_eq = self.f... |
def market_clearing_prices(self):
"""
Calculates the equilibrium prices for goods 1 and 2 by solving the system of equations for market clearing.
Returns:
Equilibrium prices for goods 1 and 2.
"""
def equations(p):
p1, p2 = p
self.set_prices(p... | The code calculates the Social Welfare Function (SWF) for multiple values of τ (tau) by iterating through each τ value, recalculating equilibrium prices, determining optimal labor supply, and computing SWF using the provided social cost of carbon (kappa). It returns a list of tuples pairing each τ with its correspondin... | def calculate_swf_for_different_taus(self, tau_values, kappa):
"""
Calculates the SWF for different values of tau.
Parameters:
tau_values: An array of tau values to iterate over.
kappa: the social cost of carbon emitted by production of y in equilibrium
Returns:
... |
def market_clearing_prices(self):
"""
Calculates the equilibrium prices for goods 1 and 2 by solving the system of equations for market clearing.
Returns:
Equilibrium prices for goods 1 and 2.
"""
def equations(p):
p1, p2 = p
self.set_prices(p... | This function calculates the Social Welfare Function (SWF) for a given tax rate (tau) and social cost of carbon (kappa). It recalculates equilibrium prices, checks for validity, determines optimal labor via utility maximization, and computes SWF if all steps succeed. Invalid inputs or failures return infinity. | def calculate_swf_for_tau(self, tau, kappa):
"""
Calculates the SWF for a given value of tau.
Parameters:
tau: The tax rate.
kappa: The social cost of carbon emitted by production of y in equilibrium.
Returns:
The SWF for the given tau.
"""
... |
def save_state(self):
"""Saves the current state of the class parameters."""
self.saved_state = (self.par.w1A, self.par.w2A, self.par.w1B, self.par.w2B)
def find_market_equilibrium_allocation(self):
"""
Finds the market equilibrium allocation of goods.
Returns:
tuple... | This method generates random parameter draws, computes market equilibrium allocations for each draw, and plots the results in an Edgeworth box. It uses temporary state changes for each draw, restores the original state afterward, and collects equilibrium data for visualization. | def find_and_plot_equilibria_for_random_draws(self, num_draws, seed=123):
np.random.seed(seed)
random_draws = np.random.rand(num_draws, 2)
comparison_data = {}
# Save the current state before the loop
self.save_state()
for i, draw in enumerate(random_draws):
... |
def find_optimal_tau(self, kappa, tau_bounds):
"""
Finds the value of tau that gives the highest SWF using numerical optimization.
Parameters:
kappa: The social cost of carbon emitted by production of y in equilibrium.
tau_bounds: The bounds for the tax rate tau.
... | The main task of the code is to determine the optimal carbon tax rate (tau) that maximizes social welfare, compute the resulting equilibrium prices, consumption levels, production outputs, and lump-sum transfers in a market economy, and return these values as a structured dictionary. It uses given carbon cost parameter... | def calculate_optimal_tau_and_market_conditions(self, kappa, tau_bounds):
"""
Finds the optimal value of tau and calculates the equilibrium prices, consumptions, productions, and lump-sum transfer.
Parameters:
kappa: The social cost of carbon emitted by production of y in equilibrium... |
def read_token(fd):
"""
Read {token + ' '} from the file(this function also consume the space)
"""
key = ''
while True:
c = bytes.decode(fd.read(1))
if c == ' ' or c == '':
break
key += c
return None if key == '' else key.strip()
def print_info(info):
... | The function reads a sparse matrix from a file descriptor by first reading the matrix type and number of rows, then reading each sparse vector row and compiling them into a list, which is returned as the sparse matrix. | def read_sparse_mat(fd):
"""
Reference to function Read in SparseMatrix
A sparse matrix contains couples of sparse vector
"""
mat_type = read_token(fd)
print_info('\tFollowing matrix type: {}'.format(mat_type))
num_rows = read_int32(fd)
sparse_mat = []
for _ in range(num_row... |
def expect_token(fd, ref):
"""
Check weather the token read equals to the reference
"""
token = read_token(fd)
throw_on_error(token == ref,
'Expect token \'{}\', but gets {}'.format(ref, token))
def read_int32(fd):
"""
Read a value in type 'int32' in kaldi setup
... | The main task of the code is to read a specified number of index entries from a file descriptor, process each entry using the `read_index` function, and return them as a list of tuples. It first verifies the `<I1V>` token, reads the count of entries, iterates to collect each index, and returns the compiled list of inde... | def read_index_vec(fd):
"""
Read several Index and return as a list of index:
[(n_1, t_1, x_1), ..., (n_m, t_m, x_m)]
"""
expect_token(fd, '<I1V>')
size = read_int32(fd)
print_info('\tSize of index vector: {}'.format(size))
index = []
for i in range(size):
cur_index ... |
def expect_binary(fd):
"""
Read the binary flags in kaldi, the scripts only support reading egs in binary format
"""
flags = bytes.decode(fd.read(2))
# throw_on_error(flags == '\0B', 'Expect binary flags \'B\', but gets {}'.format(flags))
throw_on_error(flags == '\0B',
'E... | This function reads a matrix from a file descriptor, determining its type ('C' for compressed, 'S' for sparse, or default common) by inspecting the first character. It returns the corresponding matrix object after validating binary format if direct access is enabled. | def read_float_mat(fd, direct_access=False):
"""
Reference to function Read in class GeneralMatrix
Return compress_mat/sparse_mat/common_mat
"""
if direct_access:
expect_binary(fd)
peek_mat_type = peek_char(fd)
if peek_mat_type == 'C':
return read_compress_mat(fd)
... |
def expect_token(fd, ref):
"""
Check weather the token read equals to the reference
"""
token = read_token(fd)
throw_on_error(token == ref,
'Expect token \'{}\', but gets {}'.format(ref, token))
def read_token(fd):
"""
Read {token + ' '} from the file(this functi... | The function `read_nnet_io` parses a file descriptor to extract three components of an NnetIo object: a name, an index vector, and a matrix. It stores these in a dictionary with keys 'name', 'index', and 'matrix', prints informational messages about each component, and returns the dictionary. The function expects speci... | def read_nnet_io(fd):
"""
Reference to function Read in class NnetIo
each NnetIo contains three member: string, Index, GeneralMatrix
I store them in the dict:{'name': ..., 'index': ..., 'matrix': ...}
"""
expect_token(fd, '<NnetIo>')
nnet_io = {}
name = read_token(fd)
n... |
def expect_token(fd, ref):
"""
Check weather the token read equals to the reference
"""
token = read_token(fd)
throw_on_error(token == ref,
'Expect token \'{}\', but gets {}'.format(ref, token))
def read_int32(fd):
"""
Read a value in type 'int32' in kaldi setup
... | The function reads a sequence of NnetIo objects from a file descriptor by parsing structured tokens like '<Nnet3Eg>' and '<NumIo>', then reading the specified number of NnetIo instances via a loop. It returns a list of dictionaries representing these objects, ensuring proper format validation with expected tokens. | def read_nnet3_egs(fd):
"""
Reference to function Read in class NnetExample
Return a list of dict, each dict represent a NnetIo object
a NnetExample contains several NnetIo
"""
_ = fd.read(2).decode()
expect_token(fd, '<Nnet3Eg>')
expect_token(fd, '<NumIo>')
# num of the... |
def expect_token(fd, ref):
"""
Check weather the token read equals to the reference
"""
token = read_token(fd)
throw_on_error(token == ref,
'Expect token \'{}\', but gets {}'.format(ref, token))
def read_int32(fd):
"""
Read a value in type 'int32' in kaldi setup
... | Your return The function `read_nnet3_egs_original` parses a structured data format from a file descriptor, reading a sequence of `NnetIo` objects. It verifies expected tokens (`<Nnet3Eg>`, `<NumIo>`, `</Nnet3Eg>`), reads the count of `NnetIo` instances, and constructs a list of dictionaries (each representing an `NnetI... | def read_nnet3_egs_original(fd):
"""
Reference to function Read in class NnetExample
Return a list of dict, each dict represent a NnetIo object
a NnetExample contains several NnetIo
"""
expect_token(fd, '<Nnet3Eg>')
expect_token(fd, '<NumIo>')
# num of the NnetIo
num_io ... |
def update_time(self):
current_time = datetime.datetime.now()
self.start_time = current_time.strftime("%H:%M")
def get_commuter_rail_routes(self):
api_url = "https://api-v3.mbta.com/routes?"
filter = "filter[stop]=" + self.stop_id
filter += "&filter[type]=" + RouteType.COMMUTER_R... | The main task of the code is to initialize and prepare commuter rail data by updating timestamps, retrieving rail routes, extracting route identifiers, updating predictions, and extracting departure/arrival times for scheduling or analysis. This function sets up foundational data for tracking commuter rail operations a... | def initialize_data(self):
self.update_time()
routes = self.get_commuter_rail_routes()
self.extract_route_ids(routes)
self.update_predictions()
self.extract_departure_times()
self.extract_arrival_times() |
def getNextStop(self, line, stopID):
i = self.getIndexStop(stopID, line)
return self.lines[line][i+1][0] if i+1 < len(self.lines[line]) else None
def getAverageSpeed(self, line, d, h, stopFrom, stopTo):
iFrom = self.getIndexStop(stopFrom, line)
iTo = self.getIndexStop(stopTo, line)
... | The function calculates the arrival time at a destination stop by determining the average speed for a given line, day, and hour, then estimating travel time based on the distance between stops. If no destination is provided, it defaults to the next stop. The result is the current time adjusted by the computed travel du... | def getArrivalTime(self, line, t, stopID, destination=None):
if destination is None:
destination = self.getNextStop(line, stopID) # Next Stop
day = t.strftime("%a")
hour = str(int(t.strftime("%H")))
speed = self.getAverageSpeed(line, day, hour, stopID, destination)
... |
def _find_meta(self, dir: str) -> str:
"""
Finds the class folders in a dataset.
Args:
dir (string): Root directory path.
Returns:
tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.
Ensures:
No... | The code initializes a `DatasetFolder` class by setting up file paths for metadata, FCS files, and filter value mappings from a specified root directory. It applies optional transformations and inherits from a parent dataset class, preparing the dataset for loading and processing data with custom transformations. | def __init__(
self,
root: str,
transform: Optional[Callable] = None,
target_transform: Optional[Callable] = None,
) -> None:
super(DatasetFolder, self).__init__(root, transform=transform, target_transform=target_transform)
self.metafile = self._find_me... |
def preprocess_batch(self, inputs, chunk_length_s=30.0, stride_length_s=None, batch_size=None):
if isinstance(inputs, np.ndarray):
logger.warning(
"Numpy array passed as input - no sampling rate checks will be performed."
"It is strongly recommended to pass the input ... | This method transcribes audio inputs (files, bytes, or arrays) into text, optionally with timestamps. It processes audio in chunks, supports batching, and allows customization via parameters like language, task (transcribe/translate), and generation settings (beam search, sampling). The output includes recognized text ... | def __call__(
self,
inputs,
chunk_length_s=30.0,
stride_length_s=None,
batch_size=None,
language=None,
task=None,
return_timestamps=None,
num_beams=1,
length_penalty=1.0,
do_sample=False,
top_k=50,
temperature=1.0,
... |
def certification(self,client):
'''
CERTIFICATION STAGE:
1.USER SENDS USERNAME AND RECEIVES SERVER PUBLIC KEY
2.USER SENDS HIS PUBLIC KEY
3.SERVER SENDS USER'S CERTIFICATE TO USER
'''
done = False
while not done:
msg = client.recv(self.BUFSIZ)... | The main task of the code is to execute a multi-step protocol for a client, including public key certification, user selection, handshake, and data reception. It initializes certification, processes user selection, performs a handshake, logs completion, and finally calls the receive method to handle incoming data, ensu... | def accept_protocols(self,client):
'''
PROTOCOL PROCEDURES
1. PUBLIC KEY CERTIFICATION
2. HANDSHAKING
3. KEY GENERATION
'''
self.certification(client)
logging.info(f'{self.clients[client].username} Certicifation DONE ...')
self.user_selection(clien... |
def certification(self):
while self.server_public == None:
self.send_command('SENDPUBLIC')
if self.dec(self.socket.recv(self.BUFSIZ))[0] == 'PUBLIC':
pem = self.socket.recv(self.BUFSIZ)
self.server_public = load_pem_public_key(pem)
logging.info('Se... | The code implements a multi-stage login protocol involving user certification, user selection, and handshake initiation. It first performs certification, then receives a user list, selects a target user, and begins a handshake process. The method orchestrates these steps sequentially to facilitate secure user authentic... | def login_protocol(self):
'''
FIRST CERTIFICATION STAGE
SECOND USER LIST ARRIVES TO USER1
THIRD USER1 SELECTS USER2
FORTH HANDSHAKING BEGINS
'''
self.certification()
self.select_user()
self.receive() |
def _waitForNodeToActivate(self, node_name):
# Waits for the node within the tester namespace to become active
self.debug('Waiting for ' + node_name + ' to become active..')
node_service = node_name + '/get_state'
state_client = self.create_client(GetState, node_service)
while no... | This function waits for key Navigation 2 (Nav2) components to activate, including the AMCL localization node and the behavior tree navigator. It also waits for an initial pose to be set, then logs that Nav2 is ready for use, ensuring the system is fully initialized before proceeding with navigation tasks. | def waitUntilNav2Active(self):
self._waitForNodeToActivate('amcl')
self._waitForInitialPose()
self._waitForNodeToActivate('bt_navigator')
self.info('Nav2 is ready for use!')
return |
def parse_html(html_path):
# Text extraction with boilerpy3
html_extractor = extractors.KeepEverythingExtractor()
return split_newline(html_extractor.get_content_from_url(html_path))
def extract_from_url(url):
html_content = requests.get(url).text
try:
body_start = html_content.index('<body'... | This function scans a given URL, extracts text and PDFs, and recursively explores up to 10 linked pages within the same domain. It avoids revisiting URLs, checks for keyword matches, and aggregates content, blocks, and PDFs from all visited links. | def scan_link(link, counter=1, rname=""):
if link in scanned_links:
return dict(), dict(), "", []
scanned_links.append(link)
#print("cv_content", cv_content)
block = dict()
listed_blocks = dict()
content = ""
pdfs = []
try:
if(".pdf" in link):
pdfs.append(link... |
def scan_link(link, counter=1, rname=""):
if link in scanned_links:
return dict(), dict(), "", []
scanned_links.append(link)
#print("cv_content", cv_content)
block = dict()
listed_blocks = dict()
content = ""
pdfs = []
try:
if(".pdf" in link):
pdfs.append(link... | The main task of the code is to gather and analyze information about a person (rname) by traversing web links and PDFs from search results. It searches for biographical data, extracts content, processes text for keywords, combines results from multiple sources, and compiles structured profiles. The function returns a l... | def traverse_web_links(rname, url=None):
cv_content = ""
link_tree = list()
if url != None:
link_tree.append(url)
# goog_search = 'https://google.com/search?q=' + rname + " biography"
# goog_search = goog_search.replace(" ", "%20")
# print(goog_search)
# r = requests.get(goog_search)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.