content
stringlengths
42
6.51k
def _ev_charge_level_supported(data): """Determine if charge level is supported.""" return ( data["isElectric"] and data["evStatus"]["chargeInfo"]["batteryLevelPercentage"] is not None )
def genomic_del5_abs_37(genomic_del5_37_loc): """Create test fixture absolute copy number variation""" return { "type": "AbsoluteCopyNumber", "_id": "ga4gh:VAC.9zhlg8DRSsE87N5SngYrMDWXStzp_WOX", "subject": genomic_del5_37_loc, "copies": {"type": "Number", "value": 2} }
def _is_prefixed(cmd_line): """Whether the supplied command line has already been prefixed with an OS specific operation. """ if cmd_line is None: raise ValueError("CommandLine is required field for task.") return cmd_line.startswith('cmd.exe /c') or \ cmd_line.startswith('cmd /c') o...
def microseconds(h, m, s, f): """ Returns an integer representing a number of microseconds :rtype: int """ return (int(h) * 3600 + int(m) * 60 + int(s)) * 1000000 + int(f) * 1000
def is_proper_csd(csd_num): """ Check we've a valid CSD number Returns false if the array contains consequitive non-zero terms. """ for i in range(1, len(csd_num)): if csd_num[i] != '0' and csd_num[i - 1] != '0': return False return True
def as_formatted_lines(lines): """ Return a text formatted for use in a Debian control file with proper continuation for multilines. """ if not lines: return '' formatted = [] for line in lines: stripped = line.strip() if stripped: formatted.append(' ' + l...
def dp_fib_ls(n: int): """A dynamic programming version of Fibonacci, linear space""" res = [0, 1] for i in range(2, n+1): res.append(res[i-2] + res[i-1]) return res[n]
def recode_dose(dose_value): """This function recode the doses in Level-4 data to 8 distinct dose classes""" doses = [0.04,0.12,0.37,1.11,3.33,10.0,20.0,25.0] for x in range(len(doses)-1): if (dose_value > 0.0) & (dose_value <= 0.04): dose_value = 0.04 elif doses[x] <= round...
def asList(x): """ Convert a variable to a list. :param x: an object that you would like to convert to a list. Will raise an exception if it is iterable but not already a tuple or list. """ if isinstance(x, list): return x elif isinstance(x, tuple): return list(x) elif...
def shl(x, n): """Shift left n bits (zeros come in from the right) >>> shl(0.5, 1) 1.0 >>> shl(0.1, 1) 0.2 """ return x * 2 ** n
def ellipsis_after(text, length): """ Truncates text and adds ellipses at the end. Does not truncate words in the middle. """ if not text or len(text) <= length: return text else: return text[:length].rsplit(' ', 1)[0]+u"\u2026"
def distance(point1, point2): """ calc distance between two 3d points """ return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 + (point1[2] - point2[2]) ** 2) ** 0.5
def list_ins_pkg(args_array, yum, **kwargs): """Function: list_ins_pkg Description: This is a function stub for package_admin.list_ins_pkg. Arguments: args_array yum """ status = (True, None) class_cfg = kwargs.get("class_cfg", None) if args_array and yum and class_cf...
def get_all_indices(element, alist): """ Find the index of an element in a list. The element can appear multiple times. input: alist - a list element - objective element output: index of the element in the list """ result = [] offset = -1 while True: try: ...
def neg(element: str) -> str: """Negate a single element""" return element[1:] if element.startswith("~") else "~" + element
def make_car(manufactory, type, **car_info): """Car informations""" car_info = {} car_info['car_manufactory'] = manufactory car_info['car_type'] = type for key, value in car_info.items(): car_info[key] = value return car_info
def justTfandDf(terms): """ Format the stats for each term into a compact tuple""" tfAndDf = {} for term, value in terms.items(): tfAndDf[term] = (value['term_freq'], value['doc_freq']) return tfAndDf
def get_generic_bases(tp): """Get generic base types of a type or empty tuple if not possible. """ org = getattr(tp, '__origin__', None) if org: a = (org,) else: a = () return a + getattr(tp, "__orig_bases__", ())
def _flatten_state(state): """Reduce nested object to string.""" if isinstance(state, list): return ",".join(map(_flatten_state, state)) elif isinstance(state, dict): return ",".join(map(lambda x: ":".join(map(_flatten_state, x)), state.items())) return str(state)
def format_multipart(props): """ Flatten lists to fit the requrests multipart form data format """ ret = [] for k, v in props.items(): if type(v) == list: for item in v: ret.append((k, item)) else: ret.append((k, v)) return tuple(ret)
def get_response_code(key): """ Translates numerical key into the string value for dns response code. :param key: Numerical value to be translated :return: Translated response code """ return { 0: 'NoError', 1: 'FormErr', 2: 'ServFail', 3: 'NXDomain', 4: 'NotImp', 5: 'Refused', ...
def epsilon(current_episode, num_episodes): """ epsilon decays as the current episode gets higher because we want the agent to explore more in earlier episodes (when it hasn't learned anything) explore less in later episodes (when it has learned something) i.e. assume that episode number is directly...
def loudness_normalize(sources_list, gain_list): """Normalize sources loudness.""" # Create the list of normalized sources normalized_list = [] for i, source in enumerate(sources_list): normalized_list.append(source * gain_list[i]) return normalized_list
def adjust_release_version(release_name): """ Adjust release_name to match the build version from the executable. executable: 1.8.0_212-b04 release_name: jdk8u212-b04 executable: 11.0.3+7 release_name: jdk-11.0.3+7 executable: 12.0.1+12 release_name: jdk-12.0.1+1...
def parse_type_encoding(encoding): """Takes a type encoding string and outputs a list of the separated type codes. Currently does not handle unions or bitfields and strips out any field width specifiers or type specifiers from the encoding. For Python 3.2+, encoding is assumed to be a bytes object and ...
def remove_suffix(input_string, suffix): """ Simple function to remove suffix from input_string if available """ try: input_string = input_string.strip() if not input_string.endswith(suffix): return input_string return input_string[0 : input_string.rfind(suffix)] ...
def isValidBST(root, low_range=float('-inf'), high_range=float('inf')): """ :type root: TreeNode :rtype: bool """ if not root: return True else: print ("root: " + str(root.val)) print ("low_range: " + str(low_range)) print ("high_range: " + str(high_range)) ...
def get_cellname (ch): """Return name of cell used to store character data""" prefix = "font_" if (ord(ch) < 0x100): cellname = "{:02X}".format(ord(ch)) elif (ord(ch) < 0x10000): cellname = "{:04X}".format(ord(ch)) elif (ord(ch) < 0x1000000): cellname = "{:06X}".format(ord(...
def rfile(node): """ Return the repository file for node if it has one. Otherwise return node """ if hasattr(node, "rfile"): return node.rfile() return node
def _mac_to_oid(mac): """Converts a six-byte hex form MAC address to six-byte decimal form. For example: 00:1A:2B:3C:4D:5E converts to 0.26.43.60.77.94 Returns: str, six-byte decimal form used in SNMP OIDs. """ fields = mac.split(':') oid_fields = [str(int(v, 16)) for v in fiel...
def attrmod(list): """Calculates modifiers for a list of attributes Returns a list of modifiers""" out = [] for i in list: if i in [0,1]: out.append(-3) elif i == 2: out.append(-2) elif i == 3: out.append(-1) elif i in [4,5,6,7]: out.append(0) else: out.append((i // 2)-3) return(out)
def format_data(data, es_index): """ Format data for bulk indexing into elasticsearch """ unit = data["unit"] rate_unit = data["rateUnit"] egvs = data["egvs"] docs = [] for record in egvs: record["unit"] = unit record["rate_unit"] = rate_unit record["@timestamp"]...
def get_part_around(content, index): """ Gets the part of the given `content` around the given `index`. Parameters ---------- content : `str` The content, around what the part will be cut out. index : `str` The index of around where the part will be cut out. """ resu...
def u64i(i: int): """uint64 from integer""" return f"{i:#0{18}x}"
def callsign_to_slot(callsign): """ Convert callsign to IBP schedule time slot (0 ... 17) This is required for migration reason. """ return { '4U1UN': 0, 'VE8AT': 1, 'W6WX': 2, 'KH6WO': 3, 'KH6RS': 3, 'ZL6B': 4, 'VK6RBP': 5, 'JA...
def DeepSupervision(criterion, xs, y): #y.shape = bs * seqlen """DeepSupervision Applies criterion to each element in a list. Args: criterion: loss function xs: tuple of inputs y: ground truth """ loss = 0. for x in xs: loss += criterion(x, y) loss /= len(x...
def migrate_report_settings_from_1_to_2(data): """ Migrate scrum report template of version 1 to version 2 """ migrated = dict() template_data = data.get("template", []) or [] migrated_template = [] for item in template_data: migrated_template.append(item.replace("${today}", "${date}...
def median(x): """ Returns the median of the elements of the iterable `x`. If the number of elements in `x` is even, the arithmetic mean of the upper and lower median values is returned. >>> median([3, 7, 4]) 4 >>> median([3, 7, 4, 45]) 5.5 """ s = sorted(x) N = len(s) ...
def is_intel_email(email): """Checks that email is valid Intel email""" return email and len(email) > 10 and " " not in email and email.lower().endswith("@intel.com")
def divide_numbers(numerator, denominator): """For this exercise you can assume numerator and denominator are of type int/str/float. Try to convert numerator and denominator to int types, if that raises a ValueError reraise it. Following do the division and return the result. However if ...
def dictmerge(x, y): """ merge two dictionaries """ z = x.copy() z.update(y) return z
def get_child_nodes_osd_tree(node_id, osd_tree): """ This function finds the children of a node from the 'ceph osd tree' and returns them as list Args: node_id (int): the id of the node for which the children to be retrieved osd_tree (dict): dictionary containing the output of 'ceph osd tre...
def get_background_css(rgb, widget="QWidget", editable=False): """Returns the string that contain CSS to set widget background to specified color""" rgb = tuple(rgb) if len(rgb) != 3: raise ValueError(r"RGB must be represented by 3 elements: rgb = {rgb}") if any([(_ > 255) or (_ < 0) for _ in r...
def _to_j2kt_native_name(name): """Convert a label name used in j2cl to be used in j2kt native""" if name.endswith("-j2cl"): name = name[:-5] return "%s-j2kt-native" % name
def luhn_checksum(check_number): """http://en.wikipedia.org/wiki/Luhn_algorithm .""" def digits_of(n): return [int(d) for d in str(n)] digits = digits_of(check_number) odd_digits = digits[-1::-2] even_digits = digits[-2::-2] checksum = 0 checksum += sum(odd_digits) for d in even_...
def higher_follower_count(A, B): """ Compares follower count key between two dictionaries""" if A['follower_count'] >= B['follower_count']: return "A" return "B"
def yatch(dice): """ Score the dice based on rules for YACHT. """ points = 0 if dice.count(dice[0]) == len(dice): points = 50 return points
def isoddv2(n): """ Is odd number - Another way >>> isoddv2(5) True """ return n & 1 == 1
def deldoubleword(data): """ Args: list of strings Output: list of strings without repeated words ('no more more please' -> 'no more please') """ data = [x.split() for x in data] datalist = [] for sen in data: sen2 = [] for i in range(len(sen)): ...
def strip_end(text: str, suffix: str, case_insensitive: bool = False) -> str: """Strips the suffix from a string if present. https://stackoverflow.com/a/1038999 Arguments: text {str} -- String to check for suffix suffix {str} -- Suffix to look for. Keyword Arguments: c...
def solution(X, Y, D): """Calculates minimum amount of jumps from X to Y with jumps of length D :param X: Start position (int) :param Y: Target position (int) :param D: Jump length (int) :returns: Min number of jumps :rtype: Integer """ # write your code in Python 3.6 distance = Y ...
def get_version(raw): """ This will parse out the version string from the given list of lines. If no version string can be found a ValueError will be raised. """ for line in raw: if line.startswith("# MODULE:"): _, version = line.split(":", 1) return version.strip() ...
def info_to_name(display): """extract root value from display name e.g. function(my_function) => my_function """ try: return display.split("(")[1].rstrip(")") except IndexError: return ""
def url_from_args(year, month): """ Generate Donation log url from args e.g. https://dons.wikimedia.fr/journal/2013-12 """ return "https://dons.wikimedia.fr/journal/%04d-%02d" % (year, month)
def makepath(path): """ from holger@trillke.net 2002/03/18 See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117243 """ from os import makedirs from os.path import normpath,dirname,exists,abspath dpath = normpath(dirname(path)) if not exists(dpath): makedirs(dpath) retur...
def reverse_list(l): """ return a list with the reverse order of l """ return l[::-1]
def normalize_empty_to_none(text): """Return verbatim a given string if it is not empty or None otherwise.""" return text if text != "" else None
def addMortonCondition(mortonRanges, mortonColumnName): """ Composes the predicate with the morton ranges. """ elements = [] for mortonRange in mortonRanges: elements.append('(' + mortonColumnName + ' between ' + str(mortonRange[0]) + ' and ' + str(mortonRange[1]) + ')') if len(el...
def isfib(number): """ Check if a number is in the Fibonacci sequence number: Number to check """ num1 = 1 num2 = 1 while True: if num2 < number: tempnum = num2 num2 += num1 num1 = tempnum elif num2 == number: return Tru...
def median_s (sorted_seq) : """Return the median value of `sorted_seq`. >>> median ([1, 2, 2, 3, 14]) 2 >>> median ([1, 2, 2, 3, 3, 14]) 2.5 """ l = len (sorted_seq) if l % 2 : result = sorted_seq [l // 2] else : l -= 1 result = (sorted_seq [l // 2] + sort...
def emotion_mapping(emotions, dataset_emotions): """ Arguments: {"joy": 1, "sadness": 0.8}, ["joy", "sadness", "trust"] Returns: {"joy": 1, "sadness": 0.8, "trust": 0, "disgust": None, ...} """ all_emotions = [ "joy", "anger", "sadness", "disgust", "fear", ...
def c2f(c: float, r: int = 2) -> float: """Celsius to Fahrenheit.""" return round((c * 1.8) + 32, r)
def sentence_case(item: str) -> str: """Returns the string sentence-cased in an 05AB1E manner""" ret = "" capitalise = True for char in item: ret += (lambda: char.lower(), lambda: char.upper())[capitalise]() if capitalise and char != " ": capitalise = False capitalise...
def full_colour(problem): """ Update the problem by setting the cells that can be inferred from the onstraint that each row and column must have the same number of cells of each colour. The cells dictionary is directly updated. Returns True if any changes have been made, False otherwise. "...
def soma(x, y): """Soma x e y >>> soma(10, 20) 30 >>> soma(-10, 20) 10 >>> soma('10', 20) Traceback (most recent call last): ... AssertionError: x precisa ser int ou float """ assert isinstance(x, (int, float)), "x precisa ser int ou float" assert isinstance(y, (int, f...
def _escape_html_argument(text): """Escape a string to be usable as an HTML tag argument.""" result = "" for c in text: if c == "<": result += "&lt;" elif c == ">": result += "&gt;" elif c == "&": result += "&amp;" elif c == '"': ...
def hex_reverse(integer, size): """ Reverse a hex string, bf99 -> 99bf """ string = '{0:0{1}x}'.format(integer, size) return ''.join([string[i-2:i] for i in range(len(string), 0, -2)])
def most_populous(locations): """Disambiguate locations by only keeping the most populous ones.""" new_locations = {} for chunk in locations: new_locations[chunk] = set() for loc in locations[chunk]: biggest = (loc[0], sorted(loc[1], key=lambda x: -int(x[-1]))[0]) n...
def llhelper_can_raise(func): """ Instruct ll2ctypes that this llhelper can raise RPython exceptions, which should be propagated. """ func._llhelper_can_raise_ = True return func
def common_cells(region_one: list, region_two: list): """ Determines whether there are any cells in common between two lists of cells NB does not take in to account resolution. Cells should be at the same input resolution. :param region_one: a list of strings representing cell suids :param region_tw...
def getSelectColumns(columns): """ Prepare the columns to be selected by the SELECT statement. """ if columns == '*': return columns else: return ', '.join(columns)
def _StripLeadingOrTrailingDoubleColons(addr_string): """Strip leading or trailing double colon.""" if addr_string.startswith("::"): return addr_string[1:] if addr_string.endswith("::"): return addr_string[:-1] return addr_string
def sieve5(n): """Return a list of the primes below n.""" prime = [True] * n result = [2] append = result.append sqrt_n = (int(n ** .5) + 1) | 1 # ensure it's odd for p in range(3, sqrt_n, 2): if prime[p]: append(p) prime[p*p::2*p] = [False] * ((n - p*p - 1) //...
def convert_scan_cursor(cursor, max_cursor): """ See https://engineering.q42.nl/redis-scan-cursor/ Apply mask from max_cursor and reverse bits order """ N = len(bin(max_cursor)) - 2 value = bin(cursor)[2:] s = ("{:>0%ss}" % N).format(value) return int(s[::-1], base=2)
def move_path(current_dir, new_dir, path): """ Move a path from one directory to another. Given the directory the path is currently in, moves it to be in the second. The path below the given directory level remains the same. """ if current_dir[-1] != '/': current_dir += '/' if new_di...
def update_office(old_office, new_office): """ function returns a copy of old_office updated with values from new if applicable """ updated_office = old_office.copy() # update each field in office for newfield, newval in new_office.items(): for oldfield, oldval in old_office.items(): ...
def is_edit( request, v, edit="Edit"): """ Was an \"edit server\" button pressed? """ return v.startswith("edit_") and request.vars.get(v) == edit
def modify_leaves(f, ds): """Walks a data structure composed of nested lists/tuples/dicts, and creates a new (equivalent) structure in which the leaves of the data structure (i.e the non-list/tuple/dict data structures in the tree) have been mapped through f.""" if isinstance(ds, list): retu...
def _parse_dunder(line): """Parse a line like: __version__ = '1.0.1' and return: 1.0.1 """ item = line.split('=')[1].strip() item = item.strip('"').strip("'") return item
def post_data(data): """ Takes a dictionary of test data and returns a dict suitable for POSTing. """ r = {} for key, value in data.items(): if value is None: r[key] = "" elif type(value) in (list, tuple): if value and hasattr(value[0], "pk"): ...
def float_f(f): """Formats a float for printing to std out.""" return '{:.0f}'.format(f)
def describe_something(game, *args): """Describe some aspect of the Item""" (description) = args[0] print(description) return False
def urljoin(*args): """ Joins given arguments into an url. Trailing but not leading slashes are stripped for each argument. """ return "/".join(map(lambda x: str(x).rstrip("/"), args))
def sanitize(lines): """ remove non text unicode charachters; maybe some of them could be used to give hints on parsing?. """ return [line.replace(u'\u202b','').replace(u'\u202c','').replace(u'\x0c','') for line in lines]
def rewrite_kwargs(conn_type, kwargs, module_name=None): """ Manipulate connection keywords. Modifieds keywords based on connection type. There is an assumption here that the client has already been created and that these keywords are being passed into methods for interacting with various ...
def get_words(line): """Break a line into a list of words. Use a comma as a separator. Strip leading and trailing whitespace. """ return [word.strip() for word in line.split(',')]
def get_object_dir_prefix(objhash): """Returns object directory prefix (first two chars of object hash)""" return objhash[0:2] + "/"
def Gte(field, value): """ A criterion used to search for a field greater or equal than a certain value. For example * search for TLP >= 2 * search for customFields.cvss >= 4.5 * search for date >= now Arguments: field (value): field name value (Any): field value Returns: ...
def set_combinations(iterable): """ Compute all combinations of sets of sets example: set_combinations({{b}},{{e},{f}}) returns {{b,e},{b,f}} """ def _set_combinations(iter): current_set = next(iter, None) if current_set is not None: sets_to_combine_with = _set_combin...
def simplify_stdout(value): """Simplify output by omitting earlier 'rendering: ...' messages.""" lines = value.strip().splitlines() rendering = [] keep = [] def truncate_rendering(): """Keep last rendering line (if any) with a message about omitted lines as needed.""" if not render...
def cigar_correction(cigarLine, query, target): """ Read from CIGAR in BAM file to define mismatches. Args: *cirgarLine(str)*: CIGAR string from BAM file. *query(str)*: read sequence. *target(str)*: target sequence. Returns: *(list)*: [query_nts, target_nts] """ ...
def string_to_number(word): """ Converts from number(string) to number(integer) Args: word (`str`): number (string) Raise: Exception Returns: ret_num ('int|float'): number (integer|float) Example: >>> dev.api.string_to_number('1') ...
def s1_mission(title: str) -> str: """ sentinel competition date extractor extractor from product name """ if not title.startswith(('S1B', 'S1A','S2A','S2B')): raise ValueError("Title should start with ('S1B','S1A')") return title[:3]
def snake_to_pascal(param): """ Convert a parameter name from snake_case to PascalCase as used for AWS IAM api parameters. :param word: Dictionary of Resilient Function parameters. :return: Converted string. """ return ''.join(x.capitalize() or '_' for x in param.split('_'))
def first(X): """ Returns the first element of an iterable X. """ return next(iter(X))
def find_cluster(dd, clusters): """Find the correct cluster. Above the last cluster goes into "excluded (together with the ones from kitti cat""" for idx, clst in enumerate(clusters[:-1]): if int(clst) < dd <= int(clusters[idx+1]): return clst return 'excluded'
def egcd(a, b): """ Computes greatest common divisor (gcd) and coefficients of Bezout's identity for provided integers `a` and `b` using extended Euclidean Algorithm. Args: a (long): First integer number. b (long): Second integer number. Returns: (long, long, long):...
def pick_id(id, objects): """pick an object out of a list of objects using its id""" return list(filter(lambda o: o["id"] == id, objects))
def size_gb(size): """ Helper function when creating database :param size: interger (size in Gb) :return: integer (bytes) """ return 1024*1024*1024*size
def clean_title(title): """Remove status instructions from title""" replacements = ["RFR", "WIP", "[", "]", ":"] for replacement in replacements: title = title.replace(replacement, "") return title.strip().capitalize()