content
stringlengths
42
6.51k
def sum_node_list(node_list): """Custom sum func to avoid creating redundant nodes in Python sum func.""" node_list = [n for n in node_list if n is not None] if node_list == []: return None from operator import add from functools import reduce return reduce(add, node_list)
def extract_major_version(scala_version): """Return major Scala version given a full version, e.g. "2.11.11" -> "2.11" """ return scala_version[:scala_version.find(".", 2)]
def serialize_beneficiarios_programa(beneficiario): """ # $ref: '#/components/schemas/beneficiariosPrograma' """ if beneficiario: if beneficiario.codigo == 'DC': return { "clave": beneficiario.codigo, "valor": beneficiario.tipo_relacion } ...
def get_chebi_synonyms(chebi_ent): """ Get synonyms from ChEBI entity :param chebi_ent: :return: """ if hasattr(chebi_ent, 'Synonyms'): return [entry.data for entry in chebi_ent.Synonyms] else: return []
def find_keywords_sentences(keywords, cleaned_lines): """ Find the occurrences of the keywords in the text. :param keywords: The keywords to be searched in the lines :param cleaned_lines: The lines of the document :return: The lines with the given keywords """ accepted_lines = list() for...
def flatten_cond_gen_values(gen_eval: dict): """ Converts the coherence evaluation results into a flattened dict """ flattened_dict = {} for j, l_key in enumerate(sorted(gen_eval['cond'].keys())): for k, s_key in enumerate(gen_eval['cond'][l_key].keys()): for g_key in gen_eval['c...
def to_sbp_file_name(identifier): """ Creates file name from sbp message identifier. """ prefix = 'swiftnav.sbp.' if identifier.startswith(prefix): return identifier[len(prefix):] else: return identifier
def info_from_header(header): """Returns mb, ms, sequence extracted from header in logfile.""" from numpy import nan # If present in header information, extract mb, ms, and sequence mb = nan ms = nan sequence = '' header = str(header).replace(' ','') # remove spaces before splitting ...
def build_description(summary, description): """ Return a description string from a summary and description """ summary = (summary or '').strip() description = (description or '').strip() if not description: description = summary else: if summary and summary not in descripti...
def try_parse_float(text): """ Try to parse a string to a float. """ try: return float(text) except ValueError: return None
def single_timeseries_to_json(value=None, unit="", label="", asset_type=""): """format the information about a single timeseries in a specific JSON""" if value is None: value = [] return {"value": value, "unit": unit, "label": label, "asset_type": asset_type}
def _GenerateEstimatorConstructor(estimator_class_name, variable_types, variable_names, extension_class_name): """ Generates the consructor for the estimator class. """ code = ["\n\npublic {0}(IHostEnvironment env".format(estimator_class_name)] # Generate the Constructor parameters for var...
def compute_poi_email_ratio(poi_messages, all_messages): """ FEATURE given a number messages to/from POI (numerator) and number of all messages to/from a person (denominator), return the ratio of messages to/from that person that are from/to a POI """ ratio = 0. if type(...
def selu_initialization_std(shape): """ initialization meant to be used in conjunction with selu non-linearity. sqrt(1/fan_in) """ std = (1.0/shape[0]) ** .5 print("selu init std", shape, std) return std
def HelperParseOutput(lst): """Self defined parameter function for 'object_pairs_hook' of json.loads(). Purpose: This function helps to parse json text with duplicate keys, for instance: json text: {"key":1, "key":2, "key2":3, "key2":4} With this function, we will have the following dict: {...
def fuzzy_not(arg): """ Not in fuzzy logic Will return Not if arg is a boolean value, and None if argument is None. Examples: >>> from sympy.logic.boolalg import fuzzy_not >>> fuzzy_not(True) False >>> fuzzy_not(None) >>> fuzzy_not(False) True """ if arg is None: ...
def write_key(key, value): """Write a `key = value` line in an LTA file. Parameters ---------- key : str value : int or float or str Returns ------- str """ if isinstance(value, (str, int, float)): return f'{key} = {value}' else: return f'{key} = ' + ' '.jo...
def enumerate(lst): """ >>> enumerate(["a", "b", "c"]) [(0, 'a'), (1, 'b'), (2, 'c')] >>> for index, value in enumerate(["a", "b", "c"]): ... print index, value 0 a 1 b 2 c """ return [(i, lst[i]) for i in range(len(lst))]
def get_user_plist_path(): """ Helper function returning the path to the user account property list. """ user_plist_path = "/private/var/db/dslocal/nodes/Default/users/" return user_plist_path
def argif(cond,if_true_value,else_value): """ If cond is true, returns the if_true_value, otherwise else_value. Roughly equilvanet to a lisp (if cond true false) """ if(cond): return if_true_value else: return else_value
def splitext(fname): """Splits filename and extension (.gz safe) >>> splitext('some/file.nii.gz') ('file', '.nii.gz') >>> splitext('some/other/file.nii') ('file', '.nii') >>> splitext('otherext.tar.gz') ('otherext', '.tar.gz') >>> splitext('text.txt') ('text', '.txt') Source: ni...
def get_AC(GT): """ Convert GT to AC for a single sample """ if GT == 'None/None': AC = 'NA' else: AC = sum([int(a) for a in GT.split('/')]) return str(AC)
def unhappy_f_point_lin(list, index, other_index): """ Checks if a new point will be unhappy. Returns False if will be happy. """ if list[other_index] == 1: list[other_index] = 0 else: list[other_index] = 1 if index == 0: if list[index] != list[index + 1]: ...
def left_join(phrases): """ Join strings and replace "right" to "left" """ # l = list(phrases) return ','.join([x.replace('right', 'left') for x in phrases])
def remove_optimized_key_from_ai_list(key_list: list, optimized_dict: dict): """ :param key_list: :param optimized_dict: :return: """ for key, value in optimized_dict.items(): if value in key_list: ind = key_list.index(value) key_list.pop(ind) return key_list
def find_number(value): """Convert value to a number, if posible, and indicate success or failure Parameters: value: The variable to convert (could be _anything_) Return values: First the converted number, as float or int; then a boolean that shows whether the conversion succeeded (true) or fail...
def cat_matrices2D(mat1, mat2, axis=0): """Concatenates two matrices along a specific axis""" ans = [] if axis == 0 and len(mat1[0]) == len(mat2[0]): return mat1 + mat2 elif axis == 1 and len(mat1) == len(mat2): for i in range(len(mat1)): ans.append(mat1[i] + mat2[i]) ...
def _tupleindex(index): """Convert 'line.column' to (line, column).""" line, column = index.split('.') return (int(line), int(column))
def read_leaf_header(leaf): """ Parse the leaf header """ header = {} header["version"] = int(leaf[0]) header["merkle_leaf_type"] = int(leaf[1]) header["timestamp"] = int.from_bytes(leaf[2:10], "big") header["LogEntryType"] = int.from_bytes(leaf[10:12], "big") header["Entry"] = leaf[...
def advance_version(v, bumprule): """ Advance the version based on a version bump rule """ vercomps = v.replace('v', '').split('.') majv = int(vercomps[0]) minv = int(vercomps[1]) patchv = int(vercomps[2]) if bumprule == "major": majv += 1 minv = 0 patchv =...
def moving_average(lst, size): """ calculate simple moving average values """ if not isinstance(size, int): raise TypeError('size must be integer. {} given'.format(size)) if not size > 0: raise ValueError('size must be greater than zero. {} given'.format(size)) if len(lst) < size: ...
def flatten_research(research): """Flatten research data.""" flat = [] for pid, techs in research.items(): for tid, values in techs.items(): flat.append(dict(values, player_number=pid, technology_id=tid)) return flat
def check_password(option, opt, value): """check a password value (can't be empty) """ # no actual checking, monkey patch if you want more return value
def getFIndex(field_names, field_name): """Will get the index for a arcpy da.cursor based on a list of field names as an input. Assumes string will match if all the field names are made lower case.""" try: return [str(i).lower() for i in field_names].index(str(field_name).lower()) # Make it...
def priviledged_instructions(instr, bv, isa_specific_data): """ """ if not isa_specific_data: return False if isa_specific_data and isa_specific_data.get('privileged_instructions'): if instr[0][0].text in isa_specific_data['privileged_instructions']: return True return Fa...
def sort_list(data_list, index, reverse): """ index: int number, according to it to sort data_list""" if index is None: sorted_data_list = sorted(data_list, key=lambda x: x, reverse=reverse) else: sorted_data_list = sorted(data_list, key=lambda x: x[index], reverse=reverse) return sorted...
def extend(value, tupleo): """ extend(...) method of tupleo.tuple instance T.extend(iterable, tupleo) -> None -- extend tuple, tupleo by appending elements from the iterable """ if type(tupleo) != tuple: raise TypeError("{} is not tuple".format(tupleo)) if type(value) !=tuple: ra...
def var_name(var): """ Return the name of a variable """ for name,value in globals().items() : if value is var : return name return None
def decrement_items(inventory, items): """ :param inventory: dict - inventory dictionary. :param items: list - list of items to decrement from the inventory. :return: dict - updated inventory dictionary with items decremented. """ for item in items: inventory[item] = max(0, inventory[...
def count_same(sequence1, sequence2): """ What comes in: -- two sequences that have the same length What goes out: Returns the number of indices at which the two given sequences have the same item at that index. Side effects: None. Examples: If the sequences are: (11, 33...
def _convert_german_time_to_iso(date_string: str): """Convert a german date input as a string to ISO format (DD.MM.YYYY -> YYYY-MM-DD). ONLY DD.MM.YYYY FORMAT.""" return date_string[-4:] + '-' + date_string[3:5] + '-' + date_string[:2]
def set_optional_arguments(options, option_values, command_line_options): """ Validate and set optional command cline arguments. """ option_value_keys = option_values.keys() for option in options: if option[0] == '<': non_required_option = option[1:len(option) - 1] if non_required_option in optio...
def ATGC_content(dna_sequence): """Returns ATGC contents in the form of a dict.""" ATGCDict = {'A': 0, 'T': 0, 'G': 0, 'C': 0} for nucleotide in dna_sequence: try: ATGCDict[nucleotide] += 1 except KeyError: pass return ATGCDict
def numberIn(s): """Return a Decimal from a string that might have unicode pound symbols and commas""" number = str() for c in s: if c in '0123456789.': number = number + c if len(number) > 0: from decimal import Decimal return Decimal(number) else: return None
def compute_peg(profit, infos_boursiere): """ Returns an approximation of the PEG """ if not 'PER' in infos_boursiere: return 0 if profit is None: return None per = float(infos_boursiere['PER'].split()[0]) if profit <= 0: return 0 return round(per/profit, 1)
def count_ways(target, max_integer=None, cache=None): """ Count the number of ways of making target from sum of at least 1 integers with max_integer as the largest integer in the sum. If max_integer is not provided, count all possible ways from sum of at least 2 integers. """ # Special cases: be...
def baby_names_list_from_table_rows(a_table_rows): """ a_table_rows is a list of dictionaries return list of lists, discarding gender information contained in a_table_rows element [name, rank] list is sorted by name """ print('baby_names_list_from_table_rows') baby_names_list = [] f...
def build_bankruptcy_definition(years): """Build a bankruptcy definition Notes: This function is set according to a line of best fit from Year 0 at -10% ROI to 10% ROI by Year 7. Args: years (int): No. of years for analysis Returns: Bankruptcy definitio...
def get_iou(bb1, bb2): """ Determine Intersection over Union for two bounding boxes """ # Determine the coordinates of the intersection rectangle xmin = max(bb1[0], bb2[0]) ymin = max(bb1[1], bb2[1]) xmax = min(bb1[2], bb2[2]) ymax = min(bb1[3], bb2[3]) if xmax < xmin or ymax < ymin: ...
def get_varinfo_from_table(discipline,parmcat,parmnum): """ Return the GRIB2 variable information given values of `discipline`, `parmcat`, and `parmnum`. NOTE: This functions allows for all arguments to be converted to a string type if arguments are integer. Parameters ---------- **`discip...
def matrix_from_vectors(op, v): """ Given vector v, build matrix [[op(v1, v1), ..., op(v1, vn)], ... [op(v2, v1), ..., op(vn, vn)]]. Note that if op is commutative, this is redundant: the matrix will be equal to its transpose. The matrix is represented as a list of lists. ...
def flatten(iterable, n=1): """ remove n levels of list nesting for a list of lists assumes uniform nesting :param iterable: nested list of lists to be flattened :param n: how many levels of nesting to remove :return: flattened list """ tmp = iterable for _ in range(n): tmp =...
def find_identical_rects(frames): """Unify ChangedRects with identical key()s.""" rawRectCount = 0 cache = {} for frame in frames: content = frame.content() rawRectCount += len(content) uniqueContent = [] for r in content: key = r.key() r = c...
def request_id(request, flavor_id): """Flavor id to use on the url call.""" return request.param if hasattr(request, 'param') else flavor_id
def ref_seq_output(in_seq_name, in_ref_name, ext): """ Generate output file name :param in_seq_name: treatment name (str) :param in_ref_name: reference name (str)nt) :param ext: extension (ie. csv or pdf) :return: output filename (str) """ return "{0}_{1}.{2}".format(in_ref_name, ...
def unknown_id_to_symbol(unknown_id, header="X"): """Get the symbol of unknown whose id is |unknown_id|. :type unknown_id: int :type header: str :param unknown_id: The ID of the unknown. :param header: The symbol header. :rtype : str :return: A string that contains the symbol. """ ...
def make_config( image_h, image_w, image_d, train_split=0.8, batch_size=128, cache_images=True, crop_top=0, crop_bot=0, data_path=None, max_thr=0.5 ): """ Make a DonkeyCar config-like object if there is no config file available. Entries needed for: gather_records -> gather_tubs -> gather_tub_paths ...
def extract_row(key: str, clientresult) -> dict: """ Extract one row from the client result, and return result as dict """ data = clientresult[key] return dict(data)
def trimArray(array): """ >>> trimArray([0 for _ in range(10)]) == [0] True >>> trimArray([1, 0, 0, 0, 0, 0, 0, 0]) [1] """ for i in range(len(array) - 1, -1, -1): if array[i] != 0: return array[:i + 1] return [0]
def RPL_YOURESERVICE(sender, receipient, message): """ Reply Code 383 """ return "<" + sender + ">: " + message
def _texture(number): """Generates ARB assembly for a texture.""" return 'texture[{}]'.format(number)
def solution(value: int) -> str: """ Complete the solution so that it returns a formatted string. The return value should equal "Value is VALUE" where value is a 5 digit padded number. :param value: :return: """ result = str(value) while len(result) != 5: result = ...
def _get_axis_num(nrow, row, col): """ computes axis number Parameters ---------- nrow : int number of rows row : int row number col : int column number """ return (nrow * row + col) + 1
def _list_clean(tweet): """Splits the tweet into words based on spaces and returns this list along with a concatenated string without spaces. Args: tweet (str): Tweet text Returns: tuple """ # Tweet split into a list of words tweet_word_list = tweet.split(" ") # Tweet r...
def plist_set_version(plist_data, version_str): """ <key>CFBundleShortVersionString</key> <string>0.1</string> <key>CFBundleVersion</key> <string>0.1</string> """ plist_lines = plist_data.split("\n") plist_num_lines = len(plist_lines) out_lines = [] line_idx = 0 while line_idx < pl...
def safe_import(origin, funk1, funk2): """Safely import a function whose name was changed from a module whose name was not. This function is specially useful if the function name is not known at runtime. Args: origin (str): name of the module where the function to be imported is located fun...
def same_rank(hand, n_of_a_kind): """ Given a hand of cards, return the number of n_of_a_kind combinations of ranks. For example, with n_of_a_kind=2, the function returns the number of pairs in the hand. """ ranks = [card[1:] for card in hand] counter = 0 already_counted = [] for...
def filtered_map(method, object_list): """ Performs a map then a filter on the object list. The final filter strips out objects which evaluate to False. """ return [x for x in map(method, object_list) if x]
def get_pairs(word): """Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
def uniquify_tuples(tuples): """ Uniquifies Mimikatz tuples based on the password. cred format- (credType, domain, username, password, hostname, sid) """ seen = set() return [item for item in tuples if "%s%s%s%s"%(item[0],item[1],item[2],item[3]) not in seen and not seen.add("%s%s%s%s"%(item[0]...
def version_splitter(s): """Splits a version string into a tuple of integers. The following ASCII characters are allowed, and employ the following conversions: a -> -3 b -> -2 c -> -1 (This permits Python-style version strings such as "1.4b3".) """ version = [] accum...
def layer_type(flags): """ Returns the layer type from the feature classification flag 0 = invalid (bad or missing data) 1 = "clear air" 2 = cloud 3 = aerosol 4 = stratospheric feature 5 = surface 6 = subsurface 7 = no signal (totally attenuated) """ # type flag : bits ...
def generate(output, aid_to_ans): """ Return the answer given the Answer ID/label :param output: The answer label :param aid_to_ans: :return: """ ans = aid_to_ans[output] return ans
def improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): """Returns tokenized answer spans that better match the annotated answer. The SQuAD annotations are character based. We first project them to whitespace-tokenized words. But then after WordPiece tokenization, we can ...
def cidr_to_common(cidr_mask): """Function that returns a common mask (Ex: 255.255.255.0) for a given input CIDR mask (Ex: 24)""" cidrtocommon = { 1: "128.0.0.0", 2: "192.0.0.0", 3: "224.0.0.0", 4: "240.0.0.0", 5: "248.0.0.0", 6: "252.0.0.0", 7: "25...
def _parse_versions_json_field(line): """Parses a line like '"key": "value",' into a key and value pair.""" if line.endswith(","): line = line[:-1] k, sep, v = line.partition('": "') if not sep or not k.startswith('"') or not v.endswith('"'): return "", "" return k[1:], v[:-1]
def generate_gateway_url(project, gateway): """ Format the resource name as a resource URI. """ return 'projects/{}/global/gateways/{}'.format(project, gateway)
def is_ambiguous_align(tags, multi_align_tag): """Returns whether the read aligns to multiple locations. The multi_align_tag depends on mapper. For bowtie2 it is XS.""" for t in tags: if t[0] == multi_align_tag: return True return False
def normalize_index(i): """Ensure 0 <= i < 2.""" return max(0, min(2, i))
def get_qualified_name(obj): """Retrieve the full module path of an object. Example: .. code-block:: python from watson.http.messages import Request request = Request() name = get_qualified_name(request) # watson.http.messages.Request """ try: name = obj.__qualname...
def response_with_headers(headers, code=200): """ Content-Type: text/html Set-Cookie: user=gua """ header = 'HTTP/1.x {} VERY OK\r\n'.format(code) header += ''.join([ '{}: {}\r\n'.format(k, v) for k, v in headers.items() ]) return header
def parse_int(value, fallback=0): """ Convert a string number to integer """ if value is None: return fallback try: return int(value) except ValueError: return fallback
def adjust_ifs(content): """ Adds ':' after ')' """ for n,line in enumerate(content): count = 0 if line.strip().startswith('IF'): i = line.find('(') if i >= 0: count = 1 for k in range(i,len(line)): #print(k, line[k]...
def attack(p, k, a1, f, x, y): """ Recovers the shared secret if the coefficients are generated deterministically, and a single share is given. :param p: the prime used for Shamir's secret sharing :param k: the amount of shares needed to unlock the secret :param a1: the first coefficient of the poly...
def invertIntervalList(inputList, maxValue=None): """ Inverts the segments of a list of intervals e.g. [(0,1), (4,5), (7,10)] -> [(1,4), (5,7)] """ inputList = sorted(inputList) # Special case -- empty lists if len(inputList) == 0 and maxValue is not None: invList = [ ...
def get_labeled_spans(prop): """ :param prop: 1D: n_words; elem=bracket label :return: 1D: n_words; elem=BIO label """ def _concat_c_spans(_spans): labels = [_span[0] for _span in _spans] c_indices = [i for i, _span in enumerate(_spans) if _span[0].startswith('C')] non_ant_c_...
def is_pod_type(type_name): """ Those are types for which no class should be generated. """ return type_name in [ "Nil", "void", "bool", "real_t", "float", "double", "int", "int8_t", "uint8_t", "int16_t", "uint16_t",...
def pad(string): """ Decongest statements """ padded = string.replace("\r", "").replace("\t", " ") symbols = ["#", "%", "*", ")", "+", "-", "=", "{", "}", "]", "\"", "'", "<", ">" ] for item in symbols: padded = padded.replace(item, f" {item} ") return padded.replace("(", "( ...
def file_finder(filepath): """ Takes a filepath (str) and exracts: (1) its path, (2) its name, and (3) its extension. This metadata is filtered into a dictionary. For example, the filepath 'folder/directory/repository/file_name.txt' would return: File path: 'folder/directory/repository/' ...
def get_object_type(objects: list, types: list) -> list: """Get the object specified. Args: objects: a list of objects. types: a list of the types. Returns: A list of a certain type. """ return [item for item in objects if item.get('type') in types]
def pipe(arg, *args): """ Pipe """ last_result = arg for combinator in args: last_result = combinator(last_result) if last_result is None: return None return last_result
def format_boolean(value): """Return value as boolean.""" return_value = None if value is not None: return_value = value return return_value
def svm_grid(): """ Return grid for RandomSearchCV for the SVM classifier :return: dictionary """ C = [0.1, 1, 10, 100] kernel = ['linear', 'poly', 'rbf', 'sigmoid'] degree = [2, 3, 4, 5, 6, 7, 8] coef0 = [0.1, 1, 10, 100] gamma = ['scale', 'auto'] shrinking = [True, False] prob...
def recursive_max(items): """O(n).""" if len(items) == 1: return items[0] prev_max = recursive_max(items[1:]) return prev_max if prev_max > items[0] else items[0]
def rotate(string, bits): """ Given that all our words are stored as strings, using slice notation is the easiest way to perform rotations. :param string: :param bits: :return: """ rf = string[0: len(string) - bits] rs = string[len(string) - bits:] return rs + rf
def PlmIndex(l, m): """ Compute the index of a array of Legendre functions corresponding to degree l and angular order m. Usage ----- index = PlmIndex (l, m) Returns ------- index : integer, ndarray Index of an array of associated Legendre functions corresponding to ...
def _Join(*args): """Join parts of a gs:// Cloud Storage or local file:// path.""" # URIs always uses '/' as separator, regardless of local platform. return '/'.join([arg.strip('/') for arg in args])
def obj_type(key): """If it is a 'dir' it will end with a slash otherwise it is a 'file' """ if key[-1:] == '/': return 'directory' else: return 'file'
def watch(name, timespec, tag=None, user=None, job=None, unique_tag=False): """ .. versionadded:: 2017.7.0 Add an at job if trigger by watch job : string Command to run. timespec : string The 'timespec' follows the format documented in the at(1) manpage. tag : string ...
def get_policy_published(reportee, policy, **kw): """Return "policy_published" part for a passed `reportee` and `policy`. For now we use the hardcoded values for `adkim`, `aspf` and `pct` everywhere. """ return { "domain": reportee, "adkim": "r", "aspf": "r", "p": policy, "sp": policy, "pc...