content
stringlengths
42
6.51k
def is_hex_string(string): """Check if a string represents a hex value""" if not string.startswith("0x"): return False try: int(string, 16) return True except ValueError as _: return False
def naive_next_pos(measurement, OTHER = None): """This strategy records the first reported position of the target and assumes that eventually the target bot will eventually return to that position, so it always guesses that the first position will be the next.""" if not OTHER: # this is the first measur...
def _byte_to_str_length(codec: str) -> int: """Return how many byte are usually(!) a character point.""" if codec.startswith("utf-32"): return 4 if codec.startswith("utf-16"): return 2 return 1
def gerrit_check(patch_url): """ Check if patch belongs to upstream/rdo/downstream gerrit, :param patch_url: Gerrit URL in a string format :returns gerrit: return string i.e 'upstream'/'rdo'/'downstream' """ if 'redhat' in patch_url: return 'downstream' if 'review.rdoproject.org' in patc...
def DiskName(vm_name, disk_type, disk_number): """Returns the name of this disk. Args: vm_name: The name of the vm this disk will be attached to. disk_type: The type of the disk. disk_number: The number of this disk. Must be unique on the VM. Returns: The name of the disk. """ return "{}-dis...
def FracVisText(doc): """Fraction of visible text on the page""" soup, _ = doc try: pagesize = len(soup.decode_contents()) except Exception: pagesize = 0 return float(len(soup.get_text())) / pagesize if pagesize > 0 else 0
def all_not_none(*args): """Shorthand function for ``all(x is not None for x in args)``. Returns True if all `*args` are not None, otherwise False.""" return all(x is not None for x in args)
def shark(pontoonDistance, sharkDistance, youSpeed, sharkSpeed, dolphin) -> str: """ You are given 5 variables: sharkDistance = distance the shark needs to cover to eat you in metres, sharkSpeed = how fast it can move in metres/second, pontoonDistance = how far yo...
def validate_config(config): """Validates config""" errors = [] required_config_keys = [ 's3_bucket', 'athena_database' ] # Check if mandatory keys exist for k in required_config_keys: if not config.get(k, None): errors.append("Required key is missing from co...
def remove_trailing_slash(id): """ Remove trailing slash if not root""" if id != '/': id = id.rstrip('/') return id
def binary(code: 'int') -> 'str': """Convert code to binary form.""" return f'0b{bin(code)[2:].upper().zfill(8)}'
def render_path(path_to_item): """Returns a string representation of a path""" result = "" for pth in path_to_item: if isinstance(pth, int): result += "[{0}]".format(pth) else: result += "['{0}']".format(pth) return result
def is_year(s): """ Checks to see if the string is likely to be a year or not. In order to be considered to be a year, it must pass the following criteria: 1. four digits 2. first two digits are either 19 or 20. :param s: the string to check for "year-hood" :returns: ``True`` if it i...
def flatten(t): """Standard utility function for flattening a nested list taken from https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists.""" return [item for sublist in t for item in sublist]
def is_number(string: str) -> bool: """Checks if a given string is a real number.""" try: float(string) return True except ValueError: return False
def parse_argv(argv): """Implement a manual option parser.""" argv = list(argv) args, kwargs = [], {} while len(argv): arg = argv.pop(0) if arg[0] == '-' and len(arg) >= 2: ind = 2 if arg[1] == '-' else 1 kv = arg[ind:].split('=', 1) if len(kv) == 1: ...
def is_even(x): """ Determines if x is even """ return x % 2 == 0
def aladd(x, y): """ Function to add 2 operands """ return(x + y)
def all(ls): """ expects list of Bool """ result = True for l in ls: if l is not True: result = False return result
def _calc_target_bounding_box(bbox, source_shape, target_shape): """Calculates the bounding of the cropped target image. ``bbox`` is relative to the shape of the source image. For the target image, the number of pixels on the left is equal to the absolute value of the negative start (if any), and the n...
def prefixed_by(apath, some_paths): """Check if a path is a a subpath of one of the provided paths""" return len([p for p in some_paths if apath.find(p) == 0]) > 0
def _note(item): """Handle secure note entries Returns: title, username, password, url, notes """ return f"{item['name']} - Secure Note", "", "", "", item.get('notes', '') or ""
def filter_line(line, flag=None): """Returns the line starting with the flag""" if flag is None: return line line_flag = line.strip().split(":")[0].strip() if line_flag == flag: new_line = line.strip()[len(flag) + 1:].strip().lstrip(":").strip() return new_line return None
def find(predicate, iterable, default=None): """Return the first item matching `predicate` in `iterable`, or `default` if no match. If you need all matching items, just use the builtin `filter` or a comprehension; this is a convenience utility to get the first match only. """ return next(filter(pre...
def has_sublist(l, sublist): """Returns whether the elements of sublist appear in order anywhere within list l. >>> has_sublist([], []) True >>> has_sublist([3, 3, 2, 1], []) True >>> has_sublist([], [3, 3, 2, 1]) False >>> has_sublist([3, 3, 2, 1], [3, 2, 1]) True >>> has_sublis...
def is_(value, type_): """ Check if a value is instance of a class :param value: :param type_: :return: """ return isinstance(value, type_)
def quotewrap(item): """wrap item in double quotes and return it. item is a stringlike object""" return '"' + item + '"'
def int_to_int_array(num): """ Deprecated, use int_to_digit_array(num) """ return [int(str(num)[a]) for a in range(len(str(num)))]
def _true_hamming_distance(a: str, b: str) -> int: """ Calculate classic hamming distance """ distance = 0 for i in range(len(a)): if a[i] != b[i]: distance += 1 return distance
def calc_met_equation_hdd(case, t_min, t_max, t_base): """Calculate hdd according to Meteorological Office equations as outlined in Day (2006): Degree-days: theory and application """ if case == 1: hdd = t_base - 0.5 * (t_max + t_min) elif case == 2: hdd = 0.5 * (t_base - t_min) - 0....
def get_range_data(num_row, rank, num_workers): """ compute the data range based on the input data size and worker id :param num_row: total number of dataset :param rank: the worker id :param num_workers: total number of workers :return: begin and end range of input matrix """ num_per_pa...
def notifyRecipient(data): """Notify PR author about reviews.""" # Work in progress return data
def all(sequence, test_func = None): """ Returns 1 if for all members of a sequence, test_func returns a non-zero result. If test_func is not supplied, returns 1 if all members of the sequence are nonzero (i.e., not one of (), [], None, 0). """ for item in sequence: if test_func: ...
def average_for_active_days(timeline): """Compute the average activity per active day in a sparse timeline. :param timeline: A dictionary of non-sequential dates (in YYYY-MM-DD) as keys and values (representing ways collected on that day). :type timeline: dict :returns: Number of entities capt...
def summarize_bitmap(bitmap: list) -> str: """Give a compact text summary for sparse bitmaps""" nonzero_bits = [] for i, b in enumerate(bitmap): if b != 0: nonzero_bits.append(f'{i:x}:{b:02x}') sorted_nonzero_bits = ', '.join(sorted(nonzero_bits)) summary = f'{len(nonzero_bits)}/...
def create_argument_list_wrapped_explicit(arguments, additional_vars_following = False): """Create a wrapped argument list with explicit arguments x=y. If no additional variables are added (additional_vars_following == False), remove trailing ',' """ argument_list = '' length = 0 for argument in arg...
def validate_options(value, _): """ Validate options input port. """ if value: if "max_wallclock_seconds" not in value.get_dict(): return "the `max_wallclock_seconds` key is required in the options dict."
def ramp_geometric(phi, A): """ Weighted geometric mean according to phi. """ return A[0]**(0.5*(1.+phi))*A[1]**(0.5*(1.-phi))
def spin(c): """print out an ASCII 'spinner' based on the value of counter 'c'""" spin = ".:|'" return (spin[c % len(spin)])
def longest_common_prefix(strs): """ Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string ''. """ # Corner cases/basic cases. if len(strs) == 0: return '' if len(strs) == 1: return strs[0] ...
def is_ascii(s): """http://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii""" return all(ord(c) < 128 for c in s)
def blockquote(txt): """ Block quote some pandoc text. Returns a list of strings """ return [''] + [ "> " + t for t in txt.split('\n') ] + ['']
def cga(geoact, geoacs, subff2): """ GEOACT: GA CENTER POINT GEOACS: GA AREA C/SUB 0=None 1=Quest 2=<I2 3=<O2 4=<1/2 DA 5=<1DA 6=<2DA 7=>2DA 8=CG Returns: 0, 1, 88 """ if geoact == 2 or (geoact == 1 and 2 <= geoacs...
def list_to_lines(data): """cast list to lines or empty string""" return '\n'.join(data) if data else ''
def summation(limit): """ Returns the summation of all natural numbers from 0 to limit Uses short form summation formula natural summation :param limit: {int} :return: {int} """ return (limit * (limit + 1)) // 2 if limit >= 0 else 0
def web_template_to_frontend_top_message(template: dict) -> dict: """Transforms a frontend top level message to the web template.""" top_level_message = {} top_level_message['header_content'] = str(template['header']).strip() menu_items = list(template['menuItems']) top_level_message['top_level_opt...
def letter_grades(highest): """Create a list of grade thresholds based on the provided highest grade. :param highest: int - value of highest exam score. :return: list - of lower threshold scores for each D-A letter grade interval. For example, where the highest score is 100, and failing is <= 4...
def fast_exponentiation(a, b, q): """Compute (a pow b) % q, alternative shorter implementation :param int a b: non negative :param int q: positive :complexity: O(log b) """ assert a >= 0 and b >= 0 and q >= 1 result = 1 while b: if b % 2 == 1: result = (result * a) %...
def boolean(v=None): """a boolean value""" if isinstance(v, str): raise ValueError('please use True or False without quotes, or 1/0)') return bool(v)
def judge_index_type(index_type, target_type): """Judges whether the index type is valid.""" if index_type == target_type or (isinstance(target_type, (list, tuple)) and index_type in target_type): return True return False
def git_unicode_unescape(s, encoding="utf-8"): """Undoes git/gitpython unicode encoding.""" if s.startswith('"'): return s.strip('"').encode("latin1").decode("unicode-escape").encode("latin1").decode(encoding) return s
def values_from_syscalls(line): """ Utility method to obtain the system call count values from the relative line in the final analysis output text file. :param line: string from log file :return: int corresponding to system call frequency """ return int(line.strip().split('\t')[1])
def __write_ldif_one(entry): """Write out entry as LDIF""" out = [] for l in entry: if l[2] == 0: out.append("%s: %s" % (l[0], l[1])) else: # This is a base64-encoded value out.append("%s:: %s" % (l[0], l[1])) return "\n".join(out)
def bubble_sort(list_object): """as the name implies list_object: is a list object""" swap = False while not swap: swap = True for index in range(1, len(list_object)): if list_object[index-1] > list_object[index]: swap = False list_object[index], l...
def ensure_service_chains(service_groups, soa_dir, synapse_service_dir): """Ensure service chains exist and have the right rules. service_groups is a dict {ServiceGroup: set([mac_address..])} Returns dictionary {[service chain] => [list of mac addresses]}. """ chains = {} for service, macs in ...
def prepare_bid_identifier(bid): """ Make list with keys key = {identifier_id}_{identifier_scheme}_{lot_id} """ all_keys = set() for tenderer in bid['tenderers']: key = u"{id}_{scheme}".format(id=tenderer['identifier']['id'], scheme=tenderer['identif...
def recall(overlap_count: int, gold_count: int) -> float: """Compute the recall in a zero safe way. :param overlap_count: `int` The number of true positives. :param gold_count: `int` The number of gold positives (tp + fn) :returns: `float` The recall. """ return 0.0 if gold_count == 0 else ove...
def get_lvl(ob): """ Returns the number of parents of a given object, or, in other words, it's level of deepness in the scene tree. Parameters ---------- ob : bpy.types.object Blender object Returns ------- lvl : int The number of parents of the object. For 'None' -...
def keymap(func, d, factory=dict): """ Apply function to keys of dictionary >>> bills = {"Alice": [20, 15, 30], "Bob": [10, 35]} >>> keymap(str.lower, bills) # doctest: +SKIP {'alice': [20, 15, 30], 'bob': [10, 35]} See Also: valmap itemmap """ rv = factory() rv.update...
def mag(*args): """ Magnitude of any number of axes """ n = len(args) return (sum([abs(arg)**2 for arg in args]))**(1/2)
def _make_url(raw, sig, quick=True): """ Return usable url. Set quick=False to disable ratebypass override. """ if quick and not "ratebypass=" in raw: raw += "&ratebypass=yes" if not "signature=" in raw: raw += "&signature=" + sig return raw
def edges_to_nodes(id_edge, edges_dict): """ :param nodes: list list with id of nodes :return: list id of edges """ nodes_list = list(edges_dict.keys()) edges_id = list(edges_dict.values()) id_edge = edges_id.index(id_edge) ...
def last_month(date): """get the name of last month""" date = str(date) year = date[:4] month = date[4:] if month == '10': month = '09' elif month == '01': year = str(int(year) - 1) month = '12' else: month = int(month) - 1 if month < 10: m...
def _make_panel(search_record): """ Extract fields we currently support from a single JSON metadata file and prepare them in dict form to render search.html. Returns: (dict) that will be an element of the list of panel_data to be displayed as search results """ panel = {"keywords": sear...
def get_timestamp_format_by_ttl_seconds(ttl_value: int) -> str: """ Calculates the precision of the timestamp format required based on the TTL For example: if TTL is 3600 seconds (1hr) then return "%Y-%m-%d-%H0000" if TTL is 600 seconds (10 mins) then return "%Y-%m-%d-%H%M00" if TTL ...
def is_len(value): """ is value of zero length (or has no len at all)""" return getattr(value ,'__len__', lambda : 0)() > 0
def generate_simulation_intervals(Nd, maxlength, overlap): """ Generate a list of tuples containing the begining and the end of any simulation intervals. Parameters ---------- Nd : int Number of samples from the data set. maxlength : int Maximum length of simulation interval...
def _to_str_list(values): """Convert a list to a list of strs.""" return [str(value) for value in values]
def extract_status_code(error): """ Extract an error code from a message. """ try: return int(error.code) except (AttributeError, TypeError, ValueError): try: return int(error.status_code) except (AttributeError, TypeError, ValueError): try: ...
def find_harm_sum(i): """i: an integer > 0 takes an integer and returns the harmonic sum""" if i == 1: # print("base case: return 1") return 1 harm_sum = 1/i + find_harm_sum(i-1) # print("non-base case: return ", harm_sum) return harm_sum
def list_converter(columnheaders, labels): """ Convert input strings into input lists """ if not isinstance(columnheaders, list): if columnheaders is None: columnheaders = '' labels = '' columnheaders = columnheaders.split() labels = labels.split() ret...
def getValsItems(vals): """ :param vals: :return: """ ret = {} for i_key, i_val in list(vals.items()): try: i_val = eval(i_val) except Exception: i_val = i_val if isinstance(i_val, dict): for j_key, j_val in list(i_val.items()): ...
def get_index_in_permuted(x, L): """Mapping to undo the effects of permute4 Useful to find the location of an index in original list in Merkle tree. """ ld4 = L // 4 return x // ld4 + 4 * (x % ld4)
def right_shift(array, count): """Rotate the array over count times""" res = array[:] for i in range(count): tmp = res[:-1] tmp.insert(0, res[-1]) res[:] = tmp[:] return res
def argmax(values): """Returns the index of the largest value in a list.""" return max(enumerate(values), key=lambda x: x[1])[0]
def flatten(l): """Flattens nested lists into a single list. :param list l: a list that potentially contains other lists. :rtype: list""" ret=[] for i in l: if isinstance(i, list): ret+=flatten(i) else: ret.append(i) return ret
def linear_search(v, b): """Returns: first occurrence of v in b (-1 if not found) Precond: b a list of number, v a number """ # ############# method 1 # i = 0 # while i < len(b) and b[i] != v: # i += 1 # if i == len(b): # return -1 # return i # ############## method 2...
def extract_identifiers(response): """ Extract identifiers from raw response and return as a list. """ results = response["result_set"] print(results) ids = [res["identifier"] for res in results] return ids
def split_header(task, lines): """Returns if the task file has a header or not.""" if task in ["CoLA"]: return [], lines elif task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI"]: return lines[0:1], lines[1:] else: raise ValueError("Unknown GLUE task."...
def _digits(n): """ Outputs a list of the digits of the input integer. Int -> [Int] Note: Returns list in reverse order from what one might expect. It doesn't matter for our purposes since we're summing the squares of the digits anyway, but this can be fixed by returning res[::-1] if it bot...
def replace_key_with_value(s, replace_dict): """In string s keys in the dict get replaced with their value""" for key in replace_dict: s = s.replace(key, replace_dict[key]) return s
def GetHour(acq_time): """ gets simply the hour from the given military time """ aqtime = str(acq_time) size = len(aqtime) hr = aqtime[:size - 2] #get the hours #add the 0 if we need it to match the fire db if len(hr) == 1: hr = '0' + hr elif len(hr) == 0: hr = '00' ...
def ackermann(m: int, n: int) -> int: """Recursive implementation of Ackermann algorithm. :param m: positive integer :param n: positive integer """ if m == 0: return n + 1 elif n == 0: return ackermann(m - 1, 1) else: return ackermann(m - 1, ackermann(m, n - 1))
def comma_counter(field: str): """ :param field: :return: """ total = 0 for f in field: if f == ',': total += 1 return total
def myRound(n): """ This function rounds a number up if it has decimal >= 0.5 :param float n: input number :return int r: rounded number """ if n % 1 >= 0.5: r = int(n) + 1 else: r = int(n) return r
def getRemainingBalance(balance, annualInterestRate, monthlyPaymentRate): """ Input balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal monthlyPaymentRate - minimum monthly payment rate as a decimal Return the remaining balan...
def phred_score(letter, offset, ascii): """ Returns the Phred score of a fastq quality character. """ # Offset the string offset_string = ascii[offset - 33:] # Find the characters score score = 0 while score < len(offset_string): if letter == offset_string[score]: return ...
def escape_nmap_filename(filename): """Escape '%' characters so they are not interpreted as strftime format specifiers, which are not supported by Zenmap.""" return filename.replace("%", "%%")
def enclose_in_parenthesis(query_txt): """ Encloses each word in query_txt in double quotes. Args: query_txt: Search query Returns: '(query_word1) AND (query_word2) ...' """ query_words = query_txt.split(',') return '(' + ') AND ('.join([word for word in query_words if word])...
def powers_to_list(x): """ Takes a value that's a sum of powers of 2 and breaks it down to a list of powers of 2. (Shamelessly stolen from https://stackoverflow.com/a/30227161.) """ powers = [] i = 1 while i <= x: if i & x: powers.append(i) i <<= 1 return powers
def is_text(value): """Return True if the value represents text. Parameters ---------- value : str or bytes Value to be checked. Returns ------- bool True if the value is a string or bytes array. """ if isinstance(value, bytes) or isinstance(value, str): ...
def trim_batch_job_details(sfn_state): """ Remove large redundant batch job description items from Step Function state to avoid overrunning the Step Functions state size limit. """ for job_details in sfn_state["BatchJobDetails"].values(): job_details["Attempts"] = [] job_details["Con...
def get_type(kind, props): """Converts API resource 'kind' to a DM type. Only supports compute right now. Args: kind: the API resource kind associated with this resource, e.g., 'compute#instance' Returns: The DM type for this resource, e.g., compute.v1.instance Raises: Exception: if the ...
def fahrenheit(T_in_celsius): """ returns the temperature in degrees Fahrenheit """ return (T_in_celsius * 9 / 5) + 32
def fizzBuzz(num: int) -> str: """It returns Fizz, Buzz, FizzBuzz or the number that you passed if is divisible by 3, 5, 3 or 5, or the number if it is none of the later Args: num (int): The number that you want to use for the FizzBuzz algorith Returns: str: Fizz, Buzz, FizzBuzz or the...
def first_player_wins(a, b): """ If tie : Returns 0 If first player wins : Returns 1 If second player wins : Returns -1 """ if a == b: return 0 elif [a, b] == ["R", "S"] or [a, b] == ["S", "P"] or [a, b] == ["P", "R"]: return 1 return -1
def javaToClass(file) : """ simple helper function, converts a string from svn stat (or command line) to its corresponding .class file """ rval = file.replace('src','target').replace('main','classes').replace('test','test-classes').replace('.java', '.class').replace('java','').replace('\\\\','\\') ...
def blocksFundingTxs(maxTxPerBlock, lstFundingTxs): """ separate the funding transactions into blocks with constants.maxTxPerBlock amount :param maxTxPerBlock: maxTxPerBlock :param lstFundingTxs: list of funding txs :return: list of funding blocks """ lstFundingBlocks = [] i = 0 if ...
def ind2sub(idx, shape): """Linear index to tensor subscripts""" # assert len(shape) == 2 # 2D test # sub = [idx // shape[1], idx % shape[1]] # return sub sub = [None] * len(shape) for (s, n) in reversed(list(enumerate(shape))): # write subscripts in reverse order sub[s] = idx % n ...
def unpack(n, x): """Unpacks the integer x into an array of n bits, LSB-first, truncating on overflow.""" bits = [] for _ in range(n): bits.append((x & 1) != 0) x >>= 1 return bits