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 int...
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 ...
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: ...
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 v...
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 =...
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....
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 ins...
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)+"("+a...
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 ...
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, pay...
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 = f...
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...
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: r...
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 ['o...
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 ...
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 f...
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 ...
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 le...
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 li...
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...
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 = q...
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] re...
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_ ...
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 ...
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], nu...
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;'), (...
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] ...
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)...
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...
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': ...
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(['proje...
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.ev...
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(encr...
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])) ...
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 i...
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...
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-doc...
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"...
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 b...
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...
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 re...
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...
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...
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...
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 retu...
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["l...
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)....
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 /...
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', ...
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) f...
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 ...
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 ...
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_seg...
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....
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: ...
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 ""