content
stringlengths
42
6.51k
def fix_hyphen_commands(raw_cli_arguments): """Update options to match their module names with underscores.""" for i in ['gen-sample', 'run-aws', 'run-python', 'run-stacker']: raw_cli_arguments[i.replace('-', '_')] = raw_cli_arguments[i] raw_cli_arguments.pop(i) return raw_cli_arguments
def DecomposeStandardFieldName(standard_field_name): """Utility function takes a standard_field_name from the ontology and returns its composition. Example: [run_command_1] -> ['Run', 'Command'] Args: standard_field_name: a standard field name defined by Carson. Returns: list: a list of concepts that ...
def human_readable_time(time_ps: int) -> str: """Transform **time_ps** to a human readable string. Args: time_ps (int): Time in pico seconds. Returns: str: Human readable time. """ time_units = ['femto seconds', 'pico seconds', 'nano seconds', 'micro seconds', 'mili seconds'] t...
def _raw_misc_to_dict(raw): """ Converts text-form of misc to a dictionary. misc will be stored in the form ["(key1, val1)", "(key2, val2)",...] """ ret = {} for elem in raw: key, _, val = elem.partition(',') key = key[1:].strip() val = val[:-1].strip() ret[key] ...
def _reducemax_pattern(kernel_info): """Check ReduceMax and return reduce_size when true.""" for op in kernel_info['op_desc']: if op['name'] == 'ReduceMax': input_shape = op['input_desc'][0][0]['shape'] batch_size = input_shape[0] reduce_size = batch_size * input_shap...
def files_belong_to_same_module(filename_cpp, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cpp, foo_test.cpp and foo_unittest.cpp belong to the same 'module' if they are in the same directory. some/path...
def combine_labels(left, right): """ For use with the join operator &: Combine left input/output labels with right input/output labels. If none of the labels conflict then this just returns a sum of tuples. However if *any* of the labels conflict, this appends '0' to the left-hand labels and '1...
def xor(a, b): """ this function replicate the XOR operation """ if a != b: return "1" else: return "0"
def findPointMax(listInd): """ This function return the maximal not null value in a list In : list : List of index Out : maximal indexe """ i = len(listInd) - 1 while((listInd[i] == [] or listInd[i] == None) and i >= 0): i = i - 1 if i == 0: return None ...
def is_apple_item(item_pl): """Returns True if the item to be installed or removed appears to be from Apple. If we are installing or removing any Apple items in a check/install cycle, we skip checking/installing Apple updates from an Apple Software Update server so we don't stomp on each other""" # ...
def max_value(d): """ Takes a dictionary d and returns the maximum element value and its corresponding key. Raises a TypeError if any of the values are not comparable to each other. >>> max_value({'a': 12, 3: 45}) (3, 45) >>> max_value({}) is None True >>> ma...
def load_sets(path='../data/processed/', val=False): """Load the different locally save sets Parameters ---------- path : str Path to the folder where the sets are saved (default: '../data/processed/') Returns ------- Numpy Array Features for the training set Numpy Arra...
def mean(data): """Return the sample arithmetic mean of data. Arguments: data (list): A list of numbers. Returns: float: Mean of the provided data. """ n = len(data) if n < 1: raise ValueError('mean requires at least one data point') return sum(data)/flo...
def indexesof(l, fn, opposite=0): """indexesof(l, fn) -> list of indexes Return a list of indexes i where fn(l[i]) is true. """ indexes = [] for i in range(len(l)): f = fn(l[i]) if (not opposite and f) or (opposite and not f): indexes.append(i) return ind...
def stueckweise_hermite(xx, x_list, f_list, abl_list, abl = 0): """ Stueckweise Hermite-Interpolation Sei x in dem Intervall [xl,xr] := [x_list[i-1],x_list[i]] und p das kubische Polynom mit p(xl) = f_list[i-1], p(xr) = f_list[i], p'(xl) = abl_list[i-1], p'(xr) = abl_list[i] Die Funktion wertet ...
def is_irreflexive(universe, relation): """ Function to determine if a relation of a set is irreflexiver :param universe: a set :param relation: a relation on set universe return: True if relation is a reflexiver relation of set universe """ new_set = {(a, b) for a in universe for b in unive...
def to_dict(lists): """ convert lists to a dictionary where the index-th elt is the key not needed? """ return {l[i]: l for i, l in enumerate(lists)}
def parse_instream(txt): """Parse the current instruction by stripping unecessary characters and separating C + RX notation into two elements""" seq = [] # Container to hold parsed instruction for i in range(0, len(txt)): s = txt.pop(0).replace(",", "").lower() # Strip commas and make low...
def img_resize_near(grid, w2, h2): """ From techalgorithm.com """ w1 = len(grid[0]) h1 = len(grid) newgrid = [] x_ratio = w1/float(w2) y_ratio = h1/float(h2) for i in range(0, h2): py = int(i*y_ratio) newrow = [] for j in range(0, w2): px = in...
def is_palindrome_v2(head) -> bool: """Use the runner method""" # Create a reversed linked list by using the runner method fast = slow = head rev = None while fast and fast.next: fast = fast.next.next rev, rev.next, slow = slow, rev, slow.next # When a list is an even if fa...
def nth(n): """ Formats an ordinal. Doesn't handle negative numbers. >>> nth(1) '1st' >>> nth(0) '0th' >>> [nth(x) for x in [2, 3, 4, 5, 10, 11, 12, 13, 14]] ['2nd', '3rd', '4th', '5th', '10th', '11th', '12th', '13th', '14th'] >>> [nth(x) for x in [91, 92, 93, 94, 99, 100, 101, ...
def find_exacte_matching(pattern, string): """takes a DNA string and the sought pattern returns a list of the pattern's locations in the string""" location_indexes = [] for i in range(len(string) - len(pattern)+1): match = True for n in range(len(pattern)): if string[i+n] != pa...
def char_to_float(c: int, f_min: float = -100., f_max: float = 50.) -> float: """Translates char number ``c`` from -128 to 127 to float from ``f_min`` to ``f_max``. Parameters ---------- ``c`` : int value to translate ``f_min`` : float, optional (default is -100) ``f_max`` :...
def both_positive(x, y): """Returns True if both x and y are positive. >>> both_positive(-1, 1) False >>> both_positive(1, 1) True """ return (x > 0) and (y > 0)
def performance_drop_metric(results_st, results_mt): """ Calculates the performance drop of the multi-tasking system compared to a single-tasking baseline. Hardcoded for PASCAL-MT 5 tasks. """ performance_drop = 0.0 for k in results_st: l_k = 1.0 if k=="normals" else 0.0 perf...
def filter_unwanted(filename): """ Returns true for hidden or unwanted files """ return filename.startswith(".")
def _get_spm_os(swift_os): """Maps the Bazel OS value to a suitable SPM OS value. Args: bzl_os: A `string` representing the Bazel OS value. Returns: A `string` representing the SPM OS value. """ # No mapping at this time. return swift_os
def linspace(start, end, num=None, step=None): """ Args: num: numpy.linspace(start, end, num) step: start:step:end """ if num: sepera = (end-start) / (num-1) return [start+i*sepera for i in range(num)] elif step: length = int((end-start)/step) return ...
def fiscal_from_calendar_year(month_num: int, calendar_year: int) -> int: """Return the fiscal year for the input calendar year.""" # Calendar == fiscal year if month is Jan to June (< 7) return calendar_year if month_num < 7 else calendar_year + 1
def _handle_string(val): """ Replaces Comments: and any newline found. Input is a cell of type 'string'. """ return val.replace('Comments: ', '').replace('\r\n', ' ')
def get_url(city): """ Gets the full url of the place you want to its weather You need to obtain your api key from open weather, then give my_api_key the value of your key below """ my_api_key = 'fda7542e1133fa0b1b312db624464cf5' unit = 'metric' # To get temperature in Celsius weat...
def _getformat(val): """ Get the output format for a floating point number. The general format is used with 16 places of accuracy, except for when the floating point value is an integer, in which case a decimal point followed by a single zero is used. Parameters ---------- val : float ...
def validateDir(value): """Validate direction. """ msg = "Direction must be a 3 component vector (list)." if not isinstance(value, list): raise ValueError(msg) if 3 != len(value): raise ValueError(msg) try: nums = list(map(float, value)) except: raise ValueErr...
def diff(f, x, h = 1e-5): """ Approximates the derivative of a function at a given value of x. """ return ((f(x + h) - f(x - h)) / (2.0 * h))
def pad(s, width, align): """Return string padded with spaces, based on alignment parameter.""" if align == 'l': s = s.ljust(width) elif align == 'r': s = s.rjust(width) else: s = s.center(width) return s
def is_special_agenda_item(assignment): """Is this agenda item a special item? Special items appear as top-level agenda entries with their own timeslot information. >>> from collections import namedtuple # use to build mock objects >>> mock_timeslot = namedtuple('t2', ['slug']) >>> mock_assignmen...
def reduce_array_shape(shape): """ Reduce the shape of a NumPy array * Trim trailing ones * Check that remaining non-zero dimension sizes are equal Args: shape (:obj:`list` of :obj:`int`): shape of array Returns: :obj:`:obj:`list` of :obj:`int`: reduced shape """ shape = l...
def read_dm3_image_info(original_metadata): """Read essential parameter from original_metadata originating from a dm3 file""" if not isinstance(original_metadata, dict): raise TypeError('We need a dictionary to read') if 'DM' not in original_metadata: return {} main_image = original_met...
def check_cat_symb(x: str): """ Args: x: Returns: """ if type(x) is str: x = "'{0}'".format(x) else: x = str(x) return x
def read_incl_input(incl_file): """ reads in the include file :param in_file: :return: list(included_epitopes) """ included_epitopes = [] if not incl_file is None: with open(incl_file, "rU") as f: included_epitopes = f.read().splitlines() return included_epitopes...
def graph_place_tooltip(work): """Generate place tooltip Default: tooltip with all information from Place object """ for key in ["booktitle", "journal", "school", "howpublished"]: value = getattr(work, key, None) if value is not None: return key
def needs_build_output(job_name: str) -> str: """Returns the output ID for the flag for needing a build""" return f"needs-build-{job_name}"
def _find_class_construction_fn(cls): """Find the first __init__ or __new__ method in the given class's MRO.""" for base in type.mro(cls): if '__init__' in base.__dict__: return base.__init__ if '__new__' in base.__dict__: return base.__new__
def is_comment(line): """Lines starting with "#" are comments. """ return line.strip().startswith('#')
def wholeFieldPredicate(field): """Returns the whole field as-is. Examples: .. code:: python > print(wholeFieldPredicate('John Woodward')) > ('John Woodward',) """ return (str(field), )
def _encoded_str_len(l): """ Compute how long a byte string of length *l* becomes if encoded to hex. """ return (l << 2) / 3 + 2
def _etextno_to_uri_subdirectory(etextno): """Returns the subdirectory that an etextno will be found in a gutenberg mirror. Generally, one finds the subdirectory by separating out each digit of the etext number, and uses it for a directory. The exception here is for etext numbers less than 10, which are...
def is_float(value): """is float""" try: float(value) return True except ValueError: return False except TypeError: return False
def split(a_string, seperator): """ Split a string using seperator. """ return a_string.split(seperator)
def distance_sqr_2d(pt0, pt1): """ return distance squared between 2d points pt0 and pt1 """ return (pt0[0] - pt1[0])**2 + (pt0[1] - pt1[1])**2
def clean_str_HTML(html_string): """This takes a string and returns it with all HTML tags (i.e </sub>) removed.""" h = html_string h=h.replace("<br>",'') h=h.replace("<sub>",'') h=h.replace("<sup>",'') h=h.replace("</br>",'') h=h.replace("</sub>",'') h=h.replace("</sup>",'') return h
def get_best_rssi_per_location(sensors): """Find the strongest signal in each location.""" best_rssi = {} for sensor in sensors.values(): location = sensor["location"] rssi = sensor["rssi"] if rssi and (location not in best_rssi or rssi > best_rssi[location]): best_rssi[l...
def relu_mul(x): """[fastest method](https://stackoverflow.com/a/32109519/743078)""" return x * (x > 0)
def normalized_device_coordinates_to_normalized_image(image): """Map image value from [0, 1] -> [-1, 1]. """ return (image + 1.0) / 2.0
def db_begin_transaction(driver): """Begin transaction. :return: SQL command as string """ if driver in ('sqlite', 'pg'): return 'BEGIN' if driver == 'mysql': return 'START TRANSACTION' return ''
def is_palindrome_permutation(test_string): """ Assumption: Incoming string won't have punctuation marks :param test_string: :return: """ # Pre-process the given string. i.e. strip off spaces and convert all to lowercase letters test_string = test_string.replace(" ", "") test_string = ...
def red_bold(msg: str) -> str: """ Given an 'str' object, wraps it between ANSI red & bold escape characters. :param msg: Message to be wrapped. :return: The same message, which will be displayed as red & bold by the terminal. """ return '\u001b[1;31m%s\u001b[0m' % msg
def mk_basic_call(row, score_cols): """Call is pathogenic/1 if all scores are met""" cutoffs = {'mpc':2, 'revel':.375, 'ccr':.9} for col in score_cols: if row[col] < cutoffs[col]: return 0 return 1
def check_change(val: int, return_money: int, balance: int): """ This function will check in the balance sheet (Balance), how many coins is available, for a specific coin value, to correspond to the money return. """ if return_money >= val: money = return_money // val if money < ...
def get_span_labels(sentence_tags, inv_label_mapping=None): """Go from token-level labels to list of entities (start, end, class).""" if inv_label_mapping: sentence_tags = [inv_label_mapping[i] for i in sentence_tags] span_labels = [] last = 'O' start = -1 for i, tag in enumerate(sentence_tags): pos...
def arithmetic_mean(X): """Computes the arithmetic mean of the sequence `X`. Let: * `n = len(X)`. * `u` denote the arithmetic mean of `X`. .. math:: u = \frac{\sum_{i = 0}^{n - 1} X_i}{n} """ return sum(X) / len(X)
def _stringify(elems): """Convert a sequence of ranges into a string. Args: elems (list): List of 2-tuples representing ranges. Returns: str: String with lo..hi ranges concatenated. """ return ''.join(chr(lo) + chr(hi) for (lo, hi) in elems)
def int_ip_to_string(ip_int): """ Convert ip4 address from integer into string representation. Parameters ---------- ip_int : int 4-byte ip4 integer representation Returns ------- string ip4 string representation """ byte_mask = 0xFF return '.'.join( ...
def sec(x): """Return the number of days given x seconds.""" return x / 24 / 60 / 60
def isport(value): """ Return whether or not given value represents a valid port. If the value represents a valid port, this function returns ``True``, otherwise ``False``. Examples:: >>> isport('8080') True >>> isport('65536') False :param value: string to valida...
def reverse_str(numeral_str): """Reverses the order of a string.""" return numeral_str[::-1]
def complain(ctx) -> str: """No description.""" return ( "What a crap bot this is! :rage: " "Hours of time wasted on this useless procuct of a terrible coder and a lousy artist " ":rage: :rage: Is this bot even TESTED before the updates are published... " "Horrible, just HORRIBLE...
def get_codes(metadata): """Read dimension codes and their dimension names from metadata dictionary. Args: metadata: dictionary of metadata Returns: dimensions_with_codes(list) dimension_codes(list) """ dimensions_with_codes = [] dimension_codes = [] # add CODES o...
def barycentric(vector1, vector2, vector3, u, v, w): """ barycentric coordinates are normalized. barycentric coordinates are known as areal coordinates. very useful in ray tracing and figuring out the center of three point constraints. w = 1-u-v; u + v + w = 1.0; :return: <tuple> barycentric...
def dec2bin(dec, bits=15): """ function: convert dec to bin :param dec: :param bits: :return: """ bin_nums = "{0:0{bitNums}b}".format(dec, bitNums=bits) return bin_nums
def range_to_number(interval_str): """Converts "X-Y" -> "X".""" if not '-' in interval_str: return int(interval_str) # If first character is -, X is a negative number if interval_str.startswith('-'): number = '-' + interval_str.split('-')[1] else: number = interval_str.split...
def third_order_poly(x, a, b, c, d): """ :param x: :param a: :param b: :param c: :param d: :return: """ return a + b * x + c * x ** 2 + d * x ** 3
def sign_of_weight(x, weight): """ Determines the sign of a weight, based on the value of the first digit of the gene. :param x: int, range [0, 9] First digit of the gene. :param weight: int Weight determined from the gene. :return: int Signed ...
def get_type_from_dict(config_dict: dict) -> str: """Get model type from config dict. Args: config_dict: Config dict. Returns: Model type. """ return config_dict.get("model_type", config_dict.get("type", ""))
def generate_network_url(project_id, network): """Format the resource name as a resource URI.""" return 'projects/{}/global/networks/{}'.format(project_id, network)
def binary_dominates(a, b): """Returns whether a binary dominates b""" for ai, bi in zip(a, b): if bi > ai: return False if a == b: return False return True
def _ilog2(x): """Compute the ceiling of the base-2 logarithm of a number.""" i = 0 while x > (1 << i): i += 1 return i
def log_in(user: str, pwd): """ :type pwd: object :type user: object """ return f'The user name is: {user} with password {pwd}'
def startGame(jsonData): """set constants at game start and print some data""" gameID,playerID = (jsonData['gameID'],jsonData['playerID']) # store id of current game session, and player number print("json data:",jsonData) print("gameID: {0}\nplayerID: {1}".format(gameID, playerID)) return gameID,pla...
def _parse_condor_submit_job_id(condor_submit_out): """Parse job id from condor_submit output string. Assume format: Submitting job(s). 1 job(s) submitted to cluster 8. """ return float(condor_submit_out.split()[-1])
def center(s, l, delim='#'): """Center a text s at a length l""" start = int(l/2 - len(s)/2) remain = l - (start + len(s)) return delim * start + s + delim * remain
def RGB_to_rgb(r, g, b): """ Convert RGB values to rgb values :param r,g,b: (0,255) range floats :return: a 3 element tuple of rgb values in the range (0, 1) """ return (float(r) / 255, float(g) / 255, float(b) / 255)
def relatively_prime(a, b): """ Returns true or false for whether the given numbers are relatively prime, having no common factors other than 1. """ for number in range(2, min(a, b) + 1): if a % number == b % number == 0: return False return True
def get_alias(infos): """Get aliases of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- pairs : list List of tuples (param alias, param name). """ pairs = [] for x in infos: for y in x: if...
def selected_indices(total_number_of_indices, desired_number_of_indices=None): """Returns a list of indices that will contain exactly the number of desired indices (or the number of total items in the list, if this is smaller). These indices are selected such that they are evenly spread over the whole sequence.""...
def collect_state_action_pairs(iterator): # concat state and action """ Overview: Concate state and action pairs from input iterator. Arguments: - iterator (:obj:`Iterable`): Iterables with at least ``obs`` and ``action`` tensor keys. Returns: - res (:obj:`Torch.tensor`): Sta...
def get_mount_info(pools, volumes, actions, fstab): """ Return a list of argument dicts to pass to the mount module to manage mounts. The overall approach is to remove existing mounts associated with file systems we are removing and those with changed mount points, re-adding them with the n...
def make_links(line): """Split a line into parts, return a dictionary of chain links.""" link_parts = line.split(";") chain_dict = { k: v for k, v in tuple([x.split('-') for x in link_parts]) } return chain_dict
def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new ha...
def iseven(n): """ Return True if n is an even number and False otherwise. """ return (n % 2 == 0)
def binary_srch_exact(a,t,lo,hi): """ Here, a is a rotated sorted array. """ while hi>=lo: mid=(lo+hi)//2 if a[mid]==t: return mid elif a[mid]<t: lo=mid+1 elif a[mid]>t: hi=mid-1 return -1
def get_azimuth(angle): """Converts headings represented by angles in degrees 180 to -180to Azimuth Angles. Will also normalize any number to 0-360 """ if angle <= 180 and angle > 90: azimuth_angles = 360.0 - (angle - 90) else: azimuth_angles = abs(angle - 90) if abs(azimuth_angles)...
def check_features_name(columns_dict, features_dict, features): """ Convert a list of feature names (string) or features ids into features ids. Features names can be part of columns_dict or features_dict. Parameters ---------- features : List List of ints (columns ids) or of strings (bu...
def get_image_modality(image_modality): """Change image_modality (string) to rgb (bool) and flow (bool) for efficiency""" if image_modality == "joint": rgb = flow = True elif image_modality == "rgb" or image_modality == "flow": rgb = image_modality == "rgb" flow = image_modality == ...
def _iterate(arrays, cur_depth, iterators, n): """ dfs algorithm for returning the next iterator value Args: arrays: A list of 1-D arrays cur_depth: the depth of the dfs tree in current call iterators: a list of iterators n: number of arrays Returns: new iterator value """ ...
def is_alive(cell): """returs True if a cell is alive and false, otherwise.""" return True if cell == 1 else False
def ami_architecture(ami_info): """ Finds source AMI architecture AMI tag. Parameters ---------- ami_info : dict AMI information. Returns ------- string Architecture of source AMI. """ for tag in ami_info['Tags']: if tag['Key'] == 'Architecture': ...
def mimic_preprocessing(text): """ :param text: :return: """ # remove junk headers that concatenate multiple notes sents = [] skip = False for line in text.split('\n'): if line.strip() == '(Over)': skip = True elif line.strip() == '(Cont)': skip =...
def base36encode(number, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): """Converts an integer to a base36 string.""" if not isinstance(number, int): number = int(number) base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <= number < len(alphabet)...
def ord_prio(prio): """Compute the ordinal number of a text priority :param prio: string :rtype: integer """ return {"urgmust": 1, "must": 2, "high": 3, "medium": 4, "low": 5}.get(prio, 5)