content
stringlengths
42
6.51k
def get_special_case_tol(dataset, tree_type, method, default_tol=1e-5): """ Special cases for `leaf_inf` and `leaf_refit`. Input dataset: str, dataset. tree_type: str, tree-ensemble model. method: str, explainer. default_tol: float, original tolerance. Return - ...
def isThumb(frame): """ Check Thumb flag from CPSR """ try: regs = frame.GetRegisters()[0] # general purpose registers cpsr = [reg for reg in regs if reg.GetName()=='cpsr'][0] thumb_bit = int(cpsr.GetValue(), 16) & 0x20 if thumb_bit >> 5 != 0: return True except: pass return False
def init_admin_chat_ids(admin_chat_id: str): """load the admin_chat_ids saved in api_config to list for faster access Returns: list: A List containing all chat id's allowed to exchange admin-messages with the bot """ admin_chat_list = [] admin_chat_id_split = admin_chat_id.split(',') fo...
def get_subplot_size(lenx, i): """ Gets the subplot size as a tuple depending on the number of datasets passed. This is used for creating henry regime subplots. :param lenx: int Number of datasets :param i: Iterator :return: tuple of shape (x, y, z) """ if lenx <= 4: ...
def get_italic_token(token): """Apply italic formatting to a given token. https://api.slack.com/docs/message-formatting#message_formatting Args: token (str): String sequence with a specific definition (for parser). Returns: str: bold formatted version of a token. """ return "_...
def find_sympts(lines): """ Given the contents of a Gnuplot script find the symmetry points To draw the band structure the symmetry points along the path of k-points is needed. The GW code stores this information in the Gnuplot script that draws the band structure. Hence this routine parses ...
def find_between(s, first, last): """Find string.""" try: start = s.index(first) + len(first) end = s.index(last, start) return s[start:end] except ValueError: return ""
def check_range(value, mode=0): """ Validate ranges of column (mode=1) or row (mode=0) """ if not isinstance(value, int): value = int(value) bound = 16384 if mode else 1048756 value %= bound return value
def geo_features(geo): """extracts a list of features, for multiple types of input""" features = geo try: features = geo.__geo_interface__ except AttributeError: pass try: features = features['features'] except TypeError: pass return features
def _kwargs_sq_processor(kwargs): """ Converts all values within a provided dictionary to string values @param kwargs: @return: """ if not isinstance(kwargs, dict): raise TypeError for k in kwargs.keys(): if isinstance(kwargs[k], str): kwargs[k] = f'\'{kwargs[k]}...
def rindex(l, v): """Like list.index(), but go from right to left.""" return len(l) - 1 - l[::-1].index(v)
def _get_master(cluster_spec, task_type, task_id): """Returns the appropriate string for the TensorFlow master.""" if not cluster_spec: return '' # If there is only one node in the cluster, do things locally. jobs = cluster_spec.jobs if len(jobs) == 1 and len(cluster_spec.job_tasks(jobs[0])...
def isNoisyComponent(labels, signalLabels=None): """Given a set of component labels, returns ``True`` if the component is ultimately classified as noise, ``False`` otherwise. :arg signalLabels: Labels which are deemed signal. If a component has no labels in this list, it is deemed no...
def feature_list(collection): """get features list from collection""" return collection['features']
def _x_orientation_rep_dict(x_orientation): """Create replacement dict based on x_orientation.""" if x_orientation.lower() == 'east' or x_orientation.lower() == 'e': return {'x': 'e', 'y': 'n'} elif x_orientation.lower() == 'north' or x_orientation.lower() == 'n': return {'x': 'n', 'y': 'e'}...
def first_non_repeating_character(string): """ One way to do this is to have two dictionaries one which keeps the count of character, other dictionary will keep the first appearance of the character (index). After a traversal. Look in first dictionary for characters occurring once and output the one whi...
def _sanitize_identifier(identifier_pattern): """Sanitizes a substance identifier so it can be used in a file name. Parameters ---------- identifier_pattern: str The identifier to sanitize. Returns ------- str The sanitized identifier. """ identifier_pattern = i...
def calculate(a: int, operator: str, b: int) -> int: """ Simple calculator. >>> calculate(a = 3, operator = "+", b = 4) 7 >>> calculate(a = 3, operator = "-", b = 4) -1 >>> calculate(a = 3, operator = "*", b = 4) 12 >>> calculate(a = 3, operator = "/", b = 4) 0 >>> calculate...
def strip_word(word): """Converts a word to lowercase and strips out all non alpha characters.""" stripped = "" word = word.lower() for char in word: ascii = ord(char) if ascii >= 97 and ascii <= 122: stripped += char return stripped
def is_prime(n: int) -> bool: """ Returns True if n is prime, else returns False. :param n: int :return: bool """ if n <= 1: return False if n == 2: return True if not n & 1: # This is bitwise and. n & 1 is true for all odd numbers. return False # I avoid ...
def _get_mappings(field_spec, lookup_key): """ retrieve the field aliasing for the given key, refs or fields """ mappings = field_spec.get(lookup_key, []) if isinstance(mappings, list): mappings = {_key: _key for _key in mappings} return mappings
def attr_or_key(obj, k): """Get data for `k` by doing obj.k, or obj[k] if k not an attribute of obj >>> d = {'a': 1, 2: 'b', '__class__': 'do I win?'} >>> attr_or_key(d, 'a') 1 >>> attr_or_key(d, 2) 'b' >>> attr_or_key(d, '__class__') <class 'dict'> That last one shows that `attr_o...
def format_dict_as_lines(action_data): """Given a dictionary, format it as list of lines for presentation in tikibar. """ data = [] for key in sorted(action_data): data.append('{key}:{value}'.format(key=key, value=action_data[key])) return '\n'.join(data)
def inteiro_positivo(x): """ -Verifica se o argumento = numero inteiro e positivo (ou zero) Input: -x: elemento a ser testado Output: -Booleano Funcoes externas ao Python usadas: -- Nota:usada no tipo Posicao (construtor e reconhecedor) """ if isinstance(x, int) and x>=0: return True else: return Fa...
def _get_state(inspect_results): """ Helper for deriving the current state of the container from the inspect results. """ if inspect_results.get("State", {}).get("Paused", False): return "paused" elif inspect_results.get("State", {}).get("Running", False): return "running" el...
def _read(f): """ Reads in the content of the file. :param f: the file to read :type f: str :return: the content :rtype: str """ return open(f, 'rb').read()
def RetriveUserIds(json_obj): """Get all user ids in a list of Tweet objects.""" rst_set = set() def _helper(current_obj): if 'entities' in current_obj: if 'user_mentions' in current_obj['entities']: if current_obj['entities']['user_mentions']: for user_obj in current_obj['entities'][...
def bin_to_int(bits, bpw): """ Convert a list of bits to an integer """ sign_limit = 2**(bpw-1)-1 conv = (2**bpw) value = 0 for bit in reversed(bits): value = (value << 1) | bit if value > sign_limit: value -= conv return value
def link(href, text): """Generate a link""" return '<a href="' + href + '">' + text + '</a>'
def parse_id_list(id_list) -> str: """ Converts a list of IDs to a comma-delimited string """ if type(id_list) is list: returned = "" for s in id_list: if len(returned) > 1: returned += "," returned += str(s) return returned else: retur...
def set_tags(config, tags): """ set gloabal tags setting in config """ config['tags'] = tags return True
def normalize_chord_case(word: str) -> str: """ Normalizes the case of a chord. Example: >>> normalize_chord_case('gM#') 'Gm#' """ ret = '' if len(word) > 1: return word[0].upper() + word[1:].lower() else: return word.upper()
def _remove_complex_types(dictionary): """ junos-eznc is now returning some complex types that are not serializable by msgpack. Kill those. """ for k, v in dictionary.items(): if isinstance(v, dict): dictionary[k] = _remove_complex_types(v) elif hasattr(v, "to_eng_string...
def pipeline(*functions): """ Construct a filter pipeline from a list of filter functions Given a list of functions taking an iterable as their only argument, and which return a generator, this function will return a single function with the same signature, which applies each function in turn for e...
def legal(a, b): """ Returns True if the given index is on the board - that is, both indices in the range 0 -> 7 """ return a in range(8) and b in range(8)
def configUnmapped(func, param: str): """ Helper to determine if a parameter mapping was set to None. :param func: The function to check. :param param: The parameter name to check. :return: True if the parameter mapping was set to none. """ return hasattr(func, '__cfgMap__') and param in fu...
def model_cropheatflux(netRadiationEquivalentEvaporation = 638.142, soilHeatFlux = 188.817, potentialTranspiration = 1.413): """ - Name: CropHeatFlux -Version: 1.0, -Time step: 1 - Description: * Title: CropHeatFlux Model * Author: Pierre Martre ...
def cli_repr(obj): """ Variant of standard `repr` that returns string suitable for using with a Command Line Interface, like the one enforced by `bash`. This is designed to get a `str`. Other input can be incompatible. """ # Replace ' with " because it is for CLI mostly (bash) # and there is no differen...
def max_produkt(n): """vrednost produkta najvecjih n-mestnih st""" return (10**(n) - 1) * (10**(n) - 1)
def part_1(puzzle_input): """Function which calculates the solution to part 1 Arguments --------- Returns ------- """ puzzle_input = int(puzzle_input) recipe_scores = [3, 7] elf_1 = 0 elf_2 = 1 while len(recipe_scores) < (puzzle_input + 10): score_sum = reci...
def find_block_end(row, line_list, sentinal, direction=1): """ Searches up and down until it finds the endpoints of a block Rectify with find_paragraph_end in pyvim_funcs """ import re row_ = row line_ = line_list[row_] flag1 = row_ == 0 or row_ == len(line_list) - 1 flag2 = re.match...
def _is_simple_mask(mask): """A simple mask is ``(2 ** n - 1)`` for some ``n``, so it has the effect of keeping the lowest ``n`` bits and discarding the rest. A mask in this form can produce any integer between 0 and the mask itself (inclusive), and the total number of these values is ``(mask + 1)``. ...
def vader_output_to_label(vader_output): """ map vader output e.g., {'neg': 0.0, 'neu': 0.0, 'pos': 1.0, 'compound': 0.4215} to one of the following values: a) positive float -> 'positive' b) 0.0 -> 'neutral' c) negative float -> 'negative' :param dict vader_output: output dict from...
def merge_dicts(samples_dict_1, samples_dict_2): """merge dicts of pairs so {sample: [1.r1, 1.r2, 2.r1, 2.r2]""" samples_dict_new = {} for key in samples_dict_1: samples_dict_new[key] = samples_dict_1[key] + samples_dict_2[key] return samples_dict_new
def split_dishes2val_test(dishes): """splist_dishes2train_val :param dishes: :return (train_content: list, val_content: list) """ val_content = [] test_content = [] for i, dish in enumerate(dishes): if i % 2: val_content += dish else: test_content += ...
def _b(strs): """ Convert a list of strings to binary UTF8 arrays. """ if strs is None: return None if isinstance(strs, str): return strs.encode('utf8') return list([s.encode('utf8') if s is not None else None for s in strs])
def average_error_to_weight(error): """ Given the average error of a pollster, returns that pollster's weight. The error must be a positive number. """ return error ** (-2)
def keyfr(frame=0, duration=1000, **kwargs): """ Returns a single keyframe with given parameters :param frame: name or number of image for this keyframe :param duration: time in milliseconds for this keyframe :param angle: degrees of clockwise rotation around a center origin :param flipx: set True to flip image ...
def quadratic_vertex_derivative_b(x, a, b, c): """The partial derivative with respect to parameter {@code b} for vertex form of quadratic function :param x: independent variable :param a: coefficient {a} of quadratic function :param b: the x coordinates of the vertex :param c: the y coordinates ...
def index_based(index,value,input_list): """ only create a state if the eigenvalue is in the index list. """ if index in input_list: return True else: return False
def trailing_stop_loss_switch(value): """enable/disable trailing stop loss settings""" if "trailingstoploss" in value: return False, False return True, True
def removeAmbiguousBases(seq): """ Converts ambiguous bases to - as required by PhyML""" new_seq = "" for char in seq: if char not in ["A", "T", "C", "G"]: char = "-" new_seq += char return new_seq
def extract_doc_type(image_annotation): """ This function extracts the document type from the annotation performed on the Identity Documents :param image_annotation: the annotation from the annotated image :return: the document type """ recto_verso = "" type = "" for annotation in image_...
def sizeof_fmt(num, suffix='B'): """ Human-readable string for a number of bytes. http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1000.0: return "%3.1f%s%...
def f_value_with_digit_sum(n): """ Build the smallest number which digit sum is n. """ n9, d = divmod(n, 9) if d == 0: return '9' * n9 else: return str(d) + '9' * n9
def GPE_gpemgh(mass,gravity,height): """Usage: Find gravitational potential energy from mass, gravity and height""" result=mass*gravity*height return result
def hass_to_wilight_saturation(value): """Convert hass saturation 0..100 to wilight 1..255 scale.""" return min(255, round((value * 255) / 100))
def simple_interest(P,r,t): """ P = Principal Amount I = Interest Amount r = Rate of Interest per year in decimal """ I = P*r*t A = P + I return A
def get_filename_pair(filename): """ Given the name of a SPAR data file (e.g. /home/me/foo.sdat) or parameters file (e.g. c:/stuff/xyz.spar), returns a tuple of (parameters_filename, data_filename). It doesn't matter if the filename is a fully qualified path or not. This is a little shaky on ca...
def convert_string_to_list(value, delimiter): """ Splits a string using the provided delimiter. Parameters: value (str): string to be split. delimiter (str): delimiter used to split the string. Returns: list: a string converted to a list. """ try: return valu...
def metric_slug(value): """Given a redis key value for a metric, returns only the slug. Applying this filter to the keys for each metric will have the following results: * Converts ``m:foo:<yyyy-mm-dd>`` to ``foo`` * Converts ``m:foo:w:<num>`` to ``foo`` * Converts ``m:foo:m:<yyyy-mm>`` to ``f...
def inside(x, a, b): """ test x \in (a, b) or not """ l = 0 # if not torch.isreal(x): # return l if a <= b: if x >= a and x <= b: l = 1 else: if x >= b and x <= a: l = 1 return l
def refine_MIDDLEWARE_CLASSES(original): """ Django docs say that the LocaleMiddleware should come after the SessionMiddleware. Here, we make sure that the SessionMiddleware is enabled and then place the LocaleMiddleware at the correct position. Be careful with the order when refining the Middleware...
def fce2array(sr, pat): """Converts functions into arrays """ se = "".join(sr) so = "" ln = len(se) while ln > 0: # find pattern pos = se.find(pat) if pos < 0: break # position just behind the pattern pos += len(pat) sl = list(se)...
def warning(expression, string, font=None): """ Error for command prompt Count=If count is needed, then you have to change countError to something else than None: assign countError to variable put before loop, which equals 1. After the warning you have to implement the incrementation...
def is_float(s): """ Return True if this is a float with trailing zeroes such as `1.20` """ try: float(s) return s.startswith('0') or s.endswith('0') except: return False
def is_phrasal(subtree): """True if this treebank subtree is not a terminal or a preterminal node.""" return isinstance(subtree, list) and \ (len(subtree) == 1 or isinstance(subtree[1], list))
def filter_results(results, skip_list): """ Remove results for methods on the skip list. """ result = [] for method, res in results: include = True for skip in skip_list: if skip in method: include = False break if include: ...
def dss_bundle_to_dos(dss_bundle): """ Converts a fully formatted DSS bundle into a DOS bundle. :param dss_bundle: :return: """ dos_bundle = {} dos_bundle['id'] = dss_bundle['uuid'] dos_bundle['version'] = dss_bundle['version'] dos_bundle['data_object_ids'] = [x['uuid'] for x in dss...
def compute_protein_mass(protein_string): """ Return the mass of a protein string as a float >>> compute_protein_mass("SKADYEK") 821.392 """ mass_table = {"A" : 71.03711, "C" : 103.00919, "D" : 115.02694, "E" : 129.04259, "F...
def change_extension(filename, extension): """Change file extenstion to @extension. >>> change_extension('file_name.py', 'html') 'file_name.html' >>> change_extension('file_name.with.dots.html', 'py') 'file_name.with.dots.py' """ return '.'.join(filename.split('.')[:-1] + [extension])
def get_docomo_post_data(number, hidden_param): """Returns a mapping for POST data to Docomo's url to inquire for messages for the given number. Args: number: a normalized mobile number. Returns: a mapping for the POST data. """ return {'es': 1, 'si': 1, '...
def no_progress_count_plane(no_progress, n=8): """ :param int no_progress: Integer value denoting the number of total no-progress moves made. :param int n: Chess game dimension (usually 8). :return: An n x n list containing the same value for each entry, the no_progress number. :rtype:...
def GCD(a , b): """ define a function GCD which takes two integer inputs and return their common divisor""" com_div =[1] i =2 while i<= min(a,b): if a % i == 0 and b % i ==0: com_div.append(i) i = i+1 return com_div[-1]
def to_datetime(timestamp): """converts a timestamp to a Sheets / Excel datetime""" EPOCH_START = 25569 # 1970-01-01 00:00:00 SECONDS_IN_A_DAY = 86400 return timestamp / SECONDS_IN_A_DAY + EPOCH_START
def _asciizToStr(s): """Transform a null-terminated string of any length into a Python str. Returns a normal Python str that has been terminated. """ i = s.find('\0') if i > -1: s = s[0:i] return s
def oc_to_vlan_range(value): """ Converts an industry standard vlan range into a list that can be interpreted by openconfig. For example: ["1", "2", "3..10"] -> "1, 2, 3-10" """ return ",".join(["{}".format(s).replace("..", "-") for s in value])
def quintic_ease_in_out(p): """Modeled after the piecewise quintic y = (1/2)((2x)^5) ; [0, 0.5) y = (1/2)((2x-2)^5 + 2) ; [0.5, 1] """ if p < 0.5: return 16 * p * p * p * p * p else: f = (2 * p) - 2 return (0.5 * f * f * f * f * f) + 1
def _create_groups(together: list): """Returns unions of pairs Args: together (list): Pairs of individuals who should be together Returns: list: Nested list of groups, ordered largest to smallest Example: >>> together = [["a", "b"], ["a", "e"], ["d", "g"]] >>> _create_...
def get_image_parameters( particle_center_x_list=lambda : [0, ], particle_center_y_list=lambda : [0, ], particle_radius_list=lambda : [3, ], particle_bessel_orders_list=lambda : [[1, ], ], particle_intensities_list=lambda : [[.5, ], ], image_half_size=lambda : 25, image_background_level...
def _flip(r, u): """Flip `r` if `u` is negated, else identity.""" return -r if u < 0 else r
def decoder(permutation): """ decoder takes a permutation array and returns the corresponding depermutation array necessary to decode a permuted string """ depermutation = [] for x in range (0, len (permutation)): depermutation.append (permutation.index(x)) return depermutation
def _interval_contains_close(interval, val, rtol=1e-10): """ Check, inclusively, whether an interval includes a given value, with the interval expanded by a small tolerance to admit floating point errors. Parameters ---------- interval : (float, float) The endpoints of the inter...
def case2args(case): """ Parse case and Convert case into pod-compatible string """ s = case.split(" ") s = [q for q in s if q] # remove empty strings s[0] += ".json" return s
def unliteral(lit_type): """ Get base type from Literal type. """ if hasattr(lit_type, '__unliteral__'): return lit_type.__unliteral__() return getattr(lit_type, 'literal_type', lit_type)
def _content_parse(value: str): """ :param value: :return: """ try: res = int(value) except ValueError: try: res = float(value) except ValueError: res = value return res
def swap(string, nameA, nameB): """ Swap all occurances of nameA with nameB and vice-versa in the string. Parameters ---------- string : str The string to modify. nameA : str The substring to replace with `nameB`. nameB : str The substring to replace with `nameA`. ...
def extended_gcd(a, b): """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb""" # r = gcd(a,b) i = multiplicitive inverse of a mod b # or j = multiplicitive inverse of b mod a # Neg return values for i or j are made positive mod b or a respectively # Iterateive Version is faster ...
def fsnative2glib(path): """Convert file system to native glib format""" assert isinstance(path, bytes) return path
def _ExtStorageEnvironment(unique_id, ext_params, size=None, grow=None, metadata=None, name=None, uuid=None, snap_name=None, snap_size=None, exclusive=None): """Calculate the environment for an External Storage...
def get_temp_disk_for_node_agent(node_agent: str) -> str: """Get temp disk location for node agent :param node_agent: node agent :return: temp disk location """ if node_agent.startswith('batch.node.unbuntu'): return '/mnt' elif node_agent.startswith('batch.node.windows'): return ...
def convertStr(s): """Convert string to either int or float.""" if s is None: return None try: ret = int(s) except ValueError: ret = None return ret
def next_quarter(year, quarter, num=1): """return next quarter for Gregorian calendar""" if quarter not in range(1, 5): raise ValueError("invalid quarter") quarter -= 1 # for mod, div quarter += num year += quarter / 4 quarter %= 4 quarter += 1 # back return year, quarter
def findFractionOfPixelWithinCircle(xmin, xmax, ymin, ymax, r, cx = 0.0, cy = 0.0, ndiv = 16): """ Find the fraction of a pixel that is within a hard circular mask. Arguments: xmin -- left edge xmax -- right edge ymin -- lower edge ymax -- upper edge r -- radius of circle Keyword a...
def compute_num_cells(max_delta_x, pt_0_y, pt_1_y): """compute the number of blocks associated with the max_delta_x for the largest spatial step (combustion chamber) Args: max_delta_x (double): User defined maximum grid spacing. pt0x (double): x-coordinate of bottom LHS cookstove combustion chambe...
def gwh_to_twh(gwh): """Convert GWh to TWh Arguments --------- gwh : float GWh Returns ------- twh : str TWh """ twh = gwh / 1000.0 return twh
def padded_text(word, max_length, centered): """ Returns padded text with spaces (centered or not) """ word_str = str(word) len_word = len(word_str) if centered: len_pad = max_length - len_word if len_pad % 2 == 0: pad = int(len_pad / 2) l, r = pad, pad ...
def vis85(n): """ OOO OO OOO OO OOOO OOOOOO OO OOO OOOO OOO OOOO OOOO Number of Os: 4 12 24 """ result = '' if n == 1: result = 'OO\nOO' return result result...
def stripdefaults(target, removeempty=list(), removeexact=dict()): """ Make output dicts smaller by removing default entries. Keys are removed from `target` in place Args: target (dict): dictionary to remove entries from removeempty (list): Remove keys in this list from target if the key ...
def subsentence_comma(sentence): """ delete ',' or changed on ';' Input=sentence Output=sentence """ # init i = 0 while i < len(sentence): if sentence[i] == ',': sentence[i] = ';' # We delete it if it is at the end of the sentenc...