content
stringlengths
42
6.51k
def format(pat, x): """ format(pat, x) pat.format(x) """ return pat.format(x)
def Imprimir_Mensaje_2(msj): """ Imprime un mensaje :param msj: (str) Variable con el mensaje. :returns msjcomple: (str) Variable con el mensaje completo """ print('El mensaje es:',msj) msjcomple = 'El mensaje es: ' + msj return msjcomple
def days_in_month_360(month=0, year=0): """Days of the month (360 days calendar). Parameters ---------- month : int, optional (dummy value). year : int, optional (dummy value). Returns ------- out : list of int days of the month. Notes ----- Appropriate for use as 'days_in_cycle' function in :class:`Calendar`. This module has a built-in 360 days calendar with months: :data:`Cal360`. """ return range(1, 31)
def translateTaps(lowerTaps, pos): """Method to translate tap integer in range [0, lowerTaps + raiseTaps] to range [-lower_taps, raise_taps] """ # Hmmm... is it this simple? posOut = pos - lowerTaps return posOut
def get_nested_dict_entry_from_namespace_path(d, namespace_path): """Obtain the entry from a nested dictionary that corresponds to the path given in namespace format. A namespace path specifies the keys of the nested dictionary as a dot-separated string (e.g., "key1.key2.key3"). :param d: The nested dictionary to traverse (dict) :param namespace_path: A dot-separated string containing the keys used to traverse the dictionary (str) :return: object """ # Try to split off the namespace path into the first key and the rest of the keys split_namespace_path = namespace_path.split('.', 1) if len(split_namespace_path) == 1: # Only one key for a non-nested dict; return the result return d[split_namespace_path[0]] else: cur_key, path_remainder = split_namespace_path return get_nested_dict_entry_from_namespace_path(d[cur_key], path_remainder)
def filter_list(l): """return a new list with the strings filtered out""" return [i for i in l if not isinstance(i, str)]
def R_total(deltaT_sub, Q_drop): """ total thermal resistance of a single drop Parameters ---------- deltaT_sub: float temperature difference to the cooled wall in K Q_drop: float rate of heat flow through drop in W Returns ---------- R_total: float total thermal resistance of drop in K/W """ R_total = deltaT_sub / Q_drop return R_total
def _combine_texts_to_str(text_corpus, ignore_words=None): """ Combines texts into one string. Parameters ---------- text_corpus : str or list The texts to be combined. ignore_words : str or list Strings that should be removed from the text body. Returns ------- texts_str : str A string of the full text with unwanted words removed. """ if isinstance(ignore_words, str): words_to_ignore = [ignore_words] elif isinstance(ignore_words, list): words_to_ignore = ignore_words else: words_to_ignore = [] if isinstance(text_corpus[0], list): flat_words = [text for sublist in text_corpus for text in sublist] flat_words = [ token for subtext in flat_words for token in subtext.split(" ") if token not in words_to_ignore ] else: flat_words = [ token for subtext in text_corpus for token in subtext.split(" ") if token not in words_to_ignore ] return " ".join(flat_words)
def structparse_ip_header_embedded_protocol(bytes_string: bytes): """Takes a given bytes string of a packet and returns information found in the IP header about the embedded protocol at the next level of encapsulation. Examples: >>> from scapy.all import *\n >>> icmp_pcap = rdpcap('icmp.pcap')\n >>> firstpacket = icmp_pcap[0]\n >>> thebytes_firstpacket = firstpacket.__bytes__()\n >>> structparse_ip_header_embedded_protocol(thebytes_firstpacket)\n {'embedded_protocol': 'ICMP'} Args: bytes_string (bytes): Reference a bytes string representation of a packet. Returns: dict: Returns a dictionary. """ import struct # # We define a lookup table for embedded protocols we want to specify embedded_protocols_dict = {17:'UDP', 6:'TCP', 1:'ICMP'} # # We skip the first 14 bytes which are the Ethernet header ip_layer_plus = bytes_string[14:] # # This uses 'network byte order' (represented by '!') which is Big Endian (so we could have use '>' instead of '!'); we then ignore the first 9 bytes of the IP header using '9x', and process the next 1 byte as an unsigned integer using 'B' # - we use the [0] because the '.unpack()' method always returns a tuple, even when a single element is present, and in this case we just want a single element embed_protocol_num = ( struct.unpack('!9xB', ip_layer_plus[:10]) )[0] # # Here we define a fallback answer in case the "protocol number" is not one we specified in our "embedded_protocols_dict" embed_protocol_num_notfound = f'Undefined Protocol, protocol number: {embed_protocol_num}' # # We do a lookup of the 'embed_protocol_num' that we parsed out of the bytes, and specify the fallback value as a catch-all proto_name = embedded_protocols_dict.get(embed_protocol_num, embed_protocol_num_notfound) # results = {} results['embedded_protocol'] = proto_name return results
def hexify(ustr): """Use URL encoding to return an ASCII string corresponding to the given UTF8 string >>> hexify("http://example/a b") b'http://example/a%20b' """ # s1=ustr.encode('utf-8') s = "" for ch in ustr: # .encode('utf-8'): if ord(ch) > 126 or ord(ch) < 33: ch = "%%%02X" % ord(ch) else: ch = "%c" % ord(ch) s = s + ch return s.encode("latin-1")
def zenodo_fetch_resource_helper(zenodo_project, resource_id, is_record=False, is_file=False): """ Takes a Zenodo deposition/record and builds a Zenodo PresQT resource. Parameters ---------- zenodo_project : dict The requested Zenodo project. auth_parameter : dict The user's Zenodo API token is_record : boolean Flag for if the resource is a published record is_file : boolean Flag for if the resource is a file Returns ------- PresQT Zenodo Resource (dict). """ if is_file is False: if is_record is True: kind_name = zenodo_project['metadata']['resource_type']['type'] date_modified = zenodo_project['updated'] else: kind_name = zenodo_project['metadata']['upload_type'] date_modified = zenodo_project['modified'] kind = 'container' title = zenodo_project['metadata']['title'] hashes = {} extra = {} for key, value in zenodo_project['metadata'].items(): extra[key] = value else: kind = 'item' kind_name = 'file' title = zenodo_project['key'] date_modified = zenodo_project['updated'] hashes = {'md5': zenodo_project['checksum'].partition(':')[2]} extra = {} return { "kind": kind, "kind_name": kind_name, "id": resource_id, "title": title, "date_created": zenodo_project['created'], "date_modified": date_modified, "hashes": hashes, "extra": extra}
def _should_reverse_image(format): """ Reverses the array format for JPG images Args: format: The format of the image input Returns: bool: True if the image should be reversed. False otherwise """ should_reverse = ["JPG"] if format in should_reverse: return True else: return False
def dice_coefficient(sequence_a, sequence_b): """(str, str) => float Return the dice cofficient of two sequences. """ a = sequence_a b = sequence_b if not len(a) or not len(b): return 0.0 # quick case for true duplicates if a == b: return 1.0 # if a != b, and a or b are single chars, then they can't possibly match if len(a) == 1 or len(b) == 1: return 0.0 # list comprehension, preferred over list.append() ''' a_bigram_list = [a[i : i + 2] for i in range(len(a) - 1)] b_bigram_list = [b[i : i + 2] for i in range(len(b) - 1)] a_bigram_list.sort() b_bigram_list.sort() # assignments to save function calls lena = len(a_bigram_list) lenb = len(b_bigram_list) # initialize match counters matches = i = j = 0 while i < lena and j < lenb: if a_bigram_list[i] == b_bigram_list[j]: matches += 2 i += 1 j += 1 elif a_bigram_list[i] < b_bigram_list[j]: i += 1 else: j += 1 score = float(matches) / float(lena + lenb) return score
def rotate_right(v, n): """ bit-wise Rotate right n times """ mask = (2 ** n) - 1 mask_bits = v & mask return (v >> n) | (mask_bits << (32 - n))
def make_queue_name(mt_namespace, handler_name): """ Method for declare new queue name in channel. Depends on queue "type", is it receive event or command. :param mt_namespace: string with Mass Transit namespace :param handler_name: string with queue time. MUST be 'command' or 'event' :return: new unique queue name for channel """ return '{}.{}'.format(mt_namespace, handler_name)
def process_molecules_for_final_mdl(molecules): """ grab molecule defintions from mdlr for final mdl. """ molecule_str = "" for idx, molecule in enumerate(molecules): diffusion_list = molecule[1]['diffusionFunction'] molecule_name = molecule[0][0] component_str = "" component_list = molecule[0][1:] for c_idx, component in enumerate(component_list): if c_idx > 0: component_str += ", " c_name = component['componentName'] try: c_loc = component['componentLoc'] x1, y1, z1 = c_loc[0], c_loc[1], c_loc[2] c_rot = component['componentRot'] x2, y2, z2, angle = c_rot[0], c_rot[1], c_rot[2], c_rot[3] component_str += "{}{{loc=[{}, {}, {}], rot=[{}, {}, {}, {}]}}".format(c_name, x1, y1, z1, x2, y2, z2, angle) except KeyError: component_str += c_name molecule_str += "\t{}({})\n".format(molecule_name, component_str) # molecule_str += "\t{\n" # molecule_str += "\t\t{} = {}\n".format(diffusion_list[0], diffusion_list[1]) # molecule_str += "\t}\n" return molecule_str
def _human_size(nbytes): """Return a human-readable size.""" i = 0 suffixes = ["B", "KB", "MB", "GB", "TB"] while nbytes >= 1000 and i < len(suffixes) - 1: nbytes /= 1000.0 i += 1 f = ("%.2f" % nbytes).rstrip("0").rstrip(".") return "%s%s" % (f, suffixes[i])
def coerce_int(obj): """Return string converted to integer. .. Usage:: >>> coerce_int(49) 49 >>> coerce_int('49') 49 >>> coerce_int(43.22) 43 """ try: return int(obj) if obj else obj except ValueError: return 0
def build_shell_arguments(shell_args, apps_and_args=None): """Build the list of arguments for the shell. |shell_args| are the base arguments, |apps_and_args| is a dictionary that associates each application to its specific arguments|. Each app included will be run by the shell. """ result = shell_args[:] if apps_and_args: for (application, args) in apps_and_args.items(): result += ["--args-for=%s %s" % (application, " ".join(args))] result += apps_and_args.keys() return result
def map_compat_network_region(network_region: str) -> str: """ Map network regions from old to new Note that network regions aren't really geos and there are networks within geos like DKIS (NT) and NWIS (WA) that need to retain their network_region """ if not network_region or not type(network_region) is str: return network_region network_region = network_region.strip() if network_region == "WA1": return "WEM" return network_region
def trim(value): """ Strips the whitespaces of the given value :param value: :return: """ return value.strip()
def remove_duplicates(any_list): """Remove duplicates without changing order of items Args: any_list (list): List of items Returns: list: List without duplicates """ final_list = list() for item in any_list: if item not in final_list: final_list.append(item) return final_list
def fib(n): """Recursive function to return the nth Fibonacci number """ if n <= 1: return n else: return(fib(n-1) + fib(n-2))
def second_half(string: str) -> str: """Return second half of a string.""" if len(string) % 2 != 0: raise ValueError(f"Ivalid string'{string}' with length {len(string)}") else: return string[int(len(string) / 2):]
def corner_points(m, cell_num, x, y): """ :param m: :param cell_num: :param x: :param y: :return: """ # Your code here sq_size = m / cell_num top_left = (x, y) top_right = (x + sq_size, y) bottom_left = (x, y + sq_size) bottom_right = (x + sq_size, y + sq_size) return [top_left, top_right, bottom_left, bottom_right]
def arduino_map(x, in_min, in_max, out_min, out_max): """ copy the function map from Arduino """ return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
def hex_to_bin(hex_number): """converts a hexadecimal number to binary""" return bin(int(hex_number, 16))[2:]
def __must_be_skipped(type_id): """Assesses whether a typeID must be skipped.""" return type_id.startswith("<dbo:Wikidata:")
def trailer(draw): """ trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME """ #'(' [testlist] ')' | '[' subscript ']' | '.' NAME return ''
def stringToInt(text): """ returns an integer if the string can be converted, otherwise returns the string @param text: the string to try to convert to an integer """ if text.isdigit(): return int(text) else: return text
def add_feed(msg, change, addition): """Adds an element to a given RethinkDB feed. Returns the msg and feed.""" if not change['old_val']: msg[addition] = change['new_val'][addition] elif change['new_val'][addition] != change['old_val'][addition]: msg[addition] = change['new_val'][addition] return msg, change
def _is_vendor_extension(key): """Return 'True' if a given key is a vendor extension.""" return key.startswith("x-")
def is_dunder(attr_name: str) -> bool: """ Retuns whether the given attr is a magic/dunder method. :param attr_name: """ return attr_name.startswith("__") and attr_name.endswith("__")
def read_python_source(filename): """Read the Python source text from `filename`. Returns bytes. """ with open(filename, "rb") as fin: source = fin.read() return source.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
def _process_field(item, field_mapping): """ Process the mapping rules for a given field. :param item: The item from the Overpass response. :param field_mapping: The field mapping to apply (not pre-processed). :return: The new value of the field. """ # Handle the special address filter properties = item.get('properties', {}) if field_mapping == '<ADDRESS>': housenumber = properties.get('contact:housenumber') if housenumber: return '%s, %s' % ( housenumber, properties.get( 'contact:street', properties.get('contact:place') ) ) else: return '%s' % properties.get( 'contact:street', properties.get('contact:place') ) # Parse the mapping for cast and checks cast, check = None, None if field_mapping.startswith('!'): field_mapping, check = field_mapping[1:], '!' if '|' in field_mapping: field_mapping, cast = field_mapping.split('|')[:2] if '==' in field_mapping: field_mapping, check = field_mapping.split('==')[:2] # Get the current value of the field new_value = properties.get(field_mapping) # Eventually apply check if check == '!': return new_value is None elif check: return new_value == check # Eventually apply cast operation if cast == 'int': return int(new_value) if new_value else None if cast == 'bool': if new_value in ['yes', '1']: return True elif new_value in ['no', '0']: return False return None return new_value
def string_list(argument): """ Converts a space- or comma-separated list of values into a python list of strings. (Directive option conversion function) Based in positive_int_list of docutils.parsers.rst.directives """ if ',' in argument: entries = argument.split(',') else: entries = argument.split() return entries
def merge_sort(elements): """ Use the simple merge sort algorithm to sort the :param elements. :param elements: a sequence in which the function __get_item__ and __len__ were implemented, as well as the slice and add operations. :return: the sorted elements in increasing order """ length = len(elements) if not length or length == 1: return elements volume = 2 while length > volume / 2: index = 0 while length - index >= volume: tmp = [] i, j, limit = index, index + volume / 2, index + volume mid_limit = j while i < mid_limit and j < limit: if elements[j] < elements[i]: tmp.append(elements[j]) j += 1 else: tmp.append(elements[i]) i += 1 if i < mid_limit: tmp += elements[i:mid_limit] else: tmp += elements[j:limit] for value in tmp: elements[index] = value index += 1 if length - index > volume / 2: tmp = [] i, j = index, index + volume / 2 mid_limit = j while i < mid_limit and j < length: if elements[j] < elements[i]: tmp.append(elements[j]) j += 1 else: tmp.append(elements[i]) i += 1 if i < mid_limit: tmp += elements[i:mid_limit] else: tmp += elements[j:] for value in tmp: elements[index] = value index += 1 volume *= 2 return elements
def r_max(nxs): """ Find the maximum in a recursive structure of lists within other lists. Precondition: No lists or sublists are empty. """ largest = None first_time = True for e in nxs: if type(e) == type([]): val = r_max(e) else: val = e if first_time or val > largest: largest = val first_time = False return largest
def preprocess_codebook(codebook): """ Removes trajectories from keys and puts the trajectories into single symbol list format. Also removes skills with 0 frequency. """ trajectories = codebook.pop('trajectories') codebook_with_spaces = {} for key, value in codebook.items(): if key == 'probabilities' or key == 'length_range': continue # skip these if value > 0: codebook_with_spaces[key] = value single_symbol_traj_split = [] for trajectory in trajectories: for symbol in trajectory.split(" "): if symbol != "": single_symbol_traj_split.append(symbol) #trajectories = "".join(trajectories) return single_symbol_traj_split, codebook_with_spaces
def _fmt_and_check_cutoffs(cutoffs, vocab_size): """Parse and get the cutoffs used in adaptive embedding + adaptive softmax Parameters ---------- cutoffs The cutoffs of the vocab_size Size of the vocabulary Returns ------- cutoffs The parsed cutoffs, will be [0, c0, c1, ..., c_{k-1}, V] If the original cutoffs is empty or is None, return None """ # Sanity checks if cutoffs is None: return None if isinstance(cutoffs, int): cutoffs = [cutoffs] else: cutoffs = list(cutoffs) if len(cutoffs) == 0: return None if cutoffs != sorted(cutoffs): raise ValueError('cutoffs must be a sorted list of cutoff values. ' 'Got {}, but expected {}'.format(cutoffs, sorted(cutoffs))) if len(set(cutoffs)) != len(cutoffs): raise ValueError('cutoffs cannot contain duplicates! cutoffs={}'.format(cutoffs)) if not cutoffs: raise ValueError('cutoffs must not be empty. Got {}'.format(cutoffs)) if cutoffs[0] <= 0: raise ValueError('The first cutoff value ({}) must be greater 0.'.format(cutoffs[0])) if cutoffs[-1] >= vocab_size: raise ValueError( 'The last cutoff value ({}) must be smaller than vocab_size ({}).'.format( cutoffs[-1], vocab_size)) return cutoffs
def is_valid_value_for_issns(issns_dict): """ Expected issns_dict is a dict keys: 'epub' and/or 'ppub' values: issn (1234-5678) """ try: if len(issns_dict) == 0 or not set(issns_dict.keys()).issubset({'epub', 'ppub'}): raise ValueError( f"Expected dict which keys are 'epub' and/or 'ppub'. Found {issns_dict}") if len(issns_dict.keys()) != len(set(issns_dict.values())): raise ValueError(f"{issns_dict} has duplicated values") for v in issns_dict.values(): if len(v) != 9 or v[4] != "-": raise ValueError(f"{v} is not an ISSN") except AttributeError: raise ValueError( f"Expected dict which keys are 'epub' and/or 'ppub'. Found {issns_dict}") return True
def separate_content_and_variables(text, boundary='{# /variables #}'): """Separate variables and content from a Markdown file""" # Find boundary pos = text.find(boundary) # Text contains variables if pos > 0: return(text[:pos].strip(), text[(pos + len(boundary)):].strip()) # Text does not contain variables return ('', text)
def _parse_output_string(string_value: str) -> str: """ Parses and cleans string output of the multimeter. Removes the surrounding whitespace, newline characters and quotes from the parsed data. Some results are converted for readablitity (e.g. mov changes to moving). Args: string_value: The data returned from the multimeter reading commands. Returns: The cleaned-up output of the multimeter. """ s = string_value.strip().lower() if (s[0] == s[-1]) and s.startswith(("'", '"')): s = s[1:-1] conversions = {'mov': 'moving', 'rep': 'repeat'} if s in conversions.keys(): s = conversions[s] return s
def flatten(data, parent_key="", separator=".", **kwargs): """ Reference Name ``flatten`` Turn a nested structure (combination of lists/dictionaries) into a flattened dictionary. This function is useful to explore deeply nested structures such as XML output obtained from devices over NETCONF. Another usecase is filtering of the keys in resulted dictionary, as they are the strings, glob or regex matching can be applied on them. :param data: nested data to flatten :param parent_key: string to prepend to dictionary's keys, used by recursion :param separator: string to separate flattened keys :return: flattened structure Based on Stackoverflow answer: https://stackoverflow.com/a/62186053/12300761 All credits for the idea to https://github.com/ScriptSmith Sample usage:: flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3] }) >> {'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'd.0': 1, 'd.1': 2, 'd.2': 3} """ items = [] if isinstance(data, dict): for key, value in data.items(): new_key = "{}{}{}".format(parent_key, separator, key) if parent_key else key items.extend(flatten(value, new_key, separator).items()) elif isinstance(data, list): for k, v in enumerate(data): new_key = "{}{}{}".format(parent_key, separator, k) if parent_key else k items.extend(flatten({str(new_key): v}).items()) else: items.append((parent_key, data)) return dict(items)
def valid(number): """ Returns true if the number string is luhn valid, and false otherwise. The number string passed to the function must contain only numeric characters otherwise behavior is undefined. """ checksum = 0 number_len = len(number) offset = ord('0') i = number_len - 1 while i >= 0: n = ord(number[i]) - offset checksum += n i -= 2 i = number_len - 2 while i >= 0: n = ord(number[i]) - offset n *= 2 if n > 9: n -= 9 checksum += n i -= 2 return checksum%10 == 0
def pop_key(keys, pop_dict): """[Pop key and return value if one is in argument. otherwise just pop off dictionary] """ if isinstance(keys, list): for key in keys: pop_key(key, pop_dict) elif keys in pop_dict: return pop_dict.pop(keys) return None
def filter_id(mention: str): """ Filters mention to get ID "<@!6969>" to "6969" Note that this function can error with ValueError on the int call, so the caller of this function must take care of this """ for char in ("<", ">", "@", "&", "#", "!", " "): mention = mention.replace(char, "") return int(mention)
def find_cycles(perm): """ Finds the cycle(s) required to get the permutation. For example, the permutation [3,1,2] is obtained by permuting [1,2,3] with the cycle [1,2,3] read as "1 goes to 2, 2 goes to 3, 3 goes to 1". Sometimes cycles are products of more than one subcycle, e.g. (12)(34)(5678) """ pi = {i: perm[i] for i in range(len(perm))} cycles = [] while pi: elem0 = next(iter(pi)) # arbitrary starting element this_elem = pi[elem0] next_item = pi[this_elem] cycle = [] while True: cycle.append(this_elem) del pi[this_elem] this_elem = next_item if next_item in pi: next_item = pi[next_item] else: break cycles.append(cycle[::-1]) # only save cycles of size 2 and larger cycles[:] = [cyc for cyc in cycles if len(cyc) > 1] return cycles
def get_studies_with_attribute(attribute_name, attribute_dict): """Get identifiers of studies whose metadata contains the given attribute_name. Parameters ---------- attribute_name : str The name of an attribute to check against attribute_dict in order to identify studies containing this attribute. attribute_dict : dict Dictionary whose keys are study identifiers and values are lists of attributes found in a particular metadata file. This is the sort of dictionary returned by get_attributes_by_study. Returns ------- list List of all study identifiers of studies that contain the attribute_name in metadata to which attribute_dict relates. """ studies = [] for study_id, attributes in attribute_dict.items(): if attribute_name in attributes: studies.append(study_id) return studies
def str2bool(v): """Convert a string to a boolean. Arguments: v {str} -- string to convert Returns: {bool} -- True if string is a string representation of True """ return str(v).lower() in ("yes", "true", "t", "1")
def attrname(obj, lower_name): """Look up a real attribute name based on a lower case (normalized) name.""" for name in dir(obj): if name.lower() == lower_name: return name return lower_name
def get_pkg_vendor_name(pkg): """ Method to extract vendor and name information from package. If vendor information is not available package url is used to extract the package registry provider such as pypi, maven """ vendor = pkg.get("vendor") if not vendor: purl = pkg.get("purl") if purl: purl_parts = purl.split("/") if purl_parts: vendor = purl_parts[0].replace("pkg:", "") else: vendor = "" name = pkg.get("name") return vendor, name
def draft_window_position(m) -> str: """One of the named positions you can move the window to""" return "".join(m)
def unique_char(string): """.""" individuals = set() string = ''.join(string.lower().split(' ')) for char in string: if char in individuals: return False individuals.add(char) return True
def set_difficulty(difficulty): """Set the difficulty level""" if difficulty == "easy": return 10 elif difficulty == "hard": return 5
def flatten_list(input_list): """Flatten multi-layer list ot one-layer.""" flattened_result = list() for ipt in input_list: if isinstance(ipt, (tuple, list)): flattened_result.extend(flatten_list(ipt)) else: flattened_result.append(ipt) return flattened_result
def path_to_file(path): """ Path to file /impl/src/main/java/com/mogujie/service/mgs/digitalcert/utils/CertUtil.java .../CertUtil.java :param path: :return: """ paths = path.split('/') paths = list(filter(None, paths)) length = len(paths) return '.../{0}'.format(paths[length - 1])
def add_zero_frame(matrix): """adds frame of zeros around matrix""" n = len(matrix) m = len(matrix[0]) res = [[0 for j in range(m+2)] for i in range(n+2)] for i in range(n+1): for j in range(m+1): if not(i == 0 or j == 0 or i == n+1 or j == m+1): res[i][j] = matrix[i-1][j-1] return res
def updated_full_record(full_record): """Update fields (done after record create) for Dublin Core serializer.""" full_record["access"]["status"] = "embargoed" return full_record
def merge(pinyin_d_list): """ :rtype: dict """ final_d = {} for overwrite_d in pinyin_d_list: final_d.update(overwrite_d) return final_d
def get_or_else(data, key, default_value = None): """ Tries to get a value from data with key. Returns default_value in case of key not found. """ if not data: return default_value try: return data[key] except: return default_value
def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repay: int ) -> float: """ Formula for amortization amount per month: A = p * r * (1 + r)^n / ((1 + r)^n - 1) where p is the principal, r is the rate of interest per month and n is the number of payments >>> equated_monthly_installments(25000, 0.12, 3) 830.3577453212793 >>> equated_monthly_installments(25000, 0.12, 10) 358.67737100646826 >>> equated_monthly_installments(0, 0.12, 3) Traceback (most recent call last): ... Exception: Principal borrowed must be > 0 >>> equated_monthly_installments(25000, -1, 3) Traceback (most recent call last): ... Exception: Rate of interest must be >= 0 >>> equated_monthly_installments(25000, 0.12, 0) Traceback (most recent call last): ... Exception: Years to repay must be an integer > 0 """ if principal <= 0: raise Exception("Principal borrowed must be > 0") if rate_per_annum < 0: raise Exception("Rate of interest must be >= 0") if years_to_repay <= 0 or not isinstance(years_to_repay, int): raise Exception("Years to repay must be an integer > 0") # Yearly rate is divided by 12 to get monthly rate rate_per_month = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly number_of_payments = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) )
def format_time(total_minutes: int) -> str: """Format time.""" end_hours, end_minutes = divmod(total_minutes, 60) end_hours = end_hours % 24 return f"T{end_hours:02g}:{end_minutes:02g}Z"
def message_warning(msg, *a, **kwargs): """Ignore everything except the message.""" return str(msg) + '\n'
def database_label(database): """Return normalized database label for consistency in file names. """ if database: return database else: return 'database_na'
def _diff(*a): """Returns difference between list t1, and list tn. """ return set.difference(*tuple(map(lambda x : set(x), a)))
def checksum(data): """ Compute a checksum for DATA. """ # Remove this later after development assert isinstance(data, bytearray), "data must be a bytearray" chk = data[0] for i in range(1, len(data)): chk ^= data[i] return chk
def get_ingredients(raw_text): """toma un texto y saca una lista de items y sus cantidades""" ingredients = [] for l in raw_text.split('\n'): if len(l) > 1: ingredients.append(l.split(' ')) return ingredients
def sane_parser_name(name) -> bool: """ Checks whether given name is an acceptable parser name. Parser names must not be preceded or succeeded by a double underscore '__'! """ return name and name[:2] != '__' and name[-2:] != '__'
def dictify(obj): """ Convert any object to a dictionary. If the given object is already an instance of a dict, it is directly returned. If not, then all the public attributes of the object are returned as a dict. """ if isinstance(obj, dict): return obj else: return { k: getattr(obj, k) for k in dir(obj) if not k.startswith('_') }
def get_unique_survey_and_business_ids(enrolment_data): """Takes a list of enrolment data and returns 2 unique sets of business_id and party_id's :param enrolment_data: A list of enrolments :return: A pair of sets with deduplicated survey_id's and business_id's """ surveys_ids = set() business_ids = set() for enrolment in enrolment_data: surveys_ids.add(enrolment["survey_id"]) business_ids.add(enrolment["business_id"]) return surveys_ids, business_ids
def format_interval(t): """ Formats a number of seconds as a clock time, [H:]MM:SS Parameters ---------- t : int Number of seconds. Returns ------- out : str [H:]MM:SS """ mins, s = divmod(int(t), 60) h, m = divmod(mins, 60) if h: return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s) else: return '{0:02d}:{1:02d}'.format(m, s)
def join_with_function(func, values1, values2): """Join values using func function.""" return [ func(value1, value2) for value1, value2 in zip(values1, values2) ]
def _decode_json_int(o): """_decode_json_int Loads integers in a json as int. Pass in as parameter `object_hook` for `json.load`. """ if isinstance(o, str): try: return int(o) except ValueError: return o elif isinstance(o, dict): return {_decode_json_int(k): _decode_json_int(v) for k, v in o.items()} elif isinstance(o, list): return [_decode_json_int(v) for v in o] else: return o
def quersumme(integer): """bildet die Quersumme einer Zahl""" string = str(integer) summe = 0 for ziffer in string: summe = summe + int(ziffer) return summe
def load_env(context): """Get the current environment for the running Lambda function. Parses the invoked_function_arn from the given context object to get the name of the currently running alias (either production or staging) and the name of the function. Example: arn:aws:lambda:aws-region:acct-id:function:stream_alert:production Args: context: The AWS Lambda context object. Returns: {'lambda_region': 'region_name', 'account_id': <ACCOUNT_ID>, 'lambda_function_name': 'function_name', 'lambda_alias': 'qualifier'} """ env = {} if context: arn = context.invoked_function_arn.split(':') env['lambda_region'] = arn[3] env['account_id'] = arn[4] env['lambda_function_name'] = arn[6] env['lambda_alias'] = arn[7] else: env['lambda_region'] = 'us-east-1' env['account_id'] = '123456789012' env['lambda_function_name'] = 'test_streamalert_rule_processor' env['lambda_alias'] = 'development' return env
def point_in_rectangle(point, rect_min, rect_max) -> bool: """ Check if a point is inside a rectangle :param point: a point (x, y) :param rect_min: x_min, y_min :param rect_max: x_max, y_max """ return rect_min[0] <= point[0] <= rect_max[0] and rect_min[1] <= point[1] <= rect_max[1]
def fib(n): """Fib without recursion.""" a, b = 0, 1 for i in range(1, n + 1): a, b = b, a + b return b
def LSC(X, Y): """Return table such that L[j][k] is length of LCS for X[0:j] and Y[0:k].""" n, m = len(X), len(Y) # introduce convenient notations L = [[0] * (m+1) for k in range(n+1)] # (n+1) x (m+1) table for j in range(n): for k in range(m): if X[j] == Y[k]: # align this match L[j+1][k+1] = L[j][k] + 1 else: L[j + 1][k + 1] = max(L[j][k + 1], L[j + 1][k]) # choose to ignore one character return L
def check_sender_agency(msg): """ deprecated. originally designed to help lookup the agency by the sender. this is problematic because occasionally a contact sends on behalf of multiple agencies. keeping this code for reference but it's not advisable to implement, i.e. could result in false matches. """ return # todo: check for multiple matches ie double agents sender = [x for x in msg['payload']['headers'] if x['name'] == 'From'][0]['value'] matching_agencies = [ agency for agency in contacts_by_agency if sender in contacts_by_agency[agency] ] if matching_agencies: return matching_agencies[0]
def get_allowed_categories(version): """ Modelnet40 categories 0 - airplane 1 - bathtub 2 - bed 3 - bench 4 - bookshelf 5 - bottle 6 - bowl 7 - car 8 - chair 9 - cone 10 - cup 11 - curtain 12 - desk 13 - door 14 - dresser 15 - flower_pot 16 - glass_box 17 - guitar 18 - keyboard 19 - lamp 20 - laptop 21 - mantel 22 - monitor 23 - night_stand 24 - person 25 - piano 26 - plant 27 - radio 28 - range_hood 29 - sink 30 - sofa 31 - stairs 32 - stool 33 - table 34 - tent 35 - toilet 36 - tv_stand 37 - vase 38 - wardrobe 39 - xbox """ assert version in ["small", "big", "airplane", "chair", "sofa", "toilet"] if version == "big": return [0, 2, 5, 6, 7, 8, 17, 30, 35] if version == "small": return [0, 7, 8, 35] if version == "airplane": return [0] if version == "chair": return [8] if version == "sofa": return [20] if version == "toilet": return [35] return 0
def option_to_text(option): """Converts, for example, 'no_override' to 'no override'.""" return option.replace('_', ' ')
def _decodebytestring(a): """ Convert to string if input is a bytestring. Parameters ---------- a : byte or str string or bytestring Returns ------- str string version of input """ if isinstance(a, bytes): return a.decode() else: return a
def fileobj_closed(f): """ Returns True if the given file-like object is closed or if f is a string (and assumed to be a pathname). Returns False for all other types of objects, under the assumption that they are file-like objects with no sense of a 'closed' state. """ if isinstance(f, str): return True if hasattr(f, 'closed'): return f.closed elif hasattr(f, 'fileobj') and hasattr(f.fileobj, 'closed'): return f.fileobj.closed elif hasattr(f, 'fp') and hasattr(f.fp, 'closed'): return f.fp.closed else: return False
def extract_usernames(events): """Extracts the username from a list of password change events.""" output = [] for event in events: separate = event.decode().split(",") output.append(separate[1]) return output
def normalize_ctu_name(name): """Ensure name is in the normal CTU form.""" return name.title().replace('Ctu', 'CTU').replace('Iot', 'IoT')
def extract_object_from_included(object_type, object_id, included): """ Helper function that retrieves a specific object. @:param type String that represents the object class. @:param id String that represents the id of the object. @:param List of objects. @:return object in JSON or None """ for object in included: if object["type"] == object_type and object["id"] == object_id: return object return None
def flatten(tree): """Flattens a tree to a list. Example: ["one", ["two", ["three", ["four"]]]] becomes: ["one", "two", "three", "four"] """ i = 0 while i < len(tree): while isinstance(tree[i], (list, tuple)): if not tree[i]: tree.pop(i) if not len(tree): break else: tree[i:i+1] = list(tree[i]) i += 1 return tree
def _gr_xmin_ ( graph ) : """Get x-min for the graph >>> xmin = graph.xmin() """ # _size = len ( graph ) if 0 == _size : return 0 # x_ , y_ = graph.get_point ( 0 ) # return x_
def compare_slots(slots, quizproperty): """ compare slots to find if users answer matches """ proplower = quizproperty.lower() for key, val in slots.items(): if val.get('value'): lval = val['value'].lower() if lval == proplower: return True return False
def file_from_list_of_images(file_list, current_file, request): """ return filename from file_list depends of request request: position on the list """ if file_list: if request == "first": file = file_list[0] elif request == "previous": if current_file in file_list: position = file_list.index(current_file) if position > 0: file = file_list[position - 1] else: file = None else: file = file_list[0] elif request == "next": if current_file in file_list: position = file_list.index(current_file) if position <= len(file_list) - 2: file = file_list[position + 1] else: file = None else: file = file_list[-1] elif request == "last": file = file_list[-1] else: file = None else: file = None if file == current_file: file = None return file
def points2d_at_height(pts, height): """Returns a list of 2D point tuples as 3D tuples at height""" if isinstance(pts, tuple): if len(pts) == 2: return [(*pts, height)] return [(pts[0], pts[1], height)] pts3d = [] for pt in pts: if len(pt) == 3: pts3d.append((pt[0], pt[1], height)) else: pts3d.append((*pt, height)) return pts3d
def get_model_name(obj): """ returns the model name of an object """ return type(obj).__name__
def _tuplify(an_iterable): """Given an iterable (list, tuple, numpy array, pygamma.DoubleVector, etc.), returns a native Python type (tuple or list) containing the same values. The iterable is converted to a tuple if it isn't already a tuple or list. If it is a tuple or list, it's returned unchanged. """ if isinstance(an_iterable, (tuple, list)): # It's already a native Python type return an_iterable else: return tuple(an_iterable)
def show_bad(spot, guess): """ Shows a bad door, given the prize spot & guess """ if spot==1: return 2 if guess==3 else 3 if spot==2: return 1 if guess==3 else 3 if spot==3: return 1 if guess==2 else 2
def get_rel_pos(abs_pos, ex_num, rel_starts): """Convert absolute position to relativ.""" if len(rel_starts) == 1: return abs_pos ex_num_0 = int(ex_num) - 1 rel_pos_uncorr = abs_pos - rel_starts[ex_num_0] rel_pos = rel_pos_uncorr if rel_pos_uncorr >= 0 else 0 return rel_pos
def c_string_to_str(array) -> str: """ Cast C-string byte array to ``str``. """ return bytes(array).partition(b'\0')[0].decode('utf-8')
def resume(server_id, **kwargs): """Resume server after suspend.""" url = '/servers/{server_id}/action'.format(server_id=server_id) req = {"resume": None} return url, {"json": req}
def get_tag_value(x, key): """Get a value from tag""" if x is None: return '' result = [y['Value'] for y in x if y['Key'] == key] if result: return result[0] return ''
def hinderedRotor2D(scandir, pivots1, top1, symmetry1, pivots2, top2, symmetry2, symmetry='none'): """Read a two dimensional hindered rotor directive, and return the attributes in a list""" return [scandir, pivots1, top1, symmetry1, pivots2, top2, symmetry2, symmetry]