dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def load_variable(self, name_of_variable, path='./'): # https://stackoverflow.com/questions/6568007/how-do-i-save-and-restore-multiple-variables-in-python file_address = path + name_of_variable + '.pckl' f = open(file_address, 'rb') variable = pickle.load(f) f.close() ret...
The main task of the code is to train a model using Particle Swarm Optimization (PSO) to determine optimal quantization levels for data transformation. It applies Discrete Cosine Transform (DCT) blockwise, quantizes the transformed data based on the optimized levels, and performs Fisher Discriminant Analysis (FDA) on t...
def fit(self, X, y, path_to_save_base, load_previous_fit=False): self.X_train = X self.y_train = y if load_previous_fit: path_to_save = path_to_save_base + "/reg_par1=" + str(self.regularization_parameter1) +", reg_par2=" + str(self.regularization_parameter2) + "/" self.U...
def DCT_blockwise(self, X): # X, X_dct: columns are samples, rows are features X_padded = self.zero_pad_if_necessary(X=X) n_blocks_in_height = int(self.padded_image_height / self.block_size) n_blocks_in_width = int(self.padded_image_width / self.block_size) X_dct = np.zeros(X_pad...
The code tests two image processing scenarios using DCT: (1) For test_index=1, it applies blockwise DCT, quantizes coefficients with 15.4 levels, calculates compression rate, and reconstructs images via inverse DCT. (2) For test_index=2, it evaluates a cost function using 2.3 quantization levels. Both cases involve pri...
def test_functions(self, X, y, test_index): self.X_train = X self.y_train = y np.random.seed(555) if test_index == 1: X_dct = self.DCT_blockwise(X=X) n_quantization_levels_array = 15.4 * np.ones((64,)) # n_quantization_levels_array = 250 * np.ones((64,...
def load_papers(source="s2ag", sample=True) -> List[Dict]: """Load papers from source.""" if source != "s2ag": raise NotImplementedError("Sorry, only 's2ag' source is supported.") if not sample: raise NotImplementedError("Sorry, only sample data loading is supported.") if source == "s2ag...
(The code's main task is to process academic papers by loading them, deduplicating entries, saving the cleaned data as JSONL files locally, and uploading the results to an S3 bucket using specified configurations. The process is logged for tracking, ensuring data consistency and cloud storage accessibility.)
def main(): logger.info("Starting with configurations: %s", config) logger.info("Loading papers.") sample_s2ag_papers = load_papers() sample_s2ag_papers_deduped_df = deduplicate_papers(sample_s2ag_papers) save_df_as_jsonl(sample_s2ag_papers_deduped_df, config["output"]["local_path"]) upload_outp...
def sheep_move(self): log = "Debug level: sheep_move " logging.debug(log) for i in range(self.sheep_number): if self.sheep_list[i].alive: self.sheep_list[i].move() def wolf_attack(self): for i in range(self.sheep_number): if self.sheep_list[i].ali...
The code simulates a predator-prey interaction over multiple turns. It moves sheep, checks wolf attacks, updates positions, tracks alive sheep and eaten counts, logs data to JSON/CSV files, and pauses each round for user input. The loop terminates if no sheep remain.
def start_simulation(self): log = "Debug level: start_simulation " logging.debug(log) for i in range(self.turns_number): if self.alive_sheep_number == 0: return self.sheep_move() if self.wolf_attack(): self.wolf_move() ...
def split(root: Node, key: int) -> Tuple[Node, Node]: """ We split current tree into 2 trees with key: Left tree contains all keys less than split key. Right tree contains all keys greater or equal, than split key """ if root is None: # None tree is split into 2 Nones return (None, Non...
The function `interactTreap()` processes user commands to insert or delete keys in a treap data structure. It continuously accepts input commands (`+ key` to add a key, `- key` to remove all nodes with the key), updates the treap using `insert` or `erase` functions, and prints the treap's state after each operation. Th...
def interactTreap(): """ Commands: + key to add key into treap - key to erase all nodes with key After each command, program prints treap """ root = None while True: cmd = input().split() cmd[1] = int(cmd[1]) if cmd[0] == "+": root = insert(root, cmd[...
def forward_propagation_one_ex(self, i, e): """ description: forward propagation for one training example; data x label y ---parameter--- i: index """ # self.gradient_checking() # X = minmax_scale(self.X[i,:,:], feature_range = (0, 1), axis = 0) ...
This code trains a neural network model (Detector) using gradient descent. It iterates over epochs, processes each training example with forward propagation to compute loss, performs backpropagation to update weights, and tracks cumulative loss. The model predicts outputs, adjusts parameters via learning rate, and prin...
def train(self, songs): lr = self.lr loss = [] print("Starting to train Detector..........") for e in range(self.epoch): print("Epoch {}/{}".format(e, self.epoch)) lost = 0 for i in progressbar.progressbar(range(self.m)): total_lost, Y_...
def read_prefs(pref_1_filename, pref_2_filename): # This function reads preferences from two files # and returns two-dimensional preference lists and the length of a list. with open(pref_1_filename, 'r') as f: hospital_raw = f.read().splitlines() with open(pref_2_filename, 'r') as f: stu...
The main task of the code is to handle different parts of a matching problem based on the input arguments. It reads hospital and student preferences, then executes either the Gale-Shapley algorithm (Q1) to generate a stable matching, checks the stability of a provided matching (Q2), or verifies the uniqueness of the ma...
def main(): # Do not modify main() other than using the commented code snippet for printing # running time for Q1, if needed if(len(sys.argv) < 5): return "Error: the program should be called with four arguments" hospital_prefs_raw = sys.argv[1] student_prefs_raw = sys.argv[2] match_fi...
def get_message(): webhook = request.json url = 'https://webexapis.com/v1/messages/' + webhook["data"]["id"] get_msgs = requests.get(url, headers=webex_api_header, verify=True) message = get_msgs.json()['text'] return message def get_trello_cards(board_id, list_name): list_id = get_trello_list_id(board_id,...
This code processes incoming Webex messages, parses user commands, interacts with Trello API to manage boards/cards, and sends formatted markdown responses. It handles commands like listing cards, creating lists/cards, and secret commands, while validating inputs and providing feedback through Webex.
def send_message(): webhook = request.json url = 'https://webexapis.com/v1/messages' msg = {'roomId': webhook["data"]["roomId"]} sender = webhook["data"]["personEmail"] message = get_message().lower() # .lower() is only needed for case-insensitive string comparison (in this way commands are recognized regardless o...
def refresh_static_data(self): """ This method sets data that can't be changed from the dvd settings window. It must be called before painting a menu """ if self.config.PAL: self.y=576.0 else: self.y=480.0 self.title_list = [] counter = 0 ...
The main task of the code is to generate DVD menu assets by creating multiple background image variations (unselected, selected, active) for each page, converting them into MPEG files using a menu converter, and returning the list of conversion processes and menu entry data. It organizes outputs in a specified director...
def create_dvd_menus(self, file_list, base_path): self.file_list = file_list self.refresh_static_data() cv = devedeng.converter.converter.get_converter() menu_folder = os.path.join(base_path,"menu") try: os.makedirs(menu_folder) except: pass ...
def read_next_number(file): num_str = file.readline() if num_str != "`\n" and num_str != '': num = int(num_str.replace("\n", "")) return num return None def DataPrepare(B, C): B1 = [] B2 = [] CurrentB1 = True temp = B[0] while B != []: B.pop(0) if B == ...
The main task of the code is to implement a polyphase merge sort algorithm, which externally sorts a large dataset by iteratively merging sorted runs from multiple files (mainLine.txt, buf1.txt, buf2.txt). It splits input data into halves, prepares runs, and alternates input/output files to merge runs of increasing siz...
def PolyphaseMergeSort(): A = [] with open('mainLine.txt', 'r') as mainLine: num = read_next_number(mainLine) while num is not None: A.append(num) num = read_next_number(mainLine) B = A[:len(A)//2] C = A[len(A)//2:] print(B, C) DataPrepare(B, C) runMin...
def graph_info(G, verbosity=True): '''count clusters, nodes, terminals and edges of G''' terminals = get_terminals(G) n_clusters = len(extract_proper_clusters(G)) n_nodes, n_edges, n_terminals = len(G.nodes()), len( G.edges()), len(terminals) if verbosity == True: print('Number of ...
The main task of the code is to trim a graph by iteratively removing edges based on a landscape function and a range of alpha values until a specified condition on the graph's properties is satisfied, then returning the resulting connected sub-graphs (clusters). The process involves computing graph properties, evaluati...
def trim_graph_landscape(G, box_size, condition, sigma, verbosity=False): '''Trims graph using the landscape function. We scan over a range of values of alpha, and stop when a condition over the trimmed graph properties is satisfied. Outputs a list of connected sub-graphs (clusters). ''' # copy original gra...
def num_periods(self): return len(self._uf) def set_graph_period_attribute(self, name, values): """Set graph attribute per period. Args: name (str): name of the attribute values (int or float or list): list of values per period, or a number if constant """ ...
This code initializes a graph object with period-based attributes, discount factors, and STP file parsing capabilities. It sets up multi-period graph structures by configuring period suffix formats, node/edge attributes, and discount factors. The class handles graph, node, and edge period attributes, enabling time-depe...
def __init__( self, root_node: int = None, discount_factors=None, stp_file=None, default_prize=1, default_weight=1, node_period_attributes: dict = None, edge_period_attributes: dict = None, graph_period_attributes: dict = None, graph_period...
def get_tabs(self): tabs = [] for i,markdown in enumerate(os.listdir(os.path.join(self.project_name,"tabs"))): if(markdown[-2:] !="md"): continue with open(os.path.join(self.project_name,"tabs",markdown),"r") as markdownfile: template = self.compil...
The code compiles markdown files in a project's "pages" directory into HTML files, storing metadata like name, date, and index in a list. It generates an "index.html" page by rendering a template with reversed post entries and tabs, enabling dynamic content organization and updates for a static website.
def compile(self): #compile all markdown files in the directory,and refresh index page posts = [] tabs = self.get_tabs() for i,markdown in enumerate(os.listdir(os.path.join(self.project_name,"pages"))): if(markdown[-2:] !="md"): continue with open(...
def connect(): global connected global con global cursor try: con = db.connect( host = "localhost", database = "umc", port = 5432, user = "azis", password = "123" ) cursor = con.cursor() connected = True except: connected = False return cursor def insert_data(): global connected global ...
The code defines a function `show_menu(sql)` that displays a database management menu with options to insert, view, update, delete, search data, or exit. Based on user input, it calls corresponding functions like `insert_data()`, `show_data(sql)`, etc., using the provided SQL parameter where relevant. The menu handles ...
def show_menu(sql): print("\n=== APLIKASI DATABASE PYTHON ===") print("1. Insert Data") print("2. Tampilkan Data") print("3. Update Data") print("4. Hapus Data") print("5. Cari Data") print("0. Keluar") print("------------------") menu = input("Pilih Menu: ") a = connect() if menu == "1": insert_data() el...
def generate_population(pop_size, cities): return [random.sample(list(cities.keys()), len(cities)) for _ in range(pop_size)] def evolve_population(population, cities): p1, p2 = random.sample(population, 2) child = crossover_and_mutate(p1, p2) worst_route = max(population, key=lambda route: r...
The code implements a genetic algorithm to solve the Traveling Salesman Problem (TSP). It generates an initial population of routes, iteratively evolves them through selection and crossover, and selects the shortest route after specified iterations. The function returns the optimal route and its total distance, minimiz...
def run_genetic_algorithm(cities, pop_size, num_iterations): population = generate_population(pop_size, cities) for _ in range(num_iterations): evolve_population(population, cities) best_route = min(population, key=lambda route: route_distance(route, cities)) best_distance = route_dist...
def _get_warning(self): if len(self.warning) == 0: return "" return "WARNING :\n\t" + "\n\t".join(self.warning) + "\n\n\n" def _get_result(self) -> str: a = "RESULTS :\n" a+= " " + " Model | Optimizer | Dataset || optimization_parameters || accura...
The main task of the code is to generate a string representation of an object by concatenating outputs from multiple private methods, including warnings, results, remaining tasks, general information, thread details, and epoch lines, providing a consolidated summary of the object's state and progress.
def __str__(self): a = self._get_warning() a += self._get_result() a += self._get_task_remaining() a += self._get_general_info() a += self._get_thread() a += self._get_epoch_line() return a
def parse_ID(self): return self.parse_element(0, 'ID') def parse_with_ignore(self, parse): ignore_was = self.ignore self.ignore = True res = parse() self.ignore = ignore_was return res def parse_shtopor(self): return self.parse_element(0, 'SHTOPOR') def parse_body...
The main task of the code is to parse an "R" structure by first parsing an ID, then conditionally parsing a dot (if not ignored). If the dot parsing fails, it proceeds to parse "shtopor" and "body" components, ensuring structural validation. The function ultimately returns True upon successful parsing.
def parse_R(self): self.parse_ID() if not self.parse_with_ignore(self.parse_dot): self.parse_shtopor() self.parse_body() return True
def parse_opening_bracket(self): return self.parse_element(1, '(') def parse_body(self): # BODY -> (M;)*M # ; = + self.parse_list(self.parse_M, self.parse_semicolon) def parse_closing_bracket(self): return self.parse_element(1, ')')
The method 'parse_brackets' sequentially processes a bracket-enclosed structure by parsing the opening bracket, the internal content (body), and the closing bracket, ensuring syntactic correctness and structural integrity in the parsed data.
def parse_brackets(self): self.parse_opening_bracket() self.parse_body() self.parse_closing_bracket()
def parse_R(self): self.parse_ID() if not self.parse_with_ignore(self.parse_dot): self.parse_shtopor() self.parse_body() return True def check_end(self): if self.end: self.ignore = False self.error() def parse_dot(self): return self...
This function parses an input string `s` by repeatedly calling `parse_R`, `check_end`, and `parse_dot` until the string is fully processed. It handles exceptions during parsing, returning 1 if an error occurs, or 0 if no errors are found, indicating successful parsing.
def parse_S(self, s): self.s = s self.end = len(s) == 0 try: while not self.end: self.parse_R() self.check_end() self.parse_dot() except Exception as e: print(e) return 1 print('No errors occurred...
def parse_with_ignore(self, parse): ignore_was = self.ignore self.ignore = True res = parse() self.ignore = ignore_was return res def parse_brackets(self): self.parse_opening_bracket() self.parse_body() self.parse_closing_bracket() def parse_ID(self): ...
This method parses an atom by checking if it starts with an opening bracket (using parse_with_ignore). If true, it parses brackets; otherwise, it parses an identifier (ID). The main task is to determine the atom's structure and trigger the appropriate parsing logic.
def parse_atom(self): if self.parse_with_ignore(self.parse_opening_bracket): self.parse_brackets() else: self.parse_ID()
def loadData(valid = False): global k, epochs, trainData, validData, num_pts, dim, trainLoss, validLoss k = 3 # Set number of clusters epochs = 500 # Set number of epochs. Set to 800 for 100D # trainData = np.load('data100D.npy') # Comment either this or 2D trainData = np.load('data2D.npy') [n...
The code implements a Gaussian Mixture Model (GMM) using TensorFlow. It loads data, builds a computational graph with optimizer, loss function, and cluster parameters (centroids, variances, weights). It trains the model over epochs, computes training loss, and assigns data points to clusters. If validation is enabled, ...
def GMM(valid = False): loadData(valid) # Load the Data optimizer, loss, logPosterior, centroid, variance, weight, trainingInput = buildGraph() init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(0,epochs): _, trainLoss[i], mU, v...
def initialize_metric_trackers(self) -> None: """Initializes TensorFlow trackers which computes the mean of all metrics. Initializes TensorFlow trackers which computes the mean of all metrics. Args: None. Returns: None. """ self.train_loss = tf....
This code trains and validates a neural network model over multiple epochs using provided datasets. It initializes metrics, tracks training/validation loss and accuracy, updates history logs, and implements early stopping if performance stagnates. The function iterates through epochs, trains the model on batches, valid...
def fit(self) -> None: """Trains & validates the loaded model using train and validation dataset. Trains & validates the loaded model using train and validation dataset. Args: None. Returns: None. """ # Initializes TensorFlow trackers which comp...
def waitForAllPlayers(self): while True: active = True for player in self.State['players']: if player.State['active'] == False: active = False break if active: return def setState(self, keyVa...
This code initializes a game by waiting for players, setting the game mode to 'ACTIVE', and broadcasting initial setup data (players, categories, scores) to all players. It then transitions the game to 'RUNNING', sets the first turn, and broadcasts the initial game state. The loop continuously receives and processes pl...
def run(self): print('Inside game thread') self.waitForAllPlayers() self.setState(dict( gameMode = 'ACTIVE', )) pck = dict( type = 'HAND_SHAKE', players_count = self.State['allowed_players'], categories = self.board.State['catego...
def stopped(self): return self.State['_stop'].isSet() def updateState(self): self.delete_complete_games() self.switch_inactive_to_active_list() def addPlayer(self, player): ADD_SUCCESSFUL = False for i in range(self.State['inactive_count']): game = self.State...
The code initializes a game server controller, starts a connection listener to accept incoming player connections, and processes each connected player in a separate thread. It continuously checks for new players, retrieves them from a queue, initiates handshake protocols, and registers players. The loop runs until the ...
def run(self): print('GameController Started') listener_attr = dict( IP = SERVER_IDENTITY['IP'], PORT = SERVER_IDENTITY['PORT'] ) connectionlistener = ConnectionListener(**listener_attr) connectionlistener.start() while self.stopped() == False: ...
def get_all_tables(self): for table in set(self.client.list_tables(self.dataset_id)): self.tables.add(self.get_single_table(table.table_id)) return self.tables def createTable(self, table): if table.table_id not in self.table_dict: self.table_dict[table.table_id] = self.c...
The main task of the code is to convert all tables into a JSON format. It initializes a dictionary, iterates through each table using `get_all_tables()`, processes each table with `createTable()`, and finally writes the collected data into a JSON file using `write_to_json()`. This method aggregates table data into a st...
def all_tables_to_json(self): self.table_dict = dict() for table in self.get_all_tables(): self.createTable(table) self.write_to_json()
def sentiment_valence(self, valence, sentitext, item, i, sentiments): is_cap_diff = sentitext.is_cap_diff words_and_emoticons = sentitext.words_and_emoticons item_lowercase = item.lower() if item_lowercase in self.lexicon: #get the sentiment valence valence = self...
This function analyzes text to determine sentiment polarity by evaluating words, emoticons, and contextual modifiers. It processes each word/emoticon, checks for boosters or specific phrases, calculates valence scores, adjusts for negations using '_but_check', and returns a dictionary with positive, negative, and neutr...
def polarity_scores(self, text): """ Return a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence. """ sentitext = SentiText(text) #text, words_and_emoticons, is_cap_diff = self.preprocess...
def get_request(function: str, url: str) -> requests.Response | None: """ Send a request to a webpage and returns the response. :param function: The name of the calling function. :param url: The url to connect to. :return: The response. If error 404, returns None. """ global T_R global ...
The function processes GitHub Actions in a specified category by checking each action's validity through its Marketplace page and GitHub link. It extracts data such as repository details, verification status, and metrics (versions, dependents, contributors, stars, etc.), storing valid, unprocessed actions in a dictiona...
def thread_data(pages: list, category: str, save_data: dict, already_fetched: list) -> None: """ For each Action on a category: - Check if it has a valid MP page. - If so, check if it has a valid link to a github page. - If so, get some data about it. :param pages: The list of pages...
def header_normal_state(last_state, line, info): new_state = state.Normal if line.startswith('/*'): info['comment'] = line if not line.replace(' ', '').endswith('*/\n'): new_state = state.MultiComment else: new_state = state.Comment elif line.startswi...
The code parses a header file to extract macros, typedefs, and exports using a state machine. It reads the file line-by-line, transitions between states (e.g., Normal, Comment, Macro), and populates the `info` dictionary with parsed data. Finally, it returns the extracted macros, typedefs, and exports.
def get_header_content(header): f = open(header, 'r') if not f: print('ERROR: Could not open header {}'.format(header)) return info = { 'depth': 0, 'comment': "", 'macros': "", 'typedefs': "", 'exports': "" } current_state = st...
def delete_cropped_images_from_storage(): # current dateTime now = datetime.now() # convert to string date_time_str = now.strftime("%Y-%m-%d#%H:%M:%S") count = 0 # delete local history folder for file in os.listdir(dest): os.remove(dest + file) # delete local uploads folde...
The main task of the code is to process an image by detecting and cropping products using two models (DETR and fine-tuned DETR), then storing the results and visualizing the detected objects with bounding boxes. It loads models, cleans storage, runs object detection, filters bounding boxes, crops products, and plots th...
def main(): # load detr model and OCR-Donut-CORD model captioner = pipeline('image-to-text', model='jinhybr/OCR-Donut-CORD') # delete all images from storage in folder cropped and related document delete_cropped_images_from_storage() delete_old_detected_products() # load detr model a...
def run_worflow(my_image, my_model): # mean-std normalize the input image (batch-size: 1) img = transform(my_image).unsqueeze(0) # propagate through the model outputs = my_model(img) return outputs def filter_bboxes_from_outputs(outputs,im, threshold=0.8): # keep only pred...
The code's main task is to perform object detection on an image ('milk535.png') using a pre-trained model. It processes the image through a workflow, extracts bounding box probabilities and coordinates, filters relevant detections, and visualizes the results by overlaying the detected objects on the original image with...
def predict(): img_name = './milk535.png' im = Image.open(img_name) outputs = run_worflow(im, model) prob, boxes = filter_bboxes_from_outputs(outputs, im=im) return plot_finetuned_results(im, prob, boxes)
def run_worflow(my_image, my_model): # mean-std normalize the input image (batch-size: 1) img = transform(my_image).unsqueeze(0) # propagate through the model outputs = my_model(img) return outputs def filter_bboxes_from_outputs(outputs,im, threshold=0.8): # keep only pred...
This function handles file uploads by saving the received image to a server directory, storing its path in a session, processing it with a model to detect objects, and returning annotated results with bounding boxes. It secures filenames, uses Flask's session storage, and leverages image processing libraries for analys...
def uploader(): if request.method == 'POST': file = request.files['file'] # Extracting uploaded data file name img_filename = secure_filename(file.filename) # Upload file to database (defined uploaded folder in static path) file.save(os.path.join(app.config['UPLOAD_FOLDER'], i...
def run_worflow(my_image, my_model): # mean-std normalize the input image (batch-size: 1) img = transform(my_image).unsqueeze(0) # propagate through the model outputs = my_model(img) return outputs def filter_bboxes_from_outputs(outputs,im, threshold=0.8): # keep only pred...
The code defines a Flask route handling image uploads. It processes POST requests, validates file input, loads an image, runs an object detection model, filters bounding boxes, and returns visualized results. If no file is uploaded, it displays an error message and a form for uploading images. The main task is to detec...
def test(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] im = Image.open(file) outputs = ...
def draw_map(map_to_draw): px = GAME_OBJECTS["PLAYER"].x py = GAME_OBJECTS["PLAYER"].y rx = -1 ry = -1 w = constants.CELL_WIDTH h = constants.CELL_HEIGHT adj_w = int(constants.SCREEN_WIDTH/2) adj_h = int(constants.SCREEN_HEIGHT/2) for x in range(px-adj_w,px+adj_w): rx+=1 ...
The main task of the code is to render the game's current state on the screen by clearing the background, drawing the game map, rendering all game objects, displaying debug information and messages, and updating the display with pygame.display.flip().
def draw_game(): #global SURFACE_MAIN # CLEAR SURFACE SURFACE_MAIN.fill(constants.COLOR_DEFAULT_BG) # DRAW MAP draw_map(GAME_MAP) # Draw objects for obj in GAME_OBJECTS.values(): obj.draw() # draw debug menu draw_debug() draw_message() # UPDATE DISPLAY pygame...
def select_monsters(level, game_map): creature_player = comp_Creature("Carl", isplayer=True, hp=constants.INIT_HP, atk=constants.INIT_ATK, ini=1, ...
This code initializes a roguelike game environment by setting up window dimensions, map generation with walkable areas and walls, player and monster placement, field-of-view (FOV) calculations using a torch light source, and rendering the game map, GUI, and debug information for a turn-based dungeon exploration experie...
def __init__(self, window_width, window_height, cell_size, map_width, map_height, map=None, game_objects=None, level=1, light_source="torch"): self.turn = 0 self.game_messages = [] self.fps = 0 self.game_messages.append(("Welcome to RogueLight!", constants.COLOR_YELLOW))...
def game_handle_keys(): #TODO get player input event_list = pygame.event.get() #TODO process input for event in event_list: if event.type == pygame.QUIT: return "QUIT" if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: GAME_OBJECTS["PLA...
The main task of the code is to manage a game loop that processes player input, updates game state (including light source mechanics, mana, and turn counters), triggers AI actions for game objects, updates field-of-view maps, and renders the game at a fixed FPS, terminating when the player's HP drops below 1 or the pla...
def game_main_loop(): global TURN, LIGHTSOURCE, TORCH_COUNTER, MAGIC_COUNTER, TORCH_RADIUS, MANA global FOV_MAP, IMAP, COL_MAP_R, COL_MAP_G, COL_MAP_B game_quit = False # definition of action player_action = "idle" while not game_quit: TURN+=1 if LIGHTSOURCE=="torch": ...
def checkWinner(board): if board[1] == board[2] == board[3] == board[4] == board[5] and (board[5] != ' '): return True elif (board[6] == board[7] == board[8] == board[9] == board[10] ) and (board[6] != ' '): return True elif board[11] == board[12] == board[13] == board[14] == board[15] and (...
The code defines a game loop that alternates between a player's move and a bot's move until a winner is determined. The loop continues running as long as `checkWinner(board)` returns `False`, ensuring gameplay persists until a winning condition is met.
def game(): while not checkWinner(board): playerMove(board) botMove()
def get_names(result) -> tuple[str, str]: # Result to tuple of ligand names nm = list(result['unit_results'].values())[0]['name'] toks = nm.split() if toks[2] == 'repeat': return toks[0], toks[1] else: return toks[0], toks[2] def get_result_energies(results, time, timestep): ...
The function processes simulation results from JSON files in a specified directory by filtering valid results, organizing them into a structured dictionary grouped by simulation names and types, extracting energy data based on given time and timestep parameters, and writing the compiled output to a specified location.
def analyze_all_results(resultsdir, time, timestep, output): # Find all possible jsons json_fns = glob.glob(str(resultsdir) + '/*json', recursive=True) # Filter only results jsons results_fns = filter(is_results_json, json_fns) # pair legs of simulations together into dict of dicts leg...
def show_mark(self, pos, player, row, col, saved_marks): click_sound.play() self.closest_click(pos) # If player is X if player == 1: self.cross_rect = cross.get_rect(center = (self.coor_x, self.coor_y)) WIN.blit(cross, (self.cross_rect)) # If player is O if player == 2: self.circle_rect = circle....
The code updates the game screen with the player's mark, checks for a win or tie, displays the result, and handles replay logic. If a win/tie occurs, it shows the outcome, prompts for replay, resets the board if replayed, switches the player, and restarts the game. It returns updated saved marks after processing.
def update_screen(self, pos, row, col, saved_marks): # Saves the spot that the player chose # Shows the mark on the screen # Checks if there is a winner self.show_mark(pos, self.player, row, col, saved_marks) global run if self.board.get_winner(row, col, self.player, saved_marks): self.show_winner(self...
def bfs(start, end, edges): paths = [[start]] visited_nodes = [start] index = 0 while(index<len(paths)): selectedPath = paths[index] selectedNode = selectedPath[-1] for item in edges: if(item[0] == selectedNode): visited_nodes.append(item[1]) ...
The function performs an uninformed search on a graph defined in a file, using specified methods (BFS, DLS, IDDFS, UCS). It reads the graph's edges, processes them, and delegates to the chosen search algorithm to find a path from the start to goal node, returning results like path, visited nodes, or cost.
def UnInformedSearch(method_name, problem_file_name, maximum_depth_limit): edges = [] with open(problem_file_name) as file: lines = file.read().splitlines() for item in lines[2:]: edges.append(item.split()) for element in edges: element[2] = int(element[2]) if meth...
def ucsMaze(start, end, mazeArray): queue = [] queue.append([start]) #a list containing the paths visited = [] #a list containing the processed positions in the maze while(len(queue)>0): path = queue[0] selectedPosition = path[-1] queue.remove(queue[0]) i...
This function performs informed search (UCS or AStar) on a maze or puzzle problem. It reads input from a file, parses start/end positions and grid data, then applies the specified algorithm to solve the problem, returning the solution path.
def InformedSearch(method_name, problem_file_name): with open(problem_file_name) as file: lines = file.read().splitlines() if(problem_file_name[0] == 'm'): start = (int(lines[0][1:lines[0].index(',')]), int(lines[0][lines[0].index(',')+1:-1])) #x,y positions of the start tuple ...
def setup_optim(args, model, rank): '''Setup the optimizer based on simulation and runtime configuration. Always Returns: optimizer, None, None When not simulating: optimizer, epoch_list, scheduler''' # if simulating variant 1: LR depends on worker rank! # for the attack thread (worker == 0), use...
The main task of the code is to train a machine learning model on the CIFAR-10 dataset using PyTorch, with configurable modes for normal training, attack simulation (stale learning rate or stale parameters), or baseline training. It initializes the optimizer, scheduler, and data loaders, handles distributed training vi...
def train(rank, args, model, device, dataloader_kwargs): """The function which does the actual training Calls train_epoch once per epoch, each call is an iteration over the entire dataset the train_epoch function which is called depends on the runtime configuration; ie, simulated VARIANT 1/2, basel...
def loadImagePath(image_folder): image_dict = {} for folder in os.listdir(image_folder): for file in os.listdir(os.path.join(image_folder,folder)): path = os.path.join(folder,file) image_dict[path]=[] return image_dict def loadLabel(label_folder): annotation_dict = {} ...
The code evaluates object detection performance using F1 score, precision, and recall by comparing predicted bounding boxes with ground truth annotations on the WIDER_val dataset. It adjusts the IoU threshold via command-line arguments, loads image/label data, merges annotations, generates predictions, and calculates m...
def main(): threshold = 0.5 assert len(sys.argv)<3 if(len(sys.argv)==2): threshold = float(sys.argv[1]) else: print("use default iou threshold {}".format(threshold)) data_root = "WIDER_val" image_folder = os.path.join(data_root,"images") label_folder = os.path.joi...
def read_file(filename): return pipe( open_file_in_current_dir, lambda x: x.read() )(filename) def hex_string_to_binary(s): returnval = "" for char in s: returnval += hex_char_to_binary_string(char) return returnval def parse_contents_to_tree(bs): version = binary_string_...
The code reads a file's contents, converts them from hexadecimal to binary, parses the binary data into a tree structure, and returns the resulting tree.
def solution(filename): contents = read_file(filename) binary_contents = hex_string_to_binary(contents) tree = parse_contents_to_tree(binary_contents) return tree
def check_dna_length(dna_length): if dna_length < 100 or dna_length > 1000: raise Exception('String length should be in the range from 100 to 1000') def check_gc(gc_percent): if gc_percent < 20 or gc_percent > 80: raise Exception('GC structure should be in the range from 20 to 80') def generate_...
The code generates a random DNA sequence based on user-provided length and GC content, identifies the longest open reading frame (ORF), translates it into a protein sequence, and reports the ORF's length, direction, and translation. If no valid ORF is found or it's too short, it provides corresponding messages.
def main(): print('Please, enter DNA`s length') dna_length = int(input()) check_dna_length(dna_length) print('Please, enter GC percent') gc_percent = int(input()) check_gc(gc_percent) dna = generate_random_dna(dna_length, gc_percent) print('Generated DNA is {}'.format(dna)) opposite_...
def load_all_files(file_paths): final_results = {} for fp in file_paths: data = load_file(fp) for item in data: q_id = item["id"] if "id" in item else item["q_id"] final_results.setdefault(q_id, []) final_results[q_id].append(item) return final_results def...
The main task of the code is to process input data using multiple prediction files (e.g., utility, retrieval, relevance, groundness) to generate structured output with annotated tokens. It filters and combines data based on dataset-specific rules, applies random sampling for negative samples, and constructs outputs by ...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--utility_pred', type=str, nargs="+") parser.add_argument('--retrieval_i_only', type=str, default=None, nargs="+") parser.add_argument('--retrieval_multi', type=str, nargs="+") parser.add_argument('--groudnes...
def _dict_extra(side, more, less): explanation = [] extra = {k: v for k, v in more.items() if k not in less} if extra: n = len(extra) explanation.append(f"{side} contains {n} more item{'' if n == 1 else 's'}:") explanation.extend(pprint.pformat(extra).splitlines()) return explana...
The function `_explain_m_dict` compares two objects (a `MatcherDict` and a regular dict or two `MatcherDict`s) to explain mismatches. If both are `MatcherDict`, it warns against comparing them. Otherwise, it identifies which side is the `MatcherDict`, generates an explanation using `_dict_extra`, computes differences w...
def _explain_m_dict(left, right, verbose=0): if isinstance(left, MatcherDict) and isinstance(right, MatcherDict): return ["Should not compare two M.dict() instances"] if isinstance(left, MatcherDict): matcher_side, val, matcher, left_d, right_d = "Left", right, left, left.d, right else: ...
def _dict_extra(side, more, less): explanation = [] extra = {k: v for k, v in more.items() if k not in less} if extra: n = len(extra) explanation.append(f"{side} contains {n} more item{'' if n == 1 else 's'}:") explanation.extend(pprint.pformat(extra).splitlines()) return explana...
The function compares two dictionaries (`left` and `right`) to identify and explain differences. It first checks for keys present in one dictionary but not the other (`_dict_extra`), then compares common keys (`_dict_diff`). The result is a list of explanations detailing discrepancies, preserving key order. The `verbos...
def _explain_dict(left, right, verbose=0): explanation = [] for side, more, less in [("Left", left, right), ("Right", right, left)]: explanation.extend(_dict_extra(side, more, less)) # NOTE: not using sets here to preserve keys order diff = _dict_diff([k for k in right if k in left], left, rig...
def _dict_diff(keys, left, right, verbose=0): # NOTE: we use simple key with no ["..."] wrapping to make it cleaner items = {k: compare_eq(left[k], right[k], verbose) for k in keys if left[k] != right[k]} return Explanation(prefix="Differing items:", items=items) if items else [] def register_explainer(op, ...
This function compares two objects (left and right), handling cases where one or both are Matcher instances. It extracts attributes from each, constructs dictionaries of their properties, and uses _dict_diff to generate a difference explanation. If both are Matchers, it explicitly prohibits comparing them directly. The...
def _explain_m(left, right, verbose=0): if isinstance(left, Matcher) and isinstance(right, Matcher): return ["Should not compare two M() instances"] if isinstance(left, Matcher): matcher, left_d = left, left.attrs right_d = {k: getattr(right, k, missing) for k in left_d} else: ...
def _load_m3u_playlist(self, file_path): for uri in self._read_m3u_playlist(file_path): self._add_track(uri['path'], uri['title']) def _load_stream(self, file_path, title=None): # TODO: read id3 here if os.path.islink(file_path): file_path = os.path.realpath(file_path) ...
The code loads a file from different data sources (RawObject/DSObject) by determining its MIME type and size, then processes it as a M3U playlist or stream. It handles missing tracks, emits a signal for them, and sets focus on the first row.
def load_file(self, jobject, title=None): if isinstance(jobject, datastore.RawObject): logging.debug('Loading a datastore.RawObject') file_path = mime_path = jobject.file_path title = jobject.metadata['title'] elif isinstance(jobject, datastore.DSObject): ...
def match_mesh_to_partial(vertices, pose): y1_pose, x2_pose, y3_pose = pose y_rot = get_y_rot(y1_pose) x2_rot = get_x_rot(x2_pose) y3_rot = get_y_rot(y3_pose) base_rot = np.eye(4) base_rot[:3, :3] = Rotation.from_euler('xyz', [180, 0, -90], degrees=True).as_matrix() t = y_rot @ x2_rot @ y...
This code loads a 3D mesh from a partial and ground truth path, aligns it using pose data, normalizes the mesh by centering and scaling to unit diameter, and returns the processed 3D points as a float32 array for training or evaluation in a neural network.
def __getitem__(self, idx): partial_path = self.data[idx][0] ground_truth_path = self.data[idx][1] vertices = np.load((self.root / ground_truth_path / 'vertices.npy').as_posix()) triangles = np.load((self.root / ground_truth_path / 'triangles.npy').as_posix()) p3, p2, p1 = Path...
def deployData (self): if self.output_dir == self.web_dir: self.log("Skipping data deployment because output and web directories are the same: " + self.output_dir) else: cmd = 'rsync -av "%s" "%s"' % (self.output_dir, os.path.dirname(self.web_dir)) self.log("Deploying...
The main task of the code is to deploy essential components including data, genome index files (if configured), index structures, CGI scripts, and informational documents, likely for initializing or configuring a bioinformatics or web service environment.
def go (self) : self.deployData() if 'taxonid' in self. cfg: self.deployGenomeIndexFile() self.deployIndex() self.deployCgi() self.deployInfoDoc()
def iou2d_calculator(bboxes1, bboxes2, mode='iou', is_aligned=False, scale=1., dtype=None): """2D Overlaps (e.g. IoUs, GIoUs) Calculator.""" """Calculate IoU between 2D bboxes. Args: bboxes1 (Tensor): bboxes have shape (m, 4) in <x1, y1, x2, y2> format, or shape (m, 5) in <x1, y1, x2, ...
This function computes anchor-to-ground-truth assignments by calculating IoU and distance metrics, selects top candidates, applies thresholds, and generates target labels, bounding boxes, class scores, and foreground masks for training object detection models. It handles empty GT cases and incorporates IoU-based soft l...
def forward(self, anc_bboxes, n_level_bboxes, gt_labels, gt_bboxes, mask_gt, pd_bboxes): r"""This code is based on https://github.com/fcjian/TOOD/blob/master/mmdet/core/bbox/assigners/atss_assigner.py ...
def assignment_maze(): """ Makes the maze for DV2619 Assignment 2 Task 3 """ maze = Maze(7, 20) maze.set_start(0) maze.set_end(138) maze.connect_node(0, "r") maze.connect_node(1, "r") maze.connect_node(2, "r") maze.connect_node(3, "r") maze.connect_node(3, "d") #split maz...
The code's main task is to solve a maze using a genetic algorithm. It initializes a maze, applies the genetic algorithm with parameters (population size=100, mutation rate=0.01, generations=10000), prints the resulting path, and evaluates its fitness against the maze. The process demonstrates evolutionary computation f...
def main(): maze = assignment_maze() print(maze.make_map()) asd = maze_genetic_algorithm(maze, 100, 0.01, 10000) print(asd) print(eval_fitness(asd[1], maze)) return 0
def getBinDescArray(inputDirectory): binDescArray = [] with open(inputDirectory) as file: line = file.readline() while line: binDescArray.append(line[:-1]) line = file.readline() return binDescArray def getOxygenGeneratorRating(binDescArray): position = 0 whil...
The main task of the code is to calculate a life support rating by multiplying the oxygen generator rating and CO2 scrubber rating derived from binary descriptor arrays obtained from an input directory.
def getLifeSupportRating(inputDirectory): binDescArray = getBinDescArray(inputDirectory) oxygenGeneratorRating = getOxygenGeneratorRating(binDescArray) co2ScrubberRating = getCO2ScrubberRating(binDescArray) return oxygenGeneratorRating * co2ScrubberRating
def get_game_files(): folder_path = './games' game_files = [file for file in os.listdir(folder_path) if file.endswith('.html')] return game_files def parse_games(game_files): games = [] for file in game_files: game_name_1 = os.path.splitext(file)[0] game_name = game_name_1.replace(...
The main task of the code is to generate an index.html file by retrieving game files, parsing their data, rendering an HTML template with the parsed games, and saving the rendered output. The function orchestrates fetching, processing, and persisting game-related content into a static HTML page for display.
def index(): game_files = get_game_files() games = parse_games(game_files) rendered_template = render_template('index.html', games=games) save_index_html(rendered_template) # Save the rendered template to a file return 'index.html saved successfully!'
def get_ip(*argsv, **kwargs): ret_ip = [] if len(argsv) == 1: ip_name = argsv[0] else: ip_name = 'all_ip' ips = search_ip(ip_name) if kwargs: for prop, prop_val in kwargs.items(): print('Return for all IP containing ' + ip_name + ' with ' + prop + ' = ' + prop_val) for ip in ips: dt_prop_val = get_...
The code reads and prints MII (Media Independent Interface) register values from a network device's PHY (Physical Layer) interface. It first validates the Ethernet and PHY addresses, then iterates through 32 MII registers, printing their names and corresponding MDIO (Management Data Input/Output) values for diagnostic ...
def mii_dump(): eth_addr_temp = get_ip('ethernet', status='okay') eth_addr = get_ip_addr(eth_addr_temp[0]) if eth_addr > 0: base_addr = eth_addr + 0x34 print('found valid ethernet IP at ' + hex(base_addr)) else: return -1 phy_addr = get_phy_addr(base_addr) if phy_addr == -1: print('Error: No valid phy ...
def send_ack(self,ticket_number): self.ack_listener(Commands.CMD_ACKNOWLEDGE,ticket_number) def ticket_from_bytes(self,b): return (int.from_bytes(b[:8],'big',signed=True) , b[8:]) def command_from_bytes(self,b): length = int.from_bytes(b[:2],'big',signed=True) b = b[2:] res = str...
This method receives and processes network packets, handling connection commands, ticket-based data/ACK processing, and listener commands. It logs received packets, updates the boat address on connect commands, manages ticket states, and routes unrecognized commands to listener handlers for further processing.
def get_packet(self): self.address_lookup.ping_server() # send random acc to boat server, enables hole punching self.send_ack(300) try : packet , addr = self.sock.recvfrom(512) except : return if (packet == ''): return if no...
def get_params() -> Params: """ If the item only contains one string, just return it. Otherwise, return a list. """ raw_params = st.experimental_get_query_params() params: Params = {} for key, value in raw_params.items(): if len(value) == 1: params[key] = value[0] e...
The main task of the code is to generate a hash from input parameters, check if it already exists in a database table, and if not, store the hash along with the parameters as a JSON string in the table. It returns the generated hash, ensuring unique parameter sets are recorded once.
def save_hash_if_not_exists(params: Params = None) -> str: if params is None: params = get_params() hash = get_hash_from_params(params) if not is_hash_in_table(hash): add_row( TABLE, {"hash": hash, "params": json.dumps(params)}, ) return hash
def tree(label, branches = []): for branch in branches: assert is_tree(branch), 'branches must be trees' return [label] + list(branches) def label(tree): return tree[0]
The main task of the code is to construct a binary tree where each node's label represents the sum of its two children's labels, recursively building a structure that mirrors the Fibonacci sequence. For n > 1, the function generates a tree with left and right subtrees corresponding to fib_tree(n-2) and fib_tree(n-1), r...
def fib_tree(n): if n <= 1: return tree(n) else: left, right = fib_tree(n-2), fib_tree(n-1) return tree(label(left)+label(right), [left, right])
def get_all_gap_cols(self): all_gaps = list(range(0, self.sequence_length())) for seq in self.values(): all_gaps[:] = [i for i in all_gaps if seq[i] == '-'] return all_gaps def sequence_length(self): if self.is_aligned(): return len(list(self.values())[0]) def rem...
This function identifies and removes all gap-containing columns from the object, then returns the indices of the remaining columns. It first retrieves gap columns, excludes them from a range of indices, removes the gap columns, and returns the list of valid indices.
def delete_all_gaps(self): rem = set(self.get_all_gap_cols()) subset = [x for x in range(0, self.sequence_length()) if x not in rem] self.remove_columns(set(rem)) return subset
def positive_case(x, y, s): """ Fill in the missing letters of given string when both costs are positive. Parameters ---------- x: int cost of 'CJ' y: int cost of 'JC' s: str The string Returns ------- new string with all '?' replace by C or J. """ ...
The function `find_cost` calculates the minimal cost of a string `s` based on given costs for 'CJ' (x) and 'JC' (y). It categorizes the string into one of three types based on the signs of x and y (both positive, both negative, or mixed) and applies corresponding handling logic. After determining the string type, it co...
def find_cost(x, y, s): """ Find the minimal cost of a string for given costs. The solution idea is to first find the type this test string belongs too and fill in the missing chars, then compute the cost and return it. There are three types of string, namely where both costs are positive, both neg...
def getMetaTags(soup: BeautifulSoup): tags = {} for tag in soup.find_all("meta"): if tag.get("name") and tag.get("content"): tags[tag.get("name")] = tag.get("content") return tags def getArrayFromString(content: str): return content.split(",") def getOg(soup: BeautifulSoup): prop...
The main task of the code is to scrape and structure data from a webpage using BeautifulSoup, extract metadata, links, images, and content, handle special cases like Wikipedia infoboxes, and store the processed data in Elasticsearch. It also manages link discovery for further crawling while respecting robots.txt rules.
def scrapeData(soup: BeautifulSoup, obj: dict, es_client: Elasticsearch): if not obj.get("url"): return data = {} meta = getMetaTags(soup) robots = Robots(getArrayFromString(meta.get("robots", ""))) if robots.canIndex(): parsedUrl = parse_url(obj.get("url")) isGoogleSearch = ...
def get_change_list(uni_diff_text): patch_set = PatchSet(StringIO(uni_diff_text)) change_list = [] # list of changes # [(file_name, [row_number_of_deleted_line], # [row_number_of_added_lines]), ... ] for patched_file in patch_set: file_path = patched_file.path...
The code retrieves and processes Git commit diffs for a specified repository. It clones or accesses the repo, extracts a commit's changes, filters them, and generates analysis results for both the base commit and its parent commit. The results are combined and saved, focusing on change tracking between commits.
def get_diff(commit_sha, parrent_commit_sha, repo_name, base_path): repo_path = f'{base_path}/clone_repo/{repo_name.split("/")[0]}_{repo_name.split("/")[1]}/' try: repository = git.Repo.clone_from( f'zxtoh@example.com', repo_path ) except: repository = git.Repo(repo_path)...
def findMemberById(id): result = None for member in members: if (member.tracker_id == id): result = member return result def findGroupById(id): result = None for group in groups: if (str(group.id) == id): result = group return result def delete_member_by_...
The code processes missing elements by iterating through trackers, retrieving associated members and their groups, removing members from groups, and deleting them. It handles missing elements by cleaning up related data structures, ensuring consistency in group-member relationships and removing invalid entries.
def handle_missing_elements(missing_elements): missing_trackers, missing_labels = missing_elements.trackers_array, missing_elements.labels_array for index, tracker in enumerate(missing_trackers): member = findMemberById(tracker) group = findGroupById(str(member.group)) group.removeMembe...
def create_member(tracker, group=None): new_member = Member(tracker, group, moment) members.append(new_member) log = f'NEW ELEMENT HAS BEEN SPOTED: {new_member.tracker_id}' write_log(log, moment, 0) return new_member def create_group(label): new_group = Group([], f'Group {int(label)}', label, m...
The code creates a member for each tracker ID and a group for each unique label (excluding -1). It populates each group with members by matching tracker IDs to their corresponding labels, adding members to groups and updating their group assignments at a specified moment.
def create_new_members_and_groups(record): tracker_id = record.trackers_array labels = record.labels_array # CREATED A MEMBER PER TRACKER AND A GROUP PER LABEL for index, tracker in enumerate(tracker_id): create_member(tracker) import numpy as np for idx, label in enumerate(np.unique(l...
def getAllGroupLabels(): labels = [] for group in groups: labels.append(group.label) return labels def findGroupByLabel(label): result = None for group in groups: if (group.label == label): result = group return result def create_member(tracker, group=None): new...
This function processes new elements by associating each tracker with a group. If the label exists, it adds the tracker to the existing group; if not, it creates a new group and adds the tracker there. It updates group memberships and tracks newly created labels for potential future use.
def handle_new_elements(new_elements): all_labels = getAllGroupLabels() new_trackers, new_labels = new_elements.trackers_array, new_elements.labels_array just_created = [] for index, label in enumerate(new_labels): if (label in all_labels): group = findGroupByLabel(label) ...
def _get_build_dir(self): """Get the location of a build directory in case we need to download clang-format """ return os.path.join(os.path.curdir, "build") def lint(self): """Lint files command entry point """ files = self.get_files_to_check() self._lint...
This script applies clang-format to a Git repository, parsing command-line arguments to determine actions like linting, reformatting, or checking patches. It supports specifying the clang-format path, repository location, languages, directories, and regex filters. Mutually exclusive options handle different operations,...
def run(self): """Main entry point """ logger.info("Initializing script...") parser = argparse.ArgumentParser() parser.description = ("Apply clang-format to a whole Git repository. " "Execute this script and provide it with the " ...
def unroll_map(sdfg: SDFG, state: SDFGState, unroll_entry: nd.MapEntry, unroll_factor: int, new_param_name="k", update_memlets=True): tile_prefix = sdfg._find_new_name("bank") map_range_int = None try: map_range_int = int(symbolic.resolve_symbol_to_constant(unroll_entry.map.range[0][1], sdfg)) ...
This code unrolls a map in an SDFG (Synchronous Dataflow Graph), splitting arrays and adjusting memory assignments. It modifies array locations, replaces old parameters with new dimensions, updates memlet paths for data flow, and propagates changes. The goal is to optimize memory usage by distributing data across banks...
def apply(self, sdfg: SDFG) -> Union[Any, None]: state: SDFGState = sdfg.nodes()[self.state_id] unroll_entry: nd.MapEntry = state.nodes()[self.subgraph[ self._map_entry]] unroll_exit = state.exit_node(unroll_entry) split_arrays, no_split_arrays, unroll_factor, split_dimensio...
def gen_trajs(self): if self.graph.get_graph_name() == 'mat1': traj = [8,4,5,9,8,9,5,1,2,3,7,11,10,9] * 10 else: traj = [] return traj def update_point_cells(self): self.P = self.get_point_cells_activity(self.curr_node) def update_map_cells(self): self.M =...
The code trains a model by iteratively updating two matrices (MM and GM) using trajectory data. It generates trajectories, updates spatial cells, handles matrix inversion errors, and applies weighted updates to MM and GM via matrix operations. The matrices are clamped to non-negative values, their diagonals zeroed, and...
def train(self): log = [] traj = self.gen_trajs() for self.curr_node in traj: self.update_point_cells() try: self.update_map_cells() except np.linalg.LinAlgError: print('Training not finished due to matrix inversion error') ...
def connect(self): my_db = Path("PULock.db") if my_db.is_file(): print("Database has found") pass else: print("Creating database") con = sqlite3.connect("PULock.db") print("Database created successful") self.create_table(c...
This code inserts a new USB record into a database table, handling ID generation by incrementing from the last used ID if the provided ID is 0. It checks for duplicate serial numbers, skips insertion if found, and adds the record with specified model and serial otherwise.
def insert(self, id, model, serial): con = self.connect() cursor = con.cursor() if id == 0 or id == '0': id = int(id) id = id + 1 ids_from_table = self.verify_ids() serial_list = self.verify_serial() for count in range(0, len(serial_list)): ...
def load_from_storage(self, stored_textobject): self.files = stored_textobject['files'] self.absolute_files = stored_textobject['absolute_files'] self.is_ebook = stored_textobject['is_ebook'] def load_from_path(self, path): path = Path(path) self.is_ebook = False self.fil...
The code initializes an object by loading text data either from existing stored metadata (if available) or from a specified path (directory, file, or epub). It assigns the storage, checks for pre-stored 'TextObject' metadata, loads accordingly, and updates the storage with the loaded data.
def __init__(self, storage, path=None): """ parameters: - path: path to where the text is. currently supports directories, a file, and an epub """ self.storage = storage stored_textobject = self.storage.metadata.get('TextObject') if stored_textobject: ...
def readdata(file): #read file and get variables time,u,v time=[] u=[] v=[] with open(file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row...
The code tests multiple functions related to processing wind data from a CSV file. It verifies data reading, speed/direction calculations, time conversion, 10-minute averaging, and output formatting. Assertions check specific values, mathematical ranges, and correctness of computed fields like speed, direction, and ave...
def test_answer(): infile = './test_sample.csv' #test csv file reading time, u, v =readdata(infile) assert time[9] == '2020-03-27 04.09.00' assert u[9] == 1.753224 assert v[9] == -3.335626 u_test=random.randrange(-30, 30, 0.01) v_test=random.randrange(-30, 30, 0.01) #test cal_speed assert cal_speed(u_...
def check_detection_prob(self, node_id, within_fov=True): sum_prob = self.accum_detection_prob(node_id) sum_prob_norm = (sum_prob - polygon_configs['prob_mean']) / polygon_configs['prob_var'] sum_prob_sigmoid = 0.5 + 0.5 / (1 + math.exp(-sum_prob_norm)) if within_fov: if sum...
This function generates a polygon from detected points within a specified field of view (FOV) by sampling angular sectors, selecting closest valid points, and adding virtual nodes for gaps. It processes range/azimuth data, filters valid detections, constructs polygon nodes with confidence scores, and optionally removes...
def calculate_polygon(self, angle_intr, origin=[0, 0], fov=[-math.pi/2, math.pi/2], add_virt=True, is_remove_spike=False): self.fov = fov overlap_agl = 0 # parameter setup # initiate values append_y_last = 0 append_x_last = 0 num_virt = 0 # calculate the range an...
def get_params(self): """Get all weights/biases rolled into one array.""" params = self.weights[0].ravel() for w in self.weights[1:]: params = np.concatenate((params, w.ravel())) for b in self.biases: params = np.concatenate((params, b.ravel())) return par...
This function computes the numerical gradient of a model's parameters by perturbing each parameter slightly, calculating the cost before and after the perturbation, and using the central difference formula to estimate the gradient. It returns the gradient vector, restoring parameters to their original values afterward.
def numgrad(self, x, y): """Get a numerical estimate of the gradient vector at (x,y).""" paramsInitial = self.get_params() numgrad = np.zeros(paramsInitial.shape) perturb = np.zeros(paramsInitial.shape) e = 1e-5 for p in range(len(paramsInitial)): # Set p...
def set_dasp_nodes(self): self.V_start = self.get_starter_nodes() self.Vn = self.get_ds_customers() self.V_end = self.get_end_nodes() self.get_outlier_nodes() self.Vl.extend(self.V_start) self.Vl.extend(self.Vn) self.Vl.append(self.milp_model.v[self.d_station]) ...
This code initializes a solution structure for a drone routing problem, setting up MILP model components, tour data, customer assignments, and node indices for optimization. It organizes tours, tracks assigned customers, and prepares variables for constraints like route sequences, drone stations, and outlier handling, ...
def __init__(self, model, solution, d_station): self.drone_to_customer = [] self.milp_model = model self.tours = solution["tours"] self.dasp_tours = [] self.assigned_customers = solution["assigned_customers"] self.dasp_solution = {"tours": [], "assigned_customers": self....
def getTupleTour(model): tours = getTrucksTour(model) tuple_tours = [] for tour in tours: tuples_tour = tourToTuple(tour) tuple_tours.append(tuples_tour) return tuple_tours def get_customer_drone_edges(model): drone_to_customers_edges = [] for var in model._vars: if "y_d_...
The function `plotTours` visualizes routes (tours) generated by a model, focusing on drone deliveries originating from drone stations. It retrieves tours and drone delivery edges, filters deliveries starting at drone stations, and plots the tours along with these filtered drone paths using `plotNodes`. The task involve...
def plotTours(model, v, eps): tuple_tours = getTupleTour(model) drone_deliveries = get_customer_drone_edges(model) for tour in tuple_tours: drone_deliveries_from_s = [] for i, _ in tour: if v[i].node_type == NodeType.DRONE_STATION: drone_deliveries_from_s.extend(l...
def is_one_class_label(self, y): if len(y) == 0: return True val = y[0] for label in y: if label != val: return False return True def _best_split(self, x, y, feat_idxs): result = np.argmax( [self._information_gain(y, x[:, feat_i...
This function recursively builds a decision tree by selecting the best feature to split on, using the median as the threshold, and creating left and right child nodes. It stops when maximum depth is reached, minimum samples are met, or no further splits are possible, assigning the most common class label as the node's ...
def _grow_tree(self, node, x, y, depth=0): if (depth > self.max_depth and depth > self.min_samples_split) \ or len(y) == 0 or self.is_one_class_label(y): if len(y) > 0: node.value = Counter(y).most_common(1)[0][0] else: node.value = 0 ...
def AddRandomBooster(self): boosterType = random.choice([ SpinBooster, VelocityBooster, GravityBooster, ]) w, h = self.surf.get_size() booster = boosterType( ( random.randint(int(0 + w / 4), int(3 * w / 4)), ...
This code renders a game scene by drawing gravity points, boosters, units, and particles. It checks for unit deaths, calculates gravitational forces, handles collisions between units/boosters, spawns explosion particles when units die, updates physics, and manages game state transitions like game over. The function als...
def Draw(self, clock): self.surf.fill((0, 0, 0)) if len(self.units) == 1: self.gameOver = True for gravity in self.gravities: pygame.draw.circle( self.surf, gravity.color, gravity.center, gravity.strength ...
def Protein_to_number(self, string): """ This will conbert the string to a specific grop of proteins for example A is similar to G they will both be define as 1 """ st = "" for i in string: st += str(self.AminoTable[i][0]) return st def Word_docu...
The code processes two protein sequences by converting them into numerical representations, identifies exact matches of substrings (minimum length 3) between them, records their positions in a DataFrame, converts matches back to protein notation, and generates a Word document highlighting these matches for analysis.
def __init__(self, string1, string2, Output_name): self.str1 = string1.get().replace(" ", "").replace("\n", "") self.str2 = string2.get().replace(" ", "").replace("\n", "") self.minnumber = 3 # give by Lorenso self.strsplit = [] self.doc = docx.Document() self.AminoTable...
def getMatchingSourceIndex(self,timeList,target): minDelta=2*60*60+1 for i in range(0,len(timeList)): delta=abs(timeList[i]-target.time) if delta<minDelta: minDelta=delta minSourceIndex=i if minDelta>2*60*60: return None retur...
The main task of the code is to match targets with the best-fitting source based on time, clone EXIF data from the matched source to the target, or apply default EXIF values if no match is found. It skips targets with GPS data when overwrite is False, logs matching results, and ensures each target receives appropriate ...
def matchNext(self,overwrite=True): timeList=[] for source in self.sources: timeList.append(source.time) for target in self.targets: if target.hasGPS and not overwrite: continue matchedSourceIndex=self.getMatchingSourceIndex(timeList,target) ...
def quarterly_info(page, stock): """summary""" stock_data = [] stats_dict = stats(page, stock) financial_dict = financials(page, stock) quarterly_dict = stats_dict | financial_dict stock_data.append(quarterly_dict) quarterly_data = {quarterly_date(): stock_data} # quarter_list.append(qua...
The function retrieves and updates quarterly financial data for a specified stock from Yahoo Finance. It checks if the quarterly data JSON file exists; if not, it creates the file and populates it with initial data. If the file exists, it verifies if new data is available based on the current month. If so, it updates t...
def process_stocks(page, stock): """Get all of the quarterly data from Yahoo Finance""" path = Path(f"stock_data/{stock}", "quarterly.json") now = datetime.now() month = now.month quarter_list = [] # * if "quarterly.json" doesn't exist create folder and run quarterly_info # * if "quarterl...
def train_epoch(self, epoch): self.model.train() train_running_results = {'images_in_epoch': 0, 'accumulated_train_loss': 0} train_bar = tqdm(self.train_dataloader, ncols=150) iters = len(train_bar) for idx, (reference_images, target_images, captions) in enumerate(train_bar): ...
The main task of the code is to train a model for a specified number of epochs, performing validation at regular intervals on either the CIRR or FIQ dataset. It evaluates the model's performance using recall metrics, logs results with wandb, and saves the best-performing model checkpoint based on average evaluation sco...
def train(self): best_score = 0 self.model.to(self.device) for epoch in range(self.num_epochs): self.train_epoch(epoch) if epoch % self.validation_frequency == 0: results_dict = {} if self.dataset == 'cirr': results = s...
def _process_first_frame(self, frame): print("Processing first frame") # function to process the first frame faces = self.face_detector(frame, cv=True) if len(faces) == 0: raise ValueError("Face is not detected") else: self.coords = faces[0][0] fac...
The main task of the code is to process a video frame by detecting and tracking a face, estimating head pose, transforming key points, and generating a transformed image using a neural network model. It handles the first frame separately, smooths face coordinates, prepares inputs, and outputs the processed face along w...
def _inference(self, frame): # function to process the rest frames with torch.no_grad(): self.n_frame += 1 if self.first_frame: self._process_first_frame(frame) self.first_frame = False else: pass if self.n_f...
def requestVote(self): logger.info("Node {} contesting election".format(self.id)) self.status = 'CANDIDATE' self.vote_count = 1 for k in get_client_map().items(): c = self.get_client(k[0]) if not c: continue id = k[0] if id ...
The main task of the code is to implement a leader election mechanism in a distributed system. It repeatedly attempts to request votes for itself, and if successful, declares itself the leader and broadcasts this status. If unsuccessful, it checks the cluster for an existing leader. If none is found, it adjusts the ele...
def start_election(self): while(True): logger.info("Sleeping for {}".format(self.election_timeout)) time.sleep(self.election_timeout) if self.requestVote(): self.setLeaderId(self.id) self.vote_count = 0 self.status = "LEADER" ...
def get_client(self,node_id): client_obj = self.clients.get(node_id)['client_obj'] if client_obj is None or self.clients.get(node_id)['active'] ==False: #If none check whether connected again try: client_obj = Client(self.clients.get(node_id)['host'],self.clients....
The function `getLeaderNode` identifies the current leader node in a distributed system. If the existing leader is unreachable, it initiates an election to select a new leader, updates the leader ID, and returns it. If no leader is known, it checks the cluster and starts an election if necessary, ensuring consistent le...
def getLeaderNode(self): if self.leader_id: if self.leader_id==self.id: return self.leader_id leader_client = self.get_client(self.leader_id) try: if leader_client is None or not leader_client.pingInternal(): ra...
def has_started(self): return len(self.c_proc)>0 def stop(self): if not self.has_started(): return self.map([], l_quit=True) def spawn(self, f): """internal helper function""" def func(q_in,q_out,mail,job_is_done): while True: (i, i_worker, x) =q_in.ge...
This code initializes and launches multiple worker processes to execute tasks in parallel using Python's multiprocessing module. It sets up shared memory structures (queues, lists, locks) for inter-process communication and synchronization, creates worker processes that run a specified function or wrapper, and manages ...
def start(self, f=None, n_CPU=0): """Launch workers. f: method, task for worker, default None, if None, worker runs a wrapper task, which expect the first argument to be a registered method name n_CPU: number of workers to launch.""" if self.has_started(): print('Already star...
def display_town_text(): #Display the town text using the for loop for a in range (len(town_text)): print('{:d}) {:s}'.format(a+1,town_text[a])) def display_town_menu(choice1): #Display town menu gl...
The code defines the main game loop, handling player interactions based on location (town, open space, Rat King encounter). It uses global variables for damage and loot, randomly generates values, and processes player choices through different menus (town, combat, outdoor) to progress the game, manage encounters, and d...
def start_game(): #Main function to start the game global hero_damage #global values ...
def codesign_dump_entitlements(component: Path) -> Dict[Any, Any]: entitlements_str = decode_clean( run_process("/usr/bin/codesign", "--no-strict", "-d", "--entitlements", ":-", str(component)).stdout ) return plist_loads(entitlements_str) def dump_prov_entitlements(prov_file: Path) -> Dict[Any, Any...
The main task of the code is to prepare a component's entitlements and bundle identifier for code signing by modifying the bundle ID, mapping old identifiers to new ones, adjusting entitlements based on provided options, and generating a temporary entitlements file. It handles provisioning profile integration, wildcard...
def __prepare_primary( self, component: Path, workdir: Path, ): info_plist = component.joinpath("Info.plist") info: Dict[Any, Any] = plist_load(info_plist) embedded_prov = component.joinpath("embedded.mobileprovision") old_bundle_id = info["CFBundleIdentifier"...
def __prepare_primary( self, component: Path, workdir: Path, ): info_plist = component.joinpath("Info.plist") info: Dict[Any, Any] = plist_load(info_plist) embedded_prov = component.joinpath("embedded.mobileprovision") old_bundle_id = info["CFBundleIdentifier"...
This code signs multiple components (e.g., .app/.appex files) by preparing them in a temporary directory, managing signing jobs, removing AppStore data, applying ID patches, and ensuring dependencies are resolved before final signing. It handles primary/secondary signing workflows, waits for sub-component completion, a...
def sign(self): with tempfile.TemporaryDirectory() as tmpdir_str: tmpdir = Path(tmpdir_str) job_defs: List[Tuple[Path, Optional[ComponentData]]] = [] for component in self.components: print(f"Preparing component {component}") if component.suf...
def checkKey(dict, key): if key in dict: if dict[key] == 'True': return 1 else: return 0 else: return 0 def LSH2(C,nBand,nRow,s): final_result = collect_candidate_pairs2(C,nBand,nRow,s) # get buckets of restaurant profiles with original restaurant i...
The function generates restaurant recommendations using collaborative filtering and cosine similarity between user profiles (derived from reviews) and item profiles (restaurant attributes). It filters restaurants, builds feature matrices, computes user-item similarity, and returns top-N recommendations, evaluation metr...
def recommend(uid,quick_rec,top_N,extra_recs,restaurants,reviews,minStars,minRev,k,nBands,nRows,s,write2csv): # ensure correct types N = int(top_N) # top-N recs quick_rec = int(quick_rec) # remove restaurants without any attributes for i,restaurant in enumerate(restaurants): if restaurant[...
def listeFileTrainAndTest(): files=os.listdir('.') print(files) listFileTest = [ f for f in files if ( str(f).startswith("test") and str(f).endswith(".csv") ) ] #print("listFileTest =>",listFileTest) listFileTrain = [ f for f in files if ( str(f).startswith("training") and str(f).endswith(".csv") ) ] #print("lis...
The main task of the code is to perform k-fold cross-validation on a neural network model using varying k values (2-9) and iteration counts (100000), evaluating performance metrics (RMSE, precision, recall) across multiple training/test file pairs. It systematically trains the network, splits data into validation folds...
def test(): path = os. getcwd() listFileTrain,listFileTest=listeFileTrainAndTest() liste_k=[2,3,4,5,6,7,8,9] #liste_k=[2,3,4] liste_de_valeur=[100000] #pour 9 neurones dans la couche cachee #liste_de_valeur=[100000,500000] #pour 8 neurones dans la couche cachee #l...
def listeFileTrainAndTest(): files=os.listdir('.') print(files) listFileTest = [ f for f in files if ( str(f).startswith("test") and str(f).endswith(".csv") ) ] #print("listFileTest =>",listFileTest) listFileTrain = [ f for f in files if ( str(f).startswith("training") and str(f).endswith(".csv") ) ] #print("lis...
The code evaluates a neural network's performance across varying training iterations on multiple datasets, calculating RMSE, precision, and recall for both training and test sets. It stores results in CSV files, comparing model metrics for each iteration count to analyze performance trends.
def test(): liste_de_valeur=[80000,100000,150000,200000,250000,300000,350000,400000,450000,500000,550000,600000,650000,700000,750000,800000,850000,900000,950000,1000000] #liste_de_valeur=[1] path = os. getcwd() listFileTrain,listFileTest=listeFileTrainAndTest() for nbre_iter in liste_de_va...
def findUsers(str1): substr = "<a class=\"_1s79 _52jh\">" end = len(substr) res = findAllOccurence(str1, substr) print(res) return [str1[res[i] + end:str1.find("</a></h3>", res[i] + 19)] for i in range(len(res))] """ substr = "<div class=\"_14ye\">" end = len(substr) res = findA...
The code scrapes comments from a webpage by iterating through paginated URLs, appending extracted user data and comments to global variables. It uses requests to fetch pages, processes HTML content to find comments, and stops when no new comments are found or after 11 pages. Additional functions for navigation are call...
def searchcom(URL): global users global currcomments global comments try: page = requests.get(URL) mainURL = URL """ f = open("scraped.txt", "w") f.write(page.text) f.close() """ q = True try: pagenum = 0 sti...
def searchcom(URL): global users global currcomments global comments try: page = requests.get(URL) mainURL = URL """ f = open("scraped.txt", "w") f.write(page.text) f.close() """ q = True try: pagenum = 0 sti...
The main task of the code is to extract and process user comments from a Facebook URL by parsing the URL for a specific parameter (fbid), retrieving comment data via the `searchcom` function, cleaning/normalizing the comments, and storing the results in both a serialized pickle file and text files. It also attempts to ...
def searchURL(self): global users global currcomments global comments users = [] currcomments = [] comments = [] global fbid URL = self.textEdit_2.toPlainText() fbid = URL[URL.find('fbid=') + len('fbid='):URL.find('&')] s...
def filter2(self, filterarr): filterarr = self.table_to_list(self.tableWidget) headersMainLen = len(self.headersMain) headersMain = self.headersMain self.tableWidget_3.setRowCount(0) self.tableWidget_3.setColumnCount(len(headersMain)) self.tableWidget_3.setHorizo...
This code connects UI buttons to specific functions: `pushButton` triggers `filter2` with `currentfilter`, `pushButton_2` calls `newText`, and `pushButton_3` initiates `searchURL`. It also initializes widgets, setting up the interface's interactive elements and their associated actions.
def setupUIAdditions(self): self.pushButton.clicked.connect(lambda: self.filter2(self.currentfilter)) self.pushButton_2.clicked.connect(lambda: self.newText()) self.pushButton_3.clicked.connect(lambda: self.searchURL()) self.initializeWidgets()
def doubleHashHex (data): """ Perform Bitcoin's Double-SHA256 hash on the given hex string. """ hasher = hashlib.sha256 () hasher.update (binascii.unhexlify (data)) data = hasher.digest () hasher = hashlib.sha256 () hasher.update (data) return reverseHex (hasher.hexdigest ()) def reverseHex (data):...
The function generates an auxiliary proof-of-work (auxpow) as a hexadecimal string to either solve (ok=True) or not solve (ok=False) a given block. It constructs a coinbase transaction, computes transaction hashes, builds a block header, and mines the block to meet the target difficulty. The resulting auxpow combines t...
def computeAuxpow (block, target, ok): """ Build an auxpow object (serialised as hex string) that solves (ok = True) or doesn't solve (ok = False) the block. """ block = bytes (block, "ascii") # Start by building the merge-mining coinbase. The merkle tree # consists only of the block hash as root. co...
def cnt2angle(cnt): return cnt * ANG_PER_STEP / (DRV_PRESC * RED_RATIO) def state2speed(accel, angle, start_speed): speed_sqr = 2 * accel * angle + start_speed**2 if speed_sqr < 0: return 0 return speed_sqr**0.5 def speed2pwm(speed): return int(round(abs(speed) * DRV_PRESC * RED_RATIO / ANG_PER_STEP)) def stop_t...
This code handles a motor control task by converting sensor data (count, acceleration) into angle and speed, adjusting PWM frequency to control motor speed, and stopping the task when the target angle is reached. It continuously monitors and adjusts the motor's operation based on real-time feedback.
def tmr_handler(self, _tmr): self.angle = cnt2angle(self.cnt) self.speed = state2speed(self.accel, self.angle, self.task[1]) self.pwm.freq(speed2pwm(self.speed)) if self.angle >= self.task[0]: self.stop_task(None) print(self.angle, self.speed)
def read_file(path): with open(path, 'r') as f: return f.read().split('\n') def expand_rows_cols(data, factor): data = expand(data, factor) data = transpose(data) data = expand(data, factor) return transpose(data) def find_galaxies(universe): galaxies = [] for i, line in enumerate(un...
The code reads input data, expands the universe's rows and columns, identifies galaxy positions, and calculates the sum of all pairwise distances between galaxies in the expanded grid.
def main(): data = read_file("test_input") expanded_universe = expand_rows_cols(data, 2) galaxies = find_galaxies(expanded_universe) total = 0 for i, galaxy in enumerate(galaxies): for nb_galaxy in galaxies[i+1:]: total += distance(galaxy, nb_galaxy) print(total)
def test_connection(self) -> None: """ Tests for successful connectivity to the Frigidaire server :return: """ return self.get_request(self.regional_base_url, "/one-account-user/api/v1/users/current?countryDetails=true", self.get_headers_frigidaire("GET", include_bearer_token=Tru...
The code authenticates with the Frigidaire API by validating an existing session key or initiating a full authentication flow if invalid. It retrieves tokens, identity details, and user credentials through multiple API requests, ultimately obtaining and storing a session key for API access. Exceptions are raised on fai...
def authenticate(self) -> None: """ Authenticates with the Frigidaire API This will re-authenticate if the session key is deemed invalid Will throw an exception if the authentication request fails or returns an unexpected response :return: """ if not self.regio...
def get_request(self, url: str, path: str, headers: Dict[str, str]) -> Union[Dict, List]: """ Makes a get request to the Frigidaire API and parses the result :parm url: Base URL for the request (no slashes) :param path: The path to the resource, including query params :param head...
This function retrieves detailed information for a specific appliance using the Frigidaire API. It authenticates, fetches appliance data, re-authenticates if needed, and returns the 'reported' properties of the matching appliance by ID. If not found, it raises an exception.
def get_appliance_details(self, appliance: Appliance) -> Dict: """ Uses the Frigidaire API to fetch details for a given appliance Will authenticate if the request fails :param appliance: The appliance to request from the API :return: The details for the passed in appliance ...