dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def add_movie():
name = input('Enter name:')
director = input('Enter director:')
year = input('Year')
movies.append({
'name': name,
'director': director,
'year': year
})
def show_movies(movies_list):
for movie in movies_list:
show_movie_details(movie)
def find_mo... | The code defines a menu function that repeatedly prompts the user for input, executing corresponding actions: 'a' to add a movie, 's' to display movies, 'f' to find movies, and 'q' to quit. It handles unknown commands with an error message, looping until the user selects 'q' | def menu():
user_input = input("Choose an option:")
while user_input != 'q':
if user_input == 'a':
add_movie()
elif user_input == 's':
show_movies(movies)
elif user_input == 'f':
find_movies()
else:
print('Unknown command...')
... |
def init():
## This function simply reads the polymer as an input,
## and that's it. It's the first user input when
## code is executed. The polymer type is used for the
## index of refraction and titling purposes
## Ask for polymer type
polymer = input("Please type polymer (e.g. PVC, PS, PMMA): ")
## Verify th... | The main task of the code is to read a file containing spectral data, approximate the thickness of a polymer using the data, generate plots of the spectra, and print the calculated thickness values for each scan. The code initializes the polymer, validates its support, reads input files, processes data in a specified d... | def main():
## Initialize
polymer = init()
## Confirm that polymer is supported by code
if polymer == False:
return
## Read file
file_name = input("Please provide file name. ")
header, data, num_of_scans = read_file(file_name)
## Enter directory to place plots
os.chdir("./Plots/Approx")
t = approxi... |
def init():
## This function simply reads the polymer as an input,
## and that's it. It's the first user input when
## code is executed
## Ask for polymer type
polymer = input("Please type polymer (e.g. PVC, PS, PMMA): ")
## Verify that code recognizes the polymer
if polymer == "PVC":
print("Polyvinyl Chloride... | The code's main task is to analyze polymer spectral data by determining thickness (d) using least squares, residual minimization, and MCMC methods. It reads input files, validates polymer support, processes data, computes optimal parameters, generates plots, and outputs thickness values with uncertainties for each scan... | def main():
## Initialize
polymer = init()
## Confirm that polymer is supported by code
if polymer == False:
print("Unsupported Polymer")
return
## Read file
file_name = input("Please provide file name. ")
header, data, num_of_scans = read_file(file_name)
## Use SciPy to find thickness (d) via least s... |
def get_sample_of_n_chars(self, n):
gaps = irand(self.hbuffer, size=n+1)
labels_bitmaps = [self.get_next_char() for _ in range(n)]
labels, _, bitmaps = zip(*labels_bitmaps)
length = sum(gaps) + sum(b.shape[1] for b in bitmaps)
image = np.zeros((self.nDims, length), dtype=float)
... | The code's main task is to generate a text sample by selecting between fixed-length, random-length, or varying-length sampling methods based on instance variables `nchars_per_sample`, `varying_len`, and `avg_len`. It delegates to specific helper methods depending on these configuration flags to return appropriately siz... | def get_sample(self):
if self.nchars_per_sample:
return self.get_sample_of_n_chars(self.nchars_per_sample)
if self.varying_len:
return self.get_sample_of_random_len()
else:
return self.get_sample_of_len(self.avg_len) |
def checkValidCommand(self, command):
if command is None:
return True
# Get two recent commands requested and compare time.
if len(self.ActionStack) >= 2:
last = self.ActionStack[-1]
second_last = self.ActionStack[-2]
diff = last[1] - second_last[1... | This code processes user commands to control a Tello drone's movements and camera functions. It checks command validity, then maps keyboard inputs to specific actions like takeoff, directional movement (up/down/left/right), velocity adjustments, and snapshot/panorama capture. The primary task is translating user input ... | def calculateAction(self, command):
valid_command = self.checkValidCommand(command)
if valid_command:
if command is None:
self.setAllVelocity(0)
elif command == "s":
self.tello.takeoff()
elif command == "up":
self.tello... |
def draw_line(surface, color, start_pos, end_pos, mill_max, aa=True):
mill_ratio = mill_max[0]/mill_max[1] #Ratio >1 if landscape, <1 if portrait
tick = pixel_tick(mill_max)
orig_ = (int(start_pos[0] * (tick)) +10, YRES - int((start_pos[1] * (tick))) -10)
dest_ = (int(end_pos[0] * (tick)) +10, YRES - in... | This function processes CNC path data from tokens to draw lines or drill marks on a Pygame surface. It identifies coordinate boundaries from 'IP' tokens, interprets 'PD' (down) and 'PU' (up) movement commands, and renders paths using draw_line or draw_drill. The verbose flag enables status output, while parameters cont... | def draw_cnc(tokens, surface, verbose = False, max_xy=None, line=True):
line_count = 0
min_x = 0
min_y = 0
max_x = None
max_y = None
lines = 0
verborhea = False
#Search for IP token
if max_xy == None:
for t in tokens:
if t[:2] == 'IP':
v = t[2:].split(',... |
def match_cmd(cmd, num=None):
if g.look[0] == cmd:
if num == None:
return True
elif int(g.look[1:]) == num:
return True
return False
def expected(msg):
if g.config['show_error']:
sys.stderr.write("[ERR] @%d Found <%s>. Expected: %s\n" % (g.bctr, g.look, msg))
cleanu... | The main task of the code is to validate and parse a G-code command 'G64 P??' for setting maximum deviation. It checks if 'G64' is present, retrieves a token, verifies a 'P' parameter exists, and logs the command. If any required component is missing, it raises an error expecting the correct syntax. | def max_deviation():
if not match_cmd('G', 64):
expected("G64")
getToken()
if not match_cmd('P'):
expected("Parameter (P??).")
ignore_opcode('G64 P?? - Set max deviation') |
def rapid_positioning():
'''Move the tool while retracted or extend the tool'''
if not match_cmd('G', 0):
expected('G00')
getToken()
cx = 0
cy = 0
cz = 0
if match_cmd('X'):
cx = float(g.look[1:])
getToken()
if match_cmd('Y'):
cy = float(g.look[1:])
... | This function processes G-code commands by interpreting 'G', 'M', or 'S' prefixes. It executes actions like movement (G0, G1), dwell (G4), or program termination (M2), ignores certain codes (G20, M3), and aborts on unrecognized commands. It handles tool speed (S) and validates parameters, ensuring proper machine contro... | def command():
'''A command begins with either G or M, some of them require extra parameters'''
if g.look[0] == 'G':
#G-Commands
g_num = int(g.look[1:])
if g_num == 0:
rapid_positioning()
elif g_num == 1:
move_linear()
elif g_num == 4:
dwell()
elif... |
def init():
g.scr.reverse()
#EGX file preample, from header.egx
preamble = b';IN;CS6;CA8;IP0,0,30500,20500;LT;PA;\r\n\r\nPU;\r\n\r\n'
g.out_f.write(preamble)
getToken()
def command():
'''A command begins with either G or M, some of them require extra parameters'''
if g.look[0] == 'G':
... | This code compiles input data using a configuration, writing processed output to a file or stdout. It reads input bytes, initializes processing, executes commands in a loop, and writes metadata if specified. The metadata includes layer name/type and output file info. Cleanup is performed afterward. | def compile(conf):
g.config = conf
g.scr = list(open(g.config['input_filename'], 'rb').read())
if g.config['output_filename'] != '-':
g.out_f = open(g.config['output_filename'], 'wb')
else:
g.out_f = sys.stdout.buffer
init()
while g.look != '':
command()
#write meta, if required
if g.config[... |
def get_loader(self, data: list, shuffle: bool = False) -> DataLoader:
if self.dataless:
return DataLoader(
dataset=TensorDataset(torch.tensor(data[0])),
batch_size=self.batch_size,
shuffle=shuffle,
)
else:
return DataLo... | This code trains a neural network model using provided training data, optionally with validation data. It performs gradient descent iterations over specified epochs, tracks training and validation losses, and saves these losses to a CSV file if enabled. The function returns the trained neural network solver along with ... | def fit(
self,
training_data: list,
validation_data: list = None,
verbose: bool = False,
shuffle_data: bool = False,
save_losses: bool = True,
output_dir: str = None,
):
training_loader = self.get_loader(training_data, shuffle=shuffle_data)
if... |
def run_episode(initial_state_a , initial_state_b, model, max_steps ) :
action_probsA = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True)
valuesA = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True)
rewardsA = tf.TensorArray(dtype=tf.int32, size=0, dynamic_size=True)
action_probsB = tf.TensorAr... | The code defines a training step for a reinforcement learning model. It runs an episode to collect actions, values, and rewards, computes discounted returns using gamma, and calculates loss based on action probabilities and returns. Gradients are computed from the loss and applied to the model's parameters via the opti... | def train_step(initial_state_a,initial_state_b, model , optimizer, gamma, max_steps_per_episode):
"""Runs a model training step."""
with tf.GradientTape(persistent=True) as tape:
# Run the model for one episode to collect training data
action_probsA, valuesA, rewardsA , action_probsB , valuesB , rewardsB = run... |
def unroll_args(args, requires):
retval = []
for require in requires:
if isinstance(require, tuple):
val = args.get(require[0], require[1])
else:
val = args[require]
retval.append(val)
if len(requires) > 1:
return tuple(retval)
return val
def cache... | This function computes the Short-Time Fourier Transform (STFT) of an audio signal, either by loading a cached result from a file or processing the signal directly. It checks if a file path is provided; if so, it retrieves the cached STFT. Otherwise, it calculates the STFT from the input signal using specified parameter... | def maybe_cached_stft(args, window_name):
wav_file_path, fs, start, end, nfft, noverlap, win_length, center = \
unroll_args(args, ['wav_file_path', 'fs', 'start', 'end', 'nfft', 'noverlap', 'win_length', 'center'])
if wav_file_path:
tapered = cached_stft(wav_file_path, start, end, nfft, noverlap... |
def unroll_args(args, requires):
retval = []
for require in requires:
if isinstance(require, tuple):
val = args.get(require[0], require[1])
else:
val = args[require]
retval.append(val)
if len(requires) > 1:
return tuple(retval)
return val
def get_s... | The code computes the power spectral density (PSD) of an audio signal. It accepts parameters like file path, sampling rate, and STFT settings. If a file path is provided, it loads the signal and generates the PSD using `get_spectrogram`. Otherwise, it processes a preloaded signal via `stft_from_sig` with a Hann window.... | def get_psd(args):
wav_file_path, fs, start, end, nfft, noverlap, win_length, center = \
unroll_args(args, ['wav_file_path', 'fs', 'start', 'end', 'nfft', 'noverlap', 'win_length', 'center'])
if wav_file_path:
psd = get_spectrogram(wav_file_path, fs, start, end, nfft, noverlap, nfft, center)
... |
def get_url(self,url):
try:
self.driver.get(url)
except Exception as e:
print(e)
self.get_url(url)
def company_details(self):
try:
sleep(2)
table_keys=self.driver.find_elements_by_xpath(self.table_keys)
#print([ele.text for ... | The code scrapes company data from web pages using Selenium, extracts employee names, designations, investor links, and table key-value pairs, then stores the collected information into a JSON file named 'Europe.json'. It iterates through company URLs, navigates each page, gathers structured data, and writes results in... | def setdata(self,company_tups,driver): #(company_name,company_url)
self.employe_xpath="//h4[@class='__halo_textContrast_dark_AAAA __halo_fontSizeMap_size--lg __halo_fontWeight_medium styles_component__1kg4S name_9d036']"
self.designation_xpath="//h4[@class='__halo_textContrast_dark_AAAA __halo_fontSizeM... |
def removeWidgets(self, widgetArray):
for wid in widgetArray:
wid.destroy()
widgetArray.clear()
def backButton(self, screen):
# save all rooms information
self.saveData()
self.hideAllScreens()
# show homescreen
screen.pack()
def addRoom(self, room):
... | This method updates the home screen's room list by removing existing widgets, navigating back to the home screen, and dynamically adding each room from the 'rooms' list to the interface. | def setHomeScreenRooms(self):
self.removeWidgets(self.roomList)
self.backButton(self.homeScreen)
# add room list
for room in self.rooms:
self.addRoom(room) |
def makeAPIURIRequest(page):
resp = http.request("GET",
page,
headers={"Cookie": f"PHPSESSID={os.environ['CASS_SESSID']}"}
)
return resp.data.decode()
def doPanic():
global login_locked
try:
tmp=makeAPIRequest("auth")
if json.loads(tmp)["data"]["authenticated"] == Fal... | The main task of the code is to process entities like "location", "job", and "appointment" by either deleting or adding their associated assets and services based on their status or action. It retrieves data via an API, handles potential JSON errors, and uses conditional logic to execute deletion or creation operations... | def runrun():
cursor = s.Wrapper()
response = None
try:
response = makeAPIURIRequest(item["entity"]["uri"]).replace("\n","<NEWLINE>").replace("\t","<TAB>").replace("\r","<RETURN>")
library = json.loads(response)
except json.decoder.JSONDeco... |
def editEntry(self, id):
"""
Open the 'editEntry' form
"""
self.create_edit_entry_dialog = editEntryForm(id)
self.drawGroups()
def editRules(self, id):
pass
need_reload = RulesDialog(id)
if need_reload:
self.reload()
def toggleDoneEntry(self, i... | This function creates a context menu for an entry with options to edit, view rules, mark as done, or delete. It uses the entry ID to trigger corresponding actions, checks the 'Done' status from global entries, and displays the menu at the cursor position. | def entryContextMenu(self, entry_id):
menu = QMenu()
edit_entry_act = QAction("Edit Entry")
edit_entry_act.triggered.connect((lambda id: lambda: self.editEntry(id))(entry_id))
menu.addAction(edit_entry_act)
rules_act = QAction("Rules")
rules_act.triggered.connect((lambd... |
def fetch_token():
result = subprocess.run(["az","account","get-access-token","--resource-type","ms-graph"], stdout=subprocess.PIPE)
output = result.stdout.decode("utf-8")
token_data = json.loads(output)
access_token = token_data["accessToken"]
return access_token
def handle_item_roles(token, output... | The code enumerates Azure AD/Entra roles for users, groups, and service principals, filtering by name or ID. It outputs results to a file or stdout, supporting options to gather roles for specific entities or list users/groups within a role. The tool does not handle Azure RBAC, focusing solely on AAD/Entra role assignm... | def main():
# Parse arguments
parser = argparse.ArgumentParser(description="Python enumeration of Entra / Azure AD roles. Use to identify Entra ID / AAD permissions of users & groups. Does NOT enumerate Azure RBAC, only Azure AD/Entra roles.")
parser.add_argument('--output', '-o', type=str, help='Output fil... |
def ReadData(fileName):
f = open(fileName, 'r')
lines = f.read().splitlines()
f.close()
items = []
for i in range(1, len(lines)):
line = lines[i].split(',')
itemFeatures = []
for j in range(len(line) - 1):
v = float(line[j]) # Convert feature value to float
... | The code performs k-means clustering on the Iris dataset. It reads data from 'iris.txt', initializes 3 cluster centers, assigns data points to clusters, and prints the final cluster means and assignments. | def main():
items = ReadData('iris.txt')
k = 3
means = CalculateMeans(k, items)
clusters = FindClusters(means, items)
print(means)
print(clusters) |
def analyze_class(self, node: ast.ClassDef):
self.class_context = node.name
for subnode in ast.iter_child_nodes(node):
if isinstance(subnode, (ast.FunctionDef, ast.AsyncFunctionDef)):
self.analyze_function(subnode)
self.class_context = None
def analyze_function(self, ... | The main task of the code is to traverse and analyze an Abstract Syntax Tree (AST), processing class definitions, function definitions, and other nodes. It recursively analyzes classes, handles functions by setting context flags, and collects remaining nodes for further analysis, enabling structural code inspection or ... | def analyze_tree(self, tree: ast.AST):
outer_nodes = []
for node in ast.iter_child_nodes(tree):
if isinstance(node, ast.ClassDef):
self.analyze_class(node)
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
self.context = self.class_co... |
def scriptDir():
return os.path.dirname(os.path.realpath(__file__))
def verifyConfig (config):
"""Checks the loaded configuration dictionary for invalid or missing values."""
if not config:
print("Could not load configuration file.")
return False
valid = True
# Checking HOST
valid = valid and verifyConfigPr... | The code loads configuration from a .env file, reads temperature data from a DS18B20 sensor, connects to an MQTT broker, publishes status and temperature data, handles disconnections and errors, and maintains a loop for continuous sensor data publishing while managing graceful shutdowns via signal handlers. | def main():
config = dotenv_values(os.path.join(scriptDir(), ".env"))
if not verifyConfig(config):
print("Error with configuration. Check logs and README.md file for issues.")
return
print("Configuration loaded.")
print("Checking for DS18B20 sensor...")
temp = readTemperature()
if not temp:
print("Could no... |
def fetch_data(self, project_name: str) -> List[dict]:
"""
Fetches the data from the wandb project and saves them to a list of dictionaries.
@param project_name: name of the wandb project
@return: List of dictionaries with the necessary logs from the wandb project
"""
... | This function fetches WandB project data, converts it to a DataFrame, saves it as an unprocessed CSV, edits the DataFrame, filters by language if specified, and returns the processed DataFrame. | def get_wandb_overview(self, project_name: str) -> pd.core.frame.DataFrame:
"""
Covers several other functions that fetch the data from wandb and preprocess it.
@param project_name: Name of the wandb project
@return: pd.core.frame.DataFrame
"""
# if project_name is None:
... |
def check_seed_per_task(self, task_constraint: list = [], model_constraint: list = [], which_language=None,
required_seeds=None) -> pd.core.frame.DataFrame:
"""
Will create a dataframe of incomplete finetuning tasks that contains the name of the fnetuning task, the model nam... | The main task of the code is to generate performance overviews (e.g., macro-F1, micro-F1, accuracy) for language models across tasks, filtered by parameters like language, task constraints, and seeds. It compiles these metrics into an Excel report, including a completeness check, and saves them for analysis. | def create_report(self, only_completed_tasks: bool = None,
which_language: str = None,
task_constraint: list = [],
model_constraint: list = [],
required_seeds: list = None) -> pd.core.frame.DataFrame:
"""
Will creat... |
def create_template(self, columns: list = None, model_constraint: list = None) -> pd.core.frame.DataFrame:
"""
Creates an empty dataframe with predefined indices and column names that will be used to create the dataframe
with the aggregate scores.
@param columns: List of column names t... | The main task of the code is to generate a dataframe containing aggregated scores for configurations, optionally averaging scores over languages, applying task/model constraints, and including standard deviation. It processes configurations, inserts averages, post-processes columns, and writes results to CSV if specifi... | def get_config_aggregated_score(self, average_over_language=True, write_to_csv=False,
column_name="Agg.", task_constraint: list = [],
model_constraint: list = [], with_standard_deviation=False):
"""
Creates the dataframe with the c... |
def create_template(self, columns: list = None, model_constraint: list = None) -> pd.core.frame.DataFrame:
"""
Creates an empty dataframe with predefined indices and column names that will be used to create the dataframe
with the aggregate scores.
@param columns: List of column names t... | This method aggregates model performance scores across multiple languages by creating a structured DataFrame, applying task and model constraints, sorting columns, and exporting results to CSV, Excel, and LaTeX formats for analysis and reporting. | def get_language_aggregated_score(self, write_to_csv=True, task_constraint: list = [], model_constraint: list = []):
all_languages = set()
for languages in self.meta_infos['task_language_mapping'].values():
for lang in languages:
# TODO: Remove this constraint in the future
... |
def get_config_aggregated_score(self, average_over_language=True, write_to_csv=False,
column_name="Agg.", task_constraint: list = [],
model_constraint: list = [], with_standard_deviation=False):
"""
Creates the dataframe with the c... | This function aggregates dataset scores across language models and tasks, applying constraints to filter datasets/configs. It calculates average scores per model/dataset, handles missing data with warnings, and optionally writes results to CSV after formatting. The output is a dataframe summarizing aggregated performan... | def get_dataset_aggregated_score(self, average_over_language=True, write_to_csv=True, task_constraint: list = [],
model_constraint: list = []) -> None:
"""
Creates the dataframe with the dataset aggregate scores.
@param average_over_language: Boolean Value.... |
def create_infinite_map(map_width=800, map_height=600, horizontal_coordinates=0, vertical_coordinates=0, scale=300,
octaves=5, persistence=0.6, lacunarity=2.0, seed=0):
"""
Creates a 2D matrix with RGB values, representing an image of terrain
Logic: assigns a value for each pixel us... | The code creates an interactive infinite terrain map using Pygame, allowing user movement via arrow keys to navigate the generated landscape. It initializes a window, handles keyboard inputs for directional movement and seed changes, updates the map dynamically based on offsets, and displays the current seed value. The... | def infinite_map_loop(width, height, moving_speed, vertical_offset, horizontal_offset):
"""
Creates a window using the pygame module, then calls the relevant functions in order to make a terrain map and
allowing movement within the terrain
width: width resolution in pixels
height: height resolution... |
def withdraw(self, id, amount):
for user in self.users:
if user['id'] == id:
user['balance'] = user['balance'] - amount
result = {'origin': {"id": user['id'], "balance": user['balance']}}
return result, 201
return 0, 404
def deposit(self,... | The code processes events by checking the 'type' parameter and routing the request to corresponding methods: withdraw, deposit, or transfer, based on the event type. It extracts origin, destination, and amount from parameters, executes the relevant method, and returns its result. If the type is unrecognized, it returns... | def process_event(self, **params):
type = params.get("type")
origin = params.get("origin")
amount = params.get("amount")
destination = params.get("destination")
if(type == 'withdraw'):
return self.withdraw(origin, amount)
if(type == 'deposit'):
... |
def write_to_output(self, text):
self.xml_file.write(text + "\n")
def compile_term(self):
self.write_to_output("<term>")
if self.current_token_type == "IDENTIFIER":
self.write_to_output(self.current_token)
self.get_next_token()
elif self.current_token_type == "INT... | The code compiles an expression by writing XML tags, handling tokens, and recursively calling compile_term(). It processes symbols, checks for commas/parentheses, advances tokens, and ensures proper expression structure with opening/closing tags. | def compile_expression(self):
self.write_to_output("<expression>")
print(f"COMPILE_EXPRESSION {self.current_token}")
if self.current_token_value != ")" and self.current_token_value != ";":
self.compile_term()
if self.current_token_value == ",":
self.write_to_outpu... |
def write_to_output(self, text):
self.xml_file.write(text + "\n")
def get_next_token(self):
self.current_token_index += 1
if self.current_token_index < len(self.tokens):
self.current_token = self.tokens[self.current_token_index]['token']
self.current_token_type = self.tok... | This function parses a 'let' statement in a compiler, generating XML output. It checks for the 'let' keyword, processes an identifier, handles assignment with '=', compiles an expression, and validates a semicolon, writing corresponding XML tags while advancing through tokens. | def compile_let_statement(self):
if self.current_token_value == "let":
self.write_to_output("<letStatement>")
self.write_to_output(self.current_token)
self.get_next_token()
if self.current_token_type == "IDENTIFIER":
self.write_to_output(self.curre... |
def write_to_output(self, text):
self.xml_file.write(text + "\n")
def get_next_token(self):
self.current_token_index += 1
if self.current_token_index < len(self.tokens):
self.current_token = self.tokens[self.current_token_index]['token']
self.current_token_type = self.tok... | The main task of the code is to parse and compile a return statement in a programming language. It checks for the "return" keyword, writes XML tags for the return statement, processes an optional expression if present, ensures a semicolon is included, and advances the token stream. This function is part of a compiler's... | def compile_return_statement(self):
if self.current_token_value == "return":
self.write_to_output("<returnStatement>")
self.write_to_output(self.current_token)
self.get_next_token()
if self.current_token_value != ";":
self.compile_expression()
... |
def write_to_output(self, text):
self.xml_file.write(text + "\n")
def get_next_token(self):
self.current_token_index += 1
if self.current_token_index < len(self.tokens):
self.current_token = self.tokens[self.current_token_index]['token']
self.current_token_type = self.tok... | The function compiles a 'do' statement into XML by parsing tokens like "do", identifiers, ".", "(", expression lists, and ";", writing them to output while advancing through the token stream. It handles method calls with or without object references, ensuring proper syntax structure and token validation for Jack langua... | def compile_do_statement(self):
if self.current_token_value == "do":
self.write_to_output("<doStatement>")
self.write_to_output(self.current_token)
self.get_next_token()
if self.current_token_type == "IDENTIFIER":
self.write_to_output(self.current_... |
def dice_roll(self, num_of_dice):
print(f"Rolling {num_of_dice} dice...")
roll = self.roller(num_of_dice)
formatted_roll = self.format_roll(roll)
print(formatted_roll)
return roll
def check_zilch(self, roll):
return GameLogic.calculate_score(roll) == 0
def zilch_is_yes(se... | This function manages a single turn in a dice game by rolling dice, checking for a zilch (zero points), collecting keepers, updating remaining dice, displaying points/dice status, and handling user input to either roll again, bank points, or quit the game. | def play_turn(self):
num_of_dice = 6
while True:
roll = self.dice_roll(num_of_dice)
if self.check_zilch(roll):
self.zilch_is_yes()
return
dice_to_keep = self.collect_keepers(roll)
num_of_dice -= len(dice_to_keep)
... |
def start_round(self):
"""starts the round"""
print(f"Starting round {self.round_num}")
def play_turn(self):
num_of_dice = 6
while True:
roll = self.dice_roll(num_of_dice)
if self.check_zilch(roll):
self.zilch_is_yes()
return
... | The code defines a method `play_the_round` that sequentially executes three phases of a game or process: initializing the round, playing a turn, and concluding the round. Its main task is to orchestrate the complete lifecycle of a single round in a structured manner. | def play_the_round(self):
self.start_round()
self.play_turn()
self.end_round() |
def welcome(self):
print("Welcome to Ten Thousand")
print("(y)es to play or (n)o to decline")
response = input("> ")
if response == "n":
print("OK. Maybe another time")
sys.exit()
def play_rounds(self):
"""use the round limit set in game init"""
w... | The main task of the code is to initiate and manage a game by initializing the dice roller, welcoming the player, executing game rounds, and concluding with a game-over sequence. The `play` method sets up the game logic, triggers the welcome message, processes rounds of gameplay, and finalizes the game state. | def play(self, roller=GameLogic.roll_dice):
"""starts the game"""
self.roller = roller
self.welcome()
self.play_rounds()
self.game_over() |
def __get_regularity(self):
# Returns a boolean stating whether the graph is d-regular
matrix = self.__get_adjacency()
degree = np.count_nonzero(matrix[0])
for i in range(1, len(matrix)):
if np.count_nonzero(matrix[i]) != degree:
return False
return Tr... | The function determines and returns the graph's expansion property, selecting between random walk expansion (if the graph is not regular or walk=True) and lambda expansion (if the graph is regular). The boolean parameter controls whether a boolean result or numerical value is returned, with the criterion defining expan... | def get_expansion(self, walk=False, criterion=1e-8, boolean=False):
# Retrieve the expansion properties of the graph based on configuration.
# i.e. either random walk expansion, lambda expansion (if d-regular)
regularity = self.__get_regularity()
if walk is True or regularity is False:
... |
def __get_laplacian(self):
# Constructing the laplacian matrix
adjacency = self.__get_adjacency()
laplacian = -adjacency
degree = []
for i in range(len(adjacency)):
degree.append(np.count_nonzero(adjacency[i]))
np.fill_diagonal(laplacian, degree)
retu... | The code computes the Cheeger constant of a graph, along with its upper and lower bounds, using the graph's Laplacian matrix. It returns a formatted string containing the computed Cheeger constant, approximated bounds, and the Laplacian matrix. | def cheeger(self):
# Compute the cheeger constant for a graph
laplacian, _, _ = self.__get_laplacian()
ub, lb = self.__get_cheeger_bounds()
ret_str = "Cheeger constant is " + str(self.__get_cheeger()) + " with approximated upper bound " + \
str(ub) + ", and lower bound ... |
def vertex_count(self):
return len(self.vertices())
def __get_simplex_dim(self, __simplex_dict=None):
# Calculating the dimension of __simplex_dict (which is the whole complex by default)
max_dim = 1
if __simplex_dict is None:
for simplex in self.simplices():
... | The main task of the code is to construct a tensor `X` where each entry is 1 if the corresponding index represents a simplex in the complex, and 0 otherwise. The tensor's dimensions depend on the number of vertices and the complex's dimension. The code iterates through simplices of varying dimensions, updating the tens... | def __get_tensor(self):
# Builds the tensor X where x(m) = 1 iff m is a simplex in the complex. Note: m is of the dimension
# same as the complex itself. E.g. for a 3d complex, x(i,j,k) = 1 if (i,j,k) is a triangle.
size = self.vertex_count()
dim = self.__get_simplex_dim()
X = se... |
def __init_vertex_dict(self):
# Initialise an empty vertex dictionary
__vertex_dict = {}
for key in self.__get_keys():
__vertex_dict.setdefault(key, {})
return __vertex_dict
def __get_simplex_dict(self, simplices=None):
# Constructing the dictionary storing the simpli... | The main task of the code is to generate a dictionary mapping vertices (including higher-dimensional coordinates) to unique integer indices. It initializes a vertex dictionary, iterates through simplices from a simplex dictionary, and assigns sequential indices to each vertex within the dictionary structure, enabling e... | def __get_vertex_dict(self):
# Creating __vertex_dict: a dictionary of dictionaries which allocates an integer index to each vertex
# (including 'vertices' from higher dimensions, for e.g. the (1,2) in dimension 3 matrix would be stored as
# the vertex 0 etc.).
__vertex_dict = self.__ini... |
def vertices(self):
unique_elements = set()
for simplex in self.simplices():
# Adding elements to a set which prevents duplicates
for elem in simplex:
unique_elements.add(elem)
return unique_elements
def __get_link(self, vertex):
# Compute and retu... | The main task of the code is to generate a descriptive string for each vertex's link in a simplicial complex. It retrieves the link, constructs its underlying graph, computes the normalized adjacency matrix, and formats these into a human-readable output. If a link is empty, it notes the absence of a graph. The result ... | def underlying_link_graphs(self):
# Return a string containing the underlying graphs of all links and their adjacency matrices.
vertices = self.vertices()
ret_str = ""
for vertex in vertices:
link = self.__get_link((vertex,))
if len(link) > 0:
unde... |
def __get_underlying_graph(self, simplices):
# Returns the underlying graph (edges and vertices) of simplices.
__simplex_dict = self.__get_simplex_dict(simplices)
__simplex_dim = self.__get_simplex_dim(__simplex_dict)
for i in range(2, __simplex_dim):
del __simplex_dict[i + 1... | The main task of the code is to compute the maximum expansion value across all relevant graphs derived from simplices and their links. It initializes a base graph, checks its expansion, iterates through simplices, constructs graphs from their links, and updates the maximum expansion value if a higher valid expansion is... | def __get_lambda(self):
base_dict = self.__get_underlying_graph(self.simplices())
base_graph = Graph(base_dict)
max_expansion = 1e-999
expansion = base_graph.get_expansion()
if type(expansion) is not str:
if expansion > max_expansion: max_expansion = expansion
... |
def __get_simplex_dict(self, simplices=None):
# Constructing the dictionary storing the simplicial complex in format:
# { X(1) : [(edge1), (edge2), ...]
# X(2) : [(triangle1), (triangle2), ...] }
__simplex_dict = {}
if simplices is None:
simplices = self.simplices(... | The function calculates the number of underlying graphs required for plotting by iterating through simplices of specific dimensions, incrementing a count for each valid link (non-empty) found, while excluding single-vertex graphs and those without an underlying graph. | def __get_graph_count(self):
# Returns the number of underlying graphs for links that need plotting.
# The count does not include links that don't have an underlying graph, or have a single vertex graph.
count = 1
__simplex_dict = self.__get_simplex_dict()
max_dim = self.__get_si... |
def __get_complex_tree_guide(self):
tree_guide = {}
max_dim = self.__get_simplex_dim() + 1
simplex_dict = self.__get_simplex_dict()
vertex = 0
for key in range(1, max_dim):
for simplex in simplex_dict[key]:
tree_guide.setdefault(simplex, (vertex,))
... | The code constructs a graph representing a simplicial complex by connecting simplices and their faces via subset relationships. It generates a dictionary (`tree_dict`) with nodes (key 1) and edges (key 2), where edges link simplices to their containing faces. The resulting `Graph` object captures hierarchical relations... | def __get_complex_tree(self):
tree_guide = self.__get_complex_tree_guide()
tree_dict = {1: list(tree_guide.values()), 2: list()}
simplex_dict = self.__get_simplex_dict()
max_dim = self.__get_simplex_dim() + 1
for key in range(1, max_dim):
for simplex in simplex_dict[... |
def __get_vertex_dict(self):
# Creating __vertex_dict: a dictionary of dictionaries which allocates an integer index to each vertex
# (including 'vertices' from higher dimensions, for e.g. the (1,2) in dimension 3 matrix would be stored as
# the vertex 0 etc.).
__vertex_dict = self.__ini... | This function generates adjacency matrices for flattened graphs by connecting vertices that share edges through lower-dimensional simplices. It iterates over simplices, creates combinations of lower-dimensional elements, checks subset relationships, and updates the adjacency matrix to mark connections between vertices ... | def __get_adjacency_matrix_dict(self):
# Generating combos: a list of possible combinations that can be generated from each simplex.
# Completing __matrix_dict: a dictionary of np.ndarray adjacency matrices for the flattened graphs
combos = []
__vertex_dict = self.__get_vertex_dict()
... |
def __get_graph_count(self):
# Returns the number of underlying graphs for links that need plotting.
# The count does not include links that don't have an underlying graph, or have a single vertex graph.
count = 1
__simplex_dict = self.__get_simplex_dict()
max_dim = self.__get_si... | The main task of the code is to generate and display multiple underlying graphs of links and simplices in a grid layout. It creates a figure with 3 columns, plots each graph as a subplot, labels them sequentially, and saves the combined visualization as a PNG file. The graphs represent the structure of simplices and th... | def __plot_underlying_graphs(self):
# Getting the underlying graphs of all the links using the Graph object and networkX plotting
# Graphs are arranged in a grid of 3 columns
fig = plt.figure(figsize=(11.69, 8.27))
rows = (self.__get_graph_count() // 3 + 1)
i = 1
title = ... |
def filterBySafeDistance(self, poses, target):
filtered = []
for pose in poses:
if utils.separation(pose, target) <= self.safeDistance:
filtered.append(pose)
return filtered
def chooseTheBestPose(self, poses, bans=[]):
if len(poses) == 0 or len(bans) == 0:
... | This method determines a safe target position by first filtering nearby obstacles (meanies) within a safe distance from the current pose, then selecting the optimal candidate pose from possible positions while avoiding the filtered obstacles. | def targetPoseToAvoidMeanies(self):
self.allMeaniesToAvoid = self.filterBySafeDistance(
self.allMeanies, self.currentPose)
self.targetPose = self.chooseTheBestPose(
self.candidatePoses(self.currentPose), self.allMeaniesToAvoid) |
def targetPoseToAvoidMeanies(self):
self.allMeaniesToAvoid = self.filterBySafeDistance(
self.allMeanies, self.currentPose)
self.targetPose = self.chooseTheBestPose(
self.candidatePoses(self.currentPose), self.allMeaniesToAvoid)
def direction(self, bans=[]):
# If not at th... | The function `makeMove` determines Tallon's movement direction by prioritizing avoidance of Meanies, then moving toward available bonuses, and defaulting to self-directed movement if no bonuses remain. It retrieves game elements' positions, checks for obstacles, calculates target positions, and returns a direction or `... | def makeMove(self):
# This is the function you need to define
# For now we have a placeholder, which always moves Tallon
# directly towards any existing bonuses. It ignores Meanies
# and pits.
#
# Get the location of the Bonuses.
self.allBonuses = self.gameWorld.... |
def filterBasic() -> None:
"""
Toy example on filtering
Blurring an image using a Box-Filter
:return:
"""
img_path = 'scarlet_witch.png'
img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)
k_size = 11
kernel = np.... | The main task of the code is to demonstrate a series of image processing techniques, including basic/median filtering, edge detection (Sobel, Laplacian), correlation methods (simple and advanced), sharpening, and bilateral filtering. The `main()` function sequentially executes these operations to showcase different ima... | def main():
filterBasic()
filterMedian()
corrSimple()
corrAdv(use_ncc=False)
corrAdv(use_ncc=True)
edgeDetect()
filterSobel()
laplacian()
shapren()
bilateral_demo()
bilateralFull() |
def check_fleet_edges(pa_settings, reapers):
for reaper in reapers.sprites():
if reaper.check_edges():
change_fleet_direction(pa_settings, reapers)
break
def pachimari_hit(pa_settings, stats, screen, pachimari, reapers, bullets):
if stats.pachimari_left > 0:
stats.pachima... | The function updates reapers' positions, checks for collisions between the player (pachimari) and reapers, triggers collision responses, and verifies if reapers have moved beyond the screen's bottom. It ensures reapers stay within boundaries and handles game state changes like player damage or game over conditions. | def update_reapers(pa_settings, stats, screen, pachimari, reapers, bullets):
check_fleet_edges(pa_settings, reapers)
reapers.update()
if pygame.sprite.spritecollideany(pachimari, reapers):
pachimari_hit(pa_settings, stats, screen, pachimari, reapers, bullets)
check_reapers_bottom(pa_settings, st... |
def load_wav(full_path, sample_rate):
data, _ = librosa.load(full_path, sr=sample_rate, mono=True)
return data
def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=True):
mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
mel_basis = torch.from_num... | This code loads audio files with caching to improve efficiency, processes them into spectrogram features (mel, log amplitude, phase, etc.), and returns multiple transformed audio representations for training or inference. It segments/pads audio to fixed length, extracts mel-spectrograms with different parameters, and o... | def __getitem__(self, index):
filename = self.audio_files[index]
if self._cache_ref_count == 0:
audio = load_wav(filename, self.sampling_rate)
self.cached_wav = audio
self._cache_ref_count = self.n_cache_reuse
else:
audio = self.cached_wav
... |
def get_weather(self):
weather_dict = {
'type': random.choice(['Snow', 'Normal']),
'temp': round(random.uniform(9, 21), 2),
'sun': round(random.uniform(0,8), 2),
'rainfall': random.uniform(0, 0.13143)
}
return weather_dict
def choose_modifiers(... | This function updates plant growth in a game by applying weather and modifier effects, increasing the player's score with plant health, and removing harvested plants. It checks clock speed to determine weather, applies growth modifiers conditionally based on game mode, and manages plant lifecycle by eliminating matured... | def grow_plants(self, game_mode):
dead_plants = []
if self.clock_speed == 1440:
weather_today = get_weather_today()
else: weather_today = self.get_weather()
for key in self.my_plants:
plant = self.my_plants[key]
if plant.age < plant.days_to_harvest:
... |
def catch_up_days(self):
todays_date = datetime.strptime(datetime.now().strftime("%Y/%m/%d"), "%Y/%m/%d")
for _ in range(int(((todays_date.day - self.date_last_saved.day) * 1440) / self.clock_speed)):
self.grow_plants('catchup')
def ask_boolean(self, question, options):
data_to_send ... | The main task of the code is to manage a game loop that advances in-game time, fetches real-time weather data when enabled, allows user input to add new plants, applies modifiers, grows plants normally, and pauses execution based on the clock speed setting to simulate time progression. | def main_game_loop(self):
self.catch_up_days()
while True:
if self.clock_speed == 1440:
print('Using Real weather for plant')
get_metofffice_data('val/wxfcs/all/json/310004', 'weather_today')
while self.ask_boolean('Do you want a new plant (y / n)?... |
def check_player_id(self):
if self.input_buffer["msg_id"] != 1:
print('exiting: bad msg_id')
sys.exit()
elif self.input_buffer["msg"] != 'got player_id':
print('exiting: bad msg')
sys.exit()
elif self.input_buffer["player_id"] != self.my_id:
... | This code handles a player's initial setup in a game. It waits for input confirmation, checks the player's ID, and then either loads an existing game or initializes a new one based on user choice, finally entering the main game loop. | def run(self):
print(f'player_{self.my_id} joined!')
print('wating for confirmation')
while len(self.input_buffer) == 0:
pass
print('end of wait')
self.check_player_id()
load_game_question = 'Do you want to (l)oad a game or open a (n)ew game?'
if self.... |
def move_next(self):
x, y = self.probe_points[len(self.results)]
curpos = self.toolhead.get_position()
curpos[0] = x
curpos[1] = y
curpos[2] = self.horizontal_move_z
try:
self.toolhead.move(curpos, self.speed)
except homing.EndstopError as e:
... | The code initializes a probing process by registering a custom G-code command ('NEXT'), setting up necessary objects, and initiating a loop to execute probe operations. It manages a busy state, collects results, and handles exceptions to finalize the probe, ensuring continuous movement and command execution until compl... | def start_probe(self):
# Begin probing
self.toolhead = self.printer.lookup_object('toolhead')
self.gcode = self.printer.lookup_object('gcode')
self.gcode.register_command(
'NEXT', self.cmd_NEXT, desc=self.cmd_NEXT_help)
self.results = []
self.busy = True
... |
def same_advertiser_exist(self, dest, advert):
for i in self.iBGP_msg[dest]:
if i[1] == advert:
return True
return False
def remove_iBGP_ad(self, router, advert):
# called when an iBGP session is down and self is the client
# print(self.get_id(), self.iBGP... | This function processes iBGP advertisement updates by managing route entries in a data structure. It checks if a destination exists in the iBGP message dictionary, adds new routes, removes existing entries if the same advertiser updates the route, and appends the new gateway-advertiser pair. It ensures route consistenc... | def decode_iBGP_ad(self, update: list):
destinations = update['dest']
gate = update['gate']
advertiser = update['advertiser']
for dest in destinations:
if dest not in self.iBGP_msg.keys():
self.iBGP_msg[dest] = [[gate, advertiser]]
else:
... |
def isEmpty(self): #last given
if self.getHead() == None:
return True
return False
def getTail(self):
return self._tail.link
def getCurr(self):
return self._curr.link
def getPos(self): #given by professor
#returns the current position as a number
if self.isEmp... | The main task of the code is to advance the current position to the next element in a data structure, but only if it's not empty and the tail isn't equal to the current position. It retrieves the current index, increments it by one, and updates the position, effectively moving to the next element while avoiding invalid... | def goNext(self):
if self.isEmpty() == True:
pass
elif self.getTail() == self.getCurr():
pass
else:
index = self.getPos()
newIndex = index+1
self.setPos(newIndex) |
def isEmpty(self): #last given
if self.getHead() == None:
return True
return False
def getHead(self):
return self._head.link
def getCurr(self):
return self._curr.link
def getPos(self): #given by professor
#returns the current position as a number
if self.isEmp... | The main task of the code is to move the current position to the previous element in a data structure, ensuring it doesn't go out of bounds. It checks if the structure is empty or if the current position is already at the start (head), and if not, decrements the position index by 1 to navigate backward. | def goPrev(self):
#check for beginning
#Check for end
#get position
#set position to 1-position
if self.isEmpty() == True:
pass
elif self.getHead() == self.getCurr():
pass
else:
index = self.getPos()
newIndex = index... |
def isEmpty(self): #last given
if self.getHead() == None:
return True
return False
def setHead(self, here):
self._head.link = here
def setTail(self, here):
self._tail.link = here
def setCurr(self, here):
self._curr.link = here
def isBeginning(self):
return (s... | This method inserts a node `n` before the current node in a linked list. If the list is empty, it initializes the list with `n`. If at the beginning, it sets `n` as the new head. Otherwise, it moves the current pointer back and inserts `n` there, adjusting pointers accordingly. | def insertBefore(self, n):
# inserts before curr
if self.isEmpty() == True:
#this is an empty list we are adding to therefore:
self.setHead(n) #head points to n
self.setTail(n) #tail points to n
self.setCurr(n) #current points to n
elif self.isBeg... |
def isEmpty(self): #last given
if self.getHead() == None:
return True
return False
def getTail(self):
return self._tail.link
def getHead(self):
return self._head.link
def setHead(self, here):
self._head.link = here
def setTail(self, here):
self._tail.link = he... | The code removes the current node from a doubly linked list. It handles edge cases: if empty, it does nothing; if only one node exists, it resets head, tail, and current to None. If the current node is the head, it updates the head to the next node and sets current to the new head. Otherwise, it moves to the previous n... | def remove(self):
#removes the node at curr
if self.isEmpty() == True:
pass
elif self.getTail() == self.getHead():
self.setHead(None)
self.setTail(None)
self.setCurr(None)
else:
if self.getCurr() == self.getHead():
... |
def clone_git_repo(git_url):
project_path = tempfile.mkdtemp()
Repo.clone_from(git_url, project_path)
return project_path
def diff_worker(diff,brnch, curr_commit, prev_commit, branch_name, commitHash, custom_regexes, do_entropy, do_regex, printJson, surpress_output, path_inclusions, path_exclusions, allow):... | The function analyzes code changes in a Git repository by comparing commits, generating diffs, and detecting potential issues using regex or entropy analysis. It clones the repository, iterates through commits, avoids redundant diffs, and aggregates findings into a structured JSON output containing issues, project path... | def find_strings(git_url,brnch, since_commit=None, max_depth=1000000, printJson=False, do_regex=False, do_entropy=True, surpress_output=True,
custom_regexes={}, branch=None, repo_path=None, path_inclusions=None, path_exclusions=None, allow={}):
output = {"foundIssues": []}
if repo_path:
... |
def reverse(self):
if not self.vertices_RevAdj:
self._init_reverse_copy()
for i in range(len(self.vertices)):
self.vertices[i].adj, self.vertices_RevAdj[i] = self.vertices_RevAdj[i], self.vertices[i].adj
def dfs(self):
self.n_of_cc = 0 #number_of_connected_components
... | This code calculates the number of strongly connected components (SCCs) in a directed graph using Kosaraju's algorithm. It reverses the graph, performs a depth-first search (DFS) to determine node order, then processes nodes in topological order to count SCCs by exploring unvisited nodes, incrementing the count for eac... | def n_of_scc(self): #number_of_strongly_connected_components
self.reverse()
self.dfs()
self.reverse()
self._explore_init()
scc_number = 0
for v in self.toposorted_list():
if v.id not in self.explored:
self.explore(v)
scc_number ... |
def _check_vis_connector(self):
if self.vis_connector is None:
self.vis_connector = VisualizeConnector(size=int(self.sp_size.get()))
def _update_many_images(self, results):
methods_to_draw = self._get_methods_to_draw()
methods_to_draw['system'] = True
for method, need_to_dra... | The main task of the code is to retrieve previous visualization data using `vis_connector.get_prev()`, update multiple images with the retrieved results via `_update_many_images`, and plot associated lines using `_plot_lines`. It ensures the visualization connector is active before executing these operations, enabling ... | def _prev_slide(self):
self._check_vis_connector()
results, lines = self.vis_connector.get_prev()
if results is not None:
self._update_many_images(results)
self._plot_lines(lines) |
def _check_vis_connector(self):
if self.vis_connector is None:
self.vis_connector = VisualizeConnector(size=int(self.sp_size.get()))
def _update_many_images(self, results):
methods_to_draw = self._get_methods_to_draw()
methods_to_draw['system'] = True
for method, need_to_dra... | The main task of the code is to retrieve the next set of visualization data (results and lines) from a connector, update displayed images with the new results, and plot the lines if valid data is received. It ensures the visualization system is properly connected, fetches the next data batch, and applies updates to mai... | def _next_slide(self):
self._check_vis_connector()
results, lines = self.vis_connector.get_next()
if results is not None:
self._update_many_images(results)
self._plot_lines(lines) |
def _check_vis_connector(self):
if self.vis_connector is None:
self.vis_connector = VisualizeConnector(size=int(self.sp_size.get()))
def _update_many_images(self, results):
methods_to_draw = self._get_methods_to_draw()
methods_to_draw['system'] = True
for method, need_to_dra... | The main task of the code is to retrieve all visualization data from the connector, update multiple images with the results, and plot the associated lines to display the current state of the visualization. It ensures the connector is valid, fetches data, and triggers updates to the visual elements. | def _show_all(self):
self._check_vis_connector()
results, lines = self.vis_connector.get_all()
if results is not None:
self._update_many_images(results)
self._plot_lines(lines) |
def _prev_slide(self):
self._check_vis_connector()
results, lines = self.vis_connector.get_prev()
if results is not None:
self._update_many_images(results)
self._plot_lines(lines)
def start(self):
self.is_run = not self.is_run
if not self.is_run:
... | This code initializes a GUI interface for visualizing image processing techniques. It sets up a window with controls (spinbox, checkboxes) to configure parameters and select methods like DFT, DCT, histogram, etc. Multiple canvases display corresponding image transformations and a graph. Buttons allow navigation, starti... | def __init__(self, controller=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.controller = controller
self.images = {}
self.canvas = {}
self.var = {}
self.image_id = {}
self.methods_list = ['system', 'histogram', 'dft', 'dct', 'scale', 'gradient']
... |
def check_enter_exit_loop(track):
loops = count_boxes["loops"]
for loop in loops:
# print(loop)
pt0, pt1, pt2, pt3 = loop["points"]
# check entering line
if len(track.centroidarr) > 20:
tp2, tp1 = track.centroidarr[-1], track.centroidarr[-20]
# check enter... | The code performs real-time object detection and tracking using a deep learning model, with the primary task of counting objects (e.g., vehicles) as they move through predefined zones (straight, left, right) in video streams or images. It initializes a SORT tracker for object tracking, processes each frame to detect an... | def detect(save_img=False):
global save_dir
global time_stamp
global names
global loop_boxes
global opt
source, weights, view_img, save_txt, imgsz, trace, colored_trk = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace, opt.colored_trk
save_img = not opt.no... |
def handle_distlist_data(self):
'''gets distribution list data'''
self.pwrshl_get_distlist()
self.import_distlist()
self.pwrshl_get_distlist_members()
self.extract_data_from_file(self.path+'\_distlist_members.txt')
def handle_mailcontact_data(self):
'''handles grabbing ma... | The main task of the code is to execute the primary script by sequentially processing distribution list data, mail contact data, BambooHR data, and SmartSheet data through dedicated handler methods, ensuring all necessary data operations are performed as intended. | def run(self):
'''runs main script as intended'''
self.handle_distlist_data()
self.handle_mailcontact_data()
self.get_bamboohr_data()
self.grab_smartsheet_data() |
def getResultsAgainstPlayerId(self, opponentId):
return self.getResultsWithFilter(lambda simpleResult: opponentId == simpleResult.opponentId)
def getWinResultsFromResultList(self, results):
return list(filter(lambda simpleResult: simpleResult.myPoints > simpleResult.opponentPoints, results))
def getPoin... | This function prints a detailed player profile, showing performance stats against each opponent team. It calculates and displays game counts, wins/losses, average points scored against specific opponents, and compares these metrics to overall team averages. | def printPlayerProfile(self, teamLocators):
## A breakdown of how each player has done
print("Profile for " + self.team.__str__())
for teamId in teamLocators.getAllTeamIds():
if teamId == self.team.id:
continue
opponentTeam = teamLocators.getTeamFromId(tea... |
def build_train_graph(self):
is_training_ph = tf.placeholder(tf.bool, shape=(), name="is_training")
with tf.name_scope("data_loading"):
# generate training and validation batches ( we do not need labels)
train_batch, n_samples_train = self.generate_batches(
... | This code trains a neural network using TensorFlow, managing sessions, checkpoints, and summaries. It initializes the graph, runs training steps with progress tracking, logs metrics like RMSE and standard deviations, and validates periodically by evaluating loss. The training resumes from checkpoints if specified, and ... | def train(self, config):
"""High level train function.
Args:
config: Configuration dictionary
Returns:
None
"""
self.config = config
self.build_train_graph()
self.collect_summaries()
with tf.name_scope("parameter_count"):
... |
def create_txt(new_file, component):
template = f"""<?xml version="1.0" encoding="utf-8"?>
<!-- Test -->
<!DOCTYPE curve SYSTEM "eagle.dtd">
<eagle version="7.7.0">
<drawing>
<settings>
<setting alwaysvectorfont="no"/>
<setting verticaltext="up"/>
</settings>
<grid distance="0.1" unitdist="inch" unit="inch" style=... | The main task of the code is to generate a library file (lbr) by orchestrating multiple functions: retrieving component details, creating text sections, generating footprint and symbol data, linking pins to pads, and adding device/technology metadata. The process assembles these elements into a structured library file ... | def main():
# Component and library questions function
lib_name, component = questions.component_questions()
# Create first text part of lbr file
create_txt(lib_name, component)
# Create and add Footprint data to lbr file
smd_pads = footprint_create(lib_name, component)
# Create and ... |
def update_moving_sprites(self, delta_time: float) -> None:
"""
Manage the moving sprites
Args:
delta_time (float)
"""
for moving_up in self.static_moving_up_list:
moving_sprite = moving_up.update(
delta_time
) # See if a new ... | This method updates game elements by handling animations, physics, and collisions. It checks for player death (via collisions or screen boundaries), triggers death logic if triggered, updates the viewport, processes physics, and checks for win conditions. The core tasks include updating sprites, managing physics intera... | def on_update(self, delta_time: float) -> None:
"""
Arcade update
Args:
delta_time (float)
"""
# Update various separate classes
self.not_enough_power_label.update(delta_time)
self.update_moving_sprites(delta_time)
self.power.update(delta_time... |
def do_trn(self, process_mode=0):
self.model.train()
for batch_ndx, (src_batch, tgt_batch) in enumerate(
tqdm(zip(self.src_trn_dl, self.tgt_trn_dl), total=len(self.src_trn_dl)), start=1):
self.compute_batch(src_batch, tgt_batch, len(self.src_trn_dl), batch_ndx)
t... | The main task of the code is to execute different processing workflows based on the `process_mode` value. If mode 0, it performs training (`do_trn`). For mode 1, it trains, evaluates matches, updates status, and saves results. For mode 2, it skips training and directly evaluates, updates status, and saves results. Inva... | def main(self):
if self.process_mode == 0:
self.do_trn(self.process_mode)
elif self.process_mode == 1:
self.do_trn(self.process_mode)
self.eval_to_match()
self.update_curr_match_status()
self.save_final_info()
elif self.process_mode == ... |
def init_id2label_label2id(self):
label2id = {}
id2label = {}
for cname in self.df.columns:
label2id[cname] = label2id[cname] if cname in label2id else len(label2id)
id2label[label2id[cname]] = cname
return id2label, label2id
def deal_with_numerical_column(self):
... | This code initializes a data processing class for handling structured datasets, configuring parameters like fragment dimensions, column sampling probabilities, and numerical column binning. It sets up label mappings, validates input constraints, and prepares a static dataset if specified, enabling fragment-based data a... | def __init__(self, df, ds_length,
frag_height,
frag_width,
table_name,
static_n_sample=None,
col_name_prob=0.0,
col_name_variant_prob=0.5, schema_process_type=None,
numerical_col_bins=0, numerical_col_... |
def _off_screen(self) -> None:
"""Method to change the screen's state to 'OFF'."""
self._canvas.create_rectangle(self._screen_corners["X1"], self._screen_corners["Y1"], self._screen_corners["X2"], self._screen_corners["Y2"], fill="grey10", outline="black")
self._canvas.create_text(self._canvas_s... | The main task of the code is to handle mouse click events on a graphical interface, toggling device states like power, charging, display, lock, and settings based on which UI element is clicked. It manages interactions with buttons such as power, charger, home, unlock, lock, and settings, updating internal states and t... | def _press(self, event) -> bool:
"""Method to handle 'press' events i.e. clicks on the canvas."""
#print("powered_on", self._powered_on, "|display_on", self.display_on, "|locked", self._locked, "|is_charging", self._is_charging, "|power_draw", self._power_draw, "|settings", self._settings)
""" ... |
def analyze_states(states):
cor1s = []
cor2s = []
cor3s = []
intervals1 = []
intervals2 = []
intervals3 = []
t_0 = 500
for state in states:
q0, q1 = state[0], state[1]
#q0, q1 = state[2], state[3]
interval1, cor1 = frequency_analysis(q0[t_0:])
i... | This code compares pre- and post-learning neural states by analyzing their intervals and amplitudes. It generates scatter plots showing period (interval) and amplitude distributions, with pre-learning data in green and post-learning in red. The plots visualize changes in neural dynamics before and after learning, saved... | def analysis1(pre_learn_states, post_learn_states, plotdir):
cor1s_pre, cor2s_pre, cor3s_pre, intervals1_pre, intervals2_pre, intervals3_pre = \
analyze_states(pre_learn_states)
cor1s_post, cor2s_post, cor3s_post, intervals1_post, intervals2_post, intervals3_post = \
analyze_states(post_learn_st... |
def test_expired(self):
if self.expires < datetime.now().timestamp():
return self.update()
return 0
def update(self):
headers = {
"Authorization": f"Basic {self.enc_64_client_info()}"
}
parameters = {
"grant_type": "refresh_token",
... | The main task of the code is to check if a Spotify playlist named 'MusicSaver' exists for the user. If it exists, it returns the playlist ID; if not, it creates a new private playlist with the name 'MusicSaver' and a specific description, then returns the newly created playlist's ID. The code also handles token refresh... | def auxiliar_playlist(self):
"""
look for 'MusicSaver'
if it doesn't exist, create it
"""
if self.test_expired():
self.update()
parameters_find = {
"limit": Spotify.PLAYLISTS_LIMIT
}
r_playlists = requests.get(
... |
def test_expired(self):
if self.expires < datetime.now().timestamp():
return self.update()
return 0
def update(self):
headers = {
"Authorization": f"Basic {self.enc_64_client_info()}"
}
parameters = {
"grant_type": "refresh_token",
... | The function retrieves the URI of the currently playing music item from a service (e.g., Spotify) by making an authenticated API request. It first checks if a session token has expired, updating it if necessary, then fetches the current track's URI from the "/me/player/currently-playing" endpoint and returns it. | def find_current_music(self):
if self.test_expired():
self.update()
r_find = requests.get(
f"{self.baseURL}/me/player/currently-playing", headers=self.bearer_auth())
track_id = r_find.json()['item']['uri']
return track_id |
def test_expired(self):
if self.expires < datetime.now().timestamp():
return self.update()
return 0
def update(self):
headers = {
"Authorization": f"Basic {self.enc_64_client_info()}"
}
parameters = {
"grant_type": "refresh_token",
... | The main task of the code is to add the current music track to a specified playlist by sending a POST request with the track's URI. It first checks if an update is needed, constructs the request with authentication headers, and returns the HTTP status code of the response. | def add_track(self):
if self.test_expired():
self.update()
uris = {
"uris": [self.find_current_music()]
}
r_add = requests.post(f"{self.baseURL}/playlists/{self.auxiliar_playlist()}/tracks",
headers=self.bearer_auth(), json=uris)
... |
def scan_directory(path, opts):
'''Scans the given path, building a list of files that need to be included
in the project (valid source files)'''
path = os.path.normcase(os.path.normpath(path))
print(u'Scanning directory:', path)
rootSkips = [x.lower() for x in opts.skip_top_dirs]
allSkips = ... | The main task of the code is to scan a project directory, compare its files with those listed in a .vcxproj project file and its corresponding .filters file, and either report discrepancies or update the project files to match the actual files on disk. It handles header, source, and resource files, allowing users to sc... | def main():
# Get command line arguments
opts = parser.parse_args()
# Find the .vcxproj file
if opts.project and os.path.isfile(opts.project):
projFile = opts.project
elif os.path.isfile(u'CBash.vcxproj'):
# Cheat a little bit for CBash and just search directly for the project
... |
def width(self):
return self.axis_size(0)
def height(self):
return self.axis_size(1)
def axis_min(self, axis):
if self._ranges.get(axis, None) is None:
self._ranges[axis] = (
min([x[axis] for x in self.grid]),
max([x[axis] for x in self.grid]),
... | The code generates a visual grid representation of data using PIL, customizing cell sizes, colors, and text. It draws cells with specified colors, adds labeled text, handles multiple fonts, and saves the output as PNG images. The function supports dynamic grid adjustments, text placement, and optional callbacks for ext... | def draw_grid(
self,
color_map=DEFAULT_COLOR_MAP,
cell_size=(10, 10),
extra_text=None,
extra_text_rows=0,
font_size=14,
image_copies=1,
extra=None,
extra_callback=None,
text_xy=None,
show_lines=True,
default_color=(64, 64, 6... |
def x_range(self, pad=0):
return self.axis_range(0, pad=pad)
def y_range(self, pad=0):
return self.axis_range(1, pad=pad)
def width(self):
return self.axis_size(0) | The code rotates the grid 90 degrees clockwise by copying values from original positions (x, y) to new positions (y, width - x), using a temporary dictionary to preserve original values during the transformation. | def rotate(self):
temp = {}
for x in self.x_range():
for y in self.y_range():
temp[(x, y)] = self[x, y]
width = self.width() - 1
for x in self.x_range():
for y in self.y_range():
self[(y, width - x)] = temp[(x, y)] |
def x_range(self, pad=0):
return self.axis_range(0, pad=pad)
def y_range(self, pad=0):
return self.axis_range(1, pad=pad)
def width(self):
return self.axis_size(0) | The code flips the x-axis of a grid by creating a temporary copy of the original values, then replacing each position (x, y) with the value from (width - x, y), effectively mirroring the data horizontally. | def flip_x(self):
temp = {}
for x in self.x_range():
for y in self.y_range():
temp[(x, y)] = self[x, y]
width = self.width() - 1
for x in self.x_range():
for y in self.y_range():
self[(width - x, y)] = temp[(x, y)] |
def x_range(self, pad=0):
return self.axis_range(0, pad=pad)
def y_range(self, pad=0):
return self.axis_range(1, pad=pad)
def height(self):
return self.axis_size(1) | This method flips the y-axis of a grid by creating a temporary copy of the original values, then reassigning each element to its mirrored position along the vertical axis. It iterates through all coordinates, storing original values in a dictionary, then replaces each element with the value from its vertically flipped ... | def flip_y(self):
temp = {}
for x in self.x_range():
for y in self.y_range():
temp[(x, y)] = self[x, y]
height = self.height() - 1
for x in self.x_range():
for y in self.y_range():
self[(x, height - y)] = temp[(x, y)] |
def width(self):
return self.axis_size(0)
def height(self):
return self.axis_size(1)
def draw_grid(
self,
color_map=DEFAULT_COLOR_MAP,
cell_size=(10, 10),
extra_text=None,
extra_text_rows=0,
font_size=14,
image_copies=1,
extra=None,
... | The main task of the code is to generate an animation by drawing multiple frames in parallel (using multiprocessing) or sequentially. It processes each frame with parameters like color mapping, cell size, and text, updates progress, and renders grids while handling timing checks and callbacks. The animation is created ... | def draw_frames(
self,
color_map=DEFAULT_COLOR_MAP,
cell_size=(10, 10),
repeat_final=0,
font_size=10,
extra_callback=None,
show_lines=True,
use_multiproc=True,
):
from datetime import datetime, timedelta
import multiprocessing
i... |
def x_range_hex(self, y, pad=0):
if y % 2 == 0:
return [x for x in self.x_range(pad=pad) if x % 2 == 0]
else:
return [x for x in self.x_range(pad=pad) if x % 2 == 1]
def height(self):
return self.axis_size(1)
def axis_min(self, axis):
if self._ranges.get(axis, Non... | The code calculates and returns the dimensions and minimum axis values of a hexagonal grid. It determines the width as the maximum x-range length between two axes, sets the height using a dedicated method, and identifies the minimum x and y values for grid positioning. | def get_grid_hex_size(self):
return {
"width": max(len(self.x_range_hex(0)), len(self.x_range_hex(1))),
"height": self.height(),
"x_min": self.axis_min(0),
"y_min": self.axis_min(1),
} |
def get_grid_hex_size(self):
return {
"width": max(len(self.x_range_hex(0)), len(self.x_range_hex(1))),
"height": self.height(),
"x_min": self.axis_min(0),
"y_min": self.axis_min(1),
}
def y_range(self, pad=0):
return self.axis_range(1, pad=pad)
de... | This function generates a hexagonal grid image using PIL, drawing hexagons based on specified parameters like size, color map, and scaling. It creates multiple image copies, saves them as PNGs, and adjusts rendering based on 'show_all' flag, grid coordinates, and hexagonal tiling logic. | def draw_grid_hex(
self,
image_copies=1,
hex_size=10,
color_map=DEFAULT_COLOR_MAP,
size=None,
background_color=BACKGROUND_COLOR,
outline=BACKGROUND_COLOR,
show_all=False,
scale=1.0,
):
from PIL import Image, ImageDraw
hex = (
... |
def split2images_situs(split):
split_images = list(dev.keys())
split_situs = list(dev.values())
return split_images, split_situs
def situs2frames_verbs(situs):
situs_frame_verb = [situ2frames_verbs(situ) for situ in situs]
situs_frames, situs_verbs = list(zip(*situs_frame_verb))
return situs_fra... | This function processes a split input to extract roles and nouns from frames derived from a situs. It first splits the input into images and situs, converts the situs into verb-related frames, then separates these frames into roles and nouns, returning both as output. | def split2roles_nouns(split):
_, split_situs = split2images_situs(split)
split_situs_frames, _ = situs2frames_verbs(split_situs)
split_situs_frames_roles, split_situs_frames_nouns = situs_frames2roles_nouns(split_situs_frames)
return split_situs_frames_roles, split_situs_frames_nouns |
def __set_array(self, array):
if isinstance(array, np.ndarray):
self.__array = array
def __set_rowCount_and_colCount(self):
self.__rowCount, self.__colCount = self.__array.shape
def __find_mines(self):
self.__mines_list = np.where(self.__array == '*')
def __hint_numbers_generator(sel... | The code initializes a grid by setting its array, dimensions, mine positions, and generating hint numbers for a Minesweeper-like game. | def __init__(self, array):
self.__set_array(array)
self.__set_rowCount_and_colCount()
self.__mines_list = []
self.__find_mines()
self.__hint_numbers_generator() |
def write_status(self, message):
self.msglist.append(message)
self.ui.statusbar.showMessage(self.msglist[-1])
def initialize_connection(self, conn):
# connection is authorized once the client requests coils 7, 77, 777 and 7777 to be turned ON
# after receiving a write_single_coil operati... | This code implements a Modbus TCP server that listens for client connections, processes Modbus function codes (1-16) for reading/writing coils, discrete inputs, and holding/input registers, unpacks received data, validates requests, and sends appropriate responses. It maintains device status, logs operations with times... | def run(self):
self.tcp_socket.bind((self.tcp_ip, self.tcp_port))
self.tcp_socket.listen()
self.conn, self.addr = self.tcp_socket.accept()
with self.conn:
self.write_status("(" + str(datetime.now().strftime("%H:%M:%S")) +
")Connected by" + str(se... |
def handle_message(self) -> bool:
"""
This function handles incoming chat messages.
"""
if not self.update.message and self.update.effective_chat:
self.bot.send_message(
chat_id=self.update.effective_chat.id, text="send text"
)
return ... | The main task of the code is to execute the program's core functionality by handling a message, reading another message, and retrieving an answer. It first processes a message using `handle_message()`, checks for validity, then reads a message with `read_message()`, validates it, and finally calls `get_answer()` to pro... | def main(self) -> Any:
"""
Execute the main functionality of the program.
"""
ia = self.handle_message()
if not ia:
return
mm = self.read_message()
if not mm:
return
self.get_answer()
return |
def is_prime(n):
alist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
if n == 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
for a in alist:
if n == a:
return True
if not... | The code implements Pollard's Rho algorithm to factorize a composite number $ n $ into its prime factors. It recursively applies the algorithm to find non-trivial divisors of $ n $, using modular arithmetic and greatest common divisors (gcd) to detect factors, returning prime factors once identified. | def pollardRho(n):
if is_prime(n):
return n
if n == 1:
return 1
if n % 2 == 0:
return 2
x = random.randrange(2, n)
y = x
c = random.randrange(1, n)
d = 1
while d == 1:
x = ((x ** 2 % n) + c + n) % n
... |
def _bottomRightAlien(self):
"""
Return the bottom right alien in the 2D _aliens list
"""
for i in reversed(self._aliens):
if i is not None:
for alien in i:
if alien is not None:
return alien
def _shiftAlienDown(self... | This method controls the movement of aliens across the screen by updating their direction and position based on elapsed time. It checks if aliens have reached screen edges, reverses their horizontal direction when necessary, and shifts them downward when changing direction. The movement speed is determined by the accum... | def _alienTime(self,dt):
"""
Method to march the aliends across the screen.
It determines when and which direction the aliens should be moving
Parameter dt: The time in seconds since last update
Precondition: dt is a number (int or float)
"""
self._time = self._t... |
def _randomFire(self):
"""
Pick a random number of steps between 0 and BOLT_RATE to make aliens
fire randomly.
Number of steps are numbers from 0 to BOLT_RATE(inclusive)
"""
self._stepRandom = random.randint(1,BOLT_RATE)
def _moveShip(self,direction):
"""
... | This method updates game elements (ship, bolts, aliens) by handling movement, firing, collisions, and game state checks. It processes direction input, updates positions over time (dt), creates projectiles, checks for collisions between ship/alien bolts, and verifies if aliens have passed the defense line or been elimin... | def update(self,direction,dt,game):
"""
Method to update ship, bolt, alien
Parameter direction: direction of ship
Precondition: direction is either left or right
Parameter dt: The time in seconds since last update
Precondition: dt is a number (int or float)
Par... |
def handle_rate(self, resp, states, stage):
rate_message = []
if states:
finalMessage = None
for state in states:
print(finalMessage)
if finalMessage:
finalMessage.append("\n")
else:
finalMess... | The function retrieves and processes case data from an API based on country, stage, and parameters like 'states', 'top_bottom', or 'rate'. It formats and returns tailored messages (e.g., state-specific stats, top/bottom rankings, or rate calculations) depending on input flags, using helper methods. Debugging info is pr... | def get_count_by_country(self, country, stage, states, top_bottom, rate,sender_id):
cases_url = self.base_url + "cases?country={countryVal}".format(
countryVal=country
)
# Get some debugging info about the cache
print(self.session.cache)
print('Cached URLS:', self.ses... |
def f_tf (self , t, X, Y, Z):
# nonlinear term
return -tf.reduce_sum(tf.square(Z), 1, keepdims=True)
def _one_time_net (self , x, name ):
with tf.compat.v1.variable_scope ( name ):
x_norm = self . _batch_norm (x, name ='layer0_normal')
layer1 = self . _one_layer (x_norm ,... | The code builds a neural network for time-dependent computations using TensorFlow 1.x. It initializes placeholders for input data (dW, X) and training mode, defines variables (Y0, Z0) for initial conditions, and iteratively updates states (Y, Z) over time steps via custom functions f_tf and _one_time_net. The network c... | def build ( self ):
start_time = time . time ()
# build the whole network by stacking subnetworks
self .dW = tf.compat.v1.placeholder (tf. float64 ,
[None , self.d, self. n_time ],name ='dW')
self .X = tf.compat.v1.placeholder (tf. float64 ,[None , sel... |
def get_overlay():
_, frame = camera.read()
img = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
h, w, _ = img.shape
# get overlay, resize to fit height of bg whilst matching aspect ratio
overlay = cv2.imread("layout.png")
overlay_h, overlay_w, _ = overlay.shape
percentage = h / overlay... | The code connects to a server, initializes hand tracking via MediaPipe, and processes real-time camera input to detect hand gestures. It overlays interactive elements on the video feed, draws hand landmarks, and generates controller inputs based on detected hands. The loop continues until Esc is pressed, releasing reso... | def main():
s.connect((SERVER_MAC, PORT))
overlay = get_overlay() # get overlay using 1st frame
while camera.isOpened(): # run application
_, frame = camera.read()
img = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
height, width, _ = img.shape
img.flags.writeable =... |
def center_target_on_pose(whole_body, base, gripper, OSVOS, img_sub, pose_file, s_des, Je_pinv, pose_filter = [], error_max = 30):
load_pose(whole_body, pose_file, pose_filter)
error_sum = 100
error_logic = abs(Je_pinv).sum(axis=0) > 0
while error_sum > error_max:
mask, n_mask_pxls = get_mask(img_sub, OSVOS)
if... | The code's main task is to control a robotic arm to grasp a target object using visual feedback. It adjusts the arm's position and wrist orientation based on the object's detected position (mask_center_init), employing different Jacobian matrices and target configurations to achieve precise grasping. The function itera... | def grab_target(whole_body, base, gripper, OSVOS, img_sub, name, mask_center_init):
w_max_iv = 350; w_min_wr = 235
s_des_iv = [240, 330]; s_des_ps3_x_grasp = [240, 220];
s_des_ps3_tri = [240, 180]
Je_pinv = np.array([[0, -0.001],[0.001, 0]])
Je_pinv_tri = np.array([[0, -0.001],[0.0002, 0]])
Je_pinv_lat = np.array... |
def load_pose(whole_body, pickle_file, filter_list = []):
pose = pickle.load(open(pickle_file, 'rb'))
for i, pose_name in enumerate(filter_list):
del pose[pose_name]
whole_body.move_to_joint_positions(pose)
def largest_region_only(init_mask):
labels = label(init_mask)
bin_count = np.bincount(labels.flat)
if len... | The code's main task is to control a robot to detect, grasp, and place colored blocks using computer vision (OSVOS). It segments objects in the grasp image, identifies target positions, and executes grasping and placement actions based on mask analysis. The robot iteratively processes blocks, prioritizing them by posit... | def main(OSVOS, grasp_img_sub, robot_state_sub, base_odometry_sub, base, whole_body):
gripper = robot.get('gripper')
names = ['r','y','b']
r_dir = './r.ckpt-10001'
y_dir = './y.ckpt-10001'
b_dir = './b.ckpt-10001'
dirs = [r_dir, y_dir, b_dir]
cab_pos = ['tll','tr','tl']
n_targets = len(names)
print ('\n\nRobo... |
def getAllTeamsByLeague(path):
teams = []
driver = initDriver()
driver.get(path)
time.sleep(2)
teamsList = driver.find_elements_by_xpath("//*[starts-with(@id, 'standings-')]/tr[*]/td[*]/a[@class='team-link ']")
i = 0
while i < len(teamsList):
anchor = teamsList[i]
teamURL = anchor.get_attribute("h... | The main task of the code is to aggregate unique football teams from multiple leagues (La Liga, Premier League, etc.), retrieve all links associated with each team's website, and process data from those links. It iterates through each team, prints progress updates, and collects data using the `getDataByLinks` function,... | def getJsonFromAllTeams():
teams = getAllTeamsByLeague(LA_LIGA_ENDPOINT)
teams += getAllTeamsByLeague(PREMIER_LEAGUE_ENDPOINT)
teams += getAllTeamsByLeague(SERIE_A_ENDPOINT)
teams += getAllTeamsByLeague(BUNDESLIGA_ENDPOINT)
teams += getAllTeamsByLeague(LIGUE_1_ENDPOINT)
teams += getAllTeamsByLeague(UCL_ENDP... |
def askNumber():
right=False
num=0
while(not right):
try:
num = int(input("Enter a number: "))
right=True
except ValueError:
print('Error, please enter a valid number')
return num
def getAllLinksTeam(baseURL):
driver = initDriver()
driver.get(baseURL)
i = 0
links = []
time.sl... | The code provides a menu-driven interface to retrieve sports match and team data from Whoscored.com. Users can fetch JSON data via URLs, select teams from major leagues (LaLiga, Premier League, etc.), get live match updates, and monitor ongoing matches. It includes functions for data extraction, live match tracking, an... | def menu():
toQuit = False
option = 0
while not toQuit:
print ("1. Get JSON data entering team URL")
print ("2. Select team from LaLiga")
print ("3. Get JSON data entering single match")
print ("4. Get JSON data from La Liga (Spain), Premier League (England), Serie A (Italy), Bundesliga (Germany),... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.