content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def calc_overlap(row): """ Calculates the overlap between prediction and ground truth and overlap percentages used for determining true positives. """ set_pred = set(row.predictionstring_pred.split(' ')) set_gt = set(row.predictionstring_gt.split(' ')) # Length of each and intersection ...
98e65250f82ab13b23de049fd80a59dea30ccce2
705,225
def _bucket_from_workspace_name(wname): """Try to assert the bucket name from the workspace name. E.g. it will answer www.bazel.build if the workspace name is build_bazel_www. Args: wname: workspace name Returns: the guessed name of the bucket for this workspace. """ revlist = [...
4cf3f4505a894f63258846abbe41b3b787485d40
705,227
def get_attrib_uri(json_dict, attrib): """ Get the URI for an attribute. """ url = None if type(json_dict[attrib]) == str: url = json_dict[attrib] elif type(json_dict[attrib]) == dict: if json_dict[attrib].get('id', False): url = json_dict[attrib]['id'] elif json...
838b698e3475ebdc877b29de6f3fd446d2be1cdf
705,230
import inspect def super_class_property(*args, **kwargs): """ A class decorator that adds the class' name in lowercase as a property of it's superclass with a value constructed using the subclass' constructor with the given arguments. So for example: class A: pass @super_class_property(foo=5) ...
ecfd38ba3d7ea96266278ed6be6cf0ba87263d7d
705,232
def merge(sorted1, sorted2): """Merge two sorted lists into a single sorted list.""" if sorted1 == (): return sorted2 elif sorted2 == (): return sorted1 else: h1, t1 = sorted1 h2, t2 = sorted2 if h1 <= h2: return (h1, merge(t1, sorted2)) else: ...
7c02b345b3d1e7c67e363e1535c608575a313f75
705,235
def slice_repr(slice_obj): """ Get the best guess of a minimal representation of a slice, as it would be created by indexing. """ slice_items = [slice_obj.start, slice_obj.stop, slice_obj.step] if slice_items[-1] is None: slice_items.pop() if slice_items[-1] is None: if slice...
c894f66478ec830a4968d0cfc5d9e146457012b6
705,237
import math def squeezenet1_0_fpn_feature_shape_fn(img_shape): """ Takes an image_shape as an input to calculate the FPN output sizes Ensure that img_shape is of the format (..., H, W) Args img_shape : image shape as torch.Tensor not torch.Size should have H, W as last 2 axis Retu...
d56fe3d834bcd9633727defe3ad9a27ea756ed40
705,239
import types def _copy_fn(fn): """Create a deep copy of fn. Args: fn: a callable Returns: A `FunctionType`: a deep copy of fn. Raises: TypeError: if `fn` is not a callable. """ if not callable(fn): raise TypeError("fn is not callable: %s" % fn) # The blessed way to copy a function. co...
37fca64ddaadfc8a6a24dce012af2143038cacd2
705,241
def getTJstr(text, glyphs, simple, ordering): """ Return a PDF string enclosed in [] brackets, suitable for the PDF TJ operator. Notes: The input string is converted to either 2 or 4 hex digits per character. Args: simple: no glyphs: 2-chars, use char codes as the glyph ...
bd5b7abd1b5ceb0b273e99e30ecc248482ed7476
705,245
def check_skip(timestamp, filename): """ Checks if a timestamp has been given and whether the timestamp corresponds to the given filename. Returns True if this condition is met and False Otherwise" """ if ((len(timestamp) > 0) and not(timestamp in filename)): return True elif ((len(...
738043fb554f20b79fa3ac8861f9e60d0d697e5e
705,246
def is_tabledap(url): """ Identify a dataset as an ERDDAP TableDAP dataset. Parameters ---------- url (str) : URL to dataset Returns ------- bool """ return "tabledap" in url
9f4650bc3a3bc0794637b042c1779a84d7c02779
705,247
import torch def cal_area(group_xyz): """ Calculate Area of Triangle :param group_xyz: [B, N, K, 3] / [B, N, G, K, 3]; K = 3 :return: [B, N, 1] / [B, N, G, 1] """ pad_shape = group_xyz[..., 0, None].shape det_xy = torch.det(torch.cat([group_xyz[..., 0, None], group_xyz[..., 1, None], torc...
bbafa626c1833b5bde81303b4038081dae7bc965
705,251
def quicksort(inputArray): """input: array output: new sorted array features: stable efficiency O(n^2) (worst case), O(n log(n)) (avg case), O(n) (best case): space complexity: O(n) method: Pick the last element in the array as the pivot. Separate values into arrays based on whether they...
2a8036ba038f4f7a8e817175d9a810184911ce4b
705,253
def cubic_spline_breaksToknots(bvec): """ Given breakpoints generated from _cubic_spline_breaks, [x0, x0, x0, x0, x1, x2, ..., xN-2, xf, xf, xf, xf], return the spline knots [x0, x1, ..., xN-1=xf]. This function ``undoes" _cubic_spline_breaks: knot_vec = _cubic_spline_breaks2knots(_cubic_spline_breaks(knot_vec)) ...
15a73dea4b001e05bd67075ec21e15247db1f031
705,259
def _SanitizeDoc(doc, leader): """Cleanup the doc string in several ways: * Convert None to empty string * Replace new line chars with doxygen comments * Strip leading white space per line """ if doc is None: return '' return leader.join([line.lstrip() for line in doc.spli...
7ca6f17296c9b23c05239092e28c8d6b4df7c725
705,267
def pop_execute_query_kwargs(keyword_arguments): """ pop the optional execute query arguments from arbitrary kwargs; return non-None query kwargs in a dict """ query_kwargs = {} for key in ('transaction', 'isolate', 'pool'): val = keyword_arguments.pop(key, None) if val is not No...
d4ae2df3158660f62e21153d943922692f633b76
705,268
def lico2_ocp_Ramadass2004(sto): """ Lithium Cobalt Oxide (LiCO2) Open Circuit Potential (OCP) as a a function of the stochiometry. The fit is taken from Ramadass 2004. Stretch is considered the overhang area negative electrode / area positive electrode, in Ramadass 2002. References ---------- ...
2c0902e1d1cdec9ac7626038e34092933665bf84
705,272
import time def find_workflow_component_figures(page): """ Returns workflow component figure elements in `page`. """ time.sleep(0.5) # Pause for stable display. root = page.root or page.browser return root.find_elements_by_class_name('WorkflowComponentFigure')
1a56a0a348803394c69478e3443cbe8c6cb0ce9c
705,276
def query_left(tree, index): """Returns sum of values between 1-index inclusive. Args: tree: BIT index: Last index to include to the sum Returns: Sum of values up to given index """ res = 0 while index: res += tree[index] index -= (index & -index) ...
e293194c86ad1c53a005be290ba61ef2fff097c8
705,282
def find_language(article_content): """Given an article's xml content as string, returns the article's language""" if article_content.Language is None: return None return article_content.Language.string
4a228779992b156d01bc25501677556a5c9b7d39
705,286
import collections def extract_stats(output): """Extract stats from `git status` output """ lines = output.splitlines() return collections.Counter([x.split()[0] for x in lines])
41d8aef4df3401ee8127ad0b72402ff9c54c41e3
705,294
def add_custom_encoder_arguments(group): """Define arguments for Custom encoder.""" group.add_argument( "--enc-block-arch", type=eval, action="append", default=None, help="Encoder architecture definition by blocks", ) group.add_argument( "--enc-block-repea...
f49a778b78351a08bdb411e8004d00da0ccd96a4
705,298
def sign(x): """Returns sign of x""" if x==0: return 0 return x/abs(x)
677dfd796b0ee354fbcaf78b58cf7a5a660446b5
705,300
def echo_handler(completed_proc): """Immediately return ``completed_proc``.""" return completed_proc
53f3ef51bf349ac5146014ef25b88326d5bc010e
705,302
import random def random_choice(choices): """returns a random choice from a list of (choice, probability)""" # sort by probability choices = sorted(choices, key=lambda x:x[1]) roll = random.random() acc_prob = 0 for choice, prob in choices: acc_prob += prob if roll <= acc_...
f477abe220fa9d87ee3692bed8c41973af4c637c
705,303
import torch def convert_label_to_color(label, color_map): """Convert integer label to RGB image. """ n, h, w = label.shape rgb = torch.index_select(color_map, 0, label.view(-1)).view(n, h, w, 3) rgb = rgb.permute(0, 3, 1, 2) return rgb
a37ec3ad382f88bdc9de8fbc2b4e2524213607c3
705,304
def in_nested_list(my_list, item): """ Determines if an item is in my_list, even if nested in a lower-level list. """ if item in my_list: return True else: return any(in_nested_list(sublist, item) for sublist in my_list if isinstance(sublist, list))
3daeaf89099bf19ba82eabfedd943adfb32fc146
705,306
def is_prebuffer() -> bool: """ Return whether audio is in pre-buffer (threadsafe). Returns ------- is_prebuffer : bool Whether audio is in pre-buffer. """ is_prebuffer = bool(RPR.Audio_IsPreBuffer()) # type:ignore return is_prebuffer
8afa4979578be310fd71b22907c99bb747780454
705,308
def _get_interface_name_index(dbapi, host): """ Builds a dictionary of interfaces indexed by interface name. """ interfaces = {} for iface in dbapi.iinterface_get_by_ihost(host.id): interfaces[iface.ifname] = iface return interfaces
0217f6ef8d4e5e32d76a4fc0d66bf74aa45f8c36
705,309
def delchars(str, chars): """Returns a string for which all occurrences of characters in chars have been removed.""" # Translate demands a mapping string of 256 characters; # whip up a string that will leave all characters unmolested. identity = "".join([chr(x) for x in range(256)]) return str...
a220202a05e0ead7afa6226ef309c56940a1d153
705,313
def bytes2hex(bytes_array): """ Converts byte array (output of ``pickle.dumps()``) to spaced hexadecimal string representation. Parameters ---------- bytes_array: bytes Array of bytes to be converted. Returns ------- str Hexadecimal representation of the byte array. ...
19019ee1e3cd45d671f53e0ae4fd92b283c3b38d
705,314
from pathlib import Path def to_posix(d): """Convert the Path objects to string.""" if isinstance(d, dict): for k, v in d.items(): d[k] = to_posix(v) elif isinstance(d, list): return [to_posix(x) for x in d] elif isinstance(d, Path): return d.as_posix() return...
91dbda7738308dd931b58d59dad8e04a277034ea
705,316
def firstLetterCipher(ciphertext): """ Returns the first letters of each word in the ciphertext Example: Cipher Text: Horses evertime look positive Decoded text: Help """ return "".join([i[0] for i in ciphertext.split(" ")])
87f37d1a428bde43c07231ab2e5156c680c96f91
705,318
from pathlib import Path from typing import Tuple import re def parse_samtools_flagstat(p: Path) -> Tuple[int, int]: """Parse total and mapped number of reads from Samtools flagstat file""" total = 0 mapped = 0 with open(p) as fh: for line in fh: m = re.match(r'(\d+)', line) ...
60c6f9b227cefdea9877b05bb2fe66e4c82b4dd1
705,319
def app_files(proj_name): """Create a list with the project files Args: proj_name (str): the name of the project, where the code will be hosted Returns: files_list (list): list containing the file structure of the app """ files_list = [ "README.md", "setup.py", ...
2c6cbf112c7939bea12672668c8a5db1656b6edd
705,320
import torch def log_safe(x): """The same as torch.log(x), but clamps the input to prevent NaNs.""" x = torch.as_tensor(x) return torch.log(torch.min(x, torch.tensor(33e37).to(x)))
98c73b316d22ebe9ef4b322b1ba984a734422e7a
705,321
import requests def resolve_s1_slc(identifier, download_url, project): """Resolve S1 SLC using ASF datapool (ASF or NGAP). Fallback to ESA.""" # determine best url and corresponding queue vertex_url = "https://datapool.asf.alaska.edu/SLC/SA/{}.zip".format( identifier) r = requests.head(vertex...
cf489b0d65a83dee3f87887a080d67acd180b0b3
705,322
def make_anagram_dict(filename): """Takes a text file containing one word per line. Returns a dictionary: Key is an alphabetised duple of letters in each word, Value is a list of all words that can be formed by those letters""" result = {} fin = open(filename) for line in fin: w...
c6c0ad29fdf63c91c2103cefc506ae36b64a40ec
705,323
def group_property_types(row : str) -> str: """ This functions changes each row in the dataframe to have the one of five options for building type: - Residential - Storage - Retail - Office - Other this was done to reduce the dimensionality down to the top building types. ...
44aa5d70baaa24b0c64b7464b093b59ff39d6d1c
705,324
def write_simple_templates(n_rules, body_predicates=1, order=1): """Generate rule template of form C < A ^ B of varying size and order""" text_list = [] const_term = "(" for i in range(order): const_term += chr(ord('X') + i) + "," const_term = const_term[:-1] + ")" write_string = "{0} ...
3a911702be9751b0e674171ec961029f5b10a9e7
705,325
def gen_string(**kwargs) -> str: """ Generates the string to put in the secrets file. """ return f"""\ apiVersion: v1 kind: Secret metadata: name: keys namespace: {kwargs['namespace']} type: Opaque data: github_client_secret: {kwargs.get('github_client_secret')} ...
ed2702c171f20b9f036f07ec61e0a4d74424ba03
705,327
def get_props_from_row(row): """Return a dict of key/value pairs that are props, not links.""" return {k: v for k, v in row.iteritems() if "." not in k and v != ""}
a93dfbd1ef4dc87414492b7253b1ede4e4cc1888
705,328
import math def F7(x): """Easom function""" s = -math.cos(x[0])*math.cos(x[1])*math.exp(-(x[0] - math.pi)**2 - (x[1]-math.pi)**2) return s
a17060f046df9c02690e859e789b7ef2591d1a3c
705,330
from datetime import datetime def _get_stop_as_datetime(event_json)->datetime: """Reads the stop timestamp of the event and returns it as a datetime object. Args: event_json (json): The event encapsulated as json. Returns datetime: Timestamp of the stop of the event. """ name ...
958915a568c66a04da3f44abecf0acca90181f43
705,334
import string import random def gen_pass(length=8, no_numerical=False, punctuation=False): """Generate a random password Parameters ---------- length : int The length of the password no_numerical : bool, optional If true the password will be generated without 0-9 punctuation : ...
dc0ca0c228be11a5264870112e28f27817d4bbc8
705,336
def document_version_title(context): """Document version title""" return context.title
1589a76e8bb4b4a42018783b7dbead9efc91e21a
705,337
def decide_play(lst): """ This function will return the boolean to control whether user should continue the game. ---------------------------------------------------------------------------- :param lst: (list) a list stores the input alphabet. :return: (bool) if the input character is alphabet and if only one char...
3062e1335eda572049b93a60a0981e905ff6ca0d
705,339
def _md_fix(text): """ sanitize text data that is to be displayed in a markdown code block """ return text.replace("```", "``[`][markdown parse fix]")
2afcad61f4b29ae14c66e04c39413a9a94ae30f8
705,343
def hexStringToRGB(hex): """ Converts hex color string to RGB values :param hex: color string in format: #rrggbb or rrggbb with 8-bit values in hexadecimal system :return: tuple containing RGB color values (from 0.0 to 1.0 each) """ temp = hex length = len(hex) if temp[0] == "#": ...
7adcb7b247e6fe1aefa1713d754c828d1ac4a5b0
705,349
from typing import Union from typing import Mapping from typing import Iterable from typing import Tuple from typing import Any def update_and_return_dict( dict_to_update: dict, update_values: Union[Mapping, Iterable[Tuple[Any, Any]]] ) -> dict: """Update a dictionary and return the ref to the dictionary that...
8622f96a9d183c8ce5c7f260e97a4cb4420aecc7
705,351
def cutoff_depth(d: int): """A cutoff function that searches to depth d.""" return lambda game, state, depth: depth > d
af7396a92f1cd234263e8448a6d1d22b56f4a12c
705,354
def rgb_to_hex(red, green, blue): """Return color as #rrggbb for the given RGB color values.""" return '#%02x%02x%02x' % (int(red), int(green), int(blue))
7523bcb4b7a033655c9f5059fcf8d0ed656502c8
705,356
def _is_swiftmodule(path): """Predicate to identify Swift modules/interfaces.""" return path.endswith((".swiftmodule", ".swiftinterface"))
085fa4f8735ce371927f606239d51c44bcca5acb
705,357
def get_rest_parameter_state(parameter_parsing_states): """ Gets the rest parameter from the given content if there is any. Parameters ---------- parameter_parsing_states `list` of ``ParameterParsingStateBase`` The created parameter parser state instances. Returns ------- p...
e90d1ee848af7666a72d9d0d4fb74e3fedf496fa
705,365
import io def read_all_files(filenames): """Read all files into a StringIO buffer.""" return io.StringIO('\n'.join(open(f).read() for f in filenames))
efb2e3e8f35b2def5f1861ecf06d6e4135797ccf
705,366
def path_inside_dir(path, directory): """ Returns True if the specified @path is inside @directory, performing component-wide comparison. Otherwise returns False. """ return ((directory == "" and path != "") or path.rstrip("/").startswith(directory.rstrip("/") + "/"))
30ad431f9115addd2041e4b6c9c1c8c563b93fe9
705,367
def butterworth_type_filter(frequency, highcut_frequency, order=2): """ Butterworth low pass filter Parameters ---------- highcut_frequency: float high-cut frequency for the low pass filter fs: float sampling rate, 1./ dt, (default = 1MHz) period: period of the sign...
f8ff570d209560d65b4ccc9fdfd2d26ec8a12d35
705,368
def add_to_master_list(single_list, master_list): """This function appends items in a list to the master list. :param single_list: List of dictionaries from the paginated query :type single_list: list :param master_list: Master list of dictionaries containing group information :type master_list: li...
4b4e122e334624626c7db4f09278b44b8b141504
705,370
def unmatched(match): """Return unmatched part of re.Match object.""" start, end = match.span(0) return match.string[:start] + match.string[end:]
6d34396c2d3c957d55dbef16c2673bb7f571205c
705,373
def cubicgw(ipparams, width, etc = []): """ This function fits the variation in Gaussian-measured PRF half-widths using a 2D cubic. Parameters ---------- x1: linear coefficient in x x2: quadratic coefficient in x x3: cubic coefficient in x y1: linear coefficient in y y2: quadratic coeffici...
334be9d8dc8baaddf122243e4f19d681efc707cf
705,374
def get_columns_by_type(df, req_type): """ get columns by type of data frame Parameters: df : data frame req_type : type of column like categorical, integer, Returns: df: Pandas data frame """ g = df.columns.to_series().groupby(df.dtypes).groups type_dict = {k.name: v for k, v ...
aeedea92fbfb720ca6e7a9cd9920827a6ad8c6b0
705,376
def get_total(lines): """ This function takes in a list of lines and returns a single float value that is the total of a particular variable for a given year and tech. Parameters: ----------- lines : list This is a list of datalines that we want to total. Returns: -------- ...
284f8061f3659999ae7e4df104c86d0077b384da
705,377
def box(t, t_start, t_stop): """Box-shape (Theta-function) The shape is 0 before `t_start` and after `t_stop` and 1 elsewhere. Args: t (float): Time point or time grid t_start (float): First value of `t` for which the box has value 1 t_stop (float): Last value of `t` for which the ...
8f4f0e57323f38c9cfa57b1661c597b756e8c4e7
705,378
import json import time def sfn_result(session, arn, wait=10): """Get the results of a StepFunction execution Args: session (Session): Boto3 session arn (string): ARN of the execution to get the results of wait (int): Seconds to wait between polling Returns: dict|None: Di...
ba8a80e81aa5929360d5c9f63fb7dff5ebaf91f3
705,379
def to_numpy(tensor): """Convert 3-D torch tensor to a 3-D numpy array. Args: tensor: Tensor to be converted. """ return tensor.transpose(0, 1).transpose(1, 2).clone().numpy()
034e016caccdf18e8e33e476673884e2354e21c7
705,383
import time def wait_for_result(polling_function, polling_config): """ wait_for_result will periodically run `polling_function` using the parameters described in `polling_config` and return the output of the polling function. Args: polling_config (PollingConfig): The p...
663f23b3134dabcf3cc3c2f72db33d09ca480555
705,386
def file_version_summary(list_of_files): """ Given the result of list_file_versions, returns a list of all file versions, with "+" for upload and "-" for hide, looking like this: ['+ photos/a.jpg', '- photos/b.jpg', '+ photos/c.jpg'] """ return [('+ ' if (f['action'] == 'upload') else '-...
8ca8e75c3395ea13c6db54149b12e62f07aefc13
705,387
def pwm_to_duty_cycle(pulsewidth_micros, pwm_params): """Converts a pwm signal (measured in microseconds) to a corresponding duty cycle on the gpio pwm pin Parameters ---------- pulsewidth_micros : float Width of the pwm signal in microseconds pwm_params : PWMParams PWMParams ob...
e627b84bf7e01f3d4dcb98ec94271cd34249fb23
705,389
def parse_data_name(line): """ Parses the name of a data item line, which will be used as an attribute name """ first = line.index("<") + 1 last = line.rindex(">") return line[first:last]
53a9c7e89f5fa5f47dad6bfc211d3de713c15c67
705,402
def api_error(api, error): """format error message for api error, if error is present""" if error is not None: return "calling: %s: got %s" % (api, error) return None
a9269a93d51e3203646886a893998ffec6488c95
705,403
def build_template(ranges, template, build_date, use_proxy=False, redir_target=""): """ Input: output of process_<provider>_ranges(), output of get_template() Output: Rendered template string ready to write to disk """ return template.render( ranges=ranges["ranges"], header_comments=...
ec10897cb6f92e2b927f4ef84511a7deab8cd37d
705,405
import re def finder(input, collection, fuzzy=False, accessor=lambda x: x): """ Args: input (str): A partial string which is typically entered by a user. collection (iterable): A collection of strings which will be filtered based on the `input`. fuzzy (bool): perform a fuz...
1bbe22f6b38f447f20071bd810cfee6e4e491f5f
705,408
def str2int(video_path): """ argparse returns and string althout webcam uses int (0, 1 ...) Cast to int if needed """ try: return int(video_path) except ValueError: return video_path
2d4714ec53304fb6cafabd5255a838b478780f8a
705,409
def log_sum_exp(input, dim=None, keepdim=False): """Numerically stable LogSumExp. Args: input (Tensor) dim (int): Dimension along with the sum is performed keepdim (bool): Whether to retain the last dimension on summing Returns: Equivalent of log(sum(exp(inputs), dim=dim, k...
c9c867d9d81191922a56716dab128ea71821a638
705,412
def adriatic_name(p, i, j, a): """ Return the name for given parameters of Adriatic indices""" #(j) name1 = {1:'Randic type ',\ 2:'sum ',\ 3:'inverse sum ', \ 4:'misbalance ', \ 5:'inverse misbalance ', \ 6:'min-max ', \ 7:'max-mi...
d08ed926d80aa19326ab4548288a0b9cb02737e4
705,415
def gcd(number1: int, number2: int) -> int: """Counts a greatest common divisor of two numbers. :param number1: a first number :param number2: a second number :return: greatest common divisor""" number_pair = (min(abs(number1), abs(number2)), max(abs(number1), abs(number2))) while number_pair[...
9f22c315cc23e2bbf954f06d416a2c44f95ddbb7
705,416
def get_overlapping_timestamps(timestamps: list, starttime: int, endtime: int): """ Find the timestamps in the provided list of timestamps that fall between starttime/endtime. Return these timestamps as a list. First timestamp in the list is always the nearest to the starttime without going over. Par...
0ad6836d43d670f811b436e34887e159462c9ec1
705,417
def is_sequence(arg): """Check if an object is iterable (you can loop over it) and not a string.""" return not hasattr(arg, "strip") and hasattr(arg, "__iter__")
466154b8ef9d19b53744187d44dc6cd172a70f62
705,419
def fix_stddev_function_name(self, compiler, connection): """ Fix function names to 'STDEV' or 'STDEVP' as used by mssql """ function = 'STDEV' if self.function == 'STDDEV_POP': function = 'STDEVP' return self.as_sql(compiler, connection, function=function)
b1fa48801fb397590ad5fb249d928906e7c21c8a
705,420
def d_d_theta_inv(y, alpha): """ xi'(y) = 1/theta''(xi(y)) > 0 = alpha / (1 - |y|)^2 Nikolova et al 2014, table 1, theta_2 and eq 5. """ assert -1 < y < 1 and alpha > 0 denom = 1 - abs(y) return alpha / (denom*denom)
8ed796a46021f64ca3e24972abcf70bd6f64976d
705,424
def center_crop(img, crop_height, crop_width): """ Crop the central part of an image. Args: img (ndarray): image to be cropped. crop_height (int): height of the crop. crop_width (int): width of the crop. Return: (ndarray): the cropped image. """ def get_center_crop_...
6e5fafee8c34632b61d047e9eb66e9b08b5d0203
705,425
def obj_size_avg_residual(coeffs, avg_size, class_id): """ :param coeffs: object sizes :param size_template: dictionary that saves the mean size of each category :param class_id: nyu class id. :return: size residual ground truth normalized by the average size """ size_residual = (coeffs - av...
8d44d4ebf273baf460195ec7c6ade58c8d057025
705,428
def _get_chromosome_dirs(input_directory): """Collect chromosome directories""" dirs = [] for d in input_directory.iterdir(): if not d.is_dir(): continue # Just in case user re-runs and # does not delete output files elif d.name == 'logs': continue ...
5047c0c158f11794e312643dbf7d307b381ba59f
705,429
def format_imports(import_statements): """ ----- examples: @need from fastest.constants import TestBodies @end @let import_input = TestBodies.TEST_STACK_IMPORTS_INPUT output = TestBodies.TEST_STACK_IMPORTS_OUTPUT @end 1) format_imports(import_input) -> output ----- :...
91514d19da4a4dab8c832e6fc2d3c6cbe7cca04a
705,430
def extract_signals(data, fs, segmentation_times): """ Signal that given the set of segmentation times, extract the signal from the raw trace. Args: data : Numpy The input seismic data containing both, start and end times of the seismic data. fs : float The sampling f...
81ff3d0b343dbba218eb5d2d988b8ca20d1a7209
705,433
def follow_card(card, deck_size, shuffles, shuffler): """Follow position of the card in deck of deck_size during shuffles.""" position = card for shuffle, parameter in shuffles: shuffling = shuffler(shuffle) position = shuffling(deck_size, position, parameter) return position
10774bd899afde0d64cbf800bc3dad1d86543022
705,437
import torch def besseli(X, order=0, Nk=64): """ Approximates the modified Bessel function of the first kind, of either order zero or one. OBS: Inputing float32 can lead to numerical issues. Args: X (torch.tensor): Input (N, 1). order (int, optional): 0 or 1, defaults to 0. ...
5233398b240244f13af595088077b8e43d2a4b2f
705,440
def min_rank(series, ascending=True): """ Equivalent to `series.rank(method='min', ascending=ascending)`. Args: series: column to rank. Kwargs: ascending (bool): whether to rank in ascending order (default is `True`). """ ranks = series.rank(method="min", ascending=ascending) ...
a772618570517a324a202d4803983240cb54396b
705,443
import yaml def load_yaml(filepath): """Import YAML config file.""" with open(filepath, "r") as stream: try: return yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc)
e1ec81bf36d293788303e4b3379e45ecdfb38dc0
705,445
import json import logging def parse_json(json_path): """ parser JSON Args: json_path: input json file path Returns: json_dict: parser json dict result """ try: with open(json_path) as json_file: json_dict = json.load(json_file) except Exception: l...
4bb9b14d3a751451dd2a75da9b60a355934ffa65
705,446
def count_possibilities(dic): """ Counts how many unique names can be created from the combinations of each lists contained in the passed dictionary. """ total = 1 for key, value in dic.items(): total *= len(value) return total
856eee9bac0ddf3dbc7b714bb26fe6d4f003ef95
705,449
def get_dgs(align_dg_dict): """ Function that creates inverse dictionary of align_dg_dict align_dg_dict: dict. Dictionary of alignments and clustering DG assignments Returns dg_align_dict: dict, k=dg_id, v=[alignids] align_dg_dict comes from get_spectral(graph) or get_cliques(graph) """ dgs_...
85bca47657c83d2b308d38f05d1c88d9a78fa448
705,451
from typing import Optional def parse_options(dict_in: Optional[dict], defaults: Optional[dict] = None): """ Utility function to be used for e.g. kwargs 1) creates a copy of dict_in, such that it is safe to change its entries 2) converts None to an empty dictionary (this is useful, since empty diction...
d679539ba29f4acab11f5db59c324473a2e24cc6
705,452
def GetMaxHarmonic( efit ): """Determine highest-order of harmonic amplitudes in an ellipse-fit object""" # We assume that columns named "ai3_err", "ai4_err", "ai5_err", etc. # exist, up to "aiM_err", where M is the maximum harmonic number momentNums = [int(cname.rstrip("_err")[2:]) for cname in efit.colNames ...
e11645efa40ce3995788a05c8955d0d5a8804955
705,453
def no_op(loss_tensors): """no op on input""" return loss_tensors
317474aa2ed41668781042a22fb43834dc672bf2
705,455
import torch def generic_fftshift(x,axis=[-2,-1],inverse=False): """ Fourier shift to center the low frequency components Parameters ---------- x : torch Tensor Input array inverse : bool whether the shift is for fft or ifft Returns ------- shifted array """ ...
8b5f84f0ed2931a3c1afac7c5632e2b1955b1cd5
705,457
def make_new_images(dataset, imgs_train, imgs_val): """ Split the annotations in dataset into two files train and val according to the img ids in imgs_train, imgs_val. """ table_imgs = {x['id']:x for x in dataset['images']} table_anns = {x['image_id']:x for x in dataset['annotations']} keys...
d5851974ad63caaadd390f91bdf395a4a6f1514d
705,458
import tkinter as tk from tkinter import filedialog def select_file(title: str) -> str: """Opens a file select window and return the path to selected file""" root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename(title=title) return file_path
59fdb7945389c2ba75d27e1fe20b596c4497bac1
705,459
def _loop_over(var): """ Checks if a variable is in the form of an iterable (list/tuple) and if not, returns it as a list. Useful for allowing argument inputs to be either lists (e.g. [1, 3, 4]) or single-valued (e.g. 3). Parameters ---------- var : int or float or list Variable to che...
254143646416af441d3858140b951b7854a0241c
705,461
from typing import Any from typing import List from typing import Dict def transform_database_account_resources( account_id: Any, name: Any, resource_group: Any, resources: List[Dict], ) -> List[Dict]: """ Transform the SQL Database/Cassandra Keyspace/MongoDB Database/Table Resource response for neo4j...
dac566a1e09e1e395ff6fb78d6f8931a2bca58cb
705,462