content
stringlengths
42
6.51k
def _ns(s): """Remove namespace, but only if there is a namespace to begin with.""" if '}' in s: return '}'.join(s.split('}')[1:]) else: return s
def fromStr(valstr): """try to parse as int, float or bool (and fallback to a string as last resort) Returns: an int, bool, float or str Args: valstr (string): A user provided string """ try: val = int(valstr) except ValueError: try: val = float(valstr) ...
def how_many_seconds(hours: int) -> int: """Convert hours to seconds.""" return hours * (60**2)
def convert_es_responses_to_list(search_responses: list): """ Convert responses from ElasticSearch to list. This will be used in the backend """ submissions = [] for response in search_responses: submission = response["_source"] submission["score"] = response["_score"] su...
def newline_list_formatter(text_list, wrap=None): """format list with newline for each element""" return '\n'.join(text_list or [])
def mean(y): """ Return the sample arithmetic mean of y. >>> mean([1, 2, 3, 4, 4]) 2.8 """ return sum(y)/len(y)
def RemoveBadCarac(mot): """ remove a list of bad carac in a word """ bad_carac = [",", "*", "'", "]", "[", "-", ".", "!", "?", " ", '', "(", ")"] mot_propre = list() for carac in mot: if carac not in bad_carac and not carac.isnumeric(): mot_propre.append(carac) else:...
def GenerateFirefoxCommandLine(firefox_path, profile_dir, url): """Generates the command line for a process to run Firefox Args: firefox_path: String containing the path to the firefox exe to use profile_dir: String containing the directory of the profile to run Firefox in url: String containing url to...
def float_check(nums): """Check to see if input list contains only float values Given that the list containing the time and the voltage values could contain floats or strings, it is necessary to check to see if the list actually is only comprised of floats. Strings are not usable for math purposes,...
def simplify_one_coord(coords): """ Merge all overlapping line segments in a list of line segments on the same horizontal or vertical line. The line segments are given only by their start and end coordinates in one coordinate direction because they are assumed to share the other cooordinate. (Otherwise...
def to_char_array(byte_array): """Returns a string with a brace-enclosed list of C char array elements""" members = ", ".join(f"0x{int(byte):02x}" for byte in byte_array) return f"{{{members}}}"
def directly(*parts): """return parts joined directly""" return ''.join(parts)
def fractioncolor(nom, denom=1): """Color for utilization fractions.""" if denom == 0: return "r" fraction = nom / denom if fraction < .1: return "r" if fraction < .25: return "y" if fraction < .9: return 0 return "g"
def perimeter(n): """.""" p = 1 a = 0 b = 1 for i in range(n): p += a + b c = a a = b b += c return p * 4
def calc_mi(med_head_x, lat_head_x, lat_acetabulum_x, side): """Calculate migration index (MI). For the right hip, MI = (lat acetabulum - lat head) / (med head - lat head) For the left hip first need to multiple each point by -1. Args: med_head_x: x coordinate of medial head lat_head_x: ...
def update_if(cur_dict, ap_dict): """Adds item to the dict if key is not already in dict Parameters ---------- cur_dict : dict The dictionary we wish to update ap_dict : dict The dictionary we want to append to the current dictionary without overwriting any current keys ...
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() raw_tokens = text.split() # tokens = [token.strip() for token in raw_tokens] return raw_tokens
def my_split(s): """Explodes a string around commas except when in a {}-environment. See <http://stackoverflow.com/a/26809037/353337>. """ parts = [] bracket_level = 0 current = [] # trick to remove special-case of trailing chars for c in s + ",": if c == "," and bracket_level ==...
def equals_sum_fifth_powers(x): """ Return true if the number x equals the sum of its digits to the fifth power """ digit_power_sum = 0 digits_left = x while digits_left > 0: digit_power_sum += (digits_left % 10) ** 5 digits_left //= 10 return x == digit_power_sum
def partextras(labels): """Return a dictionary of extra labels for use in prompts to the user Intended use is in strings of the form "(l)ocal%(l)s". """ if labels is None: return { b"l": b"", b"o": b"", } return { b"l": b" [%s]" % labels[0], ...
def embolden(text): """ Make a string print in bold in a terminal using control codes. Note that if this text is read in other applications (not in a shell) then it probably won't work. Parameters ---------- text: str Text to be emboldened Returns ------- str ...
def _clean_names(names, remove_whitespace=False, before_dash=True): """ Remove white-space on topo matching This function handles different naming conventions for old VS new VectorView systems (`remove_whitespace`). Also it allows to remove system specific parts in CTF channel names (`before_dash`)...
def format_metric(name: str, value: float) -> str: """Format metric. Metric will be returned in the scientific format if 4 decimal chars are not enough (metric value lower than 1e-4). Args: name: metric name value: value of metric Returns: str: formatted metric """ ...
def count_change(amount): """Return the number of ways to make change for amount. >>> count_change(7) 6 >>> count_change(10) 14 >>> count_change(20) 60 >>> count_change(100) 9828 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'count_change', ['While', 'For']...
def pair_sum(A, n=0): """ O(n) but requires more memory (for the set) """ sett = set() for x in A: if n-x not in sett: sett.add(n-x) lst = [] for x in A: if n-x in sett and (x, n-x) not in lst: lst.append((x, n-x)) return lst
def strip_lines(lines, index, comment_str): """Removes leading and trailing comment lines from the file.""" is_blank = lambda x: x == '' or x == '\n' # Remove blank lines while len(lines) > 0 and is_blank(lines[index]): del lines[index] # Remove comment lines. stop_str = comment_str +...
def _pooling_output_shape( input_size, kernel_size, pad_l, pad_r, stride, dilation, ceil_mode ): """ Generates output shape along a single dimension following conventions here: https://github.com/pytorch/pytorch/blob/b0424a895c878cb865947164cb0ce9ce3c2e73ef/aten/src/ATen/native/Pool.h#L24-L38 """ ...
def is_strobogrammatic2(num: str): """Another implementation.""" return num == num[::-1].replace('6', '#').replace('9', '6').replace('#', '9')
def _GetProvides(sources): """Get all namespaces provided by a collection of sources.""" provides = set() for source in sources: provides.update(source.provides) return provides
def shell_call(cmd): """ Run a command and return output of stdout as result. """ from subprocess import check_output try: return str(check_output(cmd, shell=True), "utf-8") except: return ""
def find_start_end_dates(dates1, dates2): """Find start and end dates between lists (or arrays) of datetime objects that do not have the same length. The start date will be the later of two dates. The end date will be the earlier of the two dates. :param dates1: List or array of datetime objects ...
def is_valid_structure(ext): """ Checks if structure format is compatible with GROMACS """ formats = ['tpr', 'gro', 'g96', 'pdb', 'brk', 'ent'] return ext in formats
def sing_three(mu, c, i0=1.0): """ Calculates the intensity of a given cell in the stellar surface using the Sing et al (2009) limb-darkening law. Parameters ---------- mu (``float`` or ``numpy.ndarray``): Cosine of the angle between a line normal to the stellar surface and the ...
def subset_records(response): """Filter to subset SPC archive and only save a subset of records.""" data = response['body']['string'] index = 0 # Grab whole lines up to this maximum size while index < 4096: index = data.find(b'\n', index + 1) if index == -1: index = 409...
def parseUnit(formatString, undefined="NaN"): """Returns the unit of data item from MXElectric data message enclosed in []. Returns empty string as parse error. If the unit is not defined, string parameter undefined can be used to set it (defaults to NaN).""" opening = formatString.find('[') c...
def ele_dict_from(eles): """ Use names as keys. Names must be unique. """ ele_dict = {} for ele in eles: if ele['type'] == 'comment': continue name = ele['name'] assert name not in ele_dict ele_dict[name] = ele return ele_dict
def format_sequence(template, sequence, repl_char): """ Places the replacement character everywhere there is a False in the template list input: list list string returns: string """ return ''.join([c if b else repl_char for b, c in zip(template, sequence)])
def _trim_data(ref_data, fields): """Trim only fields in dict and return errors.""" data = {} for key in fields: data[key] = ref_data[key] return data
def sanitize_fields(attributes): """ This selects out only the valid dataservice fields to ensure that we don't try to post any additional fields to the dataservice, which will cause it to fail """ fields = { "name", "visible", "attribution", "data_access_authorit...
def get_refs_in_eval(source): """Returns list of xmlid arguments of 'ref' call in a python expression >>> get_refs_in_eval("ref('foo')") ['foo'] >>> get_refs_in_eval("('parent_id', '=', ref('foo'))") ['foo'] >>> get_refs_in_eval("('parent_id', '=', ref( \\ ... 'foo'))") ...
def setbit(x, nth_bit): """set n-th bit (i.e. set to 1) in an integer or array of integers Args: x: integer or :class:`numpy.ndarray` of integers nth_bit: position of bit to be set (0, 1, 2, ..) Returns: integer or array of integers where n-th bit is set while all other bits are kep...
def _calculate_temperature(c, h): """ Compute the temperature give a speed of sound ``c`` and humidity ``h`` """ return (c - 331.4 - 0.0124 * h) / 0.6
def transcribe(seq: str) -> str: """ transcribes DNA to RNA by generating the complement sequence with T -> U replacement """ seq_list = list(seq) for i in range(len(seq_list)): if seq_list[i] == 'A': seq_list[i] = 'U' elif seq_list[i] == 'T': seq_list[i] ...
def get_text(string, start, end, bom=True): """This method correctly accesses slices of strings using character start/end offsets referring to UTF-16 encoded bytes. This allows for using character offsets generated by Rosette (and other softwares) that use UTF-16 native string representations under Pyt...
def custom_schedule_4(epoch): """For 120 epochs each with 150 rollouts each""" if epoch < 4: return True, 5000 elif epoch < 24: return True, 1000 else: return True, 500
def remove_whitespace(word): """Removes whitespace from word""" return word.strip()
def make_slack_message_section(text: str) -> dict: """Generates an object compatiable with Slack's text section. Args: text: The text to be sent in the message. Returns: A text section message for delivery via Slack. """ return { 'type': 'section', 'text': { ...
def confusion_matrix(y_true, y_pred, labels): """Compute confusion matrix to evaluate the accuracy of a classification. Args: y_true(list of obj): The ground_truth target y values The shape of y is n_samples y_pred(list of obj): The predicted target y values (parallel to y_true) ...
def count_duplicates(t): """ Count the number of duplicate sets in a given list (t). Return an integer value. Sets greater than two are considered a single duplicate set. """ tmp = t[:] tmp.sort() count = 0 for i in range(len(t) - 1): if tmp[i] == tmp[i + 1] and tmp[i] != tmp[i -...
def fullname(o): """ Gives a full name (package_name.class_name) for a class / object in Python. Will be used to load the correct classes from JSON files """ module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ # Avoid reporting __builtin...
def get_job_ids(labelled_jobs): """gets job ids""" return [job["id"] for job in labelled_jobs]
def float_callback(input_): """Accepts only a float or '' as entry. Args: input_ (str): input to check Returns: bool: True if input is a float or an empty string, False otherwise """ if input_ != "": try: float(input_) except (ValueError, TypeError): ...
def adapt_dbm_constraint_ast(dbm_constr_ast): """Transforms the expression ast of a constraint into a clock constraint ast. Args: dbm_constr_ast: The constraint expression ast. Returns: The clock constraint ast. """ if (dbm_constr_ast["expr"]["left"]["astType"] == "BinaryExpr" ...
def nested_get(dct, keys): """ Gets keys recursively from dict, e.g. nested_get({test: inner: 42}, ["test", "inner"]) would return the nested `42`. """ for key in keys: if isinstance(dct, list): dct = dct[int(key)] else: dct = dct[key] return dct
def unique(A): """ Returns elements of A that are unique as defined by 'is' an equivalence relation. """ unique = [] for a1 in A: count = 0 for a2 in A: if a1 is a2: count +=1 if count > 1: break if count == 1: ...
def get_file_formats( interval, stations_kind, file_format_index ): """ Return the available file formats for the given 'interval' and 'stations_kind' (different file formats contain different data). Keyword arguments: interval -- data interval from the IMGW database ('monthly', 'daily'...
def poly2int(poly): """Return polygon with int coordinates.""" return [int(coord) for coord in poly]
def StrNoneChk(fld): """ Returns a blank string if none """ if fld is None: return "" return str(fld)
def some(predicate, iterable): """Determines whether the predicate applied to any element of the iterable is true. :param predicate: Predicate function of the form:: f(x) -> bool :param iterable: Iterable sequence. :returns: ``True`` if the predicate applied to any element of the...
def parse_book(book_data: dict) -> dict: """Parse book core data.""" info = {} for param in ['isbn', 'title', 'onsale', 'price', 'language', 'pages', 'publisher']: info[param] = book_data.get(param) info['cover'] = f'https://images.randomhouse.com/cover/{info["isbn"]}' info...
def convert_to_unicode(text): """ Converts `text` to Unicode (if it's not already) assuming utf-8 input.""" if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError(f"Unsupported string type: f{type(text)...
def size_type(s): """For specifying the size: either WxH, or W (square)""" if 'x' in s: width, height = s.split('x') else: width = height = s return int(width.strip()), int(height.strip())
def time_text_to_float(time_string): """Convert tramscript time from text to float format.""" hours, minutes, seconds = time_string.split(':') seconds = int(hours) * 3600 + int(minutes) * 60 + float(seconds) return seconds
def get_subroutine_name(string): """ Function that splits a string on everything before the first ( This may cause issues if there are more than one ( however, this is intended to be used on a subroutine/function decleration statement so there should only be one ( character in the entire string. ...
def sizeof_fmt(num, suffix='B'): """ From: http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size # NOQA Written by Fred Cirera """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s...
def setTextCoordinates(value, numberOfPlayers): """Change the horizontal location of where text should appear on the screen. Args: value: An integer amount of pixels that the text should be shifted to the right. numberOfPlayers: An integer showing how many players' controls will be changed. ...
def _combine_histories(history1, history2): """Combine histories with minimal repeats.""" hist2_words = history2.split(" ") add_hist = "" test_hist1 = " " + history1 + " " for i, word in enumerate(hist2_words): if " " + word + " " not in test_hist1: add_hist += " " + word ...
def make_divisible(value, divisor, min_value=None, min_ratio=0.9): """Make divisible function. This function rounds the channel number to the nearest value that can be divisible by the divisor. It is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by ...
def split_list( l1, l2): """ Usage: split_list(range(10), list(range(4,7))) ([0, 1, 2, 3], [4, 5, 6], [7, 8, 9]) """ if len(l1) < len(l2): return ([e for e in l2 if e < min(l1)], l1, [e for e in l2 if e > max(l1)]) else: return ([e for e in l1 if e < min(l2)], l2, ...
def build_masscan_command(scan_command, target_file, excluded_target_file, json_file, http_useragent): """Builds the masscan command.""" # Can only have 1 file output type. file_options = f"-iL {target_file} -oJ {json_file} --http-user-agent {http_useragent}" if excluded_target_file: file_opti...
def all_unique(iterable): """ Returns True if all of the provided args are equal to each other Args: iterable: An iterable of hashable items Returns: bool: True if all of the provided args are equal """ return len(set(iterable)) == len(iterable)
def write_all(filename, text, *, _open=open, ): """Write the given text to the file.""" with _open(filename, 'w') as outfile: return outfile.write(text)
def map_size(level_of_detail): """determines the map width and height (in pixels) at a specified level of detail level_of_detail, from 1 (lowest detail) to 23 (highest detail) returns map height and width in pixels """ return float(256 << level_of_detail)
def convert_str_to_list(sequence: str, is_ordered_sequence: bool = True, is_first_term_seq_name: bool = True): """ sequence: A string that contains a comma seperated numbers is_first_term_seq_name: True to drop the first term (i.e. A01255,1,3,5, ...) return: A list of integers in a list (String ---> Lis...
def any_negative(value): """Confirm that value(s) are nonnegative (zero allowed)""" try: return any(value < 0) except TypeError: return value < 0
def build_pubmed_url(pubmed_id) -> str: """ Generates a Pubmed URL from a Pubmed ID :param pubmed_id: Pubmed ID to concatenate to Pubmed URL :return: Pubmed URL """ return "https://pubmed.ncbi.nlm.nih.gov/" + str(pubmed_id)
def get_out_size(in_size,padding,dilation,kernel_size,stride): """computes output size after a conv or a pool layer""" return (in_size+2*padding-dilation*(kernel_size-1)-1)//stride +1
def __build_path(start_node, goal_node, nodes): """Builds a path from start to goal node based on graph of nodes""" # Build path array based on path mapping current_node = goal_node path = list() while current_node != start_node: # If node is not in mapping, no path exists if curren...
def is_number(number): """ Returns true if the input is a number or False otherwise Arguments: number (obj): The object that should be checked """ try: float(number) return True except ValueError: pass return False
def expandToDictionary(data, key: str): """ This function expand a non dictionary variable in to a dictionary with a key Eg. a = value -> {"key": value} """ if not isinstance(data, dict): return {key: data} else: return data
def create_result_section(param, result): """Function creating appropriate section in result dictionary""" if param not in result: result[param] = {} if "HMI_API" not in result[param]: result[param]["HMI_API"] = {} if "Mobile_API" not in result[param]: result[param]["Mobile_API"]...
def map(func, l: list) -> list: """ Apply a function to each element of l. map(func, l) -> [func(x1), ..., func(xn)] """ return [func(i) for i in l]
def _block_name_base(stage, block): """Get the convolution name base and batch normalization name base defined by stage and block. If there are less than 26 blocks they will be labeled 'a', 'b', 'c' to match the paper and keras and beyond 26 blocks they will simply be numbered. """ if block < 27: ...
def choose_pref_attach(degs, seed): """ Pick a random value, with a probability given by its weight. Returns a random choice among degs keys, each of which has a probability proportional to the corresponding dictionary value. Parameters ---------- degs: dictionary It contains the possi...
def substring(shorter, longer): """Returns True if the first argument is a substring of the second.""" try: longer.index(shorter) return True except Exception: return False
def fib2(n): # return fibonacci series up to n """return a list containing the fibonacci series up to n""" result = [] a, b = 0, 1 while a < n: result.append(a) a,b = b, a+b return result
def ReadFile(input_filename): """Helper function that returns input_filename as a string. Args: input_filename: name of file to be read Returns: string """ f = open(input_filename, 'rb') file_contents = f.read() f.close() return file_contents
def selection(population, size, fitness): """ Funzione di selezione data una [population] di individui una funzione di [fitness] seleziona [size} elementi dove il valore restituito da fitness e' minore :param population: [[int]] :param size: int :param fitness: [int] -> int :return: ...
def sol_1(s: str) -> dict: """using default dictionary""" from collections import defaultdict dct = defaultdict(int) for i in s: dct[i] += 1 ans = dict() for i in dct: if dct[i] > 1: ans[i] = dct[i] return ans
def compute_conv_output_dim(ifm_dim, k, stride, pad=0): """Returns spatial output dimension size for convolution with given params.""" return int(((ifm_dim + 2 * pad - k) / stride) + 1)
def percent_slower(new, old): """ `new` is X percent slower than `old` Args: new (float): measure of time old (float): measure of time (with same units as new) Returns: precent_slower: how much slower `new` is as a percentage of `old` Example: >>> new = 8.59755 ...
def humanized_time(seconds): """Converts seconds to human readable HH:MM:SS time format.""" mins, secs = divmod(seconds, 60) hours, mins = divmod(mins, 60) return "%02d:%02d:%02d" % (hours, mins, secs)
def prunecontainers(blocks, keep): """Prune unwanted containers. The blocks must have a 'type' field, i.e., they should have been run through findliteralblocks first. """ pruned = [] i = 0 while i + 1 < len(blocks): # Searching for a block that looks like this: # # +...
def mysorted(lst): """Just like sorted, but can also sorts dicts.""" if not lst: return lst try: return sorted(lst) except TypeError: if isinstance(lst[0], dict): return sorted(lst, key=lambda x: list(x.items())) raise
def pkcs7unpad(bs: bytes) -> bytes: """ A simple reverse operation. We look up the last value to tell how many bytes to remove. """ num_bytes = bs[-1] return bs[:-num_bytes]
def format_progress_bar(item): """ Format a progress bar item """ if item is not None: return "Processing {}".format(item[0])
def class_name(obj): """ Get the name of an object, including the module name if available. """ name = obj.__name__ module = getattr(obj, '__module__') if module: name = f'{module}.{name}' return name
def list_azimuthal_integ_methods(detector): """Return a list of available azimuthal integration methos. :param str detector: detector name """ if detector in ['AGIPD', 'DSSC', 'LPD']: return ['BBox', 'splitpixel', 'csr', 'nosplit_csr', 'csr_ocl', 'lut', 'lut_ocl'] return ['n...
def add_spaces(value: str, max_length=5): """Description.""" # 5 is the standard maximum length of the given value spaces = max_length - len(str(value)) if max_length > 5: return str(value) + "".ljust(spaces) return "".ljust(spaces) + str(value)
def _parse_cells(spec, maxlen): """Convert the cells spec to a range of ints.""" if not spec: raise ValueError("Empty cells spec not allowed") if set(spec) - set('0123456789-,'): raise ValueError( "Found forbidden characters in cells definition (allowed digits, '-' and ',')") ...