content
stringlengths
42
6.51k
def is_allowed_conference(c1, c2, conf_names, allowed_confs): """ Return True if at least one of c1/c2 is an allowed_conference conf_names is a list of all defined conferences (used to group things into an "other" category) """ if c1 not in conf_names: c1 = 'other' if c2 not in conf_name...
def base_modified_neighbours(adj_nodes_list, idx_mapping): """function maps the node indices to new indices using a mapping dictionary. Args: adj_nodes_list (list): list of list containing the node ids idx_mapping (dict): node id to mapped node id Returns: list: list of list co...
def name_and_age(name, age): """Returns a string stating the person's age.""" if age >= 0: return name + " is " + str(age) + " years old." else: return "Error: Invalid age"
def portCoerce(value): """ Coerce a string value to an int port number, and checks the validity. """ value = int(value) if value < 0 or value > 65535: raise ValueError("Port number not in range: %s" % (value,)) return value
def valid_sequence(sequences): """ Function that iterates through all protein sequences and validates that each sequence is made up of valid canonical amino acid letters. If no invalid values are found then None will be returned. If invalid letters are found in the sequence, the sequence index and t...
def baseref_to_localhost(base_url, baseref): """ Convert the url to localhost:1313 """ if baseref is None: return None replacement_url = "http://localhost:1313" return baseref.replace(base_url, replacement_url)
def header_has_value(header_name, header_value, headers): """Check that a header with a given value is present.""" return header_name.lower() in ( k.lower() for (k, v) in headers if v == header_value )
def area_triangle(base, height): """ Calculate the area of triange by multipling `base` by `height` """ return base * height / 2
def get_metadata_type(op): """Return the internal metadata type of the operation.""" return op.get('metadata', {}).get('@type')
def update_lr(learning_rate0, epoch_num, decay_rate): """ Calculates updated the learning rate using exponential weight decay. Arguments: learning_rate0 -- Original learning rate. Scalar epoch_num -- Epoch number. Integer decay_rate -- Decay rate. Scalar Returns: learning_rate -- U...
def pageinate(page, maxPage, n): """Helperfunction for making a pageselector, page is the current page, maxPage is the last page and n is the number of pages to show in the pageselector.""" pages = [page] min = page-1 max = page+1 while len(pages) < n: if (2 * page - min <= max or max > ...
def get_job_status(job_run_details_list): """ Processes the given list of dictionaries of glue job run details. ----------------------------------------------------------------- Required Parameter: job_run_details_list Ex - get_job_status(job_run_details_list) _______________...
def wesleying_categorizer(posts): """ For each event in posts, for each category in cat_tags, return the category with the maximum number of cat_tag matches. If matches = 0 for a post, return 'other' for that post. Returns a dictionary of all events and their corrosponding category. """ ca...
def _GenerateErrorMessage(error, user_input=None, error_idx=None): """Constructs an error message for an exception. Args: error: str, The error message that should be displayed. This message should not end with any punctuation--the full error message is constructed by appending more information to ...
def subarray(orig_arr: list) -> list: """ Time Complexity: O(n) """ l: int = len(orig_arr) left_sum = [-1 if _ == 0 else 1 for _ in orig_arr] for i in range(1, l): left_sum[i] += left_sum[i - 1] hash_table: dict = {} start, end = -1, -1 for i, el in enumerate(left_sum): ...
def candidate_symbol(comp): """ Return a character representing completion type. :type comp: fortpy.isense.classes.Completion :arg comp: A completion object returned by `fortpy.isense.Script.complete`. """ try: return comp.type[0].lower() except (AttributeError, TypeError): ...
def _gdr_score(venue): """Calculates a venue's score (for venues from guiaderodas). """ scores = venue['scores'].values() return sum(scores) / len(scores)
def compose_imports_content(imports_dict): """Compose suitable contents for an imports file. The contents will include import statements for all items in imports_dict. Args: imports_dict: Dictionary mapping package name to a list of file names belonging to that package. Returns: ...
def _pad(data, pad_id, width=-1): """pad function""" if width == -1: width = max(len(d) for d in data) rtn_data = [d + [pad_id] * (width - len(d)) for d in data] return rtn_data
def JoinOptionsList(cmd): """ For spawning processes using os.spawnv() to call Python, the options between double quotes (") must be put into just one element of the list. Turn the 'cmd' string into a list and consolidate all options between double quotes into one element. Currently not used, b...
def _add_indent(string, indent): """Add indent of ``indent`` spaces to ``string.split("\n")[1:]`` Useful for formatting in strings to already indented blocks """ lines = string.split("\n") first, lines = lines[0], lines[1:] lines = ["{indent}{s}".format(indent=" " * indent, s=s) fo...
def write_relevant_features_to_file(fname, clusters, cluster_dict, feature_dict, feature_count=5): """ Writes the features with the highest weight in each cluster to a file Parameters ---------- fname: str clusters: int Number of clusters cluster_dict: dict dict of dicts. fo...
def equal(obj1, obj2): """Check if two JSON objects are equal. :param obj1 first JSON object :param obj2 second JSON object :return True if obj1 == obj2 """ if type(obj1) != type(obj2): return obj1 == obj2 if isinstance(obj1, dict): if len(obj1) != len(obj2): retu...
def is_sorted(sequence, **kwargs): """ :type sequence: tuple or list :param kwargs: :func:`sorted` kwargs """ if not isinstance(sequence, (tuple, list)): raise TypeError('Sequence needs to be a tuple or a list') if not isinstance(sequence, list): sequence = list(sequence) r...
def reviewed_badge(user, talk): """Returns a badge for the user's reviews of the talk""" context = { 'reviewed': False, } review = None if user and not user.is_anonymous(): review = talk.reviews.filter(reviewer=user).first() if review: context['reviewed'] = True ...
def convertToCompList(indices, inMesh, comp="vtx"): """ convert indices to a list of the given component :param indices: list of integers representing the components values :type indices: list :param inMesh: the name of the mesh :type inMesh: string :param comp: the component type :...
def merge_dict(dict1, dict2): """Try to safely merge 2 dictionaries.""" if type(dict1) is not dict: raise Exception("dict1 is not a dictionary") if type(dict2) is not dict: raise Exception("dict2 is not a dictionary") dict3 = dict1.copy() dict3.update(dict2) return dict3
def mean(num_list): """ Computes the mean of a list. Parameters ---------- num_list: list List to calculate mean of Returns ------- mean: float Mean of list of numbers """ # check for list if not isinstance(num_list,list): raise TypeError('Funct...
def nth_item(line, n: int = 0): """returns the nth item from each line. :param n: the number of item position starting from 0 """ return line.split()[n]
def gen_n_dict(n): """Creates a doctionary where the keys range from 0 to the number of digits in n. The definition for each key is 0. """ n_dict = {} for i in range(0, len(str(n))): n_dict[i] = 0 return n_dict
def _save_file_name(in_files, header): """ Construct save file name :param in_files: :param header: :return: """ out_file_name = in_files + "_" for i in header: if len(out_file_name) > 100: break else: if i == " " or not i.isalnum(): ...
def split_by_pipes(cmd): """ Split the command by shell pipes, but preserve contents in parentheses and braces. Also handles nested parens and braces. :param str cmd: Command to investigate. :return list: List of sub commands to be linked """ # Build a simple finite state machine to spli...
def isMixedCase (tok): """Returns true if the token contains at least one upper-case letter and another character type, which may be either a lower-case letter or a non-letter. Examples: ProSys, eBay """ # Clojure original: # (fn [token] ;; ProSys, eBay # (if-not (empty? token...
def string_to_version(verstring): """ Return a tuple of (epoch, version, release) from a version string This function replaces rpmUtils.miscutils.stringToVersion, see https://bugzilla.redhat.com/1364504 """ # is there an epoch? components = verstring.split(':') if len(components) > 1: ...
def _split_actors(actors_with_transforms): """Splits the retrieved actors by type id""" vehicles = [] traffic_lights = [] speed_limits = [] walkers = [] for actor_with_transform in actors_with_transforms: actor = actor_with_transform[0] if 'vehicle' in actor.type_id: ...
def set_default(params, dict_default): """Set defaults for missing keys and add the key:value pairs to the dict.""" for key in dict_default: if key not in params: print("Setting a default value for " + str(key) + ": " + str(dict_default[key])) params[str(key...
def ljust(s, width): """ljust(s, width) -> string Return a left-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated. """ n = width - len(s) if n <= 0: return s return s + ' '*n
def difference(lists): """ Return the first set minus the rest. """ if len(lists) == 0: return lists if len(lists) == 1: return lists[0] finalList = set(lists[0]) for aList in lists[1:]: finalList = finalList - set(aList) return list(finalList)
def unpack_batch(batch, use_cuda): """ Unpack a batch from the data loader. """ if use_cuda: inputs = [b.cuda() if b is not None else None for b in batch[:7]] else: inputs = batch[:7] orig_idx = batch[7] word_orig_idx = batch[8] sentlens = batch[9] wordlens = batch[10] re...
def add_callers(target, source): """Combine two caller lists in a single list.""" new_callers = {} for func, caller in target.items(): new_callers[func] = caller for func, caller in source.items(): if func in new_callers: if isinstance(caller, tuple): # format...
def get_allen_relation(duration1, duration2): """Generates an Allen interval algebra relation between two discrete durations of time :param duration1: First duration of time (start_frame, end_frame) :type duration1: tuple :param duration2: Second duration of time (start_frame, end_frame) :type duration2: tuple "...
def _set_axes_labels(axes_dct, isbimol, bottom): """ alter the axes dictionary """ if isbimol: units = 'cm3/s' else: units = '1/s' if bottom: axes_dct['xlabel'] = '1000/T (1/K)' axes_dct['ylabel'] = 'k4/k1' else: axes_dct['ylabel'] = 'log10 k({0})'.format...
def mixin_dict(dest: dict, mixin: dict) -> dict: """Updates the first dict with the items from the second and returns it.""" dest.update(mixin) return dest
def val_100_to_dec(values): """Converts list/tuple of integers (0-100) into list of float values (0.0-1.0) :param values: (list|tuple) list/tuple of integers (0-100) :return: list of float values (0.0-1.0) """ return [value / 100.0 for value in values]
def lhs(var, mean): """LHS of the equation.""" return (var-mean)/mean
def decode_IP(IP_address): """ Returns a long int for an IPv4 or IPv6 address. @param IP_address : like "192.168.1.101" @type IP_address : str of decimal separated ints @return: int """ parts = IP_address.split('.') if len(parts) == 4 or len(parts) == 6: ipvalue = 0 for i in range(len(parts)...
def get_location_type(location, board_width): """ Returns the type of location passed, according to the width of the board provided. "Corner" returns 3. "Edge" returns 2. Otherwise returns 1. """ corners = (0, board_width - 1) if location[0] in corners and location[1] in corners: return 3 if location[0] i...
def classic_order(num, modulus): """Find the order classically via simple iteration.""" order = 1 while True: newval = (num ** order) % modulus if newval == 1: return order order += 1
def parse_artists(artist_credits): """ Create the artists list from the given list of artists. MusicBrainz does some weird bullshit for guests, where it will separate the big list of artists with the string ' feat. ', after which point all of the artists are guests. """ artists = [] is_guest...
def adjust_longitude(in_fc): """Adjusts longitude if it is less than -180 or greater than 180. Args: in_fc (dict): The input dictionary containing coordinates. Returns: dict: A dictionary containing the converted longitudes """ try: keys = in_fc.keys() if 'geometr...
def compare_ids(pool_of_narratives_ids, pool_of_summaries_ids) -> list: """Finds which narrative IDs are not yet among the summary IDs and thus need to be summarized.""" to_summarize = [] for i in pool_of_narratives_ids: if i not in pool_of_summaries_ids: to_summarize.append(i) retur...
def maybe_number(value): """Convert number strings to numbers, pass through non-numbers.""" try: return int(value) except ValueError: try: return float(value) except ValueError: return value
def Main(a, b, c, d): """ :param a: :param b: :param c: :param d: :return: """ f = b * d g = d / c q = a + f m = q + g h = m - q j = h % g return j
def sanitize_filename(f): """Removes invalid characters from file name. Args: f (:obj:`str`): file name to sanitize. Returns: :obj:`str`: sanitized file name including only alphanumeric characters, spaces, dots or underlines. """ keepchars = (" ", ".", "_") return "".j...
def isSameCharacterSequence(word): """ Checks if the string passed to it is in a sequence of identical characters """ if len(word) == 1: return False else: for i in range(len(word) - 1): if word[i] != word[i + 1]: return False return True
def is_test(test): """Check if a given test representation corresponds to a test and not to some container returned by Jenkins. :param test: Jenkins Job representation as a dictionary :type test: dict :returns: Whether the test representation actually corresponds to a test :rtype: bool """ ...
def max_len_string_encoded(d_rev): """ Calculate maximum length of huffman encodings Args: d_rev: dict encoded --> element Returns: maximum number of characters """ maxs = 0 for x in d_rev: len_bit = len(x) if(len_bit > maxs): maxs = len_bit re...
def ndvi( redchan, nirchan ): """ Normalized Difference Vegetation Index ndvi( redchan, nirchan ) """ redchan = 1.0*redchan nirchan = 1.0*nirchan if( ( nirchan + redchan ) == 0.0 ): result = -1.0 else: result = ( nirchan - redchan ) / ( nirchan + redchan ) return result
def filter_reserved(res): """ Filter reserved IP. :param res: :return: """ try: if res['data']['state'] == 'RESERVED': res['status'] = 'FAIL' res['message'] = 'Host records cannot be added if ip address is reserved.' return res except (TypeError, KeyE...
def tetra_clean(string): """ Checks that a passed string contains only unambiguous IUPAC nucleotide symbols. We are assuming that a low frequency of IUPAC ambiguity symbols doesn't affect our calculation. """ if not len(set(string) - set('ACGT')): return True return False
def _convert_delimiters_to_regex(*delimiters): """Converts a list of strings into a regex Arguments ------------------ *delimiters : str The delimiters as that should be converted into a regex Returns ------------------ regex : str The converted string ...
def _worker_command_line(thing, arguments): """ Create a worker command line suitable for Popen with only the options the worker process requires """ def a(name): "options with values" return [name, arguments[name]] * (arguments[name] is not None) def b(name): "boolean op...
def check_unique(items, title): """Ensure all items in an iterable are identical; return that one item.""" its = set(items) assert len(its) == 1, ("Inconsistent %s keys: %s" % (title, ' '.join(map(str, sorted(its))))) return its.pop()
def an(Rtw, y=1): """The time-weighted return expressed as an annual rate, then you need to annualize it using this function. Args: Rtw: Time-weighted return y: Number of years for the period Returns: Time-weighted return expressed as an annual rate Example: If you...
def _is_member_of(cls, obj): """ returns True if obj is a member of cls This has to be done without using getattr as it is used to check ownership of un-bound methods and nodes. """ if obj in cls.__dict__.values(): return True # check the base classes if cls.__bases__: f...
def resolve_option_flag(flag, df): """ Method to resolve an option flag, which may be any of: - None or True: use all columns in the dataframe - None: use no columns - list of columns use these columns - function returning a list of columns """ if flag is N...
def is_tagged_parameter(argument: str) -> bool: """Return True if the directive argument defines a tagged parameter, and False otherwise.""" return argument.startswith("%")
def check_uniqueness_in_rows(board: list) -> bool: """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*',\ '*543215', '*35214*', '*41532*', '*2*1***']) True >>> ...
def merge_elements_by(seq, conn, wrapped_in_par = True): """Produces a string containing all elements of the sequence merged by a provided connective.""" if len(seq) == 0: return '' elif len(seq) == 1: return seq[0] else: sf = '({0})' if wrapped_in_par else '{0}' return c...
def parse_admins(customer_admins_json): """Takes a list of customer admins and writes a file of symplexity logins where 2fa is not enabled""" print("Checking for MFA and API access") symp_2fa_disabled = [] for customer in customer_admins_json: for admin in customer['admins']: try...
def get_textbox_dimensions(contentstring): """ get relative height and width to create textbox""" x = 80 y = 0 for stringline in contentstring.splitlines(): y = y + 1 linelength = len(stringline) if linelength > x: x = linelength x = x * 8 y = y * 20 retur...
def check_filter_status(options, filter): """Check if the active filter is among the available options, and return 'checked' if filter is not active. Used in FilterDialog to select the first radio button if the filter is not active. """ for option in options: if filter == option[1]: ...
def fib_2_recursive_memoize(n, cache={}): """ Solution: Recursive solution that memorizes previously computed values by storing them in memory. Complexity: Time: O(n) Space: O(n) """ if n < 0: raise ValueError('input must be a positive whole number') if n in [0, 1]: return n if n in cache: return ca...
def has_prefix(sub_s, d): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for word in d: if word.startswith(sub_s): return True return False
def normalize_title(title): """Return title without ',' and '?'""" return title.lower().replace(',', '').replace('?', '')
def diff_action(diff): """Return 'add', 'replace', or 'delete' based on action represented by difference tuple `d`. Append "_rule" if the change is a Selector. """ if "replace" in diff[-1]: result = "replace" elif "add" in diff[-1]: result = "add" elif "delete" in diff[-1]: ...
def reverse_table(table): """ Args: table returns: table inverse Raises ValueError if input param is not a list Raises ValueError if Il ne faut pas une liste vide Raises ValueError if Il ne faut pas une liste vide """ #test du type de variable if not(isinstance(table, list)): ...
def starmap(function, argument_list): """Apply a multivariate function to a list of arguments in a serial fashion. Uses the starmap() function from itertools in Python's standard library. Args: function: A callable object that accepts more than one argument argument_list: An iterable objec...
def name(obj): """Try to find some reasonable filename for the obj.""" return (getattr(obj, 'filename', 0) or getattr(obj, '__name__', 0) or getattr(getattr(obj, '__class__', 0), '__name__', 0) or str(obj))
def time_formatter(milliseconds: int) -> str: """Inputs time in milliseconds, to get beautified time, as string""" seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ((str(d...
def logical_equivalence(*c): """Operator definition of logical equivalence taking two parameters """ nonzero_c1 = (c[0] != 0) nonzero_c2 = (c[1] != 0) return ((nonzero_c1 & nonzero_c2) | (~nonzero_c1 & ~nonzero_c2))
def correct_invalid_value(value, args): """This cleanup function replaces null indicators with None.""" try: if value in [item for item in args["nulls"]]: return None if float(value) in [float(item) for item in args["nulls"]]: return None return value ...
def deep_merge(dict1, dict2): """ overrides entries in dict1 with entries in dict2! """ if isinstance(dict1, dict) and isinstance(dict2, dict): tmp = {} for key in dict1: if key not in dict2: tmp[key] = dict1[key] else: tmp[key] = d...
def getFilename(url): """Attempts to get the filename from the URL""" components = url.split('/') fname = components[-1] if '.' in fname: return fname else: return None
def generate_may_be_proposition(proposition): """ Get may be proposition: 1:red -> *(1:red) """ may_be = "*(" + proposition + ")" return may_be
def isFasta(nm): """does this filename look like a FASTA file?""" if nm.endswith(".fa"): return True if nm.endswith(".fas"): return True if nm.endswith(".fasta"): return True if nm.endswith(".fna"): return True return False
def parse_entry(entry): """ Parse one entry and stores it to provided dict - converts value to int if possible :type entry: str :rtype: dict """ k, v = entry.split('=') try: v = int(v) except Exception: pass return {k: v}
def avg_n_dicts(dicts): """https://github.com/wronnyhuang/metapoison/blob/master/utils.py.""" # given a list of dicts with the same exact schema, return a single dict with same schema whose values are the # key-wise average over all input dicts means = {} for dic in dicts: for key in dic: ...
def detectionoutput_shape(input_shape): """ the output shape of this layer is dynamic and not determined by 'input_shape' Args: @input_shape (list of int): input shape Returns: @output_shape (list of num): a list of numbers represent the output shape """ output_shape = [-1, 6] ...
def get_built_config_distribution(built_config, minimal_diffs): """ Args: built_config: Configuration built so far minimal_diffs: List of all the minimal diffs in built config space Returns: A probability distribution over blocks in the built config -- probabilities of next removal ...
def calc_density(temp, pressure, gas_constant): """ Calculate density via gas equation. Parameters ---------- temp : array_like temperatur in K pressure : array_like (partial) pressure in Pa gas_constant: array_like specicif gas constant in m^2/(s^2*K) Returns ...
def image_filename(im_num=0, pos_num=0, channel_num=0, z_num=0): """ create a filename based on the image number, position, channel and z Micro-manager format: img_channel000_position001_time000000002_z000.tif """ filename = "img_channel{0:03d}_position{1:03d}_time{2:09d}_z{3:03d}.tif" retu...
def bbox_parse(annotation, gt_bboxes, gt_labels, gt_bboxes_ignore, cat2label): """ Parse ground-truth box in an annotation dict. There is no return in this function, because the `gt_bboxes`, `gt_labels`, `gt_bboxes_ignore` are lists, and if they have append element in this function, the change will ...
def python2round(f): """ use python2 round function in python3 """ if round(f + 1) - round(f) != 1: return f + abs(f) / f * 0.5 return round(f)
def binary_to_decimal(string): """Converts a binary string, sign bit then msb on left, to an integer. Negative numbers are assumed to be twos-complements, i.e., bitwise complement + 1.""" length = len(string) # negative part doesn't work if string[0] == '1': negative = True else: ...
def matches_filter(graph, props): """ Returns True if a given graph matches all the given props. Returns False if not. """ for prop in props: if prop != 'all' and not prop in graph['properties']: return False return True
def parse_fixed_width(types, lines): """Parse a fixed width line.""" values = [] line = [] for width, parser in types: if not line: line = lines.pop(0).replace("\n", "") values.append(parser(line[:width])) line = line[width:] return values
def subtract_nutrients(nutrients_total,nutrients): """Calculate total of all nutrients of ingrerdients after deletion the ingredient""" for nutrient in nutrients: if nutrient in nutrients_total: nutrients_total[nutrient]["amount"] -= nutrients[nutrient]["amount"] nutrients_total[...
def _full_license(image_info): """ Get the full license from the image info :param image_info: the information about a particular image :return: the full license text for the image """ license_name = image_info['license'].upper() license_version = image_info['license_version'].upper() ...
def _split_value_units(raw_str): """Take a string with a numerical value and units, and separate the two. Args: raw_str (str): the string to parse, with numerical value and (optionally) units. Returns: A tuple (value, units), where value is a string and units is either ...