content
stringlengths
42
6.51k
def decimal_to_binary(number): """ This function calculates the binary of the given decimal number :param number: decimal number in string or integer format :return : string of the equivalent binary number Algo: 1. Divide the decimal number by 2. Treat the division as an integer division. 2. Write down the remainder (in binary). 3. Divide the result again by 2. Treat the division as an integer division. 4. Repeat step 2 and 3 until result is 0. 5. The binary value is the digit sequence of the remainders from the last to first. """ if isinstance(number, str): number = int(number) binary = [] while number >= 1: remainder = number % 2 binary.append(remainder) number = number // 2 return "".join(map(str, binary[::-1]))
def last_place_added_dict(all_places_on_map): """Return dictionary containing latitude and longitude of last place saved to a map If no place has been added to map, use latitude and longitude of Hyderabad, India. """ last_place_added_dict = {} if all_places_on_map != []: #if there are places saved to the map last_place_added = all_places_on_map[-1] last_place_added_dict['latitude'] = float(last_place_added.latitude) last_place_added_dict['longitude'] = float(last_place_added.longitude) else: last_place_added_dict['latitude'] = float(17.3850) last_place_added_dict['longitude'] = float(78.4867) return last_place_added_dict
def std_pres(elev): """Calculate standard pressure. Args: elev (float): Elevation above sea-level in meters Returns: float: Standard Pressure (kPa) """ return 101.325 * (((293.0 - 0.0065 * elev) / 293.0) ** 5.26)
def _getcallargs(args, varargname, kwname, varargs, keywords): """Gets the dictionary of the parameter name-value of the call.""" dct_args = {} varargs = tuple(varargs) keywords = dict(keywords) argcount = len(args) varcount = len(varargs) callvarargs = None if argcount <= varcount: for n, argname in enumerate(args): dct_args[argname] = varargs[n] callvarargs = varargs[-(varcount - argcount):] else: for n, var in enumerate(varargs): dct_args[args[n]] = var for argname in args[-(argcount - varcount):]: if argname in keywords: dct_args[argname] = keywords.pop(argname) callvarargs = () if varargname is not None: dct_args[varargname] = callvarargs if kwname is not None: dct_args[kwname] = keywords dct_args.update(keywords) return dct_args
def minimum_os_to_simctl_runtime_version(minimum_os): """Converts a minimum OS string to a simctl RuntimeVersion integer. Args: minimum_os: A string in the form '12.2' or '13.2.3'. Returns: An integer in the form 0xAABBCC, where AA is the major version, BB is the minor version, and CC is the micro version. """ # Pad the minimum OS version to major.minor.micro. minimum_os_components = (minimum_os.split(".") + ["0"] * 3)[:3] result = 0 for component in minimum_os_components: result = (result << 8) | int(component) return result
def find_location(s, loc): """ Find where loc (linear index) in s. Returns: line number column number line itself Note: Tabs are not handled specially. """ if loc < 0 or loc > len(s): raise ValueError('Location given ({0}) is outside string'.format(loc)) count = 0 lines = s.splitlines() with_ends = s.splitlines(True) for i, (line, with_end) in enumerate(zip(lines, with_ends), 1): if count + len(line) < loc: count += len(with_end) else: col = loc - count + 1 return i, col, line
def _get_nested_position(var: str, chart: list): """Finds position of a variable inside a nested list Args: var (str): Variable we're searching for chart (list): Nested list Returns: int: Index of nested list that contains `var`. Returns None if not found. """ idx = [chart.index(i) for i in chart if var in i] if len(idx) == 1: return idx[0] if len(idx) == 0: return None else: raise KeyError("Value occurrs more than once")
def is_in_list(list, expect): """ Check whether expect is in list or not. Returns when finds expect. """ for element in list: if element == expect: return True return False
def trunk(n): """ This Trunk function takes input as rows in iteger :param n: n--> rows input -> integer :return: Nothing is returned """ for i in range(n): # for loop to cater for the spaces for j in range(n-1): print(' ', end=' ') # print stars inside the first loop counter print("****") return ""
def return_same_cookie(_): """Return same cookie.""" return ("placeholder", "placeholder")
def write_func_def(myfile, step, textrep, args, current, k_step): """Write step function implementation header """ if step["keyword"].strip() == "Given": myfile.write("\n\n#\n# Given ...\n#\n") myfile.write("@given('"+textrep+"')\n") myfile.write("def step_given_"+str(k_step)+"("+args+"):\n") myfile.write(' """\n\n Given '+textrep+"\n\n") myfile.write(' """\n') current = "given" elif step["keyword"].strip() == "When": myfile.write("\n\n#\n# When ...\n#\n") myfile.write("@when('"+textrep+"')\n") myfile.write("def step_when_"+str(k_step)+"("+args+"):\n") myfile.write(' """\n\n When '+textrep+"\n\n") myfile.write(' """\n') current = "when" elif step["keyword"].strip() == "Then": myfile.write("\n\n#\n# Then ...\n#\n") myfile.write("@then('"+textrep+"')\n") myfile.write("def step_then_"+str(k_step)+"("+args+"):\n") myfile.write(' """\n\n Then '+textrep+"\n\n") myfile.write(' """\n') current = "then" elif step["keyword"].strip() == "And": if current == "": raise Exception("`And` has to be preceeded by a "+ "line with `Given`, `When` or"+ "`Then`") myfile.write("\n\n#\n# And ...\n#\n") myfile.write("@"+current+"('"+textrep+"')\n") myfile.write("def step_"+current+"_"+str(k_step)+"("+args+"):\n") myfile.write(' """\n\n And '+textrep+"\n\n") myfile.write(' """\n') elif step["keyword"].strip() == "But": if current == "": raise Exception("`But` has to be preceeded by a "+ "line with `Given`, `When` or"+ "`Then`") myfile.write("\n\n#\n# But ...\n#\n") myfile.write("@"+current+"('"+textrep+"')\n") myfile.write("def step_"+current+"_"+str(k_step)+"("+args+"):\n") myfile.write(' """\n\n But '+textrep+"\n\n") myfile.write(' """\n') else: raise Exception("unknown keyword: "+step["keyword"]) return current
def encode_ebv(value): """ Get 01-encoded string for integer value in EBV encoding. Parameters ---------- value : int """ def _encode(value_, first_block): prefix = '0' if first_block else '1' if value_ < 128: return prefix + format(value_, '07b') return _encode(value_ >> 7, first_block=False) + \ _encode(value_ % 128, first_block=first_block) return _encode(value, first_block=True)
def IsInclude(line): """Returns True if the line is an #include/#import line.""" return line.startswith('#include ') or line.startswith('#import ')
def RPL_TRACESERVER(sender, receipient, message): """ Reply Code 206 """ return "<" + sender + ">: " + message
def split_full_metric(full_metric): """Splits a full metric name (split/name or task/split/label/name) into pieces""" pieces = full_metric.split("/") if len(pieces) == 2: # Single-task metric split, name = pieces return split, name elif len(pieces) == 4: # Mmtl metric task, payload, label, name = pieces return task, payload, label, name else: msg = ( f"Required a full metric name (split/name or task/payload/label/name) but " f"instead received: {full_metric}" ) raise Exception(msg)
def get_valid_condition(cd: str, td: str, sl: bool ) -> str: """ there are 4 conditions, one for each curve that is plotted. the design is 2x2x2""" return '-'.join([cd, td, 'shuffled' if sl else ''])
def fib_dictionary(n, d={0:1,1:1}): """ Returns the Finabocci's value for 'n' using dictionary. Args: n (int): number of interactions. d (dict): dictionary that store values. Returns: int: Fibonacci's value. """ if n in d: return d[n] else: answer = fib_dictionary(n-1) + fib_dictionary(n-2) d[n] = answer return answer
def pop_or_raise(args, missing_error, extra_error): """Pop a single argument from *args* and return it. If there are zero or extra elements in *args*, raise a `ValueError` with message *missing_error* or *extra_error*, respectively.""" try: arg = args.pop(0) except IndexError: raise ValueError(missing_error) if args: raise ValueError('{}: {}'.format(extra_error, ' '.join(args))) return arg
def unquote_string(s): """Unquote a string value if quoted.""" if not s: return s quote_char = s[0] if quote_char == "\"" or quote_char == "'": return s[1:(len(s) - 1)].replace("\\" + quote_char, quote_char) return s
def read(data): """Return the start string and the rules, as a dictionary.""" lines = data.splitlines() rules = dict() # one entry XY: L for each rewriting rule XY -> L for index in range(2, len(lines)): line = lines[index] rules[line[:2]] = line[-1] return lines[0], rules
def is_iter( obj ): """ evalua si el objeto se puede iterar Arguments --------- obj: any type Returns ------- bool True if the object is iterable """ try: iter( obj ) return True except TypeError: return False
def algaas_gap(x): """Retorna o gap do material ja calculado em funcao da fracao de Aluminio utilizamos os valores exatos utilizados pelos referidos autores Params ------ x : float a fracao de aluminio, entre 0 e 1 Returns ------- O gap em eV """ if x == 0.2: return 0.0 elif x == 0.4: return 0.185897 return -0.185897
def abbrev(name): """Abbreviate multiword feature name.""" if ' ' in name: name = ''.join(word[0] for word in name.split()) return name
def get_first_geolocation(messages): """ return the first geotagged message lat and long as tuple """ try: return [(m.latitude, m.longitude) for m in messages if m.has_geolocation()][0] except: # pylint: disable=W0702 return ()
def is_schema_recursive(schema): """ Determine if a given schema has elements that need to recurse """ # return 'recursive' in schema # old way is_recursive = False if schema['type'] == "object": for prop in schema['properties']: if schema['properties']['prop']['type'] in ['object', 'array']: return True if schema['type'] == "array": if schema['items']['type'] in ['object', 'array']: return True return False
def _validate_list(s, accept_none=False): """ A validation method to convert input s to a list or raise error if it is not convertable """ if s is None and accept_none: return None try: return list(s) except ValueError: raise ValueError('Could not convert input to list')
def replace_ellipsis(items, elided_items): """ Replaces any Ellipsis items (...) in a list, if any, with the items of a second list. """ return [ y for x in items for y in (elided_items if x is ... else [x]) ]
def red_star(c2): """ The relation between the color1 and color2 in RED stars assuming that the RED stars are 2 times brighter in color2 ---------- c2: flux in color2 ---------- Returns - flux in color1 """ c1 = 0.5*c2 return c1, c2
def _get_start_offset(lines) -> int: """Get the start offset of the license data.""" i = len(lines) - 1 count = 0 for line in lines[::-1]: if "-" * 10 in line: count += 1 if count == 2: break i -= 1 return max(i, 0)
def helper(mat1, mat2): """Recursion method to sum the matrices""" # Base case if not isinstance(mat1, list) and not isinstance(mat2, list): return mat1 + mat2 ans = [] for m in zip(mat1, mat2): ans.append(helper(m[0], m[1])) return ans
def primes_list(n): """ input: n an integer > 1 returns: list of all the primes up to and including n """ # initialize primes list primes = [2] # go through each of 3...n for j in range(3,n+1): is_div = False # go through each elem of primes list for p in primes: if j%p == 0: is_div = True if not is_div: primes.append(j) return primes
def get_extra_create_args(cmd_area, args): """ Return the extra create arguments supported by a strategy type :param cmd_area: the strategy that supports additional create arguments :param args: the parsed arguments to extract the additional fields from :returns: a dictionary of additional kwargs for the create_strategy command :raises: ValueError if a strategy has been registered but not update here """ if 'patch-strategy' == cmd_area: # no additional kwargs for patch return {} elif 'upgrade-strategy' == cmd_area: # upgrade supports: complete_upgrade return {'complete_upgrade': args.complete_upgrade} elif 'fw-update-strategy' == cmd_area: # no additional kwargs for firmware update return {} elif 'kube-rootca-update-strategy' == cmd_area: # kube rootca update supports expiry_date, subject and cert_file return { 'expiry_date': args.expiry_date, 'subject': args.subject, 'cert_file': args.cert_file } elif 'kube-upgrade-strategy' == cmd_area: # kube upgrade supports: to_version return {'to_version': args.to_version} else: raise ValueError("Unknown command area, %s, given" % cmd_area)
def roms_varlist(option): """ varlist = roms_varlist(option) Return ROMS varlist. """ if option == 'physics': varlist = (['temp','salt','u','v','ubar','vbar','zeta']) elif option == 'physics2d': varlist = (['ubar','vbar','zeta']) elif option == 'physics3d': varlist = (['temp','salt','u','v']) elif option == 'mixing3d': varlist = (['AKv','AKt','AKs']) elif option == 's-param': varlist = (['theta_s','theta_b','Tcline','hc']) elif option == 's-coord': varlist = (['s_rho','s_w','Cs_r','Cs_w']) elif option == 'coord': varlist = (['lon_rho','lat_rho','lon_u','lat_u','lon_v','lat_v']) elif option == 'grid': varlist = (['h','f','pm','pn','angle','lon_rho','lat_rho', \ 'lon_u','lat_u','lon_v','lat_v','lon_psi','lat_psi', \ 'mask_rho','mask_u','mask_v','mask_psi']) elif option == 'hgrid': varlist = (['f','dx','dy','angle_rho','lon_rho','lat_rho', \ 'lon_u','lat_u','lon_v','lat_v','lon_psi','lat_psi', \ 'mask_rho','mask_u','mask_v','mask_psi']) elif option == 'vgrid': varlist = (['h','s_rho','s_w','Cs_r','Cs_w', \ 'theta_s','theta_b','Tcline','hc']) else: raise Warning('Unknow varlist id') return varlist
def immediate_param(registers, params): """Return from registers immediate parameters.""" return registers[params[0]], params[1], params[2]
def hamming_distance(s1, s2): """Return the Hamming distance between equal-length sequences, a measure of hash similarity""" # Transform into a fixed-size binary string first s1bin = ' '.join('{0:08b}'.format(ord(x), 'b') for x in s1) s2bin = ' '.join('{0:08b}'.format(ord(x), 'b') for x in s2) if len(s1bin) != len(s2bin): raise ValueError("Undefined for sequences of unequal length") return sum(el1 != el2 for el1, el2 in zip(s1bin, s2bin))
def _split_hostport(hostport): """ convert a listen addres of the form host:port into a tuple (host, port) host is a string, port is an int """ i = hostport.index(':') host = hostport[:i] port = hostport[i + 1:] return host, int(port)
def lerp(x, from_, to): """Linear interpolates a value using the `x` given and ``(x,y)`` pairs `from_` and `to`. All x values must be numbers (have `-` and `/` defined). The y values can either be single numbers, or sequences of the same length. If the latter case, then each dimension is interpolated linearly and the output is a sequence of the same type.""" x0, x1, y0, y1 = from_[0], to[0], from_[1], to[1] if x0 == x1: return y0 # degenerate case perc = (x-x0)/float(x1-x0) # see if they're sequences try: y = [(t-f)*perc + f for f, t in zip(y0, y1)] # cast the output to the type of the input return type(y0)(y) except TypeError: y = (to[1]-from_[1])*perc + from_[1] return y
def randomized_partition(arr, low, high): """Partition the array into two halfs according to the last element (pivot) loop invariant: [low, i] <= pivot [i+1, j) > pivot """ i = low - 1 j = low pivot = arr[high] while j < high: if arr[j] <= pivot: i = i + 1 arr[i], arr[j] = arr[j], arr[i] j = j + 1 i = i + 1 arr[i], arr[high] = pivot, arr[i] return i
def convert_border(width, color, border_on): """ 1. Add border """ if border_on > 0: command = "-border " + str(abs(int(width))) + " -bordercolor \"" + color + "\"" else: command = "" return command
def pull_answers(surveys, all_questions): """ Runs through questions and pull out answers, append them to the lists in the container constructed by compile_question_data. """ for survey in surveys: for question in survey: question_id = question['question id'] answer = question['answer'] question_text = question['question text'] try: all_questions[question_id][question_text].append( int(answer) ) except ValueError: all_questions[question_id][question_text].append(None) return all_questions
def strip_path(path, strip): """Strip `path` components ends on `strip` """ strip = strip.replace('\\', '/') if not strip.endswith('/'): strip = strip + '/' new_path = path.split(strip)[-1] if new_path.startswith('build/docs/'): new_path = new_path.split('build/docs/')[-1] return new_path
def order_edges(edges_lst, ref_nodes): """Reorder edges such as reference node is on the first position.""" ret = [] for edge in edges_lst: f_, s_ = edge if f_ in ref_nodes: ref_node = f_ que_node = s_ else: ref_node = s_ que_node = f_ item = (ref_node, que_node) ret.append(item) return ret
def get_temperature_stress_factor( temperature_active: float, temperature_rated_max: float, ) -> float: """Retrieve the temperature stress factor (piT). :param temperature_active: the operating ambient temperature in C. :param temperature_rated_max: the maxmimum rated operating temperature in C. :return: _pi_t; the value of piT associated with the operating temperature. :rtype: float :raise: TypeError if passed a string for either temperature. :raise: ZeroDivisionError if passed a rated maximum temperature = 0.0. """ _pi_t = 0.0 _temperature_ratio = temperature_active / temperature_rated_max if 0.0 < _temperature_ratio <= 0.5: _pi_t = 0.5 elif 0.5 < _temperature_ratio <= 0.6: _pi_t = 0.6 elif 0.6 < _temperature_ratio <= 0.8: _pi_t = 0.8 elif 0.8 < _temperature_ratio <= 1.0: _pi_t = 1.0 return _pi_t
def LargestTripletMultiplicationSimple(arr, n): """ sort array, then extract last n """ product = -1 if len(arr) < 3: return product numbers = arr[:] numbers.sort() # keep = numbers[-n:] x = numbers[-3] y = numbers[-2] z = numbers[-1] # (x,y,z) = (numbers[-3], numbers[-2], numbers[-1]) product = x * y * z return product
def escape(s): """ Returns the given string with ampersands, quotes and carets encoded. >>> escape('<b>oh hai</b>') '&lt;b&gt;oh hai&lt;/b&gt;' >>> escape("Quote's Test") 'Quote&#39;s Test' """ mapping = ( ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ('"', '&quot;'), ("'", '&#39;'), ) for tup in mapping: s = s.replace(tup[0], tup[1]) return s
def convert_currency(val): """ 125000.00 Convert the string number value to a float - Remove $ - Remove commas - Convert to float type """ new_val = val.replace(',','').replace('$', '') return float(new_val)
def get_orig_file_name(fname): """ This function is required for gradio uploads. When a file is loaded , the name is changed. this function reqturns the orig file name which is useful in predict and debug scenario. """ fname = fname.replace("/tmp/", "") ext = fname.split(".")[-1] temp = fname.split(".")[-2] fl = temp.split("_")[0] ret = fl + "." + ext return(ret)
def generate_edges(node_list): """ From a list of nodes, generate a list of directed edges, where every node points to a node succeeding it in the list. As the PLACES variable is 0-based, the algorithm also adapts it to the 1-based system v2.0 uses. Argss: node_list (list(int)): List of nodes. """ edges = [] for i in range(len(node_list)): for j in range(i + 1, len(node_list)): edges.append((node_list[i] + 1, node_list[j] + 1)) return edges
def extract_table(text_list, shared, vname, key_col, value_col): """Takes a list of text and subsets to the rows that contain the label. Then returns a dictionary with keys from key_col and values from value_col. Used for extracting multiple values from table in output file. Needs to take a list of shared keys and subset to those """ keys = [] values = [] for line in text_list: if any(s in shared for s in line): keys.append(line[key_col-1]) values.append(line[value_col-1]) labeled_keys = [s + "_" + vname for s in keys] dictionary = dict(zip(labeled_keys, values)) return dictionary
def strip_hashes(description): """Removes hash and space sings form each line in description.""" if description is None: return '' else: lines = description.strip().splitlines() return "\n".join(line[line.index('#')+2:] for line in lines)
def type_to_emoji(type): """Converts a type to a Discord custom emoji""" emojis = {'water': '<:water:334734441220145175>', 'steel': '<:steel:334734441312419851>', 'rock': '<:rock:334734441194717195>', 'psychic': '<:psychic:334734441639575552>', 'poison': '<:poison:334734441584787456>', 'normal': '<:normal:334734441538650112>', 'ice': '<:ice:334734441421471756>', 'ground': '<:ground:334734441421471747>', 'grass': '<:grass:334734441501032448>', 'ghost': '<:ghost:334734441232728066>', 'flying': '<:flying:334734441161424900>', 'fire': '<:fire:334734441165619202>', 'fighting': '<:fighting:334734441425403905>', 'fairy': '<:fairy:334734441501163530>', 'electric': '<:electric:334734441089859586>', 'dragon': '<:dragon:334734441505226762>', 'dark': '<:dark:334734441119219713>', 'bug': '<:bug:334734441509289984>'} return emojis[type.lower()]
def alphabet_position2(text: str) -> str: """ Another person's implementation. Uses ord() """ return ' '.join(str(ord(c) - 96) for c in text.lower() if c.isalpha())
def _installable(args): """ Return True only if the args to pip install indicate something to install. >>> _installable(['inflect']) True >>> _installable(['-q']) False >>> _installable(['-q', 'inflect']) True >>> _installable(['-rfoo.txt']) True >>> _installable(['projects/inflect']) True >>> _installable(['~/projects/inflect']) True """ return any( not arg.startswith('-') or arg.startswith('-r') or arg.startswith('--requirement') for arg in args )
def format_bad_entities(test_name, test_results): """ Format error for pytest output """ msg = f"{test_name}\n" for failure in test_results["test_failures"]: msg += f"Expected {failure[1]}: {failure[2]}\n" msg += f"Observed {failure[1]}: {failure[3]}\n" return msg
def getStatusWord(status): """Returns the status word from the status code. """ statusWord = 'owned' if status == 0: return 'wished' elif status == 1: return 'ordered' return statusWord
def _strip_empty_rows(rows): """ Removes empty rows at the end and beginning of the rows collections and returns the result. """ first_idx_with_events = None last_idx_with_events = None rows_until = None for idx, row in enumerate(rows): if first_idx_with_events is None and row.events: first_idx_with_events = idx if first_idx_with_events is not None and row.events: last_idx_with_events = idx for evt in row.events: if rows_until is None or evt.end > rows_until: rows_until = evt.end if last_idx_with_events is not None and not row.events and row.end <= rows_until: last_idx_with_events = idx if not first_idx_with_events: first_idx_with_events = 0 if not last_idx_with_events: last_idx_with_events = first_idx_with_events - 1 return rows[first_idx_with_events:last_idx_with_events + 1]
def is_blank(string): """ Returns `True` if string contains only white-space characters or is empty. Otherwise `False` is returned. """ return not bool(string.lstrip())
def is_encryption_master_key_valid(encryption_master_key): """ is_encryption_master_key_valid() checks if the provided encryption_master_key is valid by checking its length the key is assumed to be a six.binary_type (python2 str or python3 bytes) """ if encryption_master_key is not None and len(encryption_master_key) == 32: return True return False
def to_iccu_bid_old(bid): """ 'AGR0000002' => u'IT\\ICCU\\AGR\\0000002' """ return "IT\\ICCU\\%s\\%s"%(bid[:3],bid[3:])
def pieces(string): """returns a list containing all pieces of string, see example below""" tag_pieces = [] for word in string.split(): cursor = 1 while True: # this method produces pieces of 'TEXT' as 'T,TE,TEX,TEXT' tag_pieces.append(str(word[:cursor])) if cursor == len(word): break cursor += 1 return tag_pieces
def betweenness_index(n_nodes, n_times, node_index, time_index, layer_index): """ find the index associated to a point in the static graph. See betweenness_centrality. """ index = n_nodes * n_times * layer_index + n_nodes * time_index + node_index return index
def get_datatype(value): """ Returns the dtype to use in the HDF5 based on the type of the object in the YAML. This isn't an exact science, and only a few dtypes are supported. In the future, perhaps we could allow for dtype annotations in the YAML to avoid this kind of ambiguity. """ if isinstance(value,str): strlen = len(value) if strlen==0: strlen=1 return 'S%d'%strlen elif isinstance(value,int): return 'int64' elif isinstance(value,float): return 'float64' elif isinstance(value,list): # only lists of numbers are supported if len(value)>0: first = value[0] if isinstance(first,int): return 'int64' else: return 'float64' else: return 'int64' raise Exception("Value has unsupported data type: "+str(type(value)))
def dist3D(start, final): """ calculates the distance between two given vectors. Vectors must be given as two 3-dimensional lists, with the aim of representing 2 3d position vectors. """ (x1, y1, z1) = (start[0], start[1], start[2]) (x2, y2, z2) = (final[0], final[1], final[2]) (xdiff,ydiff,zdiff) = (x2-x1,y2-y1,z2-z1) # Calculate the hypotenuse between the x difference, y difference and the z difference # This should give the distance between the two points distance = (xdiff **2 + ydiff ** 2 + zdiff ** 2) ** (1/2) return distance
def NomBrevet(Brev): """extracts the invention title of a patent bibliographic data""" try: if 'ops:world-patent-data' in Brev: Brev = Brev['ops:world-patent-data'] if 'exchange-documents' in Brev: Brev = Brev['exchange-documents'] if 'exchange-document' in Brev: Brev = Brev['exchange-document'] if 'bibliographic-data' in Brev: Brev = Brev['bibliographic-data'] else: return None else: return None else: return None else: return None if 'invention-title' in Brev: if type(Brev['invention-title']) == type(''): return Brev['invention-title'] elif type(Brev['invention-title']) == type(dict()): if '$' in Brev['invention-title']: return Brev['invention-title']['$'] else: titre = [] for tit in Brev['invention-title']: if '$' in tit: titre.append(tit['$']) return titre else: return None except: return None
def valid_moves(board): """Returns a list of all valid moves in the position""" moves = [] # Go through each space, if it's not X or O, append it for space in board: if space != "X" and space != "O": moves.append(space) # Return moves at the end return moves
def process_spatial(geo): """Process time range so it can be added to the dates metadata Parameters ---------- geo : list [minLon, maxLon, minLat, maxLat] Returns ------- polygon : dict(list(list)) Dictionary following GeoJSON polygon format """ polygon = { "type": "Polygon", "coordinates": [ [ [geo[0], geo[2]], [geo[0], geo[3]], [geo[1], geo[3]], [geo[1], geo[2]] ] ]} return polygon
def sol_2(s: str) -> dict: """using ascii array""" ar = [0]*26 for i in s: ar[ord(i)-97] += 1 ans = {} for i in range(26): if ar[i] > 1: ans[chr(97+i)] = ans[i] return ans
def quit_thumb(filename): """ Add at the end the file the word _thumb """ return filename.replace('_thumb', '')
def parse_complex_index(index): """ Parses a index (single number or slice or list or range) made of either purely imaginary or real number(s). Arg: index (int or complex or slice or list or range): Index of to be parsed. Returns: tuple(int or slice or list, bool): real index and boolean representing if index was real Raises: TypeError: If the `index` is made of complex but not a purely imaginary integer(s). TypeError: If the `index` is a list with different index types. TypeError: If the `index` is a slice with different index types (not regarding None). TypeError: If the `index` is neither a int / complex integer nor a list or slice or range. """ if isinstance(index, complex): if index.real != 0 or int(index.imag) != index.imag: raise TypeError("Complex indices must be purely imaginary integers.") return int(index.imag), False if isinstance(index, (int, range)): return index, True if isinstance(index, list): if len(index) == 0: return index, True if len(set(type(idx) for idx in index)) != 1: raise TypeError("Indices must either be purely imaginary integers or real integers.") if isinstance(index[0], complex): if any(idx.real != 0 or int(idx.imag) != idx.imag for idx in index): raise TypeError("Complex indices must be purely imaginary integers.") return [int(idx.imag) for idx in index], False if isinstance(index[0], int): return index, True raise TypeError("Indices in a list must be real or imaginary integers.") if isinstance(index, slice): slice_types = set( type(idx) for idx in (index.start, index.stop, index.step) if idx is not None ) if len(slice_types) == 0: return index, True elif len(slice_types) > 1: raise TypeError("All slice indices must either have the same type or be None.") if any(isinstance(idx, complex) for idx in (index.start, index.stop, index.step)): if any(idx.real != 0 or int(idx.imag) != idx.imag for idx in (index.start, index.stop, index.step) if idx is not None): raise TypeError("Complex slice indices must be purely imaginary integers.") real_slice = slice( *(int(idx.imag) if idx is not None else None for idx in (index.start, index.stop, index.step)) ) return real_slice, False if any(isinstance(idx, int) for idx in (index.start, index.stop, index.step)): return index, True raise TypeError("Indices in a slice must be real or imaginary integers.") raise TypeError("Index must be of type int or slice or list or range.")
def replace_language(path: str, lang: str) -> str: """Replace language in the url. Usage: {{ request.path|replace_language:language }} """ try: language = path.split("/")[1] except IndexError: return path if not language: return path return path.replace(language, lang, 1)
def remove_default_security_group(security_groups): """Utility method to prevent default sec group from displaying.""" # todo (nathan) awful, use a list comprehension for this result = [] for group in security_groups: if group['name'] != 'default': result.append(group) return result
def cnr(mean_gm, mean_wm, std_bg): """ Calculate Contrast-to-Noise Ratio (CNR) CNR = |(mean GM intensity) - (mean WM intensity)| / (std of background intensities) """ import numpy as np cnr = np.abs(mean_gm - mean_wm)/std_bg return cnr
def format_timedelta_to_HHMMSS(td): """Convert time delta to HH:MM:SS.""" hours, remainder = divmod(td, 3600) minutes, seconds = divmod(remainder, 60) hours = int(hours) minutes = int(minutes) seconds = int(seconds) if minutes < 10: minutes = "0{}".format(minutes) if seconds < 10: seconds = "0{}".format(seconds) return "{}:{}:{}".format(hours, minutes, seconds)
def prepare_collections_list(in_platform): """ Basic function that takes the name of a satellite platform (Landsat or Sentinel) and converts into collections name recognised by dea aws. Used only for ArcGIS Pro UI/Toolbox. Parameters ------------- in_platform : str Name of satellite platform, Landsat or Sentinel. Returns ---------- A string of dea aws collections associated with input satellite. """ # checks if in_platform not in ['Landsat', 'Sentinel']: raise ValueError('Platform must be Landsat or Sentinel.') # prepare collections if in_platform == 'Landsat': return ['ga_ls5t_ard_3', 'ga_ls7e_ard_3', 'ga_ls8c_ard_3'] elif in_platform == 'Sentinel': return ['s2a_ard_granule', 's2b_ard_granule']
def package_to_path(package): """ Convert a package (as found by setuptools.find_packages) e.g. "foo.bar" to usable path e.g. "foo/bar" No idea if this works on windows """ return package.replace('.','/')
def reverse_comp(seq): """take a sequence and return the reverse complementary strand of this seq input: a DNA sequence output: the reverse complementary of this seq""" bases_dict = {'A':'T', 'T':'A', 'G':'C', 'C':'G'} ##get the complementary if key is in the dict, otherwise return the base return ''.join(bases_dict.get(base, base) for base in seq[::-1])
def string_to_int_list(number_string): """Convert a string of numbers to a list of integers Arguments: number_string -- string containing numbers to convert """ int_list = [] for c in number_string: int_list.append(int(c)) return int_list
def blockheader2dic(head): """ Convert a block header list into a Python dictionary. """ dic = dict() dic["scale"] = head[0] dic["status"] = head[1] dic["index"] = head[2] dic["mode"] = head[3] dic["ctcount"] = head[4] dic["lpval"] = head[5] dic["rpval"] = head[6] dic["lvl"] = head[7] dic["tlt"] = head[8] # unpack the status parameters dic["S_DATA"] = (dic["status"] & 0x1) // 0x1 dic["S_SPEC"] = (dic["status"] & 0x2) // 0x2 dic["S_32"] = (dic["status"] & 0x4) // 0x4 dic["S_FLOAT"] = (dic["status"] & 0x8) // 0x8 dic["S_COMPLEX"] = (dic["status"] & 0x10) // 0x10 dic["S_HYPERCOMPLEX"] = (dic["status"] & 0x20) // 0x20 dic["MORE_BLOCKS"] = (dic["status"] & 0x80) // 0x80 dic["NP_CMPLX"] = (dic["status"] & 0x100) // 0x100 dic["NF_CMPLX"] = (dic["status"] & 0x200) // 0x200 dic["NI_CMPLX"] = (dic["status"] & 0x400) // 0x400 dic["NI2_CMPLX"] = (dic["status"] & 0x800) // 0x800 # unpack the mode parameter dic["NP_PHMODE"] = (dic["mode"] & 0x1) // 0x1 dic["NP_AVMODE"] = (dic["mode"] & 0x2) // 0x2 dic["NP_PWRMODE"] = (dic["mode"] & 0x4) // 0x4 dic["NF_PHMODE"] = (dic["mode"] & 0x10) // 0x10 dic["NF_AVMODE"] = (dic["mode"] & 0x20) // 0x20 dic["NF_PWRMODE"] = (dic["mode"] & 0x40) // 0x40 dic["NI_PHMODE"] = (dic["mode"] & 0x100) // 0x100 dic["NI_AVMODE"] = (dic["mode"] & 0x200) // 0x200 dic["NI_PWRMODE"] = (dic["mode"] & 0x400) // 0x400 dic["NI2_PHMODE"] = (dic["mode"] & 0x1000) // 0x1000 dic["NI2_AVMODE"] = (dic["mode"] & 0x2000) // 0x2000 dic["NI2_PWRMODE"] = (dic["mode"] & 0x4000) // 0x4000 return dic
def wavelength_to_rgb(wavelength, gamma=0.8): """ taken from http://www.noah.org/wiki/Wavelength_to_RGB_in_Python This converts a given wavelength of light to an approximate RGB color value. The wavelength must be given in nanometers in the range from 380 nm through 750 nm (789 THz through 400 THz). Based on code by Dan Bruton http://www.physics.sfasu.edu/astro/color/spectra.html Additionally alpha value set to 0.5 outside range """ wavelength = float(wavelength) if 380 <= wavelength <= 750: A = 1. else: A = 0.5 if wavelength < 380: wavelength = 380. if wavelength > 750: wavelength = 750. if 380 <= wavelength <= 440: attenuation = 0.3 + 0.7 * (wavelength - 380) / (440 - 380) R = ((-(wavelength - 440) / (440 - 380)) * attenuation) ** gamma G = 0.0 B = (1.0 * attenuation) ** gamma elif 440 <= wavelength <= 490: R = 0.0 G = ((wavelength - 440) / (490 - 440)) ** gamma B = 1.0 elif 490 <= wavelength <= 510: R = 0.0 G = 1.0 B = (-(wavelength - 510) / (510 - 490)) ** gamma elif 510 <= wavelength <= 580: R = ((wavelength - 510) / (580 - 510)) ** gamma G = 1.0 B = 0.0 elif 580 <= wavelength <= 645: R = 1.0 G = (-(wavelength - 645) / (645 - 580)) ** gamma B = 0.0 elif 645 <= wavelength <= 750: attenuation = 0.3 + 0.7 * (750 - wavelength) / (750 - 645) R = (1.0 * attenuation) ** gamma G = 0.0 B = 0.0 else: R = 0.0 G = 0.0 B = 0.0 return R, G, B, A
def band_matrix_traceinv(a, b, size, gram=True): """ Computes the trace of inverse band matrix based on known formula. """ if gram: if a == b: traceinv_ = size * (size+1) / (2.0 * a**2) else: q = b / a if size < 200: traceinv_ = (1.0 / (a**2 - b**2)) * \ (size - (q**2) * ((q**(2.0*size) - 1.0) / (q**2 - 1.0))) else: # Using asymptotic approximation of large sums traceinv_ = (1.0 / (a**2 - b**2)) * \ (size - ((q**2) / (1.0 - q**2))) else: traceinv_ = size / a return traceinv_
def uncurry(f, args=None, kwargs=None): """ Takes arguments as iterables and executes f with them. Virtually identical to the deprecated function apply(). * NOTE - uncurry is not the inverse of curry! * """ return f(*args, **kwargs)
def append_story_content(elements, content_type, content): """ Append content to story_content list in markdown elements """ if 'story_content' not in elements: elements['story_content'] = [] elements['story_content'].append((content_type, content)) return elements
def header_translate_inverse(header_name): """Translate parameter names back from headers.""" name_dict = {'XCENREF': 'xcen_ref', 'YCENREF': 'ycen_ref', 'ZENDIR': 'zenith_direction', 'ZENDIST': 'zenith_distance', 'FLUX': 'flux', 'BETA': 'beta', 'BCKGRND': 'background', 'ALPHAREF': 'alpha_ref', 'TEMP': 'temperature', 'PRESSURE': 'pressure', 'VAPPRESS': 'vapour_pressure'} return name_dict[header_name]
def make_array(n): """Take the results of parsing an array and return an array Args: n (None|list): None for empty list list should be [head, [tail]] """ if n is None: return [] else: return [n[0]] + n[1]
def events_to_table(maxT, T, E): """Create survival table, one entry for time j=1, ..., j=maxT.""" d = [0] * maxT n = [0] * maxT for t, e in zip(T, E): j = round(t) d[j-1] += e # observed events at time j n[j-1] += 1-e # censored events at time j N = sum(d) + sum(n) for j in range(maxT): n[j], N = N, N - (d[j] + n[j]) return d, n
def getPortFromUrl(url): """ Get Port number for given url """ if not url: raise ValueError("url undefined") if url.startswith("http://"): default_port = 80 elif url.startswith("https://"): default_port = 443 elif url.startswith("http+unix://"): # unix domain socket return None else: raise ValueError(f"Invalid Url: {url}") start = url.find('//') port = None dns = url[start:] index = dns.find(':') port_str = "" if index > 0: for i in range(index+1, len(dns)): ch = dns[i] if ch.isdigit(): port_str += ch else: break if port_str: port = int(port_str) else: port = default_port return port
def qinit(x,y): """ Dam break """ from numpy import where eta = where(x<10, 40., 0.) return eta
def is_hex(string: str) -> bool: """ Checks if a string is hexadecimal, returns true if so and false otherwise. """ try: int(string, 16) return True except ValueError: return False
def split_data(seq, train_ratio, val_ratio): """ Split data into train/val partitions """ train_num = int(len(seq) * train_ratio) val_num = int(len(seq) * val_ratio) train_seq = seq[:train_num] val_seq = seq[train_num:train_num + val_num] test_seq = seq[train_num + val_num:] return train_seq, val_seq, test_seq
def event_dict_to_message(logger, name, event_dict): """Pass the event_dict to stdlib handler for special formatting.""" return ((event_dict,), {'extra': {'_logger': logger, '_name': name}})
def confopt_int(confstr, default=None): """Check and return a valid integer.""" ret = default try: ret = int(confstr) except: pass # ignore errors and fall back on default return ret
def _GetPlotData(chart_series, anomaly_points, anomaly_segments): """Returns data to embed on the front-end for the chart. Args: chart_series: A series, i.e. a list of (index, value) pairs. anomaly_points: A series which contains the list of points where the anomalies were detected. anomaly_segments: A list of series, each of which represents one segment, which is a horizontal line across a range of values used in finding an anomaly. Returns: A list of data series, in the format accepted by Flot, which can be serialized as JSON and embedded on the page. """ data = [ { 'data': chart_series, 'color': '#666', 'lines': {'show': True}, 'points': {'show': False}, }, { 'data': anomaly_points, 'color': '#f90', 'lines': {'show': False}, 'points': {'show': True, 'radius': 4} }, ] for series in anomaly_segments: data.append({ 'data': series, 'color': '#f90', 'lines': {'show': True}, 'points': {'show': False}, }) return data
def encode(latitude, longitude, precision=12): """ Encode a position given in float arguments latitude, longitude to a geohash which will have the character count precision. """ __base32 = '0123456789bcdefghjkmnpqrstuvwxyz' __decodemap = { } lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0) geohash = [] bits = [ 16, 8, 4, 2, 1 ] bit = 0 ch = 0 even = True while len(geohash) < precision: if even: mid = (lon_interval[0] + lon_interval[1]) / 2 if longitude > mid: ch |= bits[bit] lon_interval = (mid, lon_interval[1]) else: lon_interval = (lon_interval[0], mid) else: mid = (lat_interval[0] + lat_interval[1]) / 2 if latitude > mid: ch |= bits[bit] lat_interval = (mid, lat_interval[1]) else: lat_interval = (lat_interval[0], mid) even = not even if bit < 4: bit += 1 else: geohash += __base32[ch] bit = 0 ch = 0 return ''.join(geohash)
def addMenuItem(theDictionary, item, price): """Adds an item to the menu. :param dict[str, float] theDictionary: Dict containing menu items as keys and respective prices as prices. :param str item: The name of the new item to be added to the menu. :param float or int price: The price of item. :return: True if item added to the menu or False if item was already on the menu. :rtype: bool """ item = item.upper() price = round(float(price), 2) if item in theDictionary: return False theDictionary[item] = price return True
def ruf(pol, x): """For the polynomial 'pol' (a list of its coefficients), and a value to test with 'x', returns True if 'x' is a root for the polynomial, using the Ruffini's rule. """ c = pol[0] for i in range(1, len(pol)): c = pol[i] + c*x return c == 0
def _format_rip(rip): """Hex-ify rip if it's an int-like gdb.Value.""" try: rip = '0x%08x' % int(str(rip)) except ValueError: rip = str(rip) return rip
def strbool(x): """ Return an string representation of the specified boolean for an XML document. >>> strbool(False) '0' >>> strbool(True) '1' """ return '1' if x else '0'
def append_write(filename="", text=""): """ Appends a string at the end of a text file (UTF8) and returns the number of characters added. """ with open(filename, 'a') as f: return f.write(text)
def divisible_by_2(my_list=[]): """Find all multiples of 2 in a list.""" multiples = [] for i in range(len(my_list)): if my_list[i] % 2 == 0: multiples.append(True) else: multiples.append(False) return (multiples)
def match_end_subprogram(names): """ """ if len(names) > 2: if names[0]=="END" and names[1] in ["SUBROUTINE","FUNCTION","PROGRAM"]: return names[2] if len(names) == 1: if names[0] == "END": return "OLDSTYLE_END" return ""