dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _calculate_normalized_energy(self, data):
data_freq = self._calculate_frequencies(data)
data_energy, rms_energy = self._calculate_energy(data)
energy_freq = self._connect_energy_with_frequencies(data_freq, data_energy)
return energy_freq, rms_energy
def _sum_energy_in_band(self, energy_frequencies, ... | The code detects speech regions in an audio signal by calculating the ratio of energy in a specified frequency band (speech band) to total energy within sliding windows. It outputs an array of window indices and speech flags (1 for speech, 0 for nonspeech), using thresholds to classify regions. The method includes ener... | def detect_speech(self):
'''Detects speech regions based on ratio between speech band energy
and total energy.
Output is array of window numbers and speech flags (1 - speech, 0 - nonspeech).'''
detected_windows = np.array([])
sample_window = int(self.rate*self.sample_window)
sample_overlap = in... |
def _calculate_normalized_energy(self, data):
data_freq = self._calculate_frequencies(data)
data_energy = self._calculate_energy(data)
energy_freq = self._connect_energy_with_frequencies(data_freq, data_energy)
return energy_freq
def _sum_energy_in_band(self, energy_frequencies, start_band, end_band):
... | The code detects speech regions in audio data by analyzing the ratio of energy in a specific frequency band (speech band) to total energy within sliding windows. It outputs an array of window indices and binary speech flags (1 for speech, 0 for nonspeech), applying a threshold to classify speech and smoothing the resul... | def detect_speech(self):
'''Detects speech regions based on ratio between speech band energy
and total energy.
Output is array of window numbers and speech flags (1 - speech, 0 - nonspeech).'''
detected_windows = np.array([])
sample_window = int(self.rate*self.sample_window)
sample_overlap = in... |
def decrypt_password(hashinput,hashtype):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',8080))
sending = hashinput + "|" + hashtype
s.sendall(sending.encode())
if hashtype == "GET":
output = s.recv(1024)
print(output.decode())
else:
print("[... | This code is a forensics toolkit that processes command-line arguments to perform tasks like hash cracking, file recovery, metadata extraction, and disk image analysis. It validates inputs, handles mutually exclusive operations, and executes functions such as decrypting hashes, recovering files from disk images, genera... | def main():
parser = argparse.ArgumentParser(description="Forensics toolkit")
source = parser.add_mutually_exclusive_group()
action = parser.add_mutually_exclusive_group()
source.add_argument("-H", "--hashcrack", dest="hashinput", help="Send a hash to be cracked")
parser.add_argument("-T", "--type",... |
def generate_initial_problem(items_to_consider, capacity):
knapsack = Knapsack(np.zeros(len(items_to_consider)))
while True:
knapsack.state_bit_array = np.zeros(len(items_to_consider))
knapsack.cumulative_weight = 0
for index, value in enumerate(knapsack.state_bit_array):
ran... | The code implements a hill climbing algorithm to solve the knapsack problem. It starts with an initial solution, iteratively generates neighboring solutions, selects the one with the highest value, and stops when no improvement is found. The optimal items and their cumulative value are then printed. | def hill_climbing(items_to_consider, capacity):
current_problem = generate_initial_problem(items_to_consider, capacity)
while True:
successors = generate_successors(current_problem, capacity, items_to_consider)
neighbour = get_maximum_valued_successor(successors, items_to_consider)
if ca... |
def cls():
os.system('clear')
def createUser():
cls()
nombre = input("Ingrese su nombre: ")
apellido = input("Ingrese su apellido: ")
em = input("Ingrese su email: ")
un = input("Ingrese su username: ")
co = input("Ingrese su contrasena: ")
user=User.objects.create_user(first_name=nombre... | This code presents a menu-driven interface for user management, allowing users to create accounts, list existing users, log in, or exit. It continuously displays options, processes input, and executes corresponding functions like createUser(), list_users(), and login(). Upon exiting, it clears the screen and terminates... | def handle(self, *args, **kwargs):
cls()
while(True):
print("MENU\n------\n1. Crear usuario\n2. Listar usuarios\n3. Acceder\n4. Salir")
option = input()
if option == '1':
createUser()
elif option == '2':
list_users()
... |
def MakeSet(self, point):
# set the point parent to the point itself
point.parent = point
# set initial rank of point to 0
point.rank = 0
def Find(self, x):
if x.parent == x:
return x
else:
x.parent = self.Find(x.parent)
return x.parent... | The code implements Kruskal's algorithm to compute a minimum spanning tree (MST). It initializes disjoint sets for each coordinate, sorts edges by distance, and iteratively adds edges to the MST if they connect disjoint sets (avoiding cycles). The MST is built by uniting sets and storing selected edges. Your return | def kruskal(self, coordinates, shortestDistance):
# running for loop to get each coordinate
for coordinate in coordinates:
# creating a spanning tree for each coordinate
self.MakeSet(coordinate)
# initialising a set to store the minimum_spanning_tree
minimum_span... |
def fix_images(data: Dict) -> Dict:
fixed = copy.deepcopy(data)
images_params = fixed["items"]["behavior"]["stimuli"].pop("images-params")
fixed["items"]["behavior"]["stimuli"]["images"] = images_params
set_log = fixed["items"]["behavior"]["stimuli"]["images"]["set_log"]
# kinda vital since we're ig... | The main task of the code is to process and correct specific trials in a dataset by identifying "faux go" and "faux catch" entries, applying targeted fixes to these trials, updating the trial log with the corrected entries, and maintaining accurate image parameter tracking throughout the process. | def fix_trials(data: Dict) -> Dict:
fixed = copy.deepcopy(data)
fixed_images = fix_images(fixed)
fixed_trial_log = []
initial_image_params = fixed["items"]["behavior"]["params"]["initial_image_params"]
prev_image_name = encode_image_name(
initial_image_params["Image"], initial_image_params["... |
def filter_events(trial: dict, name_fiter: str) -> list:
"""Filters event in a trial log entry based on event name.
"""
return [
event for event in trial["events"]
if event[0].startswith(name_fiter)
]
def fix_no_reward_catch(log):
early, within_window = \
classify_licks_no_re... | The function processes a log to address scenarios where licks are disabled. It checks if "licks_enabled" is True, returning early if so. Depending on whether the trial is a "catch" (True) or not (False), it filters for "rejection" or "miss" events. If such events exist, it applies specific fixes: `fix_no_reward_catch` ... | def fix_lick_disabled_log(log):
if log["licks_enabled"]:
return
is_catch = log["trial_params"]["catch"]
if is_catch is True:
rejection_events = filter_events(log, "rejection")
if len(rejection_events) < 1:
return
fix_no_reward_catch(log)
elif is_catch is Fal... |
def schedule_task(self, task):
"""
Schedules the given task to one of the workers
"""
# Waiting until there's at least one slot available
self.sem.acquire(blocking=True)
# Getting the worker id with available slots based on the scheduling algorithm
worker_id ... | (The main task of the code is to orchestrate the execution of a job by scheduling its map and reduce tasks sequentially. It first schedules all map tasks, waits for them to complete, then schedules reduce tasks, ensuring dependencies are met before finalizing the job.) | def schedule_all_tasks(self, job):
"""
Schedules map and reduce tasks of the given job
"""
for task in job["map_tasks"]:
self.schedule_task(task)
# Wait for all map tasks to complete
self.dependency_wait_mapper(job)
for task in job["reduce_tasks"... |
def input_pairs_validation(): #used for validation
names_labeled = image_names(folder = 'labeled')
names_validation = image_names(folder = 'validation')
label_keys = list(names_labeled.keys())
label_pairs = {}
targets = {i:[] for i in labels}
for n1 in label_keys[:-1]:
pair_l1 = []
... | The code validates a model's ability to estimate labels accurately by comparing true targets with model-generated estimates using the EM algorithm. It computes the fraction of correct matches per label by calculating the mean accuracy across all labels, highlighting how well the model aligns estimated labels with actua... | def validate():
label_pairs, targets = input_pairs_validation()
label_scores = E_step(model,label_pairs,1)
targets_estimate = M_step(model,label_scores,True)
#print("target ",targets[0])
#print("targets_estimate ",targets_estimate[0])
label_wise_match = {}
for l in targets.keys():
nu... |
def gen_class_prob_matrix(instances: int, classes: int) -> List[List[float]]:
"""
Generate the list of lists of random distribution for each matching instance
:param instances: The number of instances in the data_table
:param classes: The number of classes in the dataset
:return: The list of lists ... | The main task of the code is to train a classifier by generating a class probability matrix from training data, populating the classifier with these probabilities, and computing posterior probabilities for classification. The function initializes the classifier's structure, prepares probability distributions, and deriv... | def train() -> None:
# Create the initial class_prob_matrix based on data_table
global class_prob_matrix
class_prob_matrix = gen_class_prob_matrix(
num_training_instances, num_class)
# Fill the classifier with probabilities
fill_classifier()
# Create posterior values from original cla... |
def has_error(problems):
"""
Returns true or false + a message if the operation has any error.
Args:
problems (list): each item is a string for each problem
Returns:
bool, string: it returns the verification for error and the message
"""
#1) If there are to... | The code arranges arithmetic problems vertically, aligning operands and operators, and optionally displays results. It processes a list of math problems, checks for errors, and constructs a formatted string with each problem's operands, operators, dashes, and results (if requested). The output is a vertically arranged ... | def arithmetic_arranger(problems, show_answer=False):
"""
Returns the problem arranged.
Args:
problems (list): each item is a string for each problem
show_answer (bool): condition to show or not the answer of each problem
Returns:
string: problems vertic... |
def genBoard():
global board
board = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
drop_two(board)
return board
def drop_two(board):
open_spot = False
dropped = False
if (moves[len(moves)-1] != moves[len(moves)-2]):
for row in range(4):
for col in range(4):
... | This code simulates a game where a board is generated, and the user controls piece movement via directional inputs. Each move shifts the board, drops new pieces, updates the score, and redraws the board. The loop continues until the user inputs "quit", allowing interaction with the game mechanics and real-time feedback... | def Alpha_test_driver():
board = genBoard()
drop_two(board)
drawBoard(board)
print("____________")
key_pressed = ""
while (key_pressed.lower() != "quit"):
key_pressed = str(input(">: "))
print("")
if key_pressed.lower() == "up":
shift_up(board)
dro... |
def find_top_k_entities(tweets, entity_key, value_key, k):
'''
Find the K most frequently occuring entitites
Inputs:
tweets: a list of tweetss
entity_key: a string ("hashtags", "user_mentions", etc)
value_key: string (appropriate value depends on the entity type)
k: integer ... | This code processes tweets based on a specified task (1-7) by extracting entities or n-grams. It validates inputs, loads JSON data, and executes task-specific functions like finding top entities, frequent terms, or monthly trends, then prints results. | def go(args):
task = args.task
task = task[0]
if task <= 0 or task > 7:
print("The task number needs to be a value between 1 and 7 inclusive.",
file=sys.stderr)
sys.exit(1)
ek2vk = {"hashtags":"text",
"urls":"url",
"user_mentions":... |
def check_bundles(self):
""" Check bundle files for required comments. """
if 'Bundler' in self.core.plugins:
for bundle in self.core.plugins['Bundler'].entries.values():
xdata = None
rtype = ""
try:
xdata = lxml.etree.XML(b... | The `Run` method executes a series of validation checks, including verifying bundles, properties, metadata, configuration files (`cfg`), and probes. Its primary task is to ensure system components meet specified criteria, likely for configuration validation or setup integrity. | def Run(self):
self.check_bundles()
self.check_properties()
self.check_metadata()
self.check_cfg()
self.check_probes() |
def lux_calc(frame):
global luxcnt, luxsum, settings, curlux
frmgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
curlux = np.mean(frmgray)
ok = True
# check for lights out situation
if curlux < ((luxsum / luxcnt) * settings.lux_level):
applog.info("LUX STEP: %d", curlux)
luxsum = curl... | The main task of the code is to detect motion in a video stream by comparing consecutive frames using distance maps, Gaussian smoothing, and thresholding. It calculates the standard deviation of the processed distance map to determine motion presence, updating the system state (motion_hold/no_motion) based on a thresho... | def intel_movement(debug, read_cam):
global settings, frame1, frame2, cur_state
if debug:
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.namedWindow('frame')
cv2.namedWindow('dist')
frame1 = read_cam()
lux_calc(frame1)
frame2 = read_cam()
lux_calc(frame2)
while(True):
if cur_state == State.re... |
def is_cuda_cv():
global have_cuda
try:
count = cv2.cuda.getCudaEnabledDeviceCount()
if count > 0:
have_cuda = True
else:
have_cuda = False
except:
have_cuda = False
return have_cuda
def check_cuda():
CUDA_SUCCESS = 0
libnames = ('libcuda.so',... | The main task of the code is to configure and run a camera system with customizable movement detection algorithms (Adrian's or Intel's), handling input from various sources (local, RTSP, GST), logging events, and using MQTT. It parses command-line arguments, initializes camera settings, selects detection algorithms, pr... | def main(args=None):
global logwriter, csvfile, ml_dict, applog, cur_state, dimcap, video_dev
global settings, hmqtt, show_windows, read_cam, read_local_resize, remote_cam
global camera_spin, camera_capture_to_file
global cap_prefix, backup_ml, have_cuda, use_three_arg
# process cmdline arguments
ap = argp... |
def bubble_sort(list_):
if len(list_) == 1:
return
yield list_
swapped = True
while swapped:
swapped = False
for i in range(len(list_) - 1):
if list_[i] > list_[i + 1]:
list_[i], list_[i + 1] = list_[i + 1], list_[i]
swapped = True
... | This code animates a selected sorting algorithm by generating a shuffled list, initializing a matplotlib plot, and using FuncAnimation to visualize each step of the algorithm's execution, updating bar heights in real-time to demonstrate the sorting process. | def animate(self):
A = [x for x in range(self.Range)]
random.shuffle(A)
if self.Algorithm == 'Bubble Sort':
title = 'Bubble Sort'
generator = bubble_sort(A)
elif self.Algorithm == 'Insertion Sort':
title = 'Insertion Sort'
generator = inser... |
def stop(self):
self.__move_robot()
def __return_response(self) -> Movement.Response:
res = self.__request_image()
rclpy.spin_until_future_complete(self.__image_client, res)
try:
return res.result()
except Exception as e:
self.__log(str(e))
def __move_robo... | The main task of the code is to control a robot's movement along a line by adjusting motor speeds based on visual input. It calculates linear and angular speeds using the robot's distance from the line and the relative position of the line's centroid. The robot continues moving until it detects an intersection or reach... | def follow_line(self):
"""
Calculates robot motors speeds based on input image, so it keeps following line until finds intersection
"""
self.stop()
robot_image = self.__return_response()
distance = self.distance
while not (robot_image.intersection and distance > s... |
def move_past_intersection(self, distance_to_move: float = 0.46):
while (initial_position := self.position) is None:
pass
distance_function = self.__odometry.euclidian_distance_2d
while (diff := distance_function(self.position, initial_position)) < distance_to_move ... | The main task of the code is to determine the appropriate movement action based on the given `turn` parameter. If the turn is STRAIGHT, it moves past an intersection; otherwise, it executes right, left, or back turns. A 0.1-second delay is added after the action to control movement timing. | def __decision(self, turn):
if turn == Turn.STRAIGHT:
self.move_past_intersection()
return
elif turn == Turn.RIGHT:
self.turn_right()
elif turn == Turn.LEFT:
self.turn_left()
elif turn == Turn.BACK:
self.turn_back()
slee... |
def stop(self):
self.__move_robot()
def __log(self, msg: str):
self.__robot.get_logger().info(msg)
def __decision(self, turn):
if turn == Turn.STRAIGHT:
self.move_past_intersection()
return
elif turn == Turn.RIGHT:
self.turn_right()
elif turn =... | The code makes the robot follow a predefined path by iterating through coordinates, calculating required turns relative to the current direction, logging decisions, executing line-following actions, and updating the robot's direction at each step. | def __follow_path(self, path):
"""
Makes robot follow line, main method
"""
for coordinate in path:
self.stop()
turn = coordinate.convert_to_turn(self.__current_direction)
self.__log(str(turn))
self.__decision(turn)
self.follow... |
def _should_check(self):
try:
with open(self._last_checked_file_path, "r") as file:
content = file.read().strip()
try:
file_date = datetime.datetime.strptime(content, "%Y-%m-%d").date()
current_date = datetime.date.today()
... | This code checks if a package is up-to-date by comparing its current version with the latest available version. If an update is needed, it instructs the user to run a `pip install` command. It handles errors gracefully, outputs colored status messages, and updates the last-checked timestamp. The process is conditional ... | def check_for_update(self):
if self._should_check():
try:
latest_version = self._get_latest_version()
current_version = self._get_current_version()
if None not in [current_version, latest_version]:
if version.parse(current_version)... |
def release_job(job_queue_path, job_uuid, retry=0):
queue_lock.acquire()
logger.debug('[' + job_uuid + '] ' + 'Queue lock acquire. [271]')
backup_file(job_queue_path, (job_queue_path + '.bak'))
try:
with open(job_queue_path, 'r+') as job_file:
job_data = json.load(job_file, object_pa... | This function processes pending jobs by updating their status to running, executes analysis using run_kaptive, handles errors with retries, and coordinates worker threads. It manages job queues, locks files to prevent conflicts, and releases resources when tasks complete, ensuring smooth workflow execution. | def run_script(job_queue_path, upload_path, job_uuid, retry=0):
job_file_path = os.path.join(upload_path, job_uuid, 'job_list.json')
table_path = os.path.join(upload_path, job_uuid, 'kaptive_results_table.txt')
job_list_lock.acquire()
logger.debug('[' + job_uuid + '] ' + 'File list lock acquire. [160]')... |
def process_articles(urls, folder, target_article_count, save_interval):
"""
Process each article URL and organize the scraped data until the target number of articles is reached.
"""
random_numbers = random.sample(range(1, 1000000), len(urls))
# Initialize lists to store the scraped data
c... | The code performs web scraping by extracting articles from URLs in a CSV file, processes them into structured data, and splits the resulting corpus, queries, and keywords into training, validation, and test sets according to a specified ratio, saving each subset into designated folders for machine learning tasks. | def webscraping(folder, max_articles=105, save_interval=100, split_ratio={'train': 0.7, 'valid': 0.15, 'test': 0.15}):
"""
Main webscraping function orchestrating the scraping process.
"""
os.makedirs(folder, exist_ok=True)
# Define train, test, validation folders:
train_folder = os.pa... |
def edgeExists(self, src, des):
for edge in self.edges:
if edge.src == src and edge.des == des:
return True
return False
def getNode(self, key):
node = None
for currentNode in self.nodes:
if currentNode.key == key:
node = currentNod... | This code adds an edge between two nodes in a graph, ensuring no cycles are formed. It checks if the edge already exists, verifies if adding it would create a cycle, and updates node relationships (children/parents) if valid. If valid, it adds the edge and updates the nodes' attributes. If invalid (existing edge or cyc... | def addEdge(self, src, des):
if self.edgeExists(src, des):
return False
if not self.edgeExists(src, des):
node = self.getNode(src)
node2 = self.getNode(des)
if self.isChild(src, des):
print("Cannot add edge (" + str(src) + "," + str(des) ... |
def __start_main_object_block(self, object_index):
self._data_printer.start_object_block(
type_2=self._type_name,
triangles_limit=self._triangles_limit,
object_index=object_index
)
def __print_vob_data(self):
self._data_printer.print_int_property(name="pack", ... | The main task of the code is to process and print data related to a specific object, starting a main object block, printing VOB data, visual blocks, AI information, and additional data, then finalizing the block and returning an updated object index. | def print(self, object_index):
self.__start_main_object_block(object_index)
self.__print_vob_data()
self.__print_visual_block(object_index=object_index)
self.__print_ai()
self._print_additional_data()
self._data_printer.end_object_block()
return self.updated_objec... |
def __print_vob_tree_block_start(self):
self.__data_printer.start_object_block(type_1="VobTree")
def __print_vobs(self, object_index):
for index, vob in enumerate(self.__vob_tree):
object_index = self.__print_vob(vob, index, object_index)
return object_index
def __print_vob_tree_bloc... | The main task of the code is to print a VOB tree structure by first initializing a block, processing VOBs (Versioned Object Blocks) with the provided object index, finalizing the block, and returning the updated object index after operations. | def print(self, object_index):
self.__print_vob_tree_block_start()
object_index = self.__print_vobs(object_index)
self.__print_vob_tree_block_end()
return object_index |
def height(self, node):
if node is None:
return -1
return node.height
def rotate(self, node):
if self.height(node.left) - self.height(node.right) > 1:
# Left heavy
if self.height(node.left.left) - self.height(node.left.right) > 0:
# Left left case
ret... | This code inserts a new node into a binary tree, recursively placing data in the left or right subtree based on comparison. It updates the node's height after insertion and performs rotations to maintain tree balance. The function handles duplicate data by ignoring it and ensures proper structural adjustments for effic... | def insert(self, node, data):
if node is None:
return Node(data)
if data < node.data:
print("Inserting ", data)
node.left = self.insert(node.left, data)
elif data > node.data:
node.right = self.insert(node.right, data)
else:
# Ignore duplicates
return nod... |
def mean(x, axes) :
''' Returns the mean of each row in x
Give axes = 1 if single axis data is input
Give axes = 3 if 3 axis data is input
Otherwise output will be None type
'''
# checking if single axis data is provided as input
if axes == 1 and x.shape[1] == 150 :
# initializing ... | The function `return_features` computes multiple statistical features (mean, standard deviation, variance, energy, RMS, skewness, kurtosis, and number of peaks) from input data `x` along specified axes (1 or 3). It concatenates these features into a single array, returning a combined feature matrix for further analysis... | def return_features(x, axes) :
''' Returns all features (whose functions are defined here)
axes = 1 or 3 (depending on which data is being passed)
'''
x_mean = mean(x, axes)
x_std = std_dev(x, axes)
x_var = variance(x, axes)
x_energy = energy(x, axes)
x_rms = rms(x, axes)
x_skew = s... |
def __onkeydown(self, event: pygame.event) -> int:
"""Translate a key press event to a signal understood by the snake. In
particular, arrow key events will be translated to the following int
numbers:
0
3 1
2
Returns:
(int): One of the... | This function handles Pygame events to manage game state transitions. It processes quit requests, key presses for snake movement, collision checks, apple updates, and game-over conditions. Returns 0 to quit, 1 to continue playing, or 2 when the game ends due to collisions. It updates the display, tracks steps/apples, a... | def __pygame_events_handler(self) -> int:
"""Function to handle all game events.
Returns:
(int): Game state. 0-quit, 1-play, 2-game_over
"""
for e in pygame.event.get():
if e.type == pygame.QUIT:
return 0
elif self.__game_state == 2:
... |
def __update_snake(self) -> None:
"""Update the rendering of snake on the game board according to the positions
of head, bodies, and tail specified by self.__snake.
"""
for i, (x, y) in enumerate(self.__snake):
if i == 0: # head
head_pos = (x, y)
... | The code initializes a Pygame window for a snake game, sets up the game board, loads assets, renders the initial snake and apple, and enters a loop to handle user input or replay moves. It maintains the game state, updates the display at a set frame rate, and terminates when the game ends, printing a "Game over" messag... | def play(self, snake: list = [], delay: int = 0) -> None:
"""Start the pygame loop and render the default snake.
"""
self.snake = snake
pygame.init()
pygame.display.set_caption("Snaky")
# build the game __board
dim_pixel = Snaky.BLOCK_EDGE_RESOLUTION * Snaky.BOAR... |
def check_solution(solution: List[List[int]]) -> bool:
return check_columns(solution) and check_rows(solution) and check_sections(solution)
def get_empty_cells(matrix: List[List[int]]) -> list[tuple[int, int]]:
empty_cells = []
size = len(matrix)
for x in range(size):
for y in range(size):
... | (The code validates the initial solution; if valid, it attempts to solve the puzzle using empty cells. If solving succeeds, it returns the solution; otherwise, it returns the original invalid solution.) | def get_solution(initial_solution: List[List[int]]) -> List[List[int]]:
if not check_solution(initial_solution):
return initial_solution
solution = initial_solution.copy()
empty_cells = get_empty_cells(solution)
(solution, success) = solve(solution, empty_cells)
if not success:
ret... |
def print_membership_list(self):
'''
Print current membership list
return: None
'''
print(self.MembershipList)
def print_self_id(self):
'''
Print self's id
return: None
'''
print(IP + "#" + self.MembershipList[HOST][0])
def join(self, toP... | The code implements an interactive shell for a distributed system (CS425 MP2), enabling users to manage group membership (join/leave), retrieve system status (list_mem, list_self, list_master), and perform file operations (upload, download, delete, list storage locations) across a distributed file system (SDFS). It als... | def shell(self):
print("Welcome to the interactive shell for CS425 MP2. You may press 1/2/3/4 for below functionalities.\n"
"1. list_mem: list the membership list\n"
"2. list_self: list self's id\n"
"3. join: command to join the group\n"
"4. leave: command... |
def get_data(dirpath, async_data=True, time_factor=1000.0, as_dict=True, verbose=False):
client_df, msgserv_df, sanitserv_df, mockdata_df = get_actors_df(dirpath, async_data, time_factor)
all = client_df.merge(msgserv_df, how='outer', on=["query_uid", "client_uid", "query_index"], suffixes=("_client", "_msg"))... | The main task of the code is to compare asynchronous and synchronous data by analyzing tail latency and call cascades. It retrieves both data types from the specified directory, then uses `compare_tail_latency` and `compare_calls_cascade` functions to evaluate and contrast their performance metrics. The code is structu... | def main(data_dirpath, async_data=True, verbose=False):
all_async = get_data(data_dirpath, async_data=True, as_dict=False, verbose=verbose)
all_sync = get_data(data_dirpath, async_data=False, as_dict=False, verbose=verbose)
# print(all_sync)
# print(all_sync["latency"].argmax())
# print(all_sync.loc... |
def set_day_type_suffix(df: pd.DataFrame) -> str:
"""Set the day_type to be included in the filename of the
saved output
Args:
df (pd.DataFrame): DataFrame containing a day_type column
Returns:
str: The day type found in the day_type column. Returns the string
all_day_ty... | The function `make_all_maps` generates and saves multiple thematic maps of transit routes using a GeoDataFrame. It creates visualizations for route performance metrics like trip ratios, average trip counts, and trips per rider, both as continuous maps and binned by quintiles. It also highlights the worst and best perfo... | def make_all_maps(
summary_gdf_geo: gpd.GeoDataFrame, start_date: str, end_date: str
) -> None:
"""Make all maps from data specified in run_mvp or main
Args:
summary_gdf_geo (gpd.GeoDataFrame): A GeoDataFrame from the second
element of the output from compare_scheduled_and_rt.main or fr... |
def filter_day_type(df: pd.DataFrame, day_type: str) -> pd.DataFrame:
"""Filter DataFrame by type of day
Args:
df (pd.DataFrame): DataFrame containing a day_type column
day_type (str): The type of day
Raises:
ValueError: An error is raised if day_type is not one of
'wk'... | The main task of the code is to reproduce maps and JSONs from the MVP launch on 2022-11-11 by processing weekday transit data. It filters and merges GTFS, ridership, and summary data, calculates metrics like trip ratios and ridership, and generates visualizations including route maps, ward maps, and descriptive plots t... | def run_mvp() -> None:
"""Reproduce maps and JSONs from MVP launch on 2022-11-11."""
logger.info("Creating GeoDataFrame")
gdf = static_gtfs_analysis.main()
logger.info(
"Loading data for MVP." " Date range is between 2022-05-20 and 2022-11-05"
)
combined_long_df = pd.read_csv(DATA_PATH ... |
def filter_day_type(df: pd.DataFrame, day_type: str) -> pd.DataFrame:
"""Filter DataFrame by type of day
Args:
df (pd.DataFrame): DataFrame containing a day_type column
day_type (str): The type of day
Raises:
ValueError: An error is raised if day_type is not one of
'wk'... | The main task of the code is to generate geographic maps and visualizations for public transit routes, including all routes, top 10 best/worst routes, and ridership data. It processes static GTFS data, compares real-time vs scheduled trips, calculates performance metrics (e.g., trip counts, ridership ratios), filters b... | def main(day_type: str = None) -> None:
"""Generate maps of all routes, top 10 best routes,
top 10 worst routes, and ridership
Args:
day_type (str, optional): day_type to filter by. Defaults to None.
"""
logger.info("Creating GeoDataFrame")
gdf = static_gtfs_analysis.main()
logger.... |
def numba_calc_bounding_prisms(faces,vertices_white,vertices_pial,n_x,n_y,n_z):
bounding_prisms = np.zeros((n_x,n_y,n_z,1),dtype=np.int64)
for i_prism, prism_vertices_indcs in enumerate(faces):
prism_points = np.concatenate(
(vertices_white[prism_vertices_indcs],
vertices_pial[p... | The function `calc_depth_from_surfaces_on_grid` computes 3D voxel-wise cortical depth maps from white matter and pial surface data. It uses parallel processing to calculate depth values for each voxel in a grid defined by `n_x`, `n_y`, `n_z`, based on the provided surfaces and areas. The method determines the depth cal... | def calc_depth_from_surfaces_on_grid(surf_white, area_white, surf_pial, area_pial,
n_x, n_y, n_z, method, n_jobs=32):
faces = surf_pial['tris']
vertices_white = surf_white['vertices']
vertices_pial = surf_pial['vertices']
bounding_prisms = numba_calc_bounding_prisms... |
def load_fs_surf_in_grid(surf_file,grid_to_scanner):
coords, faces, volume_info = nib.freesurfer.read_geometry(surf_file,read_metadata=True)
surf = dict()
surf['nVertices'] = coords.shape[0]
surf['nTris'] = faces.shape[0]
fs_to_scanner=np.eye(4)
fs_to_scanner[:3,3]=volume_info['cras']
grid_t... | This function computes voxel depths and columns from cortical surfaces (white and pial) for both hemispheres, transforming them into the voxel space of a given volume. It merges hemisphere surfaces, calculates depth using a specified method (e.g., 'equivol'), and saves results as NIfTI images. If output files exist and... | def process_dc_voxeldepth_from_surfaces(surf_white_lh_file,area_white_lh_file,
surf_pial_lh_file,area_pial_lh_file,
surf_white_rh_file,area_white_rh_file,
surf_pial_rh_file,area_pial_rh_file,
... |
def _get_excluded_border_width(image, min_distance, exclude_border):
"""Return border_width values relative to a min_distance if requested.
"""
if isinstance(exclude_border, bool):
border_width = (min_distance if exclude_border else 0,) * image.ndim
elif isinstance(exclude_border, int):
... | The function `peak_local_max` identifies local maxima (peaks) in an input image, returning their coordinates or a boolean mask. It detects peaks separated by at least `min_distance`, applying intensity thresholds and optionally excluding border regions. Peaks are determined by comparing the original image with a dilate... | def peak_local_max(image, min_distance=1, threshold_abs=None,
threshold_rel=None, exclude_border=True, indices=True,
num_peaks=np.inf, footprint=None, labels=None,
num_peaks_per_label=np.inf, p_norm=np.inf):
"""Find peaks in an image as coordinate list or boo... |
def create_field_selectors(self):
self.field_select_frame = ttk.Frame(self.frame, style="searcher.TFrame")
fields = self.app.data.fields
self.field_selectors = []
self.field_selector_vars = []
callback = lambda : self.refill_data_by_selected_fields(self.get_selected_fields())
... | The main task of the code is to update the UI when a file is selected. It clears existing widgets in the frame, resets display fields from the app's data, and dynamically recreates UI components like field selectors, tree views, scroll bars, and search features to reflect the new data structure. This ensures the interf... | def on_file_select(self):
self.treeview_display_fields = self.app.data.fields
for c in self.frame.winfo_children():
c.destroy()
self.create_field_selectors()
self.create_tree()
self.create_scroll()
self.create_content_search()
self.has_created = True |
def apply(_x, fn, axis=0):
if axis:
x = _x.T
else:
x = _x
if len(x.shape) == 1:
return fn(x)
else:
output = np.zeros(x.shape[0])
for i in range(x.shape[0]):
output[i] = fn(x[i])
return output.T if axis else output
def get_AUC(x, y):
AUC = 0
for ... | The main task of the code is to compute and return a list of evaluation metrics for different subsets of input data. It calculates the maximum values of `y`, applies AUC, k, and C functions to full and cleared (sliced) data subsets, using `clearance` to determine the starting index for slicing. This likely evaluates mo... | def get_estimators(x, y, clearance=3):
return [
y.max(axis=1),
apply(y, lambda z: get_AUC(x, z)),
apply(y[:, clearance:], lambda z: get_AUC(x[clearance:], z)),
apply(y[:, clearance:], lambda z: get_k(x[clearance:], z)),
apply(y[:, clearance:], lambda z: get_C(x[clearance:], z... |
def is_sub_without_mistake(trie, sentence):
for letter in sentence:
if letter == " ":
place_in_word = 0
if letter in trie.keys():
trie = trie[letter]
else:
return []
if "end" in trie:
return trie["end"]
def intersection(lst1, lst2):
return ... | This code processes a sentence by splitting it into prefixes and suffixes at various positions, checking if both parts exist in a trie structure without mistakes. It then identifies intersections of valid prefixes and suffixes, applies a swap check, and updates scores for deletions, insertions, or other operations usin... | def sub_with_delete(trie, sentence,data):
res = []
for letter in range(1, len(sentence) - 1):
prefix = is_sub_without_mistake(trie, sentence[:letter])
suffix = is_sub_without_mistake(trie, sentence[letter:])
intersect = intersection(prefix, suffix)
if intersect:
arr =... |
def auto_complete_data(completed_sentence, source_text):
auto = {
"completed_sentence": completed_sentence,
"source_text": source_text,
"score": 0,
"offset": -1
}
return auto
def insert_to_trie(data, trie, sentence, i):
#insert_prefix(trie,sentence, 0, i)
insert_sofix... | The code initializes a trie structure for auto-complete functionality by reading lines from a Python C API documentation file, processing each non-empty line to populate a data dictionary and insert entries into the trie, then saving both the trie and data into JSON files for later use. | def init_tree(trie, data):
print("preparing your sources, please wait...")
for f in listdir('technology_texts/python-3.8.4-docs-text/python-3.8.4-docs-text/c-api')[:1]:
path = f"technology_texts/python-3.8.4-docs-text/python-3.8.4-docs-text/c-api/{f}"
my_file = open(path, "r", encoding="utf8")
... |
def is_sub_without_mistake(trie, sentence):
for letter in sentence:
if letter == " ":
place_in_word = 0
if letter in trie.keys():
trie = trie[letter]
else:
return []
if "end" in trie:
return trie["end"]
def update_high_score(trie, founded, data... | The function searches a trie structure for possible matches of the input sentence, considering exact substrings and variations with typos (swaps, deletions, insertions) to collect up to five candidates, then returns them as a set. | def search_in_tree(trie, sentence, data):
founded = []
if len(sentence) > 0:
founded += is_sub_without_mistake(trie, sentence)
update_high_score(trie, founded, data, sentence)
if len(sentence) > 1:
if len(founded) < 5:
founded += sub_with_swap(trie, sentence, data)
... |
def print_help():
"""
Display help
"""
print("\nHelp/Usage:\n")
print(
"python binary.py -i <input folder or .csv file> -d <output_directory> -v -h\n"
)
print("where:")
print("-i (required): input folder or .csv file.")
print("-d (optional): output folder.")
print("-v (op... | The code processes input files (from a directory or single file) by parsing and generating outputs in a structured folder hierarchy. It handles command-line arguments for input/output paths and logging, validates input paths, creates output directories dynamically, and tracks successfully/unsuccessfully parsed files us... | def main(argv, input_folder_or_file):
global input_dir, output_dir
input_files = []
output_folder = ""
try:
opts, args = getopt.getopt(argv, "vhi:o:d:h:")
except getopt.GetoptError:
print_help()
for opt, arg in opts:
if opt == "-h":
print_help()
elif... |
def reset_all_parameters():
global param_name_list, param_df_list
param_name_list.clear()
param_df_list.clear()
reset_parameters()
def refresh_param_values_ui(param_start_timestamp_series):
set_min_time_duration_box_value()
set_time_window_duration_box_value()
refresh_ts_list_box(param_star... | The function allows users to select an input folder, updates the UI with the chosen path, resets parameter values to defaults, parses the folder's parameters, and refreshes UI elements to display updated parameter lists and settings, ensuring the interface reflects the new input directory's configuration. | def select_input_folder():
global input_dir, param_name_list, cur_selected_param
open_folder = "."
if input_dir:
open_folder = os.path.dirname(input_dir)
input_dir_temp = app.select_folder(folder=open_folder)
if not input_dir_temp:
return
input_dir = input_dir_temp
input_fo... |
def num_sheets(wb):
match wb_type(wb):
case Type.XLRD:
return wb.nsheets
case Type.OPENPYXL:
return len(wb.worksheets)
def parse_input_workbook(in_wb, sheet_num, break_on_white):
"""
Parse the given sheet from the input workbook and store
the data in the parsed di... | The code processes an Excel file (either .xls or .xlsx), parses its sheets, and generates a new Excel file with sheets organized by distinct background colors. It maps each color to a new worksheet, sets the tab color of each sheet in the output file to match the original's background color, and writes the processed da... | def sort(input_file, output_file, break_on_ws):
global logger, color_to_sheet_num_map, input_dic_parsed, cur_column_per_color
input_dic_parsed.clear()
cur_column_per_color.clear()
logger.info("Processing input file: %s, break on whitespace: %d",
input_file, break_on_ws)
color_to_s... |
def reset_result_box():
result_success_list_box.clear()
result_unsuccess_list_box.clear()
result_withoutshift_list_box.clear()
files_without_timeshift.clear()
r_log_box.clear()
def update_min_t_in_file(min_t_before_val, min_t_after_val):
"""
Will read the min time duration value(s) from the ... | The main task of the code is to process audio files from a specified input directory by updating configuration parameters, executing file parsing, and displaying results in a GUI. It validates input existence, resets result displays, applies user-defined time thresholds, runs the core processing logic, and updates the ... | def process():
global input_dir, output_dir
if not input_dir:
app.warn(
"Uh oh!", "No input folder specified. Please select an input folder and run again!")
return
# Reset the result box before processing so that the new values of the
# processing results can be shown.
... |
def generate_solution(self):
available_nodes = list(range(self.dimensions))
sampled_node = random.sample(available_nodes, 1)[0]
available_nodes.remove(sampled_node)
partial_solution = [sampled_node]
#solution = self.generate_solution_iterative(partial_solution, available_nodes)
... | This code executes an optimization iteration by initializing a population of solutions, evaluating their fitness, updating the best solution found so far, and modifying the pheromone matrix to guide future searches. It returns 1 to indicate completion of the iteration. | def run(self, current_budget):
self.population = np.array([self.generate_solution() for i in range(self.pop_size)])
self.fitnesses = np.array([self.problem.evaluate(individual) for individual in self.population])
best_fitness = self.fitnesses.max()
if best_fitness > self.best_fitness_eve... |
def analyze_missing_data_features(df, show_plots, threshold = 50):
'''
This method analyzes from a dataframe all the features (columns) that
either have no data at all, or have data in only threshold % of the data
(threshold being an input)
It also plots histograms and boxplots of our missing... | The `run_clean` function executes a data cleaning pipeline by analyzing missing data in the input DataFrame, identifying features with excessive missing values, and removing them. It logs missing data statistics before and after removal, and optionally generates exploratory data analysis (EDA) plots for commodity data ... | def run_clean(df, features_info, show_plots):
'''
Main method that will call all functions to run the data cleaning
Inputs:
- df: Our merged dataframe containing all our data
- features_info: Dictionary with features info
- show_plots: If True, it will show s... |
def join(path1, path2):
'''
We join two paths
'''
if path1[-1] == '/':
return path1 + path2
else:
return path1 + '/' + path2
def create_concat(input_folder,dest_path):
'''
Runs through files, makes pandas df and then saves as csv into same
folder
'''
... | The function aggregates yearly Excel (.xls) files from the source directory into consolidated CSV files stored at the destination path. It processes folders containing multiple .xls files using `create_concat`, handles the 'hydro_reservoir' folder with `handle_hydro`, skips specified folders, and logs progress and skip... | def nord_merge(source_path, dest_path):
'''
Inputs:
source_path: Path where our raw data is located
dest_path: Path where we want to store our merged data
Returns:
No return (but it stores all files locally)
'''
logger.info('For each Nordpool feature, we aggregate a... |
def plot_reward_per_ep():
df = pd.read_csv('rewardperep.csv')
df_plot = df.mean(axis=0)
graph = df_plot.plot(title="Average Undiscounted Reward per Epoch")
graph.set_xlabel("Epoch")
graph.set_ylabel("Undiscounted Reward")
plt.savefig('output.png')
def unpack_csv(csv_filepath):
# get number ... | The main task of the code is to compare the performance of reinforcement learning algorithms (baseline vs. Q-learning) across multiple grid environments by training policies, testing their average rewards, and saving results to a CSV file. It also supports plotting rewards per episode or running single algorithm tests ... | def main():
args = sys.argv[1:]
if 'plot-reward-per-ep' == args[0]:
plot_reward_per_ep()
elif 'compare' == args[0]:
grids = args[1]
random_policies = []
q_learning_policies = []
reward_grids = []
for i, grid_csv in enumerate(os.listdir(grids)):
... |
def to_adjacency_matrix(backend):
mat = np.zeros((backend.configuration().n_qubits, backend.configuration().n_qubits))
for (u,v) in backend.configuration().coupling_map:
mat[u][v] = 1
return mat
def get_calibration_data(backend):
calibration_data = {}
for edge in backend.configuration().coup... | (The main task of the code is to execute quantum circuit synthesis on a given input circuit using three strategies—noise-aware, connectivity-aware, and baseline—targeting a specific quantum backend. It evaluates each synthesized circuit's performance in terms of CX gate count, fidelity, and runtime, saving results and ... | def full_run(og_circuit_filename, backend_output_dir, backend, timeout):
input_circuit = QuantumCircuit.from_qasm_file(og_circuit_filename)
base_name = os.path.basename(og_circuit_filename)
print(base_name)
arch = to_adjacency_matrix(backend)
calibration_data = get_calibration_data(backend)
resu... |
def get_point(self):
return self.spawnPoint.sprite
def calculate_center_time(self, tile):
tilex = tile.rect.x
tiley = tile.rect.y
spawn_point = self.get_point()
x = spawn_point.rect.x
y = spawn_point.rect.y
x_dist = abs(tilex - x)
y_dist = abs(tiley - y)
... | This code handles player collisions with horizontal boundaries. Upon collision, the player loses health, is reset to the spawn point, and becomes invincible. It calculates a "center time" for recentering mechanics and checks if the player has died, ending the game if so. | def bottomBoundary(self):
player = self.player.sprite
spawn_point = self.get_point()
x = spawn_point.rect.x
y = spawn_point.rect.y
for tile in self.boundaryHoriz.sprites():
if tile.rect.colliderect(player.rect):
player.time = pygame.time.get_ticks()
... |
def load_data():
df = pd.read_csv(DATA_PATH)
return df
def fileter_data_by_emotions(self, df):
return df[df.emotion.isin(self.__select_emotions)]
def prepare_data(self, df):
img_array = df.pixels.apply(lambda x: np.array(x.split(' ')).reshape(48, 48, 1).astype('float32'))
img_arr... | The main task of the code is to train a machine learning model on filtered emotional image data by loading and preprocessing dataset, splitting it into training, validation, and test sets, normalizing features, training the model, and saving the trained model and results for future use. | def learn(self):
if not self.__trained:
df = self.load_data()
df = self.fileter_data_by_emotions(df)
img_array, img_labels = self.prepare_data(df)
X_train, X_valid, self.__X_test, y_train, y_valid, self.__y_test = self.split_data_for_train_valid_test(
... |
def build_drive_api_v3():
credentials = build_credentials()
return googleapiclient.discovery.build('drive', 'v3', credentials=credentials).files()
def encrypt(filename,user_password,file_in):
BUFFER_SIZE = 1024 * 1024 # The size in bytes that we read, encrypt and write to at once
password = user_pass... | The code updates a Google Drive file by retrieving its metadata, encrypting new content provided via a form, and replacing the file with the encrypted data using the same file ID, then redirects to the homepage. | def updateFile(file_id):
drive_api = build_drive_api_v3()
metadata = drive_api.get(fields="name,mimeType,webViewLink", fileId=file_id).execute()
request = drive_api.get_media(fileId=file_id)
file_name = metadata['name']
password = flask.request.form.get("new")
content = flask.request... |
def build_drive_api_v3():
credentials = build_credentials()
return googleapiclient.discovery.build('drive', 'v3', credentials=credentials).files()
def encrypt(filename,user_password,file_in):
BUFFER_SIZE = 1024 * 1024 # The size in bytes that we read, encrypt and write to at once
password = user_pass... | The main task of the code is to update a file in Google Drive by encrypting user-provided content with a password, using the file's original ID. It retrieves the file's metadata, reads form inputs for content and password, temporarily stores the content, encrypts it, and uploads the encrypted file with the original ID ... | def update_file(file_id):
drive_api = build_drive_api_v3()
metadata = drive_api.get(fields="name,mimeType", fileId=file_id).execute()
file_name = metadata['name']
password = flask.request.form.get("password")
content = flask.request.form.get("content")
file_out = tempfile.TemporaryFile()
... |
def get_seconds_wait_robots(url):
"""
Check if there is any time restriction inside /robots.txt when using a
crawler
"""
rp = urllib.robotparser.RobotFileParser()
print("Checking: " + url + "/robots.txt")
rp.set_url(url + "/robots.txt")
rp.read()
# We check that we can use the crawl... | The main task of the code is to crawl web pages starting from seed URLs in either depth-first or breadth-first mode, respecting robots.txt rules, until a maximum download limit is reached. It reads seed URLs from a file, tracks visited links, and recursively or iteratively crawls content while handling exceptions for d... | def main():
"""
Open the file containing the seeds and run the crawler recursively until the
maximum number of downloads is reached
"""
global visited
global q
seeds =open(file, mode='r')
if (deep_search):
try:
for seed in seeds:
visited.add(seed.rstr... |
def load_index():
"""
Loads the index from a .pkl file
"""
global index
index = pickle.load(open("index.pkl", "rb"))
def load_queries(filename):
"""
Reads the queries from a .txt file
"""
global queries
with open(filename, 'r') as file:
lines = file.readlines()
... | The main task of the code is to process queries from a text file by loading a precomputed index, retrieving relevant texts, calculating term frequency weights for query terms, and generating search results. These results are then saved to an output text file. The function orchestrates data loading, weighting computatio... | def main():
"""
Resolves the queries from a .txt file and saves the results in a .txt file
"""
global queries
global saved_texts
load_index()
load_queries("cran-queries.txt")
load_texts("cran-1400.txt")
tfs = weighting_tf(queries) # Calculate the weights of each word in
... |
def load_lines(filename):
"""
Given a .txt file returns a list with the contents of each of its lines
"""
with open(filename, 'r') as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
d = {}
for line in lines:
separator = line.split(' ')
re... | The main task of the code is to identify quasi-duplicate documents using sim_hash with either trigrams or tokenization. It loads documents, processes them into terms, computes hashes, groups documents with identical hashes, and saves results for comparison against expected duplicates. | def main():
"""
Find quasi-duplicate documents
"""
global expected_duplicates
global restrictiveness
global processing
# Load the documents
texts = load_lines("articles_2500.train")
# Load the expected duplicates
expected_duplicates = load_results("articles_2500.truth")
# C... |
def load_lines(filename):
"""
Given a .txt file returns a list with the contents of each of its lines
"""
with open(filename, 'r') as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
d = {}
for line in lines:
separator = line.split('\t')
d... | The main task of the code is to find the most similar texts for a set of queries using cosine and Jaccard similarity measures. It loads texts, queries, and stop words, converts them into bag-of-words representations, and evaluates similarity for each query. Results are saved in a file, and the code checks relevance aga... | def main():
"""
Finds the most similar text for a set of queries
"""
# Load the texts and queries
texts = load_lines("cran-1400.txt")
queries = load_lines("cran-queries.txt")
# Load the stop words
load_stop_words("stop-words.txt")
# Load the cranqrel list to evaluate the results ob... |
def create_token_data(name, explorer_url = EXPLORER_API_URL):
total = get_token_data(name, 1, 0, explorer_url)["total"]
needed_calls = int(total / 500) + 1
data = []
offset = 0
if total > 0:
for i in range(needed_calls):
data += get_token_data(name, 500, offset, explorer_url)["it... | The main task of the code is to resolve an Ergo name to its associated blockchain box address by querying an explorer API. It retrieves token data, identifies the token's minting address, fetches transaction history, extracts the latest transaction's box ID, and returns the corresponding box address. If no data is foun... | def resolve_ergoname(name, explorer_url = EXPLORER_API_URL):
token_data = create_token_data(name, explorer_url)
if len(token_data) > 0:
token_id = get_asset_minted_at_address(token_data, explorer_url)
token_transactions = get_token_transaction_data(token_id, explorer_url)
token_last_tran... |
def create_token_data(name, explorer_url = EXPLORER_API_URL):
total = get_token_data(name, 1, 0, explorer_url)["total"]
needed_calls = int(total / 500) + 1
data = []
offset = 0
if total > 0:
for i in range(needed_calls):
data += get_token_data(name, 500, offset, explorer_url)["it... | This function retrieves the block ID of the first transaction associated with a token registered on a blockchain, using a provided explorer API. It creates token data, identifies the token's minting address, fetches its transaction history, locates the earliest transaction, and extracts the corresponding block ID. If n... | def get_block_id_registered(name, explorer_url = EXPLORER_API_URL):
token_data = create_token_data(name, explorer_url)
if len(token_data) > 0:
token_id = get_asset_minted_at_address(token_data, explorer_url)
token_transactions = get_token_transaction_data(token_id, explorer_url)
token_fi... |
def get_address_confirmed_balance(address, explorer_url = EXPLORER_API_URL):
url = explorer_url + "api/v1/addresses/" + address + "/balance/confirmed"
balance = requests.get(url).json()
return balance
def remove_invalid_tokens(token_data):
for i in token_data:
if check_name_valid(i["name"]) is F... | The main task of the code is to retrieve and validate token data associated with a blockchain address. It fetches confirmed token balances from an explorer API, filters out invalid tokens, checks mint address correctness, and returns processed token data. If no valid tokens are found, it returns None. | def reverse_search(address, explorer_url = EXPLORER_API_URL):
token_data = get_address_confirmed_balance(address, explorer_url)["tokens"]
if token_data is None:
return None
token_data = remove_invalid_tokens(token_data)
token_data = check_correct_mint_address(address, token_data)
return toke... |
def find_missing_tw_tasks(
self, issues: List[Issue], tasks: Dict[str, dict]
) -> List[Issue]:
"""Find issues in Github for which there are no tasks in TW
There can be cases when someone created an Issue on Github and we need
to ensure it in local TaskWarrior database. Get the list ... | The main task of the code is to synchronize tasks between GitHub and Taskwarrior by identifying missing tasks/issues in each system, creating them, and correcting mismatched statuses. It aggregates Taskwarrior tasks, detects GitHub issues not in Taskwarrior, creates them in Taskwarrior, checks matching descriptions for... | def resolve(self) -> None:
"""Resolve changes between Github and Taskwarrior
Get Github and Taskwarrior instances and check for all the issues in
Github which don't exists in Taskwarrior. Then check for all the tasks
in Taskwarrior which don't exists in Github. Then create all missing
... |
def detect_move(self, white_clock, black_clock, check_detect_turn = True):
detect_turn = lambda: self.detect_turn(white_clock, black_clock)
if check_detect_turn:
while self.board.turn != detect_turn():
if self.is_game_over():
return None
# prin... | The code automates a chess game by controlling a bot that interacts with a web-based chess interface. It initializes the game, detects the bot's color, monitors clocks, and alternates between using a chess engine for optimal moves and detecting opponent moves. The bot plays until the game ends, considering time limits ... | def play_game(self):
print("Game Started...")
if not self.logged_in:
time.sleep(5)
print("Started Playing...")
self.chess_board = self.driver.find_element(By.TAG_NAME, "chess-board")
self.board_flipped = "flipped" in self.chess_board.get_attribute("class")
bot... |
def get_book_move(self):
for book in self.book_paths:
try:
move = polyglot.MemoryMappedReader(book).weighted_choice(self.board).move
except:
pass
else:
return move
def _put(self, command: str) -> None:
if not self._timec... | The main task of the code is to determine the best chess move by either selecting a pre-defined book move or performing a depth-limited search using an engine. It prints detailed analysis (e.g., predicted score, nodes searched, time taken) if enabled, then returns the best move in UCI format. The function also handles ... | def get_best_move(self, print_move = True, self_time_left = 0, opponent_time_left = 0):
if self.use_book_moves:
move = self.get_book_move()
else:
move = None
if move:
move_uci = move.uci()
if print_move:
print(f"Book Move: {self.boa... |
def _generate_pieces(self):
self.images = {}
for piece in self.pieces:
image_path = os.path.join(self.assets_dir, "pieces", f"{piece}.png")
self.images[piece] = pygame.transform.scale(
# pygame.image.load(image_path),
# pygame.image.load(image_path... | This code initializes and runs a graphical user interface (GUI) for a chess game using Pygame. It sets up the display, loads game assets, handles user input events, redraws the chessboard dynamically, manages game states (e.g., turn-based logic, game over conditions), and integrates AI move generation for players. The ... | def run_gui(self):
pygame.init()
pygame.font.init()
self.initial_turn = self.turn
self.screen = pygame.display.set_mode(self.resolution)
pygame.display.set_caption("Chess")
font = pygame.font.SysFont("Comic Sans MS", 30)
self._generate_pieces()
self.clock ... |
def getGoalArea(coor):
goalArea=set()
for i in coor:
allgoal=getboomArea(i)
for tmpgoal in allgoal:
if(isEmpty(tmpgoal,coor)):
goalArea.add(tmpgoal)
return goalArea
def getboomArea(coor):
x=coor[0]
y=coor[1]
result=[]
ls=[(x-1,y-1),(x-1,y),(x-1,y+1... | The code processes input tokens to generate a mapping of points to unique boom results. It first identifies a goal area using `getGoalArea`, then iterates through each point in this area. For each point, it calculates a boom area with `getboomArea` and retrieves boom results via `getBoomResult`. These results are conve... | def getGoal(aimtokens):
goalArea=getGoalArea(aimtokens)
result={}
for point in goalArea:
boomArea=getboomArea(point)
result[point]=list(set(getBoomResult(boomArea,aimtokens)))
return result |
def getboomArea(coor):
x=coor[0]
y=coor[1]
result=[]
ls=[(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)]
for i in ls:
if(CoorIsValid(i)):
result.append(i)
return result
def getBoomResult(boomArea,aimtokens):
boomtoken=[i for i in aimtokens if i in... | The function evaluates the strategic value of each position on an 8x8 board by analyzing the difference in token counts between the player and opponent in potential "boom" areas. It calculates an evaluation value for each position, adjusting it if the position is empty and the initial value is non-zero, then returns a ... | def geteva(owntokens,opponenttokens):
alltokens=owntokens+opponenttokens
initeva={}
tmpresult={}
for i in range(0,8):
for j in range(0,8):
point=(i,j)
boomArea=getboomArea(point)
tmpresult[point]=list(set(getBoomResult(boomArea,alltokens)))
evavalu... |
def gettokengoalcomb(owntokens,opponenttokens):
initeva=geteva(owntokens,opponenttokens)
tokengoalcomb=[]
alltokens=owntokens+opponenttokens
for goalpoint in initeva.keys():
if(initeva[goalpoint]>0):
tmptokens=owntokens
elif(initeva[goalpoint]<0):
tmptokens=oppone... | The code selects tokens from the board game based on goal-combination values, prioritizing those with the highest or lowest values. It adds tokens directly if the value is non-negative or processes boom areas for negative values to determine valid tokens. The result is a list of chosen tokens meeting these criteria. | def getchoosentokens(boardgame):
alltokens=boardgame.opponenttokens+boardgame.owntokens
tokengoalcomb=gettokengoalcomb(boardgame.owntokens,boardgame.opponenttokens)
chosentokens=set()
minvalue=0
maxvalue=0
for comb in tokengoalcomb:
if(tokengoalcomb[0][2]==comb[2]):
if(comb[3... |
def getboomArea(coor):
x=coor[0]
y=coor[1]
result=[]
ls=[(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)]
for i in ls:
if(CoorIsValid(i)):
result.append(i)
return result
def getBoomResult(boomArea,aimtokens):
boomtoken=[i for i in aimtokens if i in... | The code evaluates the value of a board game movement by calculating the difference between opponent and own tokens affected by a "BOOM" action or by analyzing token combinations for strategic gain/loss. It prioritizes moves that maximize positive outcomes and minimize risks, returning a numerical evaluation score for ... | def makemovementeva(movement):
boardgame=movement[0]
owntokens=boardgame.owntokens
opponenttokens=boardgame.opponenttokens
#print(owntokens,opponenttokens)
alltokens=opponenttokens+owntokens
evavalue=0
if(movement[1][0]=="BOOM"):
coor=movement[1][1]
boomArea=getboomArea(coor)... |
def getchoosentokens(boardgame):
alltokens=boardgame.opponenttokens+boardgame.owntokens
tokengoalcomb=gettokengoalcomb(boardgame.owntokens,boardgame.opponenttokens)
chosentokens=set()
minvalue=0
maxvalue=0
for comb in tokengoalcomb:
if(tokengoalcomb[0][2]==comb[2]):
if(comb[3... | The code generates all possible moves in a board game, including "BOOM" actions (explosions) and "MOVE" actions (token movements). It checks valid coordinates, avoids opponent tokens, and creates new board states with movement records. The result includes every valid move and explosion outcome for the player's tokens. | def getpossiblemovement(boardgame):
coors=getchoosentokens(boardgame.copy())
alltokens=boardgame.owntokens+boardgame.opponenttokens
result=[]
directions=[-1,1]
for point in boardgame.owntokens:
#boom
boomArea=getboomArea(point)
tmplist=list(set(getBoomResult(boomArea,alltokens))... |
def load_file(filename):
try:
with open(filename, 'r') as file:
config = json.load(file)
setv_s = []
setv_p = []
for ch in config["channels"]:
setv_s.append(config["channels"][ch][0])
setv_p.append(config["channels"][ch][1])
... | The code loads channel data from a file, validates its values against configuration settings, and sends the validated data to a server endpoint to set channels. It checks for correct data length, performs error control, prints channel settings, and returns the server's response. | def set_channels_file(filename):
setv_s, setv_p = load_file(filename)
errors.error_control(available_server())
if len(setv_s) != config.NCHAN:
errors.error_control(-7)
for ch in range(config.NCHAN):
errors.error_control(errors.check_values(setv_s[ch], setv_p[ch]))
print('Set chan... |
def get_batchs(self, total_num, batch_size):
idx = np.random.permutation(total_num)
return [idx[i:i+batch_size] for i in range(0, len(idx), batch_size)]
def forward(self, X):
self.a[0] = X
self.z[0] = np.dot(self.a[0], self.W1.T) + self.b1.T
self.a[1] = relu(self.z[0])
se... | This function trains a neural network using mini-batch gradient descent with learning rate decay and early stopping. It iterates over epochs, processes data in batches, performs forward/backward passes, updates weights with decayed learning rate, evaluates training accuracy/loss, and terminates early if loss changes mi... | def optimize_train_only(self, X_train, Y_train, epochs, batch_size, lr=0.2, decay_rate=1, alpha=0.1, print_log=False):
for epoch in range(epochs):
# mini-batch
batchs = self.get_batchs(len(X_train), batch_size)
for i, batch in enumerate(batchs):
X_batch, Y_ba... |
def get_batchs(self, total_num, batch_size):
idx = np.random.permutation(total_num)
return [idx[i:i+batch_size] for i in range(0, len(idx), batch_size)]
def forward(self, X):
self.a[0] = X
self.z[0] = np.dot(self.a[0], self.W1.T) + self.b1.T
self.a[1] = relu(self.z[0])
se... | This code trains a neural network using mini-batch gradient descent, performing forward/backward passes, tracking training/test accuracy/loss, applying learning rate decay, and implementing early stopping if training loss stabilizes. It logs metrics, plots results periodically, and visualizes weights at key intervals d... | def optimize(self, X_train, Y_train, X_test, Y_test, epochs, batch_size, lr=0.2, decay_rate=1, alpha=0.1, print_log=False):
for epoch in range(epochs):
# mini-batch
batchs = self.get_batchs(len(X_train), batch_size)
for i, batch in enumerate(batchs):
X_batch... |
def stateFinished(self, state):
return state.finished
def currentPlayer(self, state):
if state.numActions[state.round]:
return self.nextPlayer(state, state.actingPlayer[state.round][state.numActions[state.round] - 1])
return self.nextPlayer(state, self.game_def.firstPlayer[state.roun... | This function validates game actions (raise, fold, etc.) based on current state rules. It checks if actions are allowed, adjusts invalid sizes with warnings, enforces min/max raise limits in no-limit games, and ensures folds only occur when permissible. Returns True if action is valid after adjustments, False otherwise... | def isValidAction(self, state, action):
if self.stateFinished(state) or action.type == ActionType.a_invalid:
return False
p = self.currentPlayer(state)
if action.type == ActionType.a_raise:
valid, min_, max_ = self.raiseIsValid(state)
if not valid:
... |
def getUndlNameList(criterion=""):
if criterion == "":
df = pd.read_csv(dataRootPathDB + "Underlying_Database/undlNameList.csv")
return df.undlName.values
elif criterion == "HK" or criterion == "AX" or criterion == "SI":
df = pd.read_csv(dataRootPathDB + "Underlying_Database/undlNameList... | The code compiles news headlines from specified financial instruments and sectors into a CSV file. It gathers undlNames, processes news data into a DataFrame, removes duplicates, and saves the result. The model prediction sections are commented out, so the primary task is data aggregation and storage, not signal predic... | def createNewsHeadlinePrediction(ex, sector_list):
undlNameList = getUndlNameList(ex)
for sector in sector_list:
undlNameList += getUndlNameList(sector)
start_date = formatDate(today)
end_date = formatDate(today)
#resultDict = {"undlName":[], "bull_signals":[], "bear_signals":[]}
# l... |
def merge_aug(all_pred, nu, times, weight=1.):
all_mer = copy.deepcopy(all_pred[:nu])
wei_sum = 1
for i in range(times-1):
all_mer += all_pred[nu*(i+1):nu*(i+2)]*weight
wei_sum += weight
return all_mer / wei_sum
def where2cut(all_pred, label_true, rang=[0.8,1], step=0.0025,
... | The function `see_merge` evaluates merged prediction accuracy using two thresholding strategies. It merges predictions (`all_pred`, `all_pred_`) with `merge_aug`, identifies optimal cut points via `where2cut`, visualizes trends, and computes regression-mode accuracy (`ens`) with thresholds at 0.5 and the mean of detect... | def see_merge(all_pred, all_pred_,
label_true, label_true_,
nu, nu_, times, W):
# W = 1
print(all_pred.shape)
all_mer = merge_aug(all_pred, nu, times=times, weight=W)
print(all_mer.shape)
#% % see trend
bests, cuts = where2cut(all_mer[:nu,:,:], label_true[:nu],... |
def _get_parent(self, node:TreeNode, value: int):
if (node.left is not None and node.left.value == value) or (node.right is not None and node.right.value == value):
return node
elif value < node.value:
if node.left is None:
return None
else:
... | This method deletes a node with the specified value from a binary tree. It identifies the node's parent, determines its position (left/right), and handles three cases: removing a leaf node, replacing with a single child, or finding the maximum node in the left subtree for two-child nodes. It adjusts tree structure, upd... | def delete(self, value: int):
if self.root is None:
return None
else:
parent_node = self._get_parent(self.root, value)
if parent_node is None:
return "Value to be deleted has no parent."
sub_tree = "left" if parent_node.left is not None a... |
def success(self, stanje):
self.rekurzivna(stanje)
print("[FOUND_SOLUTION]: yes")
print("[STATES_VISITED]: " + str(len(self.closed)))
print("[PATH_LENGTH]: " + str(stanje.broj))
print("[TOTAL_COST]: " + str(round(stanje.cijena, 1)))
print("[PATH]: " + self.string)
def che... | This code performs a state-space search algorithm. It explores states from the 'open' list, checking if a goal state is reached. If not, it generates next states via transitions, filters valid ones, sorts them by name, and adds them to 'open'. The process continues until the goal is found (success) or all options are e... | def start(self):
while len(self.open) > 0:
stanje = self.open.pop(0)
if stanje.ime in self.zav_imena_stanja:
self.success(stanje)
return
self.closed.add(stanje.ime)
before_sorted = []
for prijelaz in self.prijelazi[stanj... |
def success(self, stanje):
self.rekurzivna(stanje)
print("[FOUND_SOLUTION]: yes")
print("[STATES_VISITED]: " + str(len(self.closed)))
print("[PATH_LENGTH]: " + str(stanje.broj))
print("[TOTAL_COST]: " + str(round(stanje.cijena, 1)))
print("[PATH]: " + self.string)
def che... | This code performs a search algorithm by iterating through states in an open queue, checking if a goal state is reached. If not, it expands valid transitions, updates node costs, and adds new states to the queue while tracking visited states. The process continues until a goal is found (success) or the queue is exhaust... | def start(self):
while not self.open.empty():
stanje = self.open.get()
if stanje.ime in self.zav_imena_stanja:
self.success(stanje)
return
self.closed.add(stanje.ime)
for prijelaz in self.prijelazi[stanje.ime]:
if se... |
def success(self, stanje):
self.rekurzivna(stanje)
print("[FOUND_SOLUTION]: yes")
print("[STATES_VISITED]: " + str(len(self.closed)))
print("[PATH_LENGTH]: " + str(stanje.broj))
print("[TOTAL_COST]: " + str(round(stanje.cijena, 1)))
print("[PATH]: " + self.string)
def che... | This code implements a search algorithm, likely A*, by iterating through states in 'open', checking for a goal state, expanding transitions, and maintaining a priority queue sorted by cost plus heuristic. It returns success upon finding a goal or failure if the queue depletes. | def start(self):
while len(self.open) > 0:
stanje = self.open.pop(0)
if stanje.ime in self.zav_imena_stanja:
self.success(stanje)
return
self.closed.append(stanje)
for prijelaz in self.prijelazi[stanje.ime]:
if self.... |
def odaberi_klauzule(klauzule, Sos):
odabrane_klauzule = []
for i in range(len(Sos)):
for j in range(i, len(Sos)):
if i != j:
odabrane_klauzule.append((Sos[i], Sos[j]))
for j in range(len(klauzule)):
odabrane_klauzule.append((Sos[i], klauzule[j]))
retu... | The algorithm performs resolution on clauses from the knowledge base and set of support (Sos) to detect contradictions. It iteratively selects clause pairs, resolves them, checks for an empty clause (NIL), and adds resolvents to Sos. If NIL is found, it returns True; if no new clauses are generated, it returns None, in... | def algoritam(self):
while True:
nove_klauzule = []
for klauzula_1, klauzula_2 in odaberi_klauzule(self.klauzule, self.Sos):
rezolvente = self.rijesi(klauzula_1, klauzula_2)
chech = find_NIL(rezolvente)
if chech:
return ... |
def algoritam(self):
while True:
nove_klauzule = []
for klauzula_1, klauzula_2 in odaberi_klauzule(self.klauzule, self.Sos):
rezolvente = self.rijesi(klauzula_1, klauzula_2)
chech = find_NIL(rezolvente)
if chech:
return ... | The main task of the code is to execute a logical algorithm, print derived clauses and their negations if the algorithm succeeds, and conclude whether a target proposition is true. If the algorithm returns a valid clause (NIL_klauzula), it prints all clauses, the negated target, and declares the target as true. If not,... | def start(self):
NIL_klauzula = self.algoritam()
if NIL_klauzula:
for klauzula in self.klauzule:
print(str(klauzula.broj) + ". " + klauzula.__str__())
for klauzula in negiraj(self.cilj, len(self.klauzule)+1):
print(str(klauzula.broj) + ". " + klauz... |
def yArgMax(self, data_set : DataSet) -> str:
args = {}
for y in data_set.goal_description:
args[y] = 0
for data_row in data_set.data_rows:
args[data_row.label] += 1
max_value = max(args.values())
max_keys = [key for key, value in args.items() if value == ... | The main task of the code is to implement the ID3 algorithm for building a decision tree. It recursively selects the best feature to split the dataset, creates child nodes for each possible feature value, and returns a leaf node when conditions like no remaining features, uniform class labels, or maximum depth are met.... | def id3(self, D : DataSet, D_parent : DataSet, X : list[str], y : str, depth : int = 0) -> Node:
if D.size == 0:
v = self.yArgMax(D_parent)
return Node("leaf", v)
v = self.yArgMax(D)
if len(X) == 0 or D.size() == D.size_y(v):
return Node("leaf", v)
if ... |
def create_session_directory(city_default_url, session_timestamp):
# Get the city name from the url
occurrences_of_dash = [j for j in range(len(city_default_url)) if city_default_url.startswith('-', j)]
city_name = city_default_url[occurrences_of_dash[1] + 1:occurrences_of_dash[2]].lower()
# Build dire... | The main task of the code is to scrape and process hotel reviews from multiple URLs, storing hotel and review data in structured directories. It extracts hotel names from URLs, avoids duplicate processing, parses hotel and review information, and saves data in CSV files and text files. Error handling ensures robustness... | def parse_reviews_of_city(review_urls, city_default_url, user_base_url, session_timestamp, header):
processed_hotels = list()
hotel_information = dict()
# Create a directory for the current scrapping session
city_directory_path = create_session_directory(city_default_url, session_timestamp)
hotel_... |
def acceptBtnClicked(self):
if QColor(self.acceptBtn.palette().color(1)) == QColor('green'):
self.acceptBtn.setStyleSheet('background-color: red; font-size: 20px')
self.trials['accept'][self.current_trial] = 0
else:
self.acceptBtn.setStyleSheet('background-color: gree... | This method handles keyboard events to trigger specific actions: pressing Up calls `acceptBtnClicked()`, Right calls `nextBtnClicked()`, Left calls `prevBtnClicked()`, and Escape saves trial data to a CSV file and closes the window. The primary task is to enable navigation and data-saving via keyboard shortcuts in a GU... | def keyPressEvent(self, e):
if e.key() == Qt.Key_Up:
self.acceptBtnClicked()
elif e.key() == Qt.Key_Right:
self.nextBtnClicked()
elif e.key() == Qt.Key_Left:
self.prevBtnClicked()
elif e.key() == Qt.Key_Escape:
# saving
self.tri... |
def decrease_width(params: Parameters, num_pixels, roi=None):
img = params.image.copy() # copiaza imaginea originala
roi_mask = None
# daca trebuie sa eliminam un obiect
if roi:
# creeaza o masca plina cu zero-uri
# dar care in regiunea selectata are weight-uri negative
roi_mas... | The function `resize_image` processes image resizing based on specified parameters. It adjusts width, height, or content amplification, and handles object removal. Depending on the resize option, it applies transformations like width/height reduction, 90° counter-clockwise rotation for correct display, content amplific... | def resize_image(params: Parameters):
if params.resize_option == 'micsoreazaLatime':
# redimensioneaza imaginea pe latime
resized_image = decrease_width(params, params.num_pixels_width)
return resized_image
elif params.resize_option == 'micsoreazaInaltime':
# roteste imaginea r... |
def _set_cell_image(
self, coord: Coord_T, state: Optional[CellContents] = None
) -> None:
"""
Set the image of a cell.
Arguments:
coord ((x, y) tuple in grid range)
The coordinate of the cell.
state
The cell_images key for the image to be set... | This method handles a left double-click event on a cell. If the cell contains a flag, it removes the flag, updates the cell's appearance, and refreshes probability displays. If not, it marks the event as a regular click and triggers the left-button-down action for further processing. | def left_button_double_down(self, coord: Coord_T) -> None:
"""
Left button was double clicked. Call callback to remove any flags that
were on the cell.
"""
if type(self.board[coord]) is CellContents.Flag:
self.board[coord] = CellContents.Unclicked
self._se... |
def _raise_all_sunken_cells(self) -> None:
"""
Reset all sunken cells to appear raised.
"""
raise_cells = {
c for c in self._sunken_cells if self.board[c] is CellContents.Unclicked
}
if raise_cells:
for c in raise_cells:
self._set_c... | This method handles the release of a left mouse click by updating the game board's cell state. It raises sunken cells, checks the clicked cell's status, increments numbers or sets new values, then updates the cell's display and probability visualization. | def left_button_release(self, coord: Coord_T) -> None:
"""
Left mouse button was released. Change display and call callback
functions as appropriate.
"""
self._raise_all_sunken_cells()
if coord is None:
return
if self.board[coord] is CellContents.Uncli... |
def _coord_from_event(self, event: QMouseEvent) -> Optional[Coord_T]:
"""
Get cell coordinate from mouse button event.
:param event:
The mouse event.
:return:
The cell coordinate, or None if outside the board.
"""
pos = self.mapToScene(event.pos()... | This code handles mouse release events by checking which button was released, logging the action, and resetting internal states when all buttons are up. It manages double-click detection, left-button release logic, and ensures proper state transitions when no buttons are pressed. | def mouseReleaseEvent(self, event: QMouseEvent):
"""Handle mouse release events."""
if self._await_release_all_buttons and not event.buttons():
self._await_release_all_buttons = False
return
coord = self._coord_from_event(event)
## Bothclick (one of the buttons ... |
def _coord_from_event(self, event: QMouseEvent) -> Optional[Coord_T]:
"""
Get cell coordinate from mouse button event.
:param event:
The mouse event.
:return:
The cell coordinate, or None if outside the board.
"""
pos = self.mapToScene(event.pos()... | This code handles mouse press events in a Qt application, tracking button states (left, right, or both) and coordinates. It resets tracking variables when a single button is pressed, manages states for double clicks and out-of-board clicks, and triggers corresponding actions (left/right button down) based on the presse... | def mousePressEvent(self, event: QMouseEvent):
"""Handle mouse press events."""
coord = self._coord_from_event(event)
# If the button pressed here is the only button down, we reset the
# tracking variables.
# However, if the click was outside the board, we should wait for all
... |
def _coord_from_event(self, event: QMouseEvent) -> Optional[Coord_T]:
"""
Get cell coordinate from mouse button event.
:param event:
The mouse event.
:return:
The cell coordinate, or None if outside the board.
"""
pos = self.mapToScene(event.pos()... | This code handles a double left mouse click event by storing the coordinate, checking if only the left button is pressed (not both buttons), and triggering a specific action if valid. If conditions aren't met, it delegates to the regular mouse press event. | def mouseDoubleClickEvent(self, event: QMouseEvent):
"""Handle double clicks."""
self._mouse_coord = coord = self._coord_from_event(event)
if (
event.button() == Qt.LeftButton
and not self._both_mouse_buttons_pressed
and coord
):
self._was... |
def intToMAC(number):
ret = [""]*6
number = str(hex(int(number))[2:])
for i in range(0, 6):
ret[i] = number[i*2:(i*2)+2]
return (":".join(ret)).upper()
def parseFile(filePath): # file gameName|time|commonPath|localPath
ret = dict()
with open(filePath, "r") as reader:
for line in... | The code synchronizes local and common game data structures by comparing timestamps, resolving conflicts by overwriting older entries, and using a blocker file to ensure exclusive access. It reads/writes game metadata, detects modifications, backs up changes, and updates files to maintain consistency between local and ... | def sync():
# Blocker file
count = 0
blocked = True
while blocked:
while os.path.exists(commonBlockerFile):
with open(commonBlockerFile, "r") as blockerFile:
temp = blockerFile.readline().strip()
print(intToMAC(temp) + " " + intToMAC(uuid.getnode()))
... |
def sync():
# Blocker file
count = 0
blocked = True
while blocked:
while os.path.exists(commonBlockerFile):
with open(commonBlockerFile, "r") as blockerFile:
temp = blockerFile.readline().strip()
print(intToMAC(temp) + " " + intToMAC(uuid.getnode()))
... | The main task of the code is to create an interactive command-line interface that handles user input, manages reconnection attempts to a file-based system, and executes commands like "add" for game data entry or "quit/exit" to terminate the loop. It processes keyboard input in real-time, supports backspace correction, ... | def main():
loop = True
sync()
command = ""
while loop:
#RUN COMMAND
if sync() == "COMMON DNE":
writeLog("Connection failed, waiting until reconnect")
while True:
try:
open(commonPath, "r")
w... |
def check_dimensions(mval: int, nval: int):
if not all(isinstance(_, INTS) and _ > 0 for _ in [mval, nval]):
raise ValueError(f"Inputs {mval} ({type(mval)}), {nval}({type(nval)})"
+ " must be positive integers")
def words(ident: str) -> nx.Graph:
""" The Graph induced by the wor... | The main task of the code is to generate a LabeledHomomorphism instance by combining a grid graph of specified dimensions (mval x nval) with a list of words from the given wordlist. It validates the dimensions first and then constructs the object using the words and grid structure. | def problem(mval: int, nval: int, wordlist: str = 'planets') -> LabeledHomomorphism:
""" Produce the class instance for the problem """
check_dimensions(mval, nval)
return LabeledHomomorphism(words(wordlist), grid_graph(mval, nval)) |
def canRunNextPlot(self):
if(len(self.waitingPlots) == 0):
return False
if(self.getNumPlotsInStageOne() >= self.numConcurrentPlots):
return False
return True
def updatePlotStages(self):
allPlotsStages = self.getAllPlotStages()
for key, value in allPlots... | The main task of the code is to periodically check if the next plot can run, waiting for 2 minutes between checks, and updating plot stages/status until the condition `canRunNextPlot()` becomes true. | def plotUpdater(self):
while(self.canRunNextPlot() is False):
time.sleep(120)
self.updatePlotStages()
self.outputStatusOfPlots() |
def removeFullDirectories(self):
spaceOutputDirectories = []
for outputDirectory in self.outputDirectories:
freeSpace = utilFunctions.get_free_space_gb(outputDirectory)
for tempPlot in self.runningPlots:
if(tempPlot.finalLocation == outputDirectory):
... | The main task of the code is to manage Chia plot generation by adding output directories, executing waiting plots, updating plot status, and removing full directories. It iterates through directories to add them to the plotting system, runs plots in a loop, updates progress, and ensures directories are cleaned once ful... | def startPlotting(self):
for tempDir in self.outputDirectories:
os.system("chia plots add -d "+tempDir)
self.removeFullDirectories()
while(len(self.outputDirectories) > 0):
plotToRun = self.waitingPlots.pop()
self.runPlot(plotToRun)
self.plotUpdate... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.