content
stringlengths
42
6.51k
def get_context_first_matching_object(context, context_lookups): """ Return the first object found in the context, from a list of keys, with the matching key. """ for key in context_lookups: context_object = context.get(key) if context_object: return key, context_object ...
def convert_to_boolean(value): """Turn strings to bools if they look like them Truthy things should be True >>> for truthy in ['true', 'on', 'yes', '1']: ... assert convert_to_boolean(truthy) == True Falsey things should be False >>> for falsey in ['false', 'off', 'no', '0']: ... asser...
def get_max_offset_supported(atten): """Get maximum supported offset for given attenuation""" if atten >= 0.1: return (-8, +8) else: return (-2, +2)
def _parse_expected_tuple(arg, default=tuple()): """ Parse the argument into an expected tuple. The argument can be None (i.e., using the default), a single element (i.e., a length-1 tuple), or a tuple """ try: _ = iter(arg) except TypeError: tpl = tuple(default) if arg is None ...
def parse_name_scope(name): """ Given a tensor or op name, return the name scope of the raw name. Args: name: The name of a tensor or an op. Returns: str: The name scope """ i = name.rfind('/') if i != -1: return name[:i] if not name.startswith('^') else name[1:i] ...
def get_full_action_name(service, action_name): """ Gets the proper formatting for an action - the service, plus colon, plus action name. :param service: service name, like s3 :param action_name: action name, like createbucket :return: the resulting string """ action = service + ':' + action...
def bond_dimension(mps): """ Given an MPS/MPO as a list of tensors with indices (N, E, S, W), return the maximum dimension of the N indices. (Equivalently, given an MPS/MPO as a list of tensors with indices (L, U, R, D), return the maximum dimension of the L indices.) Notes: * None objects in...
def update_consistently(base, other): """Update base dict with other dict until a conflict is found. Returns whether a conflict was found.""" for key, value in other.items(): if base.setdefault(key, value) != value: # attempted update is inconsistent with content, so stop here ...
def invertIndices(selectedIndices, fullSetOfIndices): """ Returns all indices in fullSet but not in selected. """ selectedIndicesDict = dict((x, True) for x in selectedIndices) return [x for x in fullSetOfIndices if x not in selectedIndicesDict]
def camelCaseName(name): """Convert a CSS property name to a lowerCamelCase name.""" name = name.replace('-webkit-', '') words = [] for word in name.split('-'): if words: words.append(word.title()) else: words.append(word) return ''.join(words)
def registered_as_of( reference_date, # Required keyword return_expectations=None, ): """ All patients registed on the given date """ return "registered_as_of", locals()
def _has_matched_brackets(text: str) -> bool: """ Evaluate whether every opening bracket '[' in the 'text' has a matching closing bracket ']'. :param text: the text. :return: Boolean result, and associated message. """ open_bracket_stack = [] for index, _ in enumerate(text): if text...
def atof(text): """ helper for natural_keys attempt to convert text to float, or return text :param text: arbitrary text :return: float if succeeded to convert, the input text as is otherwise """ try: retval = float(text) except ValueError: retval = text return retval
def padding0(data): """ padding '0' into a number. so given a number=1, then it return '01' """ if data is None: return '00' if type(data) == str: int_data = int(data) else: int_data = data if int_data < 10: return '0' + str(int_data) else: ret...
def calculate_product(alist): """ Returns the product of a list of numbers. """ product = 1 for fact in alist: product *= fact return product
def _get_help_lines(content): """ Return the help text split into lines, but replacing the progname part of the usage line. """ lines = content.splitlines() lines[0] = 'Usage: <progname> ' + ' '.join(lines[0].split()[2:]) return lines
def apply_transform(best_transformation, current_tagged_corpus, size_of_corpus): """ Apply the best transform onto given corpus and return new tagged corpus Format of the output is same as that of input, namely: (word,tag) """ print("Applying best transform to corpus.", end="", flush...
def format_board(board): """Print off the board""" formatted_board = '-------------\n' for index in range(0, len(board)): # print player letter if present, else board index value = index + 1 if board[index] == '.' else board[index] formatted_board += f'| {value} ' if index ...
def get_plane(coords): """ three reference points points in form np.array( [ [x_1, y_1, z_1], [x_2, y_2, z_2], [x_3, y_3, z_3] ] ) make sure that three points are not in one line as this "breaks" math used here. """ # variables expanded x_1, y_1...
def first_separator_index(data, separators, check_quotes): """Find the first index of a separator in |data|.""" in_quote_type = None escaped = False for index, ch in enumerate(data): if escaped: escaped = False continue elif in_quote_type: if ch == '\\': escaped = True el...
def q_learn(old_state_action_q_value, new_state_max_q_value, reward, learn_rate=0.01, discount_factor=0.9): """ Returns updated state-action Q_value. :param old_state_action_q_value: Q_value of the chosen action in the previous state. :param new_state_max_q_value: maximum Q_value of new state. :para...
def get_enabled_vhost_path(version, domain): """ Get the path for an enabled PHP vhost file regardless of wether or not it exists. Args: version - The PHP version used in the file path domain - The domain used in the file path """ return '/opt/php-' + version + '/etc/php-fpm.d/' + d...
def inward_radial_disp_plastic(ro, Po, crit_press, v, E, rp, Pi): """ Calculates and returns the inward radial displacement for plastic analysis. """ return (ro*(1+v)/E)*(2*(1-v)*(Po-crit_press)*(rp/ro)**2-(1-2*v)*(Po-Pi))
def _sha256(sha256): """Fallback to an incorrect default value of SHA-256 hash to prevent the hash check from being disabled, but allow the first download attempt of an archive to fail and print the correct hash. Args: sha256: expected SHA-256 hash of the archive to be downloaded. """ i...
def get_seq_identity_bytes(seq: bytes, other_seq: bytes) -> float: """Return the fraction of amino acids that are the same in `seq` and `other_seq`. Examples: >>> get_seq_identity(b'AAGC', b'AACC') 0.75 """ assert len(seq) == len(other_seq) return sum(a == b for a, b in zip(seq, oth...
def interlis_model_dictionary(french_lexicon, german_lexicon): """ :param french_lexicon: lexicon of french model :param german_lexicon: lexicon of german model :return: """ if len(french_lexicon) == len(german_lexicon): unique_translations = set(list(zip(french_lexicon, german_lexicon))...
def convert_names(data, names_map): """ Dato un dict questa funzione ritorna un dict con i nomi opportunamente convertiti dalla mappa di coversione fornita.. """ converted_row = {} for csv_key, model_field in names_map.items(): converted_row[model_field] = data[csv_key] return conver...
def allowable_stress_unity_check(sigma, allowable, df=0.72): """Calculate the allowable stress unity check value. Refs: https://en.wikipedia.org/wiki/Permissible_stress_design https://en.wikipedia.org/wiki/Factor_of_safety :param sigma: applied stress level to be checked. :type sigma: float :p...
def technique(attack_id, mapped_controls): """create a technique for a layer""" return { "techniqueID": attack_id, "score": len(mapped_controls), # count of mapped controls "comment": f"Mitigated by {', '.join(sorted(mapped_controls))}", # list of mapped controls }
def cal_local_high_low_point_score(high_low_points): """ :param high_low_points: :return: """ score = 0 if len(high_low_points) <= 1: return score for i in range(1, len(high_low_points)): score_i = 0 for j in range(0, i): if high_low_points[i] >= high_low...
def split_list(tx): """ split list in two with '+' as a separator """ idx_list = [idx for idx, val in enumerate(tx) if val == '+'] idx_list1 = [idx+1 for idx, val in enumerate(tx) if val == '+'] size = len(tx) if(size == 2): # lovelace only return [tx] # lovelace + tokens tx = [tx[i: j] for...
def dotted_name(cls): """Return the dotted name of a class.""" return "{0.__module__}.{0.__name__}".format(cls)
def factorial(n): """Factorial function implementation.""" return n * factorial(n-1) if n else 1
def add64(a, b): """ Perform addition as if we are on a 64-bit register. """ return (a + b) & 0xFFFFFFFFFFFFFFFF
def member_lis(lis1, lis2): """ If lis1 is last item in lis2, it returns the rest of lis2.""" found_at = -1 if lis1 is None or lis1 == []: return [] for index, rule in enumerate(lis2): if lis1 == rule: found_at = index break # lis1 found at last pos in lis2, r...
def URLify(input_string): """Replace spaces in input_string with '%20', without using the replace() method of Python str objects, and must be done in-place. List slicing in Python is O(k), where k is the slice size, so this solution could be more optimal. Parameters ---------- input_string...
def get_action(actions, action_id): """ Gets an action by action ID @param actions (list) of Action objects @param action_id (int) action ID @return (Action) """ for action in actions: if action.id == action_id: return action return None
def get_items(matrix, items): """ :param matrix: matrix of the knapsack problem :param items: list of tuples (weight, value) :return: list of items """ # get the max value max_value = matrix[-1][-1] # get the index of the first item with a value equal to the max value i = len(items)...
def has_unknown_matches(license_matches): """ Return True if any on the license matches has a license match with an `unknown` rule identifier. :param license_matches: list List of LicenseMatch. """ match_rule_identifiers = ( license_match.rule_identifier for license_match in lic...
def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ temp = u for i in range(1, p): temp = temp * (u - i) return temp
def arg_cond_req(args_array, opt_con_req): """Function: arg_cond_req Description: This checks a dictionary list array for options that require other options to be included in the argument list. Arguments: (input) args_array -> Array of command line options and values. (input) op...
def sortSelection(A, k): """ Selects the @k-th smallest number from @A in O(nlogn) time by sorting and returning A[k] Note that indexing begins at 0, so call sortSelection(A, 0) to get the smallest number in the list, call sortselection(A, len(A) / 2) to get the median number of the list, ...
def eh_coordenada(coord): """ eh_coordenada: universal >>> logico - Determina se o valor dado e do tipo coordenada """ if not isinstance(coord, tuple) or len(coord) != 2: return False return (coord[0] in (0, 1, 2)) and (coord[1] in (0, 1, 2))
def get_dummy_from_bool(row, column_name): """Returns 0 if value in column_name is no, returns 1 if value in column_name is yes""" return 1 if row[column_name] == "yes" else 0
def utf_8_encode_array(array): """ encode 2D array to utf8 """ return [[val.encode("utf-8") for val in line] for line in array]
def GetContainingWhileContext(ctxt, stop_ctxt=None): """Returns the first ancestor WhileContext of `ctxt`. Returns `ctxt` if `ctxt` is a WhileContext, or None if `ctxt` is not in a while loop. Args: ctxt: ControlFlowContext stop_ctxt: ControlFlowContext, optional. If provided, the search will end ...
def title_to_ids(title): """Function to convert a title into the id, name, and description. This is just a quick-n-dirty implementation, and is definately not meant to handle every FASTA title line case. """ # first split the id information from the description # the first item is the id info b...
def _DictWithReturnValues(retval, pass_fail): """Create a new dictionary pre-populated with success/fail values.""" new_dict = {} # Note: 0 is a valid retval; test to make sure it's not None. if retval is not None: new_dict['retval'] = retval if pass_fail: new_dict[''] = pass_fail return new_dict
def _negaconvolution_naive(L1, L2): """ Negacyclic convolution of L1 and L2, using naive algorithm. L1 and L2 must be the same length. EXAMPLES:: sage: from sage.rings.polynomial.convolution import _negaconvolution_naive sage: from sage.rings.polynomial.convolution import _convolution_naive ...
def concat_req_field(list): """ Import in pieces grabbing main fields plus unique amount and basis of estimate fields assigns fields to variables """ source_name = ['TRIFID','CHEMICAL NAME', 'CAS NUMBER', 'UNIT OF MEASURE'] + list return source_name
def spacelist(listtospace, spacechar=" "): """ Convert a list to a string with all of the list's items spaced out. :type listtospace: list :param listtospace: The list to space out. :type spacechar: string :param spacechar: The characters to insert between each list item. Default is: " ". ...
def GetStatus(plist): """Plists may have a RunAtLoad key.""" try: return plist['RunAtLoad'] except KeyError: return 'False'
def ensure_list(i): """If i is a singleton, convert it to a list of length 1""" # Not using isinstance here because an object that inherits from a list # is not considered a list here. That is, I only want to compare on the final-type. if type(i) is list: return i return [i]
def get_interest(ammount): """ Returns the ammount owed for interests """ if ammount > 1000: return ammount - ammount * 0.98 return ammount - ammount * 0.985
def BitsInCommon(v1, v2): """ Returns the number of bits in common between two vectors **Arguments**: - two vectors (sequences of bit ids) **Returns**: an integer **Notes** - the vectors must be sorted - duplicate bit IDs are counted more than once >>> BitsInCommon( (1,2,3,4...
def get_host_finding_details_hr(host_finding_detail): """ Prepare human readable json for "risksense-get-host-finding-detail" command. Including basic details of host finding. :param host_finding_detail: host finding details from response :return: List of dict """ return [{ 'Title':...
def _make_labels_wrap(labels): """Break labels which contain more than one name into multiple lines.""" for i, l in enumerate(labels): if len(l) > 25: # Split lines at ", " and rejoin with newline. labels[i] = '\n'.join(l.split(", ")) return labels
def get_data_score(data, freq): """ Scores the bytes in data according the probability that it is English text. Used to detect correctly-decoded plaintexts """ return sum([freq[chr(ch)] for ch in data])
def _int_ceiling(value, multiple_of=1): """Round C{value} up to be a C{multiple_of} something.""" # Mimicks the Excel "floor" function (for code stolen from occupancy calculator) from math import ceil return int(ceil(value/multiple_of))*multiple_of
def iterate_parameters(parameters, default, count): """ Goes through recursively senstivity nested parameter dictionary. Args: paramters (dict): nested dictionary default (dict): default parameter dictionary count (int): number of scenarios """ for key, value in parameters.items...
def set_file_name(fig_name, fmt): """ Returns a file name with the base given by fig_name and the extension given by fmt. Parameters ---------- fig_name : str base name string fmt : str extension of the figure (e.g. png, pdf, eps) Returns -------- fi...
def check_integer(num): """Devuelve True si el string empieza por "-" y su longitud es mayor que 1.""" if num.startswith('-') and len(num) > 1: return True
def list_tokenizer(tokenizer, text_list): """Split train dataset corpus to list """ line_list = list() for text in text_list: line_list.append(tokenizer.tokenize(text)) return line_list
def fuel_requirement(module_mass): """ Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. Repeat this for the weight of the fuel until the added weight is 0. :param module_mas...
def blue(message): """ blue color :return: str """ return f"\x1b[34;1m{message}\x1b[0m"
def remove_comments(text: str) -> str: """Remove comments from a JSON string.""" return "\n".join( line for line in text.split("\n") if not line.strip().startswith("//") )
def char_to_info(kind): """ How to represent entry in gopher directory in control column. """ return {'i': " ", '0': "TEXT ", '1': " DIR "}.get(kind, "?[{}] ".format(kind))
def promote_xyz(a): """ Add a 'z' coordinate to each xy pair """ for p in a: p.append(1.0-p[0]-p[1]) return a
def ARRAY_ELEM_AT(array, idx): """ Returns the element at the specified array index. See https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/ for more details :param array: An expression that can be any valid expression as long as it resolves to an array. :param idx: An ex...
def extract(ref: str, hyp: str) -> list: """ This function extracts identifiable ambiguities. Only ambiguities within the equal amount of words in both reference and hypothesis are processed. Then the code tries to find boundaries of error string, as it subtracts common prefix and suffix of words. If le...
def find_cfn_output(key, outputs): """Return CFN output value.""" for i in outputs: if i['OutputKey'] == key: return i['OutputValue'] return None
def version_key(ver): """ A key function that takes a version and returns a numeric value that can be used for sorting >>> version_key('2') 2000000 >>> version_key('2.9') 2009000 >>> version_key('2.10') 2010000 >>> version_key('2.9.1') 2009001 >>> version_key('2.9.1.1') ...
def get_benchmark_repetition_count(runner: str) -> int: """Returns the benchmark repetition count for the given runner.""" if runner == "iree-vmvx": # VMVX is very unoptimized for now and can take a long time to run. # Decrease the repetition for it until it's reasonably fast. return 3 return 10
def unicode(word): """Only takes in a string without digits""" assert type(word) is str try: int(word) except ValueError: return sum(map(ord, word)) raise ValueError(f"Word {word} contains integer(s)")
def parenthesise(_value): """Adds a parenthesis around a values.""" return '(' + _value + ')'
def default_memnet_embed_fn_hparams(): """Returns a dictionary of hyperparameters with default hparams for :func:`~texar.tf.modules.memory.default_embed_fn` .. code-block:: python { "embedding": { "dim": 100 }, "temporal_embedding": { ...
def get_place_coords(location): """ Parses a geo coord in the form of (latitude,longitude) and returns them as an array. Note that a simple "latitude,longitude" is also valid as a coordinate set """ latitude, longitude = map(float, location.strip('()[]').split(',')) return [latitude, longitu...
def sec2hmsc(secs): """ convert seconds to (hours, minutes, seconds, cseconds) secs:float -> (int, int, int, int) """ hours, rem = divmod(secs, 3600) # extract hours minutes, rem = divmod(rem, 60) # extract minutes seconds, cseconds = divmod(rem*100, 100) ...
def coerce(string): """Changing strict JSON string to a format that satisfies eslint""" # Double quotes to single quotes coerced = string.replace("'", r"\'").replace("\"", "'") # Spaces between brace and content coerced = coerced.replace('{', '{ ').replace('}', ' }') return coerced
def make_empty_table(row_count, column_count): """ Make an empty table Parameters ---------- row_count : int The number of rows in the new table column_count : int The number of columns in the new table Returns ------- table : list of lists of str Each cell ...
def eggs(number): """Function to request your preferred number of eggs for breakfast. Parameters ---------- number : int The number of eggs you'd like for breakfast. Returns ------- str A polite request for your desired number of eggs. """ result = "{} eggs, please!...
def match_cases(original, replacement): """ Returns a copy of the replacement word with the cases altered to match the original word's case Only supports upper case, capitalised (title) and lower case - everything else gets lower cased by default""" if original.isupper(): return ...
def rev_comp(seq: str) -> str: """ Returns reverse complementary sequence of the input DNA string """ comp = { 'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N', 'M': 'K', # M = A C 'K': 'M', # K = G T 'R': 'Y', # R = A G 'Y': 'R'...
def _is_sunder(name): """ A copy of enum._is_sunder from Python 3.6. Returns True if a _sunder_ (single underscore) name, False otherwise. """ return (len(name) > 2 and name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1] != '_')
def LeapYear(year): """Leapyear returns 1 if year is a leap year and 0 otherwise. Note that leap years famously fall on all years that divide by 4 except those that divide by 100 but including those that divide by 400.""" if year%4: return 0 elif year%100: return 1 elif year%400: return 0 else: return 1
def process_anno(anno_scaled, base=0, window_radius=16000000): """ Process annotations to the format used by Orca plotting functions such as `genomeplot` and `genomeplot_256Mb`. Parameters ---------- anno_scaled : list(list(...)) List of annotations. Each annotation can be a reg...
def validate_capacity(capacity): """ Validate ScalingConfiguration capacity for serverless DBCluster Property: ScalingConfiguration.MaxCapacity Property: ScalingConfiguration.MinCapacity """ VALID_MYSQL_SCALING_CONFIGURATION_CAPACITIES = (1, 2, 4, 8, 16, 32, 64, 128, 256) VALID_POSTGRESL_SC...
def expose(fn): """ Decorator function that exposes methods of a web application to the web server. Use infront of functions that you wish to expose """ if fn: fn.exposed = True return fn
def isFloat( obj ): """ Returns a boolean whether or not 'obj' is of type 'float'. """ return isinstance( obj, float )
def NeedEnvFileUpdateOnWin(changed_keys): """Returns true if environment file need to be updated.""" # Following GOMA_* are applied to compiler_proxy not gomacc, # you do not need to update environment files. ignore_envs = ( 'GOMA_API_KEY_FILE', 'GOMA_DEPS_CACHE_DIR', 'GOMA_HERMETIC', 'G...
def return_parent_label(label_name): """ Example: Input: /education/department Output: /education """ if label_name.count('/') > 1: return label_name[0:label_name.find('/', 1)] return label_name
def remove_dash_lines(value): """Some social media values are '---------'""" return None if value[:2] == '--' else value
def _antnums_to_bl(antnums): """ Convert tuple of antenna numbers to baseline integer. A baseline integer is the two antenna numbers + 100 directly (i.e. string) concatenated. Ex: (1, 2) --> 101 + 102 --> 101102. Parameters ---------- antnums : tuple tuple containing integer ant...
def unpack_bitstring(string): """ Creates bit array out of a string :param string: The modbus data packet to decode example:: bytes = 'bytes to decode' result = unpack_bitstring(bytes) """ byte_count = len(string) bits = [] for byte in range(byte_count): value = int(...
def trunc(s, chars): """ Trucante string at ``n`` characters. This function hard-trucates a string at specified number of characters and appends an elipsis to the end. The truncating does not take into account words or markup. Elipsis is not appended if the string is shorter than the specified numb...
def u_2_u10(u_meas,height): """ % u10 = calc_u10(umeas,hmeas) % % USAGE:------------------------------------------------------------------- % % [u10] = u_2_u10(5,4) % % >u10 = 5.5302 % % DESCRIPTION:------------------------------------------------------------- % Scale wind s...
def _resolve_none(inp): """ Helper function to allow 'None' as input from argparse """ if inp == "None": return return inp
def are_all_strings_in_text(text, list_of_strings): """Check that all strings in list_of_strings exist in text Parameters ---------- text : str output from IQDMPDF.pdf_reader.convert_pdf_to_text list_of_strings : list of str a list of strings used to identify document type Retu...
def _process_transcript(transcripts, x): """ Helper method to split into words. Args: transcripts: x: Returns: """ extracted_transcript = transcripts[x].split('(')[0].strip("<s>").split('<')[0].strip().upper() return extracted_transcript
def code(text): """Returns a text fragment (tuple) that will be displayed as code.""" return ('code', text)