content
stringlengths
42
6.51k
def get_svm_model_name(model_dict, rd=None, rev=None): """ Helper function to get model name from <model_dict>, <rd> and <rev> """ model_name = 'svm_{}_cls{}'.format( model_dict['svm_type'], model_dict['classes']) if model_dict['preprocess'] is not None: model_name += ('_' ...
def _tl_type_ ( leaf ) : """Get a type for TLeaf object >>> tree = ... >>> leaf = t.leaf ( 'QQQ' ) >>> print leaf.get_type ( ) """ if not leaf : return 'NULL' branch = leaf.GetBranch () typename = leaf.GetTypeName () name = branch.GetTitle() p1 = na...
def valsplit(p: str): """Split value from path""" parts = p.split("=", maxsplit=1) if len(parts) == 1: return parts[0], None return parts[0], parts[1]
def _compute_checksum(packet): """Computes the checksum byte of a packet. Packet must not contain a checksum already Args: packet (list): List of bytes for a packet. packet must not contain a checksum as the last element Returns: The computed checks...
def logistic_equation(_, x, k, g): """ ode for the logistic equation :param _: place holder for time, not used :param x: x value :param k: slope of logistic equation :param g: upper bound of logistic equation :return: slope dx/dt """ dx = k * x * (g - x) return dx
def find_best(strings, criteria): """ Parse a list of `strings` and return the "best" element based on `criteria`. :param strings: List of string where best will be found based on `criteria`. :type strings: List[str] :param criteria: '>'-separated substrings sought in descending order. '+' ...
def BitFlip(n, N, pos): """Flips bit value at position pos from the left of the length-N bit-representation of n""" return (n ^ (1 << (N-1-pos)))
def flatten_dict(d, parent_key=tuple()): """Flatten a nested dict `d` into a shallow dict with tuples as keys. Parameters ---------- d : dict Returns ------- dict Note ----- Based on https://stackoverflow.com/a/6027615/ by user https://stackoverflow.com/users/1897/imran ...
def get_duplicated_sc_names(validated_data: dict): """ Validates if all Stop Condition names are unique. :validated_data: dict. Dictionary for validation. :return: list of duplicates. """ sc_names = [] for sc in validated_data["StopCondition"]: sc_names.append(sc["Name"]) duplica...
def remove_dups(seq): """ https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def findClosestSubPath(hdf5Object, path): """Find the closest existing path from the hdf5Object using a subset of the provided path. Returns None if no path found. It is possible if the path is a relative path. :param h5py.Node hdf5Object: An HDF5 node :param str path: A path :rtype: str ...
def get_explicit_entries(config_projects): """Pull out and return the projects in the config that were explicitly entered. The projects in the returned dict are deleted from config_projects. """ explicit_projects = { name: details for name, details in config_projects.items() if...
def convertImageIDToPaddedString(n, numCharacters=10): """ Converts the integer n to a padded string with leading zeros """ t = str(n) return t.rjust(numCharacters, '0')
def encode_data(name, form): """Right now, this is stupid. This will need to be fixed to generate a proper URL to REDcap Most likely we'll hit the REDCap db, filter to get a record ID and plunk it into the URL.""" google_url = 'https://www.google.com/#q={}'.format(name + form) return google_u...
def unpack(packed_data): """ Decompresses image data using a very simple algorithm described in 'pack'. Returns a bytearray. """ i = 0 # index for the unpacked bytearray element that we're currently on # checking the compression format version, for future compatibility in case this algo changes ...
def _check_callable(func, value): """Return true if func(value) returns is true or if *func* is *value*. """ return value is func or func(value)
def find_manual_auto_name_mismatches(manual_to_auto_map): """Finds the manual FOVs with names that do not match their corresponding auto FOV Args: manual_to_auto_map (dict): defines the mapping of manual to auto FOV names Returns: list: contains tuples with elements...
def make_rule_key(prefix, rule, group_id, cidr_ip): """Creates a unique key for an individual group rule""" if isinstance(rule, dict): proto, from_port, to_port = [rule.get(x, None) for x in ('proto', 'from_port', 'to_port')] #fix for 11177 if proto not in ['icmp', 'tcp', 'udp'] and from...
def no_set_folders(on=0): """Esconder as Configuracoes Painel de Controle, Impressoras e Conexoes de Rede DESCRIPTION Esta restricao remove as configuracoes Painel de Controle, Impressoras e Conexoes de Rede do menu Iniciar. Se as configuracoes da Barra de Tarefas tambem estiverem...
def getAddressClass(binaryString): """ This will calculate the address class of the IP address based on bits of binary string A: 0... B: 10.. C: 110. D: 1110 E: 1111 """ # initialize variable addressClass="" # troubleshooting # print(binaryString) # determine the address class if binaryStri...
def uX_to_bin(v, x): """Create a binary set of valued.""" if(v < 0): v += (1 << x) return bin(v)[2:].rjust(x, '0')
def _add_dot_prefix(meta_value): """Add dot as the prefix if missing""" if meta_value and not meta_value.startswith("."): return ".{0}".format(meta_value) return meta_value
def color_text(c: str, txt): """ To edit the text color. :param c: color. :param txt: text """ if c == 'red': return '\033[91m{}\033[m'.format(txt) elif c == 'white': return '\033[97m{}\033[m'.format(txt) elif c == 'green': return '\033[92m{}\033[m'.f...
def rsa_blind(message, randint, exponent, modulus): """ Return message RSA-blinded with integer randint for a keypair with the provided public exponent and modulus. """ return (message * pow(randint, exponent, modulus)) % modulus
def parse_hex(text): """Parse a hex number from text or fail :param text: Text to parse hex number from :type text: str :return: Parsed hex number :rtype: int :raise RuntimeError: If text does not contain a valid hexadecimal number """ try: return int(text, 0) except ValueE...
def stripperiods(aText): """Remove periods from text.""" import re # Replace by a space in case comma directly connects two words. aText = re.sub(r"\.", " ", aText) # Remove any multi-space sections (some may result from the above step) return re.sub(" {2,}", " ", aText)
def bizz_fuzz(num): """ BizzFuzz template tag. :param num: Integer :return: String or number depends on multiples conditions. """ output = '' if num % 3 == 0: output += 'Bizz' if num % 5 == 0: output += 'Fuzz' return output or num
def lcs(x, y): """ Finds longest common subsequence Code adopted from https://en.wikibooks.org/wiki/Algorithm_Implementation/ Strings/Longest_common_subsequence#Python """ m = len(x) n = len(y) # An (m+1) times (n+1) matrix c = [[0] * (n + 1) for _ in range(m + 1)] for i in range...
def EF_unsteady_states(Names): """ Constructs a CTL formula that queries whether for every variables v specified in *Names* there is a path to a state x in which v is unsteady. .. note:: Typically this query is used to find out if the variables given in *Names* are oscillating in a given attractor...
def sessions(request): """# Cookies prepeocessor """ context = {} # site_description = 'Asesalud Laboral 2727 C.A' # context['site_description'] = site_description return context
def has_argument(arg, arguments): """ Verifica se ci sono argument con la classe. """ try: if not isinstance(arguments, list): arguments = arguments.__arguments__ for idx, (args, kwargs) in enumerate(arguments): arg_name = kwargs.get( 'dest', args[...
def evaluate(pred_joins, gt_joins): """ Evaluate the performance of fuzzy joins Parameters ---------- pred_joins: list A list of tuple pairs (id_l, id_r) that are predicted to be matches gt_joins: The ground truth matches Returns ------- precision: float Precis...
def cigar_score(pairs, match_score=1, mismatch_score=-1, gap_score=-1): """ Find a custom score for cigar :param pairs: :return: number """ total = 0 for c,i in pairs: if c in ["="]: total += i*match_score elif c in ["X"]: total += i * mismatch_score ...
def _next_power_of_two(x): """Calculates the smallest enclosing power of two for an input. Args: x: Positive float or integer number. Returns: Next largest power of two integer. """ return 1 if x == 0 else 2**(int(x) - 1).bit_length()
def __zero_mat_list__(n=3): """Return a zero mat in list format. Args: n (int, optional): Length of the edge. Defaults to 3. Returns: list: List[List[int]] """ ret_list = [[0] * n for _ in range(n)] return ret_list
def dir1(obj): """ get the attributes of an object that are not interpreter-related """ return [{a: getattr(obj, a)} for a in dir(obj) if not a.startswith('__')]
def rws(t): """Remove white spaces, tabs, and new lines from a string""" for c in ['\n', '\t', ' ']: t = t.replace(c,'') return t
def int_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval . Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Returns: An int t...
def clean_str(str_, illegal_chars=(' ', '\t', ',', ';', '|'), replacement_char='_'): """ Return a copy of string that has all non-allowed characters replaced by a new character (default: underscore). :param str_: :param illegal_chars: :param replacement_char: :return:...
def merge_dict(this, other, cb): """ Merge dicts by key :param this: :param other: :param cb: :return: """ # assert isinstance(this, dict) # assert isinstance(other, dict) result = {} result.update(this) result.update(other) for key in this.keys() & other: re...
def html_color(color): """Interpret 'color' as an HTML color.""" if isinstance(color, str): if color.lower() == "r": return "#ff0000" elif color.lower() == "g": return "#00ff00" elif color.lower() == "b": return "#0000ff" elif color.startswith(...
def sql_name(raw_name): """ Cleaned column name. Args: raw_name: raw column name Returns: cleaned name suitable for SQL column """ sql_name = raw_name for to_replace in ['"', ' ', '\\', '/', '(', ')', '.']: sql_name = sql_name.replace(to_replace, '_') return...
def has_open_sequence(text: str) -> bool: """Figures out if the given text has any unclosed ANSI sequences. It supports standard SGR (`\\x1b[1mHello`), OSC (`\\x1b[30;2ST\\x1b\\\\`) and Kitty APC codes (`\x1b_Garguments;hex_data\\x1b\\\\`). It also recognizes incorrect syntax; it only considers a tag c...
def _test(transformation, word1, word2): """Tries transforming word1 and word2 with the given transform function. It tries swapping the words if the transformation fails. This function returnsthe transformed words or false if the transformation failed both ways.""" result = transformation(word1...
def decrypt_block(n, suffix, length, oracle): """ Decrypts one block of the hidden suffix appended to the user input in the oracle. """ for i in range(16): # If length of suffix is equal to the length of the suffix, return. if len(suffix) == length: return suffix ...
def splitdir(idx): """ Return a subdirectory used when a big case is split into several pieces """ name = '' if len(idx) == 0: return '' for ii, n in enumerate(idx[0:]): name += 'sp%d-split-%d/' % (ii, n) name = name[0:-1] return name
def map1to8(v): """ Limit v to the range 1-8 or None, with 0 being converted to 8 (straight ahead). This is necessary because the back-calculation to degree7 will negative values yet the input to calculate_average_instruction must use 1-8 to weight forward instructions correctly. :param v: ...
def convertgoogle(ui): """function to convert user information returned by google auth service in expected format: returns this format: e.g.:{'name':'John Smith','id': '12345', 'email': 'js@example.com','provider','google',...} """ myui = {'name':ui['name'],'given_name':ui['given_name'],'family_na...
def to_dict(arr, id_='id'): """ convert array to dict """ result = {} if isinstance(arr, dict): return arr for row in arr: result[row[id_]] = row return result
def _get_module_tag(namespace, directive): """Get the project-relative path to some Python class, method, or function. Args: namespace (str): The importable Python location of some class, method, or function. Example: "foo.bar.ClassName.get_method_data". directive (str):...
def mock_token(bona_fide, permissions, auth): """Mock a processed token.""" return {"bona_fide_status": bona_fide, "permissions": permissions, "authenticated": auth}
def score_word(a, b): """ Scores a word relative to another word. Score is defined as the number of letters that match both in value and position.""" return sum([a[i] == b[i] for i in range(len(a))])
def match_ints(ref, val): """ Todo """ return 100 if ref == val else 0
def join_urls(first_url, second_url): """ Function that returns one url if two aren't given else joins the two urls and returns them. """ if not first_url: return second_url if not second_url: return first_url first_url = first_url.strip("/") second_url = second_url.lstrip(...
def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8))
def _make_rank(fitness): """ make ranking according to fitness Arguments: ---------- fitness {list[float]} -- each indivisuals' fitness Returns: -------- rank {list[int]} -- rank Examples: --------- >>> fitness = [5, 3, 4, 1, 2] >>> rank = _make_rank(fitnes...
def count_false_positives_within_list(class_predictions, LIST_c): """ Count the number of false positives from classes in the list LIST_c LIST_c: List of classes whose predictions in class_predictions we are interested in """ false_positive_count = 0 for item in range(len(class_predictions)):...
def zero_one_loss_calc(TP, POP): """ Calculate zero-one loss. :param TP: true Positive :type TP : dict :param POP: population :type POP : int :return: zero_one loss as integer """ try: length = POP return (length - sum(TP.values())) except Exception: retu...
def calculate_standard_deviation(pessimistic, optimistic): """ Calculate the standard deviation of a task. """ return round((pessimistic - optimistic) / 6, 1)
def _vertically_expand_bounding_box(bbox: tuple, increase: int) -> tuple: """ Expand the bounding box by a given amount in the vertical direction. Keyword arguments: bbox -- the bounding box to expand increase -- the amount to expand the bounding box Returns: the expanded bounding box """ ...
def validate_config(config, service_class): """ Validates that a discovery config is valid for a specific service class """ header = config.setdefault('header', {}) if service_class != header.get('service_class'): raise Exception( "Cannot store config hash of type %s in service class %s: %s" % (header.get...
def get(server_id, **kwargs): """Return one server.""" url = '/servers/{server_id}'.format(server_id=server_id) return url, {}
def shorten(text): """Shortens width of text.""" text = text.split("\n", 1)[0] if len(text) > 50: return text[:50 - 3] + '...' return text
def is_true(value): """ Return ``True`` if the input value is ``'1'``, ``'true'`` or ``'yes'`` (case insensitive) :param str value: value to be evaluated :returns: bool Example _______ >>> is_true('1') True """ return str(value).lower() in ['true', '1', 'yes']
def good_unit_cell(uc_params, target_unit_cell, uc_tol): """check unit cell.""" flag_good_uc = False if ( abs(uc_params[0] - target_unit_cell[0]) <= (uc_tol * target_unit_cell[0] / 100) and abs(uc_params[1] - target_unit_cell[1]) <= (uc_tol * target_unit_cell[1] / 100) and ab...
def create_order(order_data): """ This is a stubbed method of retrieving a resource. It doesn't actually do anything. """ # Do something to create the resource return order_data
def html_link(text, url): """Creates an html link element from the given text and url :returns: html link element as string """ return '<a href="' + url + '">' + text + "</a>"
def transformation_remove_nl(text, *args): """ :param text: the text to run the transformation on :type text: str :return: the transformed text :type return: str """ text = text.replace('\r\n', '').replace('\n', '') return text
def bgr_int_to_rgb(bgr_int): """Convert an integer in BGR format to an ``(r, g, b)`` tuple. ``bgr_int`` is an integer representation of an RGB color, where the R, G, and B values are in the range (0, 255), and the three channels are comined into ``bgr_int`` by a bitwise ``red | (green << 8) | (blue << ...
def reverse_hashify(s): """Splits the given string s and returns a hash mapping the words to their word position in the string""" d = {} for i, word in enumerate(s.split()): d[word] = i return d
def combine_two_measurement_mean(new_mean: float, prev_mean: float, new_std: float, prev_std: float): """ Combine two measurement means using inverse-variance weighting Source: https://en.wikipedia.org/wiki/Inverse-variance_weighting :return: """ new_w = 1 / (new_std * new_std) prev_w = 1 / (p...
def winner(board): """ Returns the winner of the game, if there is one. """ possiblewin = [[[0,0],[1,1],[2,2]],[[0,0],[0,1],[0,2]], [[1,0],[1,1],[1,2]], [[2,0],[2,1],[2,2]], [[0,0],[1,0],[2,0]], [[0,1],[1,1],[2,1]], [[0,2],[1,2],[2,2]], [[0,2],[1,1],[2,0]]] for i in possiblew...
def _udev(udev_info, key): """ Return the value for a udev key. The `key` parameter is a lower case text joined by dots. For example, 'e.id_bus' will represent the key for `udev_info['E']['ID_BUS']`. """ k, _, r = key.partition(".") if not k: return udev_info if not isinsta...
def merge(left, right): """Merges two sorted sublists into a single sorted list.""" ret = [] li = ri =0 while li < len(left) and ri < len(right): if left[li] <= right[ri]: ret.append(left[li]) li += 1 else: ret.append(right[ri]) ri += 1 ...
def divide_set_value(state, config): """Set Value Divider Args: 'state': value Returns: A list ``[value, value]``. No copying is performed. """ value = config['value'] return [value, value]
def get_transceiver_sensor_description(name, lane_number, if_alias): """ :param name: sensor name :param lane_number: lane number of this sensor :param if_alias: interface alias :return: description string about sensor """ if lane_number == 0: port_name = if_alias else: p...
def dedup_unique(molecular_barcodes): """ Unique duplicate removal Count all unique UMIs. Parameters ---------- molecular_barcodes : dict dictionary with UMIs as keys and UMI counts as values Returns ---------- int Number of UMI groups """ return len(...
def user_authorization(packet): """ Returns the user's authorized duration in seconds, if unauthorized the return value will be 0. """ minute = 60 return 3 * minute
def is_falsy(x): """ Check if argument is falsy. This is the same as calling ``not bool(x)`` """ return not bool(x)
def sweep_info_table(sweep_results) -> str: """Return a string that is the summary of all sweep configurations and averages that ran.""" info_str = ( "<H2>Sweep Results</H2>\n" '<TABLE border="1">\n' ' <TR align="center">\n' " <TH>Pretap</TH><TH>Posttap</TH><TH>Mean(bit error...
def cut_levels(nodes, level): """ For cutting the nav_extender levels if you have a from_level in the navigation. """ result = [] if nodes: if nodes[0].level == level: return nodes for node in nodes: result += cut_levels(node.childrens, level) return result
def manipulatePartialChargesTag(charges): """Transform charges from float to string format.""" value = '' for charge in charges: value += str(charge) + '\n' return value
def to_bool(s): """Converts a string to a boolean""" from distutils.util import strtobool return bool(strtobool(s))
def make_car( manufacturer, type, **additions): """ Build a car profile. :param manufacturer: :param type: :param additions: :return car: """ car = dict() car['manufacturer'] = manufacturer car['type'] = type for k, v in additions.items(): car[...
def split_list(alist, wanted_parts=1): """ split list Parameters ---------- alist: list the split list wanted_parts: int the number of parts (default: {1}) Returns ------- list """ length = len(alist) #return all parts in a list, like [[],[],[]] retu...
def glob_to_regex(pattern): """Convert a 'glob' pattern for file name matching to a regular expression. E.g. "foo.? bar*" -> "foo\.. \bar.*" """ return "^"+pattern.replace(".","\.").replace("*",".*").replace("?",".")+"$"
def expand_segment(num_frames, num_target_frames, start_frame, stop_frame): """ expand the segment""" num_frames_seg = stop_frame - start_frame + 1 changes = False num_target_frames = min(num_target_frames, num_frames) if num_frames_seg < num_target_frames: while True: if start_f...
def latest_output(link, status=None): """get the latest output that each archive method produced for link""" latest = { 'title': None, 'favicon': None, 'wget': None, 'warc': None, 'pdf': None, 'screenshot': None, 'dom': None, 'git': None, ...
def pad(val: str, spaces: int = 2) -> str: """Pad val on left and right with `spaces` whitespace chars Arguments: val {str} -- string to pad Keyword Arguments: spaces {int} -- number of spaces to pad on either side (default: {2}) Returns: str -- padded string """ pad_s...
def base64_encode(encvalue): """ Base64 encode the specified value. Example Format: SGVsbG8gV29ybGQ= """ try: basedata = encvalue.encode("Base64") except: basedata = "There was an error" return(basedata)
def adjust_axial_sz_px(n: int, base_multiplier: int = 16) -> int: """Increase a input integer to be a multiple of mase_multiplier.""" remainder = n % base_multiplier if remainder == 0: return n else: return n + base_multiplier - remainder
def count_pattern(genome: str, pattern: str) -> int: """ Medium (half the time of counter like 9.5 sec for 10000 runs like below) """ count = 0 for i in range(0, len(genome) + 1 - len(pattern)): if genome[i: i + len(pattern)] == pattern: count += 1 return count
def _identify_tag_combination(tags_dict, test_tags_dict, true_value=True, none_value=None, **unused): """Test whether there all of a particular combination of tags are in ``tags_dict``. tags_dict : :obj:`dict` Dictionary of tags related to OSM element test_tags_dict : :obj:`dict` Dicti...
def join_infile_path(*paths): """ Join path components using '/' as separator. This method is defined as an alternative to os.path.join, which uses '\\' as separator in Windows environments and is therefore not valid to navigate within data files. Parameters: ----------- *paths: all str...
def compress(s): """ This solution compresses without checking. Known as the RunLength Compression algorithm. """ # Begin Run as empty string r = "" l = len(s) # Check for length 0 if l == 0: return "" # Check for length 1 if l == 1: ...
def resize_pts(pts, ow, oh, nw, nh, pos_w, pos_h): """ calculate coo of points in a resized img in pts pair of coo (x,y) """ new_pts = [] for p in pts: ox = p[0] oy = p[1] newx = (ox/float(ow)*nw) + pos_w newy = (oy/float(oh)*nh) + pos_h new_pts.append((ne...
def max_contig_sum(L): """ L, a list of integers, at least one positive Returns the maximum sum of a contiguous subsequence in L """ #YOUR CODE HERE work_L = L max_value = 0 current_value = 0 max_current_combo = [] current_combo = [] while len(work_L) > 0: for i in range(len(...
def reverse_string(string): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. string: a string returns: a rev...
def get(attribute_name, json_response, default=None): """ Get an attribute from a dictionary given its key name. :param attribute_name: Attribute name. :param json_response: Dictionary where the attribute should be. :param default: Value that has to be returned if the attribute is not there. :re...
def change_parameter_unit(parameter_dict, multiplier): """ used to adapt the latency parameters from the earlier functions according to whether they are needed as by year rather than by day :param parameter_dict: dict dictionary whose values need to be adjusted :param multiplier: float ...