content
stringlengths
42
6.51k
def check_not_finished_board(board: list): """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5',\ '*?????*', '*?????*', '*2*1***']) False >...
def percent(part, whole, need_per=True): """ Percent :param part: :param whole: :param need_per: :return: """ if need_per: per = '%' else: per = '' if part == 0 and whole == 0: return 0 return '{0}{1}'.format(100 * float(part) / float(whole), per)
def copy_list_setting(setting_name, package_control_settings, packagesmanager_settings, alternative=None): """ Makes sure that Package Control and PackagesManager have the same `setting_name`, as `installed_packages` to avoid PackagesManager uninstalling all packages after removing Package C...
def find_substring(substring, string): """ From stackoverflow... Returns list of indices where substring begins in string >>> find_substring('me', "The cat says meow, meow") [13, 19] """ indices = [] index = -1 # Begin at -1 so index + 1 is 0 while True: # Find next index o...
def question_is_nonarray(questions, question_id): """ Return whether the question exists and has no subquestions. """ if question_id not in questions: return False question = questions[question_id] if question[1] is not None or question[2] is not None: return False return Tru...
def show_navigator(context): """Show navigator""" page = context['page'] index_begin = context['index_begin'] index_end = context['index_end'] index_total = context['index_total'] mindex_begin = context['mindex_begin'] mindex_end = context['mindex_end'] return { 'page': page, ...
def worker_qualifies( units_completed: int, num_correct: int, num_incorrect: int, max_incorrect_golds: int ) -> bool: """ Return a bool of whether or not a worker is qualified to continue working on these tasks. """ # We could potentially use a scaling function on the proportion of incorrect golds ...
def get_vote_dict_from_table(vote_from_query): """ Returns a dict representation of a vote given a result from the table query :param vote_from_query: a signle result from a query to the votes table :return: dict representation of the vote """ result = dict( topic=vote_from_query["Topic"...
def skewed_heteroscedastic_mean(X): """Theoretical mean.""" mean = 4 * X * (1 - X) + X return mean
def remove_spades(hand): """Returns a hand with the Spades removed.""" spadeless_hand = hand [:] for card in hand: if "Spades" in card: spadeless_hand.remove(card) return spadeless_hand
def list_to_tuple(maybe_list): """Datasets will stack the list of tensor, so switch them to tuples.""" if isinstance(maybe_list, list): return tuple(maybe_list) return maybe_list
def UpdateDatabase(id_, images): """Update the database entries of the given asset with the given data.""" return {'status': True}
def three_partition(x): """partition a set of integers in 3 parts of same total value :param x: table of non negative values :returns: triplet of the integers encoding the sets, or None otherwise :complexity: :math:`O(2^{2n})` """ f = [0] * (1 << len(x)) for i, _ in enumerate(x): fo...
def create_response(code: int, body: str) -> dict: """ Creates a JSON response for HTTP. Args: code (int): The HTTP status code body (str): The HTTP body as a string Returns: (dict): JSON HTTP response """ return { 'headers': { 'Content-Type'...
def is_ratelimit(tweet): """ Returns True if the "tweet" is a rate-limit response. If False, then it should be an actual tweet. """ if isinstance(tweet, dict): # The tweet is a Python dictionary if 'limit' in tweet and 'track' in tweet['limit']: return True else...
def add_single(arr, val): """ Return sum of array and scalar. """ return [i + val for i in arr]
def _None(value): """ None """ return value == None or value == "None"
def longest_common_substring(data): """ Return a longest common substring of a list of strings: >>> longest_common_substring(["apricot", "rice", "cricket"]) 'ric' >>> longest_common_substring(["apricot", "banana"]) 'a' >>> longest_common_substring(["foo", "bar", "baz"]) ...
def _hex_to_rgb(_hex): """ Convert hex color code to RGB tuple Args: hex (str): Hex color string, e.g '#ff12ff' or 'ff12ff' Returns: (rgb): tuple i.e (123, 200, 155) or None """ try: if '#' in _hex: _hex = _hex.replace('#', "").strip() if len(_hex) != 6: ...
def evapfr( r_net, g0, h0 ): """ calculates the evaporative fraction after bastiaanssen (1995). It takes input of Net Radiation (see r.sun,r.eb.netrad), soil heat flux (see r.eb.g0) and sensible heat flux (see r.eb.h0). evaporative fraction evapfr( r_net, g0, h0 ) """ result = (r_net - g0 - h0) / (r_net - g0) ...
def is_sorted(t): """Checks whether a list is sorted. t: list returns: boolean """ return t == sorted(t)
def is_empty(x): """Check if empty""" if isinstance(x, bool): return False try: return not bool(x) except Exception: return False
def getDateIter(sysCode): """Return a list of dates given a coordinate system code """ if sysCode > 0: # mean dateList = (1960, 2010) elif sysCode == -1: dateList = (0, 1960) else: # apparent topocentric or focal plane; 0 is the only reasonable choice dateList...
def header_format(morsels): """Convert list of morsels to a header string.""" return '; '.join(f'{m["name"]}={m["value"]}' for m in morsels)
def count_lines_in_file(filename): """ returns the number of lines in a file. works for an empty file as well. if file does not exists, returns None. """ try: num_lines = sum(1 for line in open(filename)) return num_lines except: return None
def check_interval(child_span, parent_span): """ Given a child span and a parent span, check if the child is inside the parent """ child_start, child_end = child_span parent_start, parent_end = parent_span if ( (child_start >= parent_start) &(child_end <= parent_end) ): ...
def cell(d0, d1): """The purpose of this function is unknown.""" if d1 == 1: return [None for _ in range(d0)] else: return [[None for _ in range(d1)] for _ in range(d0)]
def compute_edit_distance(w1: str, w2: str) -> int: """ Determine the edit distances between w1 and w2, trying to turn w1 into w2. This is a very brute force approach, as shown by the length required for the last case. >>> compute_edit_distance('a', 'b') 1 >>> compute_edit_distance('aa', 'b') ...
def is_datecode(stamp): """ This function will return True or False, depending if the supplied stamp can be interpreted as a date-code string of the format YYWWD """ if type(stamp) == str: if len(stamp) == 5: year = stamp[0:2] if not year.isdigit(): re...
def _py_expand_long(subsequence, sequence, max_l_dist): """Partial match expansion, optimized for long sub-sequences.""" # The additional optimization in this version is to limit the part of # the sub-sequence inspected for each sequence character. The start and # end of the iteration are limited to th...
def is_corrupt(line): """ >>> is_corrupt('([])') (False, []) >>> is_corrupt('{()()()}') (False, []) >>> is_corrupt('<([{}])>') (False, []) >>> is_corrupt('[<>({}){}[([])<>]]') (False, []) >>> is_corrupt('(((((((((())))))))))') (False, []) >>> is_corrupt('{([(<{}[<>[]}>{[]...
def MAX(strArg, composList, atomDict): """ *Calculator Method* calculates the maximum value of a descriptor across a composition **Arguments** - strArg: the arguments in string form - compos: the composition vector - atomDict: the atomic dictionary **Returns** a float """...
def is_wrapped_method(fn): """ Checks if fn is a wrapped method/ function :param func fn: :return: """ import inspect return '__wrapped__' in fn.__dict__ and \ inspect.ismethod(fn.__dict__['__wrapped__'])
def seamCarvingCheck(op, graph, frm, to): """ :param op: :param graph: :param frm: :param to: :return: @type op: Operation @type graph: ImageGraph @type frm: str @type to: str """ #change = g...
def __recall(prediction, expectation): """ prediction: list of cut at-k pmid each element should be a tuple (pmid,score) or (pmid) expectation: list of valid pmid return recall value """ # solve the indetermination but THIS IS STUPID ITS A DATASET ERROR if len(expectation) == 0: re...
def _and (*args): """Helper function to return its parameters and-ed together and bracketed, ready for a SQL statement. eg, _and ("x=1", "y=2") => "(x=1 AND y=2)" """ return " AND ".join (args)
def stripAndRemoveNewlines(text): """Removes empty newlines, and removes leading whitespace. """ no_empty_newlines = "\n".join([ll.rstrip() for ll in text.splitlines() if ll.strip()]) return no_empty_newlines.strip()
def fold_change(c, RK, KdA=0.017, KdI=0.002, Kswitch=5.8): """calculate fold change from iptg conc, RK, and optional parameter args""" numer = RK * (1+(c/KdA))**2 denom = (1+(c/KdA))**2 + Kswitch * (1 + (c/KdI))**2 fc = (1 + (numer/denom))**-1 return fc
def dict2tabular(items, fieldorder=None): """Converts a dict of dicts to a list of lists.""" if not fieldorder: fieldorder = [] allfieldnames = set() for item in list(items.values()): allfieldnames.update(list(item.keys())) for fielname in fieldorder: allfieldnames.remove(fie...
def validateCPE(cpe): """ Returns None if CPE text is valid, validation error string otherwise. """ if not cpe.startswith("cpe:"): return 'CPE must start with "cpe:"' return None
def average(n): """ Average some values :param n: :return: """ total = 0 for i in n: total += i return float(total) / float(len(n))
def extract_list (data_str, to_float=False): """ Extract a list of floating point values from a string """ split_str = data_str.split(',') if to_float == True: split_str = [float(x) for x in split_str] return split_str
def _int_arg(s): """Convert a string argument to an integer for use in a template function. May raise a ValueError. """ return int(s.strip())
def price_i(state: dict, i: int, fee: float = 0) -> float: """Price of i denominated in HDX""" if state['R'][i] == 0: return 0 else: return (state['Q'][i] / state['R'][i]) * (1 - fee)
def fact_memoization(ar, n): """ Top down aproach https://www.geeksforgeeks.org/tabulation-vs-memoization/ """ if n == 0: return 1 if ar[n] is not None: return ar[n] else: print("call---" + str(n)) ar[n] = n * fact_memoization(ar, n - 1) return ar[n]
def strip_leading_trailing_punctuation(word): """ Remove any leading of trailing punctuation (non-alphanumeric characters """ start_index = 0 end_index = len(word) while start_index < len(word) and not word[start_index].isalnum(): start_index +=1 while end_index > 0 and not word[end_inde...
def all_in_any(a, b): """return true if every item of 'a' is found inside 'b' else return false """ if len([x for x in a if x in b]) == len(a): return True else: return False
def get_resource_dict(package_id, resource_id, acl_xml): """ Derives a resource_dict dictionary from the supplied package ID, resource ID, and access control XML values """ resource_dict = {"package_id" : package_id, "resource_id" : resource_id, "acl_xml" : ...
def get_install_cmd(click_name): """Returns cmd string to run clickable from a Seabass Libertine container""" return 'bash -c "pkcon install-local --allow-untrusted $(find -name {})"'\ .format(click_name)
def list_extract(items, arg): """Extract items from a list of containers Uses Django template lookup rules: tries list index / dict key lookup first, then tries to getattr. If the result is callable, calls with no arguments and uses the return value.. Usage: {{ list_of_lists|list_extract:1 }} (get...
def rgb_2_plt_tuple(r, g, b): """converts a standard rgb set from a 0-255 range to 0-1""" plt_tuple = tuple([x/255 for x in (r, g, b)]) return plt_tuple
def getDirName(filepath: str) -> str: """e:/test/file.txt --> e:/test/""" filepath = filepath.replace('\\', '/') index = filepath.rfind('/') if index < 0: return './' return filepath[0:index + 1]
def _ceildiv(x, y): """Rounds `x/y` to next largest integer.""" return -int(-x // y)
def is_empty(s: str) -> bool: """ Returns True if the string is equal to the empty string (''), True otherwise. Obviously this function is quite trivial. The point of having it is to allow us to profile for this criterion along with all the other criteria. See package notes for a more detailed ...
def boolean_converter(input_str): """ a conversion function for boolean """ return input_str.lower() in ("true", "t", "1", "y", "yes")
def get_et_dist(ph,w,m,marray,varray): """ Obtain the et distribution of a phase INPUT --------------------- 1. current phase (ph) (At this point it is assumed to be independent of phases) 2. workload (w) 3. number of cores (m) OUTPUT -------...
def ordered(obj): """ A function for comparing json objects """ if isinstance(obj, dict): return sorted((k, ordered(v)) for k, v in obj.items()) elif isinstance(obj, list): return sorted(ordered(x) for x in obj) else: return obj
def arg2bool(val): """Convert an argument to boolean. Parameters ---------- val : str or bool or None original value Returns ------- bool converted value """ if val is None: return False if isinstance(val, bool): return val val = val.lower() ...
def yubikey_get_yubikey_id(yubikey_otp): """ Returns the yubikey id based :param yubikey_otp: Yubikey OTP :type yubikey_otp: str :return: Yubikey ID :rtype: str """ yubikey_otp = str(yubikey_otp).strip() return yubikey_otp[:12]
def _ensure_forecast_reference_compatibility( forecast, reference_forecast, forecast_type): """Checks for compatibility between a forecast and reference forecast. Criteria: * Same variable * Same interval length * Same interval label * Made for the same site/aggregate * For probabil...
def fib(n): """ Get the nth Fibonacci number """ if n == 1 or n == 2: return 1 fib_n_1 = fib(n-1) fib_n_2 = fib(n-2) return fib(n-1) + fib(n-2)
def hate_word_occ(ordered_bow, hate_grams): """Number of hate grams in the given bag-of-words. """ score = 0 ordered_bow = list(ordered_bow) bow_counted = {gram: ordered_bow.count(gram) for gram in ordered_bow} for term in hate_grams: token = bow_counted.get(term) score += token if token != None els...
def invert_polarity(polarity, type=None): """It inverts or do a complement of the polarity""" if type == 'complement': if polarity < 0: return -(1.0 - abs(polarity)) else: return 1.0 - polarity return -1.0 * polarity
def convertToFloat(seq): """Convert a sequence with strings to floats, honoring 'Nones'""" if seq is None: return None res = [None if s in ('None', 'none') else float(s) for s in seq] return res
def list_to_hash(lst): """Convert a flat list of key value pairs to a hash""" return {lst[i]: lst[i+1] for i in range(0, len(lst), 2)};
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): """Converts an integer to a base36 string.""" """https://stackoverflow.com/questions/1181919/python-base-36-encoding""" if not isinstance(number, (int)): raise TypeError('number must be an integer') base36 = '' sign ...
def conjugate1(infinitive): """ >>> conjugate1('kalla') ('kall', ('kalla', 'kallar', 'kallade', 'kallat')) """ stem = infinitive[:-1] present = stem + "ar" preterite = stem + "ade" supine = stem + "at" return stem, (infinitive, present, preterite, supine)
def sum_factorial_digits(x): """ Returns the sum of the factorials of the digits of x """ factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] sum_factorial_digits_ = 0 for i in str(x): sum_factorial_digits_ += factorials[int(i)] return(sum_factorial_digits_)
def profile_last_step(value): """0 - 99""" return {'step':value}
def is_blank(string): """Checks if string is either empty or just whitespace.""" if not string or string.isspace(): return True return False
def index_url(year): """ Generate url of the index file for future downloading. year - > the year to download Returns: url link of the index file """ quarters = ['QTR1', 'QTR2', 'QTR3', 'QTR4'] return [f'https://www.sec.gov/Archives/edgar/full-index/{year}/{q}/master.idx' for q in quarte...
def odd_quadratic_sum(n: int) -> int: """calculate the quadratic num of odd from 1 ~ n""" return sum(n ** 2 for n in range(1, n + 1) if n % 2 == 1)
def get_detector_by_channel(config): """Return a channel -> detector lookup dictionary from a configuration""" detector_by_channel = {} for name, chs in config['channels_in_detector'].items(): for ch in chs: detector_by_channel[ch] = name return detector_by_channel
def full_class_name(o: object): """Returns the fully qualified class name of the given object. Taken from MB's answer: https://stackoverflow.com/a/13653312 """ module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ return modu...
def crop_border(img_list, crop_border): """Crop borders of images Args: img_list (list [Numpy]): HWC crop_border (int): crop border for each end of height and weight Returns: (list [Numpy]): cropped image list """ if crop_border == 0: return img_list else: ...
def human_readable(bytes): """ Return a human-readable representation of the provided number of bytes. """ for n, label in enumerate(['bytes', 'KiB', 'MiB', 'GiB', 'TiB']): value = bytes / (1024 ** n) if value < 1024: return f'{round(value, 2)} {label}' else: ...
def style_attrs_to_sets(styles): """Convert the style attributes 'combination', 'exclude', 'include' and 'require' from string to a set. styles: Style dictionary returns: Style dictionary with modified attributes""" for style_name in styles.keys(): for attr in ['combination', 'exclude', 'inclu...
def homogeneous_value(lst): """If this list contains just a single value, return it.""" assert isinstance(lst[0], str) for item in lst[1:]: if item != lst[0]: return None return lst[0]
def compute_label(results): """ Counts the number of 0's in a list of results, if it is greater than then number of 1's, output label = 0, else output label = 1 """ new_result = list(results) num_zeros = new_result.count([0]) num_ones = new_result.count([1]) if num_zeros >= nu...
def string_safe_list(obj): """ Turn an (iterable) object into a list. If it is a string or not iterable, put the whole object into a list of length 1. :param obj: :return list: """ if isinstance(obj, str) or not hasattr(obj, "__iter__"): return [obj] else: return list(ob...
def gmt(line): """parse a gmt line into id, name, gene symbols""" result = line[:-1].split("\t") return result[0], result[1], result[2:]
def ungzip(data): """Decompresses data for Content-Encoding: gzip. """ from io import BytesIO import gzip buffer = BytesIO(data) f = gzip.GzipFile(fileobj=buffer) return f.read()
def fairness_metrics_goal_threshold(metric): """Returns metric goal and threshold values. Parameters ---------- metric: str The name of the metric Returns ------- int: goal value float: threshold (+ and -) of the metric """ metrics_goal_1 = [ 'di...
def formalize_fmt_string(fmt_str): """Replace unsupported formatter""" new_str = fmt_str # Python doesn't support %lld or %llu so need to remove extra 'l' new_str = new_str.replace("%lld", "%ld") new_str = new_str.replace("%llu", "%lu") # No %p for pointer either, so use %x new_str = new_s...
def hasattr(object,attribute): """Does a property of an object exists? attribute: e.g. 'value' or 'member.value'""" try: eval("object."+attribute); return True except: return False
def filt_by_domain(domain, value): """ filt the url by domain name """ if domain in value: return True else: return False
def _get_metadata(item): """ Include popularity statistics. """ extras = ["downloads_raw", "page_views_raw", "favorites_raw"] metadata = {} for key in extras: value = item.get(key) if value is not None: metadata[key] = value return metadata
def factorization(integer): """ returns a list with prime factors """ if type(integer) != int: raise TypeError("param @integer should be int.") prime_factors = [] while integer % 2 == 0: prime_factors.append(2) integer //= 2 divisor = 3 while divisor * divisor <= intege...
def hms2decimal(RAString, delimiter): """Converts a delimited string of Hours:Minutes:Seconds format into decimal degrees. @type RAString: string @param RAString: coordinate string in H:M:S format @type delimiter: string @param delimiter: delimiter character in RAString @rtype: float @r...
def merge_color(rate): """Return pyplot color for merge rate.""" if rate < 15: return 'r' if rate < 30: return 'y' return 'g'
def remove_commented_lines(text): """Removes the commented lines""" lines = text.split('\n') cleaned_text = "\n".join([l for l in lines if not l.startswith('#')]) print(f"Cleaned text is {cleaned_text}") return cleaned_text
def get_position_from_periods(iteration, cumulative_periods): """Get the position from a period list. It will return the index of the right-closest number in the period list. For example, the cumulative_periods = [100, 200, 300, 400], if iteration == 50, return 0; if iteration == 210, return 2; ...
def to_domain(domain: str) -> str: """formats domain as Netscape cookie format spec""" if not domain.startswith("."): # if domain starts with www if len(domain.split(".")) > 2: # prepend . and join anything after domain = "." + ".".join(domain.split(".")[-2:]) els...
def get_games_from_userid(owned, userid): """ From the name we will get the games bought by this person """ games = [] for d in owned: n = d['User_id'] if n == userid: games.append(d['Game_id']) return games
def get_pi_k(k): """ Returns the length of Pi_k """ if k == 0: return 1 return 2*(3**(k-1))
def safe_abs(val): """ Safely calculates the absolute value of a value. If the value is -1 (unknown), then the result is -1 (unknown). """ return -1 if val == -1 else abs(val)
def merge(list1,list2): """ Takes two lists and merge them in a sorted list """ # Initialie the empty list result=[] i=0 j=0 # This loop runs till both input lists have non-zero elements in them # That means this loop stops when either of the input list runs out of element while ...
def accuracy(labels, predictions): """Computes the accuracy of the model's predictions against the true labels. Args: - labels (list(int)): True labels (1/-1 for the ordered/disordered phases) - predictions (list(int)): Model predictions (1/-1 for the ordered/disordered phases) Returns: ...
def total_gross_income(responses, derived): """ Return the total gross income of both claimants """ try: claimant_1 = float(responses.get('annual_gross_income', 0)) except ValueError: claimant_1 = 0 try: claimant_2 = float(responses.get('spouse_annual_gross_income', 0)) exc...
def expand_loop(start, step, length): """A convenience function. Given a loop's start, step size, and length, returns the loop values. The opposite of deconstruct_loop().""" return [start + (step * i) for i in range(length)]