content
stringlengths
42
6.51k
def validate_inventory(data_inventory): """ """ # Inventory if ('Inventory' not in data_inventory): raise Exception('Broken inventory file: Missing \'Inventory\' item.') elif (0==len(data_inventory['Inventory'])): raise Exception('Broken inventory file: \'Inventory\' item is empty.')...
def log_stability(x): """Log-stability for computing loss :param x: Input value :type x: float :return: Scaled value where :math:`\\hat{x} \\in (0, 1)` :rtype: float """ if x == 0: return 10e-9 elif x == 1: return 1.0-10e-9 else: return x
def get_disk_at(board, position): """ Return the disk at the given position on the given board. - None is returned if there is no disk at the given position. - The function also returns None if no disk can be obtained from the given board at the given position. This is for ins...
def dicompyler_roi_coord_to_db_string(coord): """ :param coord: dicompyler structure coordinates from GetStructureCoordinates() :return: string representation of roi, <z1>: <x1 y1 x2 y2... xn yn>, <zn>: <x1 y1 x2 y2... xn yn> :rtype: str """ contours = [] for z in coord: for plane in...
def _hsl2rgb(hsl): """Create an RGB integer from a HSL tuple""" def _hue(p, q, t): if t < 0: t += 1 elif t > 1: t -= 1 if t < (1.0 / 6.0): return p + ((q - p) * 6.0 * t) elif t < 0.5: return q elif t < (2.0 / 3.0): ...
def get_fqn(obj): """ This function tries to determine the fully qualified name (FQN) of the callable that is provided. It only works for classes, methods and functions. It is unable to properly determine the FQN of class instances, static methods and class methods. """ im_self = getattr(obj, "_...
def insert_best_individual(population, best_individual, n_copies_best): """ Function to Insert Best Individual Parameters ---------- population : Population best_individual : Best Individual n_copies_best : Number of Copies of Best Individual Returns ------- modifiedP...
def get_vanilla_url(version: str) -> str: """Ensures a constant and streamlined string creation for vanilla urls""" return f"https://mcversions.net/download/{version}"
def apply_default_values(table, default_values): """ Iterate through a table and use the default values as defined in launcher.json for non-mandatory columns. This is required otherwise the payload would not be constructed correctly and the post would fail. For the remaining non-mandatory columns t...
def has_write_perm(user, group, is_member): """ Return True if the user have permission to edit Articles, False otherwise. """ if (group is None) or (is_member is None) or is_member(user, group): return True return False
def getslitsize(slitname, config_file=''): """Return the slit size for a given slit name""" if slitname.strip() == 'PL0060N001': return 0.6 if slitname.strip() == 'PL0100N001': return 1.0 if slitname.strip() == 'PL0120P001': return 1.2 if slitname.strip() == 'PL0125N001': ...
def find(matrix: list, x: int) -> bool: """ Given a matrix and a number x, judge whether x is in the matrix. The matrix is increased by rows from left to right and columns from up to down. Parameters ---------- matrix: list x: int Returns -------- out: bool """ ...
def input_upload_video(field, preview=True, mime_types="video/mp4"): """Return HTML markup for a video upload input.""" return {"field": field, "preview": preview, "mime_types": mime_types}
def abmag_to_image(abmag): """ Convert AB magnitude into HSC image flux unit. """ return 10.0 ** ((27.0 - abmag) / 2.5)
def check_dict_has_kv(dictionary: dict, key, value) -> bool: """ Check if `dictionary` has entry `key` with value `value`. """ if key in list(dictionary.keys()) and dictionary[key] == value: return True return False
def encode_coord_line(index, x, y): """ Encodes given coordinate into a csv line: "index,x,y" """ if not (isinstance(index, int) and isinstance(x, int) and isinstance(y, int)): raise TypeError("parameters must be integer") return "%d,%d,%d" % (index, x, y)
def almost_zero(x, atol: float = 1e-6): """ Returns true if `x` is within a given tolerance parameter """ return abs(x) < atol
def chop_markdown_header(md): """ Remove empty lines and travis-ci header from markdown string. :param md: input markdown string :type md: str :return: simplified markdown string data :rtype: str """ md = md.splitlines() while not md[0].strip() or md[0].startswith('[!['.encode('utf-8...
def Zip(*data, **kwargs): """Recursive unzipping of data structure Example: Zip(*[(('a',2), 1), (('b',3), 2), (('c',3), 3), (('d',2), 4)]) ==> [[['a', 'b', 'c', 'd'], [2, 3, 3, 2]], [1, 2, 3, 4]] Each subtree in the original data must be in the form of a tuple. In the **kwargs, you can set the funct...
def _str_strip(string): """Provide a generic strip method to pass as a callback.""" return string.strip()
def anonymize(person_names, should_anonymize): """ Creates a map of person names. :param person_names: List of person names :param should_anonymize: If person names should be anonymized :return: """ person_name_dict = dict() person_counter = 1 for person_name in person_names: ...
def event_independence_check(prob_event1, prob_event2, prob_event1_event2): """Checks if two events are independent. This function accepts the probability of 2 events and their joint probability. And prints if the events are independent or not. Keyword arguments: prob_event1 -- probability...
def _get_filehash(filepath, hasher_factory, chunk_size, cache=None): """Compute the hash for given filepath. # Arguments filepath (str): Path to the file to hash. hasher_factory (f: f() -> hashlib._hashlib.HASH): Callable that returns an instance of the `hashlib._hashlib.HASH` inter...
def unique_list(l): """Remove duplicated from a list Args: l: A list Returns: The input list minus any duplicates """ return(list(dict.fromkeys(l)))
def get_account(item): """ return account from an item. Can be a string or a dict """ try: account = item['account'] # try value from dict except TypeError: account = item return account
def get_hex_color(layer_type): """ Determines the hex color for a layer. Some classes are given default values, all others are calculated pseudorandomly from their name. :parameters: - layer_type : string Class name of the layer :returns: - color : string containing ...
def dashed(guess): """ This function should block every word of 'guess'. :param guess: str :return: str, replace every words of 'guess' to '-'. """ new = '' for i in range(len(guess)): ch = guess[i] new +='-' return new
def checking_streak(coin_flips): """checking number of streaks of 6 in the random list""" streaks = 0 j = 0 for i, flip in enumerate(coin_flips): if j <= len(coin_flips) - 6: j += 1 #if opposite not in coin_flips[i : i+6]: if coin_flips[i : i+6].count('H') ==...
def solution(array): """ Determine whether a triangle can be built from a given set of edges. Time Complexity O(n*log(n)), because we sort the array. Space Complexity O(1). """ if len(array) > 2: array.sort() # assuming a, b, c as potential sides of a triangle, we sort the array so we can as...
def format(lines): """Format host lines""" return '\n'.join(["%s %s" % (line['code'], line['ip']) for line in lines])
def unique(list1): """ Function to remove not unique elements of a list Args: list1: List from where to obtain only unique values Returns: unique_list """ # intilize a null list unique_list = [] # traverse for all elements for i in list1: # check if exists in...
def create_label_vocab(input_data): """create label vocab from input data""" label_vocab = {} for sentence in input_data: labels = sentence.strip().split(' ') for label in labels: if label not in label_vocab: label_vocab[label] = 1 else: ...
def transform_params2tensors(inputs, lengths): """ Because DataParallel only splits Tensor-like parameters, we have to transform dict parameter into tensors and keeps the information for forward(). Args: inputs: dict. { "string1":{ 'word': wor...
def list2dict(lst): """Returns a dictionary for a list of results from compoundgenerator.""" return dict([[r[-1][0], r[0:-1]] for r in lst if r[0:-1]])
def checkStatements(value): """Check that statements list value property. Must not be None, must not contain None, and of course only statements, may be empty. """ assert value is not None assert None not in value for statement in value: assert ( statement.isStatement(...
def tupleit(lst: list) -> tuple: """Cast all lists in nested list to tuple.""" return tuple(map(tupleit, lst)) if isinstance(lst, list) else lst
def stable_uniq(L): """ Given an iterable L, remove duplicate items from L by keeping only the last occurrence of any item. The items must be hashable. EXAMPLES:: sage: from sage_setup.util import stable_uniq sage: stable_uniq( (1, 2, 3, 4, 5, 6, 3, 7, 5, 1, 5, 9) ) [2, 4,...
def binary(num): """Function to convert to Binary number of a Decimal number args: num: number in Decimal format to be converted in Binary format """ binary_str="" while num != 0: remainder = num % 2 num = num // 2 binary_str = str(remainder) + binary_...
def exe_cmd(_sock, cmd): """ execute command line :param _sock: socket fd :param cmd: command string :return: 0 success otherwise fail """ cmd = bytes(cmd + "\r\n", encoding="utf-8") try: _sock.send(cmd) except Exception as e: print("error occur", e) return -1...
def func_module1(password): """func_module1 Docstring""" if password != "bicycle": return None else: return "42"
def _expand_mappings(mappings, modifier, items): """ Expands mappings by replacing modifier with list of items in each case. """ result = {} for key, value in mappings.items(): lookup = "{" + modifier + "}" if lookup in key or lookup in value: for item in items: ...
def inconsistent_typical_range_stations(stations): """ This function checks takes in the list of stations and checks to make sure the typical range for each are consistent. Args: stations (list): List of stations (type MonitoringStation). Returns: list: List (type String) o...
def disappear_round_brackets(text: str) -> str: """ Remove round brackets and keep the text intact :param text: Text with round brackets. :return: Clean text. >>> disappear_round_brackets("trib(unus) mil(itum) leg(ionis) III") 'tribunus militum legionis III' """ text = text.replace("(",...
def minimum(a,b): """Elementwise min""" if hasattr(b,'__iter__'): return [min(ai,bi) for ai,bi in zip(a,b)] else: return [min(ai,b) for ai in a]
def prettify_agent_version(element): """Generate a processed string""" family = element['family'] major = ' %s' % element['major'] if element.get('major') else '' minor = '.%s' % element['minor'] if element.get('minor') else '' patch = '.%s' % element['patch'] if element.get('patch') else '' ret...
def notlike(matchlist: list, array: list, andop=False): """Returns a list of non-matches in the given array by excluding each object that contains one of the values in the matchlist parameter. Examples: >>> subdir_list = ['get_random.py', ... 'day6_15_payload-by-port.py', ... 'workshe...
def interpret_duration(duration_str): """Interpret a string describing the length of a podcast episode. Convert a string describing the length of a podcast episode (like "1:00") into an integer number of seconds (like 60). @param duration_str: The string encoding a duration to interpret. @type dur...
def filter_time(detail): """Web app, feed template, additional info: time""" time = detail['time'] datetime = '{} {}'.format(time['date'], time['time']) return datetime
def is_encrypted(password): """ Returns true if password string is encrypted. """ return password.startswith('{') and password.endswith('}')
def multiply(metrics, metric_name, multiplier): """Multiplies a metric by a constant value to get the points arguments: metrics -- metrics object metric_name -- the name of the metric for which points are being awarded multiplier -- How much to multiply the metric """ return dict([(user, in...
def flatten_dict(data, parent_key=None): """ This filter plugin will flatten a dict and its sublists into a single dict """ if not isinstance(data, dict): raise RuntimeError("flatten_dict failed, expects to flatten a dict") merged = dict() for key in data: if parent_key is not None...
def isNumeric(input): """Simple test for whether input is numeric or not.""" # 2015-03-19 21:36 IJMC: Created try: junk = input + 0 ret = True except: ret = False return ret
def skill_cleaner(data): """Data Cleaner for skills""" skills_cleaned = [] data = data.split(',') for element in data: element = element.title() element = element.strip() element = element.replace('Agile Methodologies', 'Agile') element = element.replace('Agile Project Ma...
def get_index(result_tuple): """Takes a tuple like (2.5, 0, 2.5, 0, 0) and makes it into (1,0,1,0,0), then converts the base two number 10100 into base ten -- 20.""" new = [] for x in result_tuple: if x == 0: new.append(0) else: new.append(1) new.reverse()...
def getKeys(dic): """ Recursively finds all nested keys for a given higher-level key in the category dictionary. Returns: List -- List of dictionary keys. """ localKeys = [] if isinstance(dic, list): for item in dic: localKeys = [*localKeys, *getKeys(item)] elif ...
def get_var_type(string: str) -> str: """Gets the type from an argument variable. Args: string: Input variable declaration Returns: The type of the argument variable as a string, e.g. "int x" -> "int". """ var = string.strip() # Unnamed variable if var in ("void", "...") or var[-1] == "*": ...
def add_to_round_two(str_to_add, round_two): """ This will add a string to the round_two array if it does not exist. It will then return the index of the string within the Array """ if str_to_add not in round_two: round_two.append(str_to_add) return round_two.index(str_to_add)
def reduce_range_overlaps(ranges): """Given a list with each element is a 2-tuple of min & max, returns a similar list simplified if possible. """ ranges = [ea for ea in ranges if ea] if len(ranges) < 2: return ranges first, *ranges_ordered = list(reversed(sorted(ranges, key=lambda ea: ea[1] - e...
def p1_f_linear(x): """DocTest module Expected Output Test - don't change or delete these lines >>> x = [565, 872, 711, 964, 340, 761, 2, 233, 562, 854] >>> print("The minimum is: ",p1_f_linear(x)) The minimum is: 2 """ # ******ENTER YOUR FINAL CHECKED CODE AFTER THIS COMMENT BLOCK***...
def evaluate_hasValue(fields): """ This function checks to see if every field in list fields has a length greater than 0. If every field has a length greater than 0, return True. If not, return False. """ return all(str(fields[field][0]) for field in fields)
def dist2sim(d): """ Converts cosine distance into cosine similarity. Parameters: d (int): Cosine distance. Returns: sim (list of tuples): Cosine similarity. """ return 1 - d / 2
def _join_file_parts(path: str, filename: str, ext: str) -> str: """Join together path components to the full path. Any of the segments can be blank, to skip them. """ return (path + '/' if path else '') + filename + ('.' + ext if ext else '')
def _positions(field): """Given an index into the puzzle (i.e. a single field, calculate and return a 3-tuple (row, column, box) of the units the field belongs to. """ row = field // 9 column = field % 9 box = (field // 3) % 3 + 3 * ((field // 9) // 3) return row, column, box
def fnv1a_32(string, seed=0): """ Returns: The FNV-1a (alternate) hash of a given string """ # Constants FNV_prime = 16777619 offset_basis = 2166136261 # FNV-1a Hash Function hash = offset_basis + seed for char in string: hash = hash ^ ord(char) hash = hash * FNV_pri...
def fdr(plist, alpha): """ Return the false discovery rate for the repeated-test p-values in plist, at significance level alpha. """ m = len(plist) plist = sorted(plist) for k in range(0, m): if (k+1) / float(m) * alpha >= plist[k]: return k
def qualify(name, prefix): """ Qualify a property name with the given prefix """ return "{prefix}:{name}".format(name=name, prefix=prefix)
def endpoint(host, port): """ Return the "host:port" string for the given host and port. """ return host + ":" + str(port)
def dna(sequence): """Finds complementary DNA sequence Arguments: sequence {String} -- A DNA sequence, e.g `ATTGC` Returns: [Stringe] -- Complementatry DNA sequence to given one """ dna = [] dictionary = {'A': 'T', 'T':'A', 'G': 'C', 'C': 'G'} for n in sequence: ...
def assert_at_least_one_succeeds(callbacks): """Invokes all callbacks and expects at least one to succeed.""" for callback in callbacks: try: callback() return True except Exception: # pylint: disable=broad-except pass raise Exception('All callbacks faile...
def primes_less_than(n): """Returns list of primes less than n. """ if n < 2: return [] ret = [2] i = 3 while True: while any(i % prime == 0 for prime in ret): i += 2 if i >= n: break ret.append(i) return ret
def import_string(import_name, silent=False): """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax...
def _get_int(p_str): """ Internal utility to convert 2 hex chars into a 1 byte int. a3 --> 163 """ l_int = 0 try: l_int = int(p_str, 16) except: l_int = 0 return l_int
def array_pyxll_function_1(x): """returns the sum of a range of floats""" total = 0.0 # x is a list of lists - iterate through the rows: for row in x: # each row is a list of floats for element in row: total += element return total
def tuple_add(tuple_a: tuple, tuple_b: tuple) -> tuple: """Return the result of the addition of two tuples.""" return tuple(map(lambda x, y: x + y, tuple_a, tuple_b)) # Source: https://stackoverflow.com/questions/497885/python-element-wise-tuple-operations-like-sum
def tags_to_string(tags, queryset=False): """ Args: tags: [{"name": "Demo"}, ...] OR [models.Tag] (if queryset=True) Returns: ['<tag.name', ...] """ if queryset: new_tags = [i.name for i in tags] else: new_tags = [i['name'] for i in tags] r...
def _parse_barcode_renamer(barcodes, barcode_renamer): """ :param barcodes: :param barcode_renamer: :return: """ if barcode_renamer is not None: renamer = {} with open(barcode_renamer) as f: for line in f.readlines(): barcode, renamed = line.split() ...
def url_basename(url, content_type): """Return best-guess basename from URL and content-type. >>> from django_downloadview.utils import url_basename If URL contains extension, it is kept as-is. >>> print(url_basename(u'/path/to/somefile.rst', 'text/plain')) somefile.rst """ return url.sp...
def getparticleeffects(schema): """Return a dictionary with each particle effect's id as key""" return {effect['id']: effect for effect in schema['result']['attribute_controlled_attached_particles']}
def _global_path_exp(path_exp): """ :param path_exp: JMESPath expression for search results :return: A JMESPath expression to search results >>> _global_path_exp("configs[?config=='system global']") "configs[?config=='global'] | [0].configs[?config=='system global']" """ return "configs[?co...
def get_precreated_dataset( precreated_datasets, name ): """ Return a dataset matching a name from the list of precreated (via async upload) datasets. If there's more than one upload with the exact same name, we need to pop one (the first) so it isn't chosen next time. """ names = [ d.name for d...
def adj_list_to_edges(adj_list): """ Transforms an adjacency list (represented as a dictiornary) in a set of edges For UNDIRECTED graphs, i.e. if v2 in adj_list[v1], then v1 in adj_list[v2] INPUT: - adj_list: a dictionary with the vertices as keys, each with a set of adjacent v...
def get_window_in_sec(s): """Returns number of seconds in a given duration or zero if it fails. Supported durations are seconds (s), minutes (m), hours (h), and days(d).""" seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400} try: return int(float(s[:-1])) * seconds_per_unit[s[-1]] ...
def flatten(lis): """Given a list, possibly nested to any level, return it flattened.""" new_lis = [] for item in lis: if type(item) == type([]): new_lis.extend(flatten(item)) else: new_lis.append(item) return new_lis
def process_position_info(task): """Process continuously sampled position related information.""" ... return task
def select_extensions(file_list, acceptable_extensions): """ Returns list of files with specified file extensions. Arguments: file_list: list of files to filter acceptable_extensions: list of extensions user wishes to keep Returns: List of files with specified ex...
def sum2(arr, NaN=False): """Return the sum of an array. If NaN==True, NaNs are ingnored and return the sum of the other elements""" if NaN: s=0 for a in arr: if a==a: s+=a else: s=sum(arr) return s
def sume(a): """ Function to sum all the elements of an array """ val = 0 for i in a: val += i return val
def write_csv(feature_vec, output_filename): """ Write the feature vector to a 1-line csv """ output_string = "" for feat in feature_vec: output_string += str(feat) + "," output_string = output_string[:-1] + "\n" with open(output_filename, "w") as outfile: outfile.write(outpu...
def my_decorated_function(name, value): # ...check_value(fix_name(negate_value(my_decorated_function))) """my original function.""" print("name:", name, "value:", value) return value
def correlation(row, edge): """ Suppression function that converts 'correlation' into 'strength' """ return row['correlation']
def get_nb_black_white_matches(given, guess, NUMBER_OF_CIRCLES): """ Return the number of black and white matches of the guessed combination with respect to the given combination. The first element in the resulting tuple reflects the number of correct colors on their positions (black matches). The s...
def _parse_env_value(val): """ Pars environment variables to bool, integer or float or default to string. :param val: :return: val coerced into a type if it looks to be of one """ if val.lower() == "false": return False elif val.lower() == "true": return True try: ...
def is_kind_of_class(obj, a_class): """True if obj is an instance or inherited from a_class, else False""" return (isinstance(obj, a_class))
def stripnull(string): """Return string truncated at first null character.""" i = string.find(b'\x00') return string if (i < 0) else string[:i]
def dict_to_tuple_list(thedict: dict): """Takes a Dictionary and converts the .items() into a list of tuples. Examples: >>> my_dict = {'item1': 'I am a raptor', 'item2': 'eat everything', 'item3': 'Till the appearance of man'} >>> my_dict.items()\n dict_items([('item1', 'I am a raptor'), ('item2', ...
def calculate_property_assignment_from_all_steps(child_assignments: list): """ Takes the assignment results from all child results and uses them to assign a result for the parent itself. This algorithm is used to assign results to a single step from child functional elements and for genome properties that ...
def check_should_do_early_stopping( record, freeze_es_at_first, es_tolerance, acc_like=True, verbose=False, ): """Check should do early stopping by the record. If the metric passed in is `acc_like`, which means "the larger the better", this method will find the index of the maximum, if there are `e...
def car_behind(opp): """ Returns True if there's a car behind ours """ return any([0 < 0 for o in [opp[0], opp[35]]])
def addList(l1, l2): """ :param list """ return [l1[i] + l2[i] for i in range(len(l1))]
def row_is_simple_header(row): """ Determine whether the row is a header row. The three cols must be "lane","sample" and "index", in order :type row: list[string] :rtype: bool """ return len(row) == 3 \ and row[0].lower() == 'lane' \ and row[1].lower() == 'sample' \ ...