content
stringlengths
42
6.51k
def single_axes(axes): """ *axes* contains positive values, then it is the position of this axis in the original matrix, otherwise it is -1 meaning this axis is an added single dimension to align all the dimensions based on the einsum equation. :param axes: axes described above :return: lis...
def get_my_guess(num_people, num_days=365): """ Compute my initial guess of the consecutive birthdays probability """ left_result = 1 - (num_people - 1) / float(2 * num_days + num_people - 1) right_result = 1 for i in range(num_people): right_result *= (num_days - 2 * i)...
def variance(xl): """Return the variance of a list.""" mean = sum(xl) / len(xl) return sum([(x - mean) ** 2 for x in xl]) / (len(xl) - 1)
def attenuation(frequency, liquid_water_temperature, liquid_water_density): """ Calculate the specific attenuation due to cloud or fog. :param frequency: The operating frequency (GHz). :param liquid_water_temperature: The liquid water temperature (K). :param liquid_water_density: The liquid water de...
def epoch_to_steps(epoch: float, steps_per_epoch: int, min_epoch: float = 0.0) -> int: """ :param epoch: the (fractional) epoch to convert to the proper number of steps :param steps_per_epoch: number of steps (batches) taken per epoch while training :param min_epoch: if the epoch is less than this, will...
def get_matching_shapes(source_shapes, target_shapes): """ Returns the matching shapes This Function will return a dict that contains the target matching shape name from the source. :param source_shapes: sources dictionary containing prefix-less shapes :type source_shapes: dict :param target:...
def generate_name(route, deployment): """ Generate the name for a route in a given deployment :param route: the id of the route :param deployment: the id of the route :return: the unique name for the route """ return f"{route}_{deployment}"
def figure_format(figure): """Takes a dollar figure and formats it with commas. :param figure: The figure to be formatted :return: The figure formatted with commas in appropriate places :rtype: str :raise ValueError: figure must contain a decimal to split str :raise ValueError: figure must be a...
def replace0(x): """ Replace any floats generated by pandas """ x = x.replace(".0\t", "\t") x = x.replace(".0\n", "\n") return(x)
def _combine_ind_ranges(ind_ranges_to_merge): """ Utility function for subdivide Function that combines overlapping integer ranges. Example [[1,2,3], [2,3], [3], [4,5], [5]] -> [[1,2,3], [4,5]] """ ind_ranges_to_merge = sorted(ind_ranges_to_merge) stack = [] result = [] for curr...
def control_input(options: int, input_ctl: int) -> bool: """Function to control input of user. Args: options: limit of input input_ctl: input of user Return: Bool """ if input_ctl is not None: if isinstance(input_ctl, int): if 0 < input_ctl <= 3: r...
def merge_datasets(num_evts_per_dataset): """ Return dict `<merged_dataset> : list of <dataset>' Associates all datasets in `num_evts_per_dataset' that belong by their name to the same PD but to a different run era. For example: isolated_mu_runa_v1, isolated_mu_runb_v1, isolated_mu_runc_v2 --> iso...
def action(function=None, *, permissions=None, description=None): """ Conveniently add attributes to an action function:: @admin.action( permissions=['publish'], description='Mark selected stories as published', ) def make_published(self, request, queryset): ...
def linear(xs, slope, y0): """A simple linear function, applied element-wise. Args: xs (np.ndarray or float): Input(s) to the function. slope (float): Slope of the line. y0 (float): y-intercept of the line. """ ys = slope * xs + y0 return ys
def valid_sample(sample): """Check whether a sample is valid. sample: sample to be checked """ return ( sample is not None and isinstance(sample, dict) and len(list(sample.keys())) > 0 and not sample.get("__bad__", False) )
def clamp(value, minimum, maximum): """ Reset value between minimum and maximum """ return max(min(value, maximum), minimum)
def solution(A): """The solution function.""" num_of_A = len(A) sum_of_A = 0 # <== The complete sum of elements of A. sum_of_A_1 = 0 # <== The sum of elements of lower indices of A. sum_of_A_2 = 0 # <== The sum of elements of higher indices of A. # Calculating the complete sum of elements ...
def indentblock(text, spaces=0): """Indent multiple lines of text to the same level""" text = text.splitlines() if hasattr(text, 'splitlines') else [] return '\n'.join([' ' * spaces + line for line in text])
def fillIdAppE(errMsg, errCode): """ Get error message :param errMsg: :param errCode: :return: error message """ return "{}{:0>4d} {}".format("EACCAPP", errCode, errMsg)
def isPostCSP(t, switch=961986575.): """ Given a GALEX time stamp, return TRUE if it corresponds to a "post-CSP" eclipse. The actual CSP was on eclipse 37423, but the clock change (which matters more for calibration purposes) occured on 38268 (t~=961986575.) :param t: The time stamp...
def sessions_with_product_views(total_sessions, sessions_with_product_views): """Return the percentage of sessions with product views during the period. Args: total_sessions (int): Total number of sessions within the period. sessions_with_product_views (int): Total number of sessions with produ...
def int2float_ensure_precision(value, scale): """Cast an int to a float with the given scale but ensure that the values (up to the scale) are correct. eg. 42112588 with scale 4 should certainly render: 4211.2588 and not 4211.258799999999 """ if scale == 0 or value == 0: return value # Add ...
def compute_score_shift(nEM, nLM, nR, c, nEMX, nLMX): """ Compute constant shift for RF score as described in FastMulRFS paper Parameters ---------- nEM : int Number of edges in MUL-tree nLM : int Number of leaves in MUL-tree nR : int Number of edges in MUL-tree...
def site_confusion(y_true, y_pred, site_lists): """What proportion of misidentified species come from the same site? Args: y_true: string values of true labels y_pred: string values or predicted labels site_lists: list of site labels for each string label taxonID -> sites Returns: ...
def div(a, b): """Divide two values, ignoring None""" if a is None: if b is None: return None else: return 1 / b elif b is None: return a return a / b
def get_traceback(exc=None): """ Returns the string with the traceback for the specifiec exc object, or for the current exception exc is not specified. """ import io, traceback, sys # pylint: disable=multiple-imports if exc is None: exc = sys.exc_info() if not exc: return N...
def getval(constraints, key, db): """ Get the value of a constraint """ value = constraints[key] if callable(value): # find param param = [e for e in db.parameters if e['Name'] == key][0] if 'Categories' not in param: return '' return [e for e in param['Categor...
def get_values(line): """ Returns the portion of an INSERT statement containing values """ return line.partition('` VALUES ')[2]
def construct_bericht_sent_query(graph_uri, bericht_uri, verzonden): """ Construct a SPARQL query for marking a bericht as received by the other party (and thus 'sent' by us) :param graph_uri: string :param bericht_uri: URI of the bericht we would like to mark as sent. :param verzonden: ISO-string ...
def sort_lists(time_list,scale_factor_list,initial_rho_list): """ Takes the lists and sorts them based on the initial_b_list. """ RHO_MAP = {initial_rho_list[i] : (time_list[i],scale_factor_list[i]) for i in range(len(initial_rho_list))} initial_rho_list.sort() time_list = [RHO_MAP[...
def format_bytes(num, suffix="B"): """ Format bytes as a human readable string. Thanks to https://stackoverflow.com/a/1094933. """ for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 ...
def match_label(_lbls: list, label: str, address: int) -> list: """ Given a label and an address, add it (if required) to the list of labels. Parameters ---------- _lbls: list, mandatory A list of the known labels and their addresses label: str, mandatory The potential new labe...
def preprocess_zenodo_metadata(raw_metadata: dict): """Method to pre-process metadata into the Zenodo format for upload.""" # If metadata comes from the UI, need to get some data into the right format. # Creators must be a JSON array # A list of dictionaries makes a JSON array type. creators = [] ...
def encode_labels(label: str, label2id: dict) -> int: """ Encodes labels with corresponding labels id. If relation is unknown, returns special id for unknown relations""" return label2id.get(label, "unk")
def update_orb_spec(spec, param): """ Update an orbital specification. Enter: spec: the text specification. param: a dictionary of parameters to update. """ lines = [line for line in spec.replace('\r', '\n').split('\n') if line.strip()] out = [] for line in lines: parts = ...
def range_size(range_list): """ calculate total size of range_list """ r_s=0 for r in range_list: r_s+= r[1]- r[0] return r_s
def lookup_object_type(rest_client, type_id): """ convert a resilient object_type_id into a label for use in api call for rule invocation :param type: internal number of object :return: object name or ValueError if not found """ lookup = ['', 'tasks', 'notes', 'milestones', 'artifacts', 'attachm...
def encDec0(i): """Round to the nearest decade, decade starts with a '0'-ending year.""" return (i // 10) * 10
def amol(lst, **kwargs): """All Math On List; a=Add, s=Subtract, m=Multiply, d=Divide, p=To the power of""" # Math Operator acting appon All values of a List data = list(lst) rng = range(len(data)) operators = kwargs.keys() if 'a' in operators:#add for i in rng: data[i] += kw...
def lyap_lrcf_solver_options(lradi_tol=1e-10, lradi_maxiter=500, lradi_shifts='projection_shifts', projection_shifts_init_maxiter=20, projection_shifts_init_seed=None, project...
def has_administrative_perm(user_level, obj, ctnr, action): """ Permissions for ctnrs or users Not related to DNS or DHCP objects """ return { 'cyder_admin': action == 'view' or action =='update', 'admin': action == 'view' or action =='update', 'user': action == 'view', ...
def second_smallest(numbers): """ Find second smallest number on a list """ m1, m2 = float('inf'), float('inf') for x in numbers: if x <= m1: m1, m2 = x, m1 elif x < m2: m2 = x return m2
def pastis_matrix_measurements(nseg): """ Calculate the total number of measurements needed for a PASTIS matrix with nseg segments :param nseg: int, total number of segments :return: int, total number of measurements """ total_number = (nseg**2 + nseg) / 2 return int(total_number)
def get_float_values(line): """ Parse csv string with float values to list of floats. :param line: csv string, e.g., ".4,2,-3.4" :return: List of floats. Empty list if parsing failed. """ result_list = [] yrp = line.split(",") for x in yrp: if x.strip() == "": resul...
def slugify(error) -> str: """Replace newlines by space.""" return str(error).replace("\n", "")
def get_otool_path(otool_line): """Parse path from a line from ``otool -L`` output. This **assumes** the format, but does not check it. Args: otool_line (str): A dependency (or ``install_name``) from ``otool -L`` output. Expected to be of the form '\t{PATH} (compatibility ...)'. R...
def PolyCoefficients(xt, coeffs): """ Returns a polynomial for ``x`` values for the ``coeffs`` provided. The coefficients must be in ascending order (``x**0`` to ``x**o``). """ o = len(coeffs) yt = 0 for i in range(o): yt += coeffs[i] * xt ** i return yt
def sn(ok): """converts boolean value to +1 or -1 """ if ok:return 1 else: return -1
def cm2inch(*tupl): """Convert input cm to inches """ inch = 2.54 if isinstance(tupl[0], tuple): return tuple(i/inch for i in tupl[0]) else: return tuple(i/inch for i in tupl)
def factorial(n): """ Return factorial of n >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] """ fact = 1 for i in range(1, n + 1): fact = fact * i return fact
def is_cmake(file_path): """ :param file_path: the path of a file :return: true if file with suffix .cmake """ return file_path.split(".")[-1] == "cmake"
def is_macho(filename): """ Check that a file is in the Mach-O format. """ with open(filename, "rb") as fp: data = fp.read(2) fp.close() return data == '\xcf\xfa'
def get_key(dict, key): """Trivial helper for the common case where you have a dictionary and want one value""" return dict.get(key, None)
def get_data_struct_name(sub): ############################################################################### """ >>> get_data_struct_name("my_sub_name") 'MySubNameData' >>> get_data_struct_name("sub") 'SubData' """ return "".join([item.capitalize() for item in sub.split("_")]) + "Data"
def screen_collection(src, cols, possibilities): """Return entries in a list of dicts where a set of fields match one of a set of possible values for those fields.""" rows = [] for row in src: check = tuple([row[col] for col in cols]) if check in possibilities: rows.append(row) ...
def save_secret_file(secret, retrieved_file): """ Save the secret data from bunary to file. """ try: with open(retrieved_file, 'wb') as f: f.write(secret) except TypeError: with open(retrieved_file, 'wb') as f: f.write(secret.encode()) return '{} saved wi...
def collatzSeq(n, outputSeq = None): """ collatzSeq(int, list) -> list accepts two inputs: - n (required): the integer against which the conjecture is about to be tested - outputSeq (optional): only used during ricursion to store the state of the current test """ if outputSeq is None: ...
def parse_params_int(params, p): """ Get and parse an int value from request params. """ val = params.pop(p, None) try: return int(val, 10) except ValueError: return None
def A2(x: int, y: int) -> dict: """Graph function using primitive output type.""" return {'a': x + y}
def find_factorial(number: int) -> int: """Return factorial for specified number.""" if number > 0: return number * find_factorial(number - 1) elif number == 0: return 1 else: raise ValueError("Negative number")
def factorial(num): """This is a recursive function that calls itself to find the factorial of given number""" if num == 1: return num else: return num * factorial(num - 1)
def get_vigra_feature_names(feature_names): """ For the given list of feature names, return the list of feature names to compute in vigra. Basically, just remove prefixes and suffixes For example: ['edge_vigra_mean', 'sp_vigra_quantiles_25'] -> ['mean', 'quantiles'] """ feature_names = list...
def compare(x, y): """Comparison helper function for multithresholding. Gets two values and returns 1.0 if x>=y otherwise 0.0.""" if x >= y: return 1.0 else: return 0.0
def _class_required(type_, class_, params): """Return true if method requires a `cls` instance.""" if not params or class_ is None: return False return type_ == 'classmethod'
def int8_from_byte(byte): """Convert one byte to signed integer.""" if byte > 127: return (256 - byte) * (-1) else: return byte
def parse_cmd(cmd): """ Split the cmd string. Delimiters are: space, simple and double quotes """ SINGLE_QUOTE = "'" DOUBLE_QUOTE = "\"" ESPACE = " " result = [] cache = "" quote_context = None collect_cache = False for char in cmd: if quote_context is None: # outsid...
def Like(field, value): """ A criterion used to search for objects having a text field's value like the specified `value`. It's a wildcard operator when the searched value must specify asteriscs. For example: * search for cases where title is like `*malspam*` * search for observable where descript...
def parse_package_status(release, package, status_text, filepath): """ parse ubuntu package status string format: <status code> (<version/notes>) :return: dict where 'status' : '<not-applicable | unknown | vulnerable | fixed>', 'fix-version' : '<version with issue fixe...
def check_input_structure_at_id(input_file_dict): """Check all input file strings and make sure they are @id format.""" all_inputs = [] error = '' for an_input_arg in input_file_dict: # skip the parameter key if an_input_arg == 'additional_file_parameters': continue i...
def addText(text): """ Updates the textbox in the corner of the svg. Ugly but works for current situation :param text: text needed to be updated :return: """ return '<text xml:space="preserve" style="font-style:normal;font-weight:normal;font-size:9.75123596px;line-height:1.25;' \ 'font-fa...
def check_type_value(val, name, expected_type, allow_none=False, print_value=True, none_msg=''): """ Check if the given value is of expected type. And also check if the val is None. :param val: the given value to check :param name: name of val :param expected_type: the expected type :param allo...
def sorted_string(string: str) -> str: """Returns string as sorted block. Examples: >>> assert sorted_string("21AxBz") == "xzAB12" >>> assert sorted_string("abacad") == "abcd-a-a" >>> assert sorted_string("") == "" """ blocks = [f"-{item}" for item in string if list(string).coun...
def bool_to_returncode(success: bool) -> int: """Return 0 if |success|. Otherwise return 1.""" if success: print('Success.') return 0 print('Failed.') return 1
def _az_string(az): """Return an azimuth angle as compass direction. >>> _az_string(0) 'N' >>> _az_string(11) 'N' >>> _az_string(12) 'NNE' >>> _az_string(360 - 12) 'NNW' >>> _az_string(360 - 11) 'N' """ assert 0.0 <= az <= 360 ...
def sm_filter_opcodes(sm_opcodes, code='equal'): """Filter SequenceMatcher opcodes Parameters ---------- sm_opcodes : sequence The result of difflib.SequenceMatcher.get_opcodes() code : string The code to remove. Returns ------- result : The sequence with the specified...
def decode_boolean_setting(setting): """ Decodes a boolean string of "True" or "False" to the coorect boolean value. """ return setting == "True"
def subclasses(cls, abstract=False, private=False): """Return the subclasses of class `cls` as a dict. If abstract, include classes with abstract methods. If private, include private classes. """ return { sc.__name__: sc for sc in cls.__subclasses__() if (abstract or not sc....
def _request_check(input_json): """Check if the request json is valid""" if input_json is None or not isinstance(input_json, dict): return 'Can not parse the input json data - {}'.format(input_json) try: c = input_json['context'] qa = input_json['qas'][0] qid = qa['qid'] ...
def mind_your_PDQs(P=range(0,3), D=range(1,3), Q=range(0,3), s=None): """ pdqs = mind_your_PDQs() pdqs['pdq'] pdq = pdqs['pdq'] """ import itertools pdqs = {} if s is None: pdqs['pdq'] = list(itertools.product(P,D,Q)) else: pdqs['PDQs'] = list(itertools.product...
def relparse(myver): """Parses the last elements of a version number into a triplet, that can later be compared: >>> relparse('1.2_pre3') [1.2, -2, 3.0] >>> relparse('1.2b') [1.2, 98, 0] >>> relparse('1.2') [1.2, 0, 0] """ number = 0 p1 = 0 p2 = 0 myne...
def correct_sentence(text: str) -> str: """ returns a corrected sentence which starts with a capital letter and ends with a dot. """ # your code here if text.endswith('.'): return text.capitalize() else: return text.capitalize() + "."
def mkdir_cmd(path): """Return mkdir command""" return " ".join(["/bin/mkdir", "-p", path])
def is_tool(name): """Check whether `name` is on PATH.""" from distutils.spawn import find_executable return find_executable(name) is not None
def parameter_dict(nested_parameter_dict, choices_dict): """Non-nested parameter as a dictionary.""" return { 'key': 'key', 'type': 'Any', 'multi': False, 'display_name': 'display', 'optional': True, 'default': 'default', 'description': 'desc', 'ch...
def maximum(a, b, *others): """The maximum value of all arguments""" return max(a, b, *others)
def list_diff(list1, list2, identical=False): """ API to get the differece in 2 lists :param list1: :param list2: :param identical: :return: """ result = list() for value in list1: if identical: if value in list2: result.append(value) else:...
def stripIfPrefixFromIfName(ifName): """Strip prerix from BDS interface name. Args: ifName (str): BDS interface name Returns: str: BDS interface name suffix """ ifName, _ , ifIndex = ifName.partition('-') if ifIndex.count('/') in (2, 4): return ifIndex elif ifInde...
def is_vararg(param_name): # type: (str) -> bool """ Determine if a parameter is named as a (internal) vararg. :param param_name: String with a parameter name :returns: True if the name has the form of an internal vararg name """ return param_name.startswith('*')
def dedup(L): """ Given a list, deduplicate it """ if L: L.sort() last = L[-1] for i in range(len(L)-2, -1, -1): if last == L[i]: del L[i] else: last = L[i] return L
def in_box(coords, box): """ Find if a coordinate tuple is inside a bounding box. :param coords: Tuple containing latitude and longitude. :param box: Two tuples, where first is the bottom left, and the second is the top right of the box. :return: Boolean indicating if the coordinates are in the box....
def greet(name): """ function greet() inside dec4 sample """ print(f"Hello {name}") return 42
def isIsomorphic(tree1, tree2): """Checks if two rooted binary trees (of type Node) are isomorphic.""" # Both roots are empty: trees isomorphic by def if tree1 == None and tree2 == None: return True # Exactly one empty: trees can not be isomorphic elif tree1 == None or tree2 == None: ...
def is_safe(board, row, col, size): """Check if it's safe to place a queen at board[x][y]""" #check row on left side for iy in range(col): if board[row][iy] == 1: return False ix, iy = row, col while ix >= 0 and iy >= 0: if board[ix][iy] == 1: return False ...
def cardlist_minus(cardlist1, cardlist2): """Subtract two cardlist dictionaries""" for name, amount in cardlist2.items(): if name in cardlist1: cardlist1[name] = cardlist1[name] - amount if cardlist1[name] <= 0: del cardlist1[name] return cardlist1
def get_link_label_position(dictionary_key_string): """Get the position of a reference-style link label from a dictionary-key string, returning the position in list format. The link label's position is stored with 3 comma-separated numbers that indicate a link label's *line number*, *left bracket index*, a...
def get_many(d, required=None, optional=None, one_of=None): """Extract values from a dict for unpacking into simple variables. ``d`` is a dict. ``required`` is a list of keys that must be in the dict. The corresponding values will be the first elements in the return list. Raise KeyError if any of ...
def fibonacci(n: int) -> int: """ :param n: the place in the Fibonacci sequence :return: the nth number of the Fibonacci sequence """ if n < 2: return n return fibonacci(n - 2) + fibonacci(n - 1)
def fsm_transition_hints(context): """ Displays hints about why a state transition might not be applicable for this the model. """ original = context.get('original', None) if not original: return {} model_admin = context.get('adminform').model_admin return { 'transition_...
def relmatrix(f, val1, val2): """ A table (2d numpy array) obtained by applying function `f` to different combinations of values from `val1` and `val2` :param f: applied function :param val1: row values :param val2: col values :return: numpy array -- the table """ res = [[''] + list(...
def clear_double_slashes(_str): """ Recursive clear double slashes from str """ while _str.count("//"): _str = _str.replace("//", "/") return _str