content
stringlengths
42
6.51k
def yesno(value, answers='yes,no,maybe'): """Output a text based on Falsyness, Trueyness and ``is None``. Example:: {{ value|yesno:"yeah,nope,maybe" }}. """ bits = answers.split(',') if len(bits) == 3: vyes, vno, vmaybe = bits elif len(bits) == 2: vyes, vno, vmaybe = bit...
def _map_theme(theme): """ Maps a survey schema theme to a design system theme :param theme: A schema defined theme :returns: A design system theme """ if theme and theme not in ["census", "census-nisra"]: return "main" return "census"
def is_music(f): """ returns if path, f, is a music file """ music_exts = ['3gp','aa','aac','aax','act','aiff','alac','amr','ape','au','awb','dct','dss','dsd','dsf','dvf','flac','gsm','iklax','ivs','m4a','m4b','m4p','mmf','mp3','mpc','msv','nmf','ogg,','opus','ra,','raw','rf64','sln','tta','voc','vox','...
def normalize(value): """Normalize an expanded JSON-LD.""" if isinstance(value, list): if len(value) == 1 and isinstance(value[0], dict) and "@value" in value[0]: return value[0]["@value"] return [normalize(v) for v in value] if isinstance(value, dict): if "@value" in va...
def simplify(n): """Remove decimal places.""" return int(round(n))
def merge(user, default): """Merge 2 data structures.""" for key, val in default.items(): if key not in user: user[key] = val else: if isinstance(user[key], dict) and isinstance(val, dict): user[key] = merge(user[key], val) elif isinstance(use...
def edge_weight_name(u, v) -> str: """Attr name when looking for edge weight between nodes `u` and `v`.""" return f"rate_{u}2{v}"
def tag_not(*tag_nots): """Select a (list of) tag_not(s).""" vtag_not = [t for t in tag_nots] return {"tag_not": vtag_not}
def merge_dict(dict1, dict2): """ Merges dict2 into dict1.""" if dict1 is None: dict1 = {} if dict2 is None: dict2 = {} result = dict1.copy() for key in dict2: result[key] = dict2[key] return result
def humanbytes(size): """Input size in bytes, outputs in a human readable format""" # https://stackoverflow.com/a/49361727/4723940 if not size: return "" # 2 ** 10 = 1024 power = 2 ** 10 raised_to_pow = 0 dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} wh...
def send_data(data, conn): """ Simplify sending information to client or disconnect the client if requested """ try: if data == "!!!DISCONNECT_CLIENT!!!": return data else: if data is not None: conn.send((data +"\n").encode()) retur...
def bigger_price(limit: int, data: list) -> list: """ TOP most expensive goods """ # your code here x = sorted(data, key=lambda x: -x['price'])[:limit] return x
def this_leibniz_term(term_index): """ Calculates a single term in the version of the Gregory-Leibniz series for calculating Pi from Pi/4. Note that this particular method is conceptually very simple, but converges very slowly. See README.md for more discussion. """ return (4.0/(term_index*...
def hamming_distance(a, b): """ Counts number of nonequal matched elements in two iterables """ return sum([int(i != j) for i, j in zip(a, b)])
def eos2period(word): """ Changing all the '<eos>' for '.' :type word: str :rtype: str """ if word == '<eos>': return '.' else: return word
def _is_ssl_on_directive(entry): """Checks if an nginx parsed entry is an 'ssl on' directive. :param list entry: the parsed entry :returns: Whether it's an 'ssl on' directive :rtype: bool """ return (isinstance(entry, list) and len(entry) == 2 and entry[0] == 'ssl' and ...
def convert_string_to_none_or_float(string): """Converts string to None or float. Args: string: str, string to convert. Returns: None or float conversion of string. """ return None if string.lower() == "none" else float(string)
def changer(x): """For bad unicode in Windows""" if not isinstance(x, (float, int)): return float(''.join([i for i in x if i.isdigit() or i == '.'])) return x
def strip_server(path): """ Removes the server part from xrdfs output. Example input: root://polgrid4.in2p3.fr:1094//dpm/in2p3.fr/home/cms/trivcat/store/user/rembserj Output: /dpm/in2p3.fr/home/cms/trivcat/store/user/rembserj Note: Returns None if the input does not match the ...
def rand_string(length: int = 16) -> str: """ Utility function for generating a random alphanumeric string of specified length :param length: length of the generated string :return: random string """ import random, string return ''.join([random.choice(string.ascii_letters + string.digits) ...
def _merge_low_pivot_high(low, pivotitem, high): """ merge three parts """ result = list() result.extend(low) result.append(pivotitem) result.extend(high) return result
def get_username(request): """Returns the username from request.""" # Retrieve the username either from a cookie (when logging out) or # the authenticated user. username = "not-login" if hasattr(request, "user"): username = request.user.username if request.session.get('staff', False)...
def remove_empty_lists(the_list): """Remove empty lists removes any [] empty lists from a list of lists.""" newlist = [] # Loop over elements in list for i in the_list: # Is element a non-empty list? then call self on it. if isinstance(i, list) and i: newlist.append(remove_em...
def reverse(x): """ :type x: int :rtype: int """ result = 0 while x != 0: temp = result * 10 + x % 10 print('temp is ' + str(temp)) print(str(temp / 10)) if temp // 10 != result: print("return") return 0 x //= 10 print(x) ...
def apply_kwargs(func, kwargs): """Wrapper for unpacking keyword function calls. Args: func (function): the function to be applied. kwargs (dict): the keywords and arguments for the function call. """ return func(**kwargs)
def persian_date(year, month, day): """Return a Persian date data structure.""" return [year, month, day]
def item_replace(input_str): """ This function accepts a string as input Removes the comma in the string and replaces it with nothing """ input_str = str(input_str) return int(input_str.replace(",", ""))
def map_range(old_min, old_max, new_min, new_max, value): """Maps a given value from the initial (first) range to a another (second) range. :param old_min: minimum of first range :type old_min: float :param old_max: maximum of first range :type old_max: float :param new_min: minimum of second r...
def isgenerictype(t): """Returns `True` if `t` is a generic type. WARNING: This is very "hackish". Caller must make sure that `t` actually is a type!""" return str(t).endswith(']')
def cubo_oct_coord_test(x, y, z): # dist2 = 2 """Test for coordinate in octahedron/cuboctahedron grid""" return (x % 2 + y % 2 + z % 2) == 2
def subND(v1, v2): """Subtracts two nD vectors together, itemwise""" return [vv1 - vv2 for vv1, vv2 in zip(v1, v2)]
def fib_whl(n): """ Compute Fibonnaci sequence using a while loop Parameters ---------- n : integer the nth Fibonnaci number in the sequence Returns ------- the nth Fibonnaci number in the sequence """ res = [0, 1] i = 0 while i<n: res.append(res[i] + r...
def split_zoom_time(timestamp): """ split the hh:mm:ss.sss zoom timestamps to seconds + ms used to calculate start and end of acoustic features """ h, m, s = timestamp.split(":") return (float(h) * 60 + float(m)) * 60 + float(s)
def begin(path): """ Open the path file and start writing a solution in it. """ global latex_file latex_file = open(path, "wt") if not latex_file: return False latex_file.write("\\begin{figure}\n") return True
def get_value(value: str) -> str: """Get the value of a given configuration line.""" return (value .split("=")[1] .strip() .replace("'", "") .replace('"', ""))
def vec_bin(v, nbins, f, init=0): """ Accumulate elements of a vector into bins Parameters ---------- v: list[] A vector of scalar values nbins: int The number of bins (accumulators) that will be returned as a list. f: callable A function f(v)->[bo,...,bn] that maps ...
def sanitize(line): """Sanitize a line.""" line = line.replace(',', '.') return line
def vhdl_package_header(name): """ Return a string with the header for a VHDL package. """ return "package {} is\n".format(name)
def standard_security_test_provider(status_ok, status_error): """ Provides the project test data for the security tests :param status_ok: expected status code when the request is allowed :param status_error: expected status code when the request is prohibited :return: list of possible arguments for...
def _get_timeout(value): """ Turn an input str or int into a float timeout value. :param value: the input str or int :type value: str or int :raises ValueError: :returns: float """ maximum_dbus_timeout_ms = 1073741823 # Ensure the input str is not a float if isinstance(value, ...
def _splitaddr(addr): """ splits address into character and decimal :param addr: :return: """ col='';rown=0 for i in range(len(addr)): if addr[i].isdigit(): col = addr[:i] rown = int(addr[i:]) break elif i==len(addr)-1: col=addr...
def int2bytes(n): """Integer to variable length big endian.""" if n == 0: return '\x00' b = '' while n: b = chr(n % 256) + b n /= 256 return b
def _build_projection_expression(clean_table_keys): """Given cleaned up keys, this will return a projection expression for the dynamodb lookup. Args: clean_table_keys (dict): keys without the data types attached Returns: str: A projection expression for the dynamodb lookup. """ ...
def collect(listing, item): """ add item to listing :param listing: :param item: :return listing: """ listing.extend(item) return listing
def __is_dunder__(name: str) -> bool: """ Function to check if item is a dunder item (starting and ending with double underscores) :param name: Name of the item :return: Boolean depicting if object is dunder or not """ return (len(name) > 5) and (name[:2] == name[-2:] == '__') and name[2] != "_...
def is_ascii(self, txt): """Returns True if string consists of ASCII characters only, False otherwise """ try: txt.encode('utf-8').decode('ASCII') except UnicodeDecodeError: return False return True
def format_movie_certification(pick_certification): """ Ensures the Movie Certification is properly formatted (parameter is the inputted Movie Certification) """ if bool(pick_certification) == True: movie_certification= str(pick_certification) else: movie_certification = None ret...
def nullstr(value): """ Return str(value) if bool(value) is not False. Return None otherwise. Useful for coercing optional values to a string. >>> nullstr(10) '10' >>> nullstr('') is None True """ if value: return str(value)
def xprod(xs1, xs2): """Creates a new list out of the two supplied by creating each possible pair from the lists""" return [[x, y] for y in xs2 for x in xs1]
def get_url(route, base_url="{{base_Url}}"): """Adds base_url environment variable to url prefix.""" url = base_url + route return url
def cleanup_time_string(t): """ convert from microseconds to seconds, and only output 3 s.f. """ time_in_seconds = float(t) / 1e6 if time_in_seconds < 1: time_in_seconds = round(time_in_seconds, 5) else: time_in_seconds = int(time_in_seconds) timestring = str(time_in_seconds...
def data_conformation(data): """Conform the data before the API call in order to transform all dictionnary, which represent entity like an id. :param data: The data to conform :type data: dict """ for key, values in data.items(): if isinstance(values, dict): _id = values.get...
def validate_json(data: dict) -> bool: """Helper function to validate json messages that come into the satellite or will be sent out of the satellite""" try: assert "data" in data.keys() assert isinstance(data["data"], str) assert "command" in data.keys() assert isinstance(da...
def sort_dict_by_value(d): """ Returns the keys of dictionary d sorted by their values """ items=list(d.items()) backitems=[[v[1],v[0]] for v in items] backitems.sort() return [backitems[i][1] for i in range(0, len(backitems))]
def pathLookup(ccd, camera, sector): """ Gets the datestring and the subdirectory for the specified PRF. The datestring and directory name can be found from the ccd, camera and sector. Inputs ------- ccd (int) number of the TESS ccd. Accepts values from 1-4. camera (int) num...
def return_one_percent(num, pop_size): """ Returns either one percent of the population size or a given number, whichever is larger. :param num: A given number of individuals (NOT a desired percentage of the population). :param pop_size: A given population size. :return: either one ...
def int_bytes_to_programmatic_units(byte_value): """Convert a byte count into OVF-style bytes + multiplier. Inverse operation of :func:`programmatic_bytes_to_int` Args: byte_value (int): Number of bytes Returns: tuple: ``(base_value, programmatic_units)`` Examples: :: ...
def time_slot(hour): """ Receives an hour as parameter Divides the day in 6 times 4 hour slots Returns the 4 hour time slot in which the given hour belongs to """ slot = list(range(0, 28, 4)) for i in range(len(slot)-1): if hour <= slot[i+1]: return (slot[i], slot[i+1])
def __remap_path_distances(temporal_distances): """ Mapping shortest paths temporal distances in hop distances :param temporal_distances: a dictionary of <node_id, reach_time> :return: a dictionary <node_id, hop_distance> """ res = {} tids = sorted(set(temporal_distances.values())) tids...
def is_builtins(obj): """Does obj seem to be the builtins?""" if hasattr(obj, 'open') and hasattr(obj, '__import__'): return True elif isinstance(obj, dict): return 'open' in obj and '__import__' in obj return False
def _FindSubjectPrefix(subject): """If the given subject starts with a prefix, return that prefix.""" for prefix in ['re:', 'aw:', 'fwd:', 'fw:']: if subject.lower().startswith(prefix): return prefix return None
def join_list(list, separator, endseparator) -> str: """Joins elements in a list with a separator between all elements and a different separator for the last element.""" size = len(list) if size == 0: return "" if size == 1: return list[0] return separator.join(list[:size - 1]) + end...
def time_from_msdos_time(data, timezone): """ Convert from MSDOS timestamp to time string """ hour = (data & 0xf800) >> 11 minute = (data & 0x7e0) >> 5 second = 2 * (data & 0x1f) return "%02d:%02d:%02d (MSDOS date/time, %s)" % (hour, minute, second, timezone)
def is_int(v): """ raise error if not """ try: int(v) return True except ValueError: return False
def result_is_empty(result): """Return True/False if there are no results.""" for trick in result: if trick != "url_encoded": if result[trick]: return False return True
def enc(x, codec='ascii'): """Encodes a string for SGML/XML/HTML""" x = x.replace('&', '&amp;').replace('>', '&gt;').replace('<', '&lt;').replace('"', '&quot;') return x.encode(codec, 'xmlcharrefreplace')
def grab_impression(txt): """ grab impression from text via looking for IMPRESSION: """ try: return txt[txt.index("IMPRESSION:"):].split("IMPRESSION:")[1] except Exception as error: print(error) return ""
def calculate_transaction_revenue(trade_volume, last_price, brokerage_fee): """Calculates transaction revenue Parameters: trade_volume (float): the amount of stocks that the user wants to sell last_price (float): the last price of the stock brokerage_fee (float): price of the transactio...
def transform_url(private_urls): """ Transforms URL returned by removing the public/ (name of the local folder with all hugo html files) into "real" documentation links for Algolia :param private_urls: Array of file links in public/ to transform into doc links. :return new_private_urls: A list of do...
def climb_stairs_final(n: int) -> int: """Optimize Space complexity""" if n == 1: return 1 elif n == 2: return 2 else: pre_n1, pre_n2 = 1, 2 for i in range(3, n+1): pre_n1, pre_n2 = pre_n2, pre_n1 + pre_n2 return pre_n2
def is_fits_file (s) : """ Tests filenames for .fits or .fit suffix. If the string contains a '*' then it is assumed to be a pattern. """ forms = ['.fits','.fit','.fits.gz','.fit.gz'] if isinstance(s,str) : if '*' in s : return False ss = s.lower() for f in forms : if ss.endswith(f) : return True else :...
def get_most_read_or_features( amb_sams: list, counts: dict) -> list: """ Get the samples that have the most counts (reads of features). Parameters ---------- amb_sams : list Sample IDs. counts : dict Count per Sample ID. Returns ------- cur_best...
def get_info(include, img_ids, num_included, num_ignored, num_occluded): """Get statistics about the current dataset. Parameters ---------- include : set of str Set of strs that represent which fitzpatrick scale categories to include. img_ids : list A sor...
def get_chain_ids_and_names(chains, ligands, waters): """Takes lists of chains, ligands and waters, and returns the chain IDs and chain names that should go in the .mmtf file. :param list chains: the chains to pack. :param list ligands: the ligands to pack. :param list waters: the waters to pack. ...
def handled_float(value, default=0): """ Returns ``float(value)`` if value is parseable by ``float()``. Otherwise returns ``default``. """ ret_val = default try: ret_val = float(value) except (TypeError, ValueError): pass return ret_val
def write_file(filename="", text=""): """write a string in a file""" with open(filename, "w") as my_file: nb_char = my_file.write(str(text)) my_file.close() return (nb_char)
def to_bool(bool_str): """Convert a string to bool. """ return True if bool_str.lower() == 'true' else False
def broadcast_gradient_args(x, y): """ Return the reduction indices for computing gradients of x op y with broadcast. Args: x (Union[list, tuple]): the shape of data input y (Union[list, tuple]): the shape of data input Returns: rx (list): the reduction indices for computing gr...
def qualifications(config): """Format participant qualificiations""" qualifications = [] # Country of origin cfg = config['crowdsource']['filter'] if 'countries' in cfg: locales = [{'Country': country} for country in cfg['countries']] qualifications.append({ 'Qualificati...
def find_acc_cut_point(native, loan): """ Calculate cut_point that will give highest accuracy for entropies. Use case is for entropies estimated from a single (native) entropy model. Parameters ---------- native : [float] List of entropies from native distribution. loan : [float] ...
def mark_exact(citation): """Highlight exact matches""" return '<mark class="exact-match">%s</mark>' % citation
def format_timedelta(seconds: int) -> str: """Returns a formatted message that is displayed whenever a command wants to display a duration""" hours = int(seconds / (60 * 60)) minutes = int(seconds % (60 * 60) / 60) return f"{hours}h {minutes}m"
def convert_torrent_status(qbtstatus, qbtforce=False): """Take in qbt state and convert to utorrent status""" utstatus = '' # DL in progress (percent progress < 1000) if qbtstatus == 'error': utstatus = '152' elif qbtstatus == 'pausedUP': # I think this is the closest thing QBT has t...
def _TrimString(s, max_len): """Trims the string if it exceeds max_len.""" if len(s) <= max_len: return s return s[:max_len+1] + '...'
def attempt_xor(input, candidate): """Attempt to XOR string with candidate char""" output = b'' for char in input: output += bytes([char ^ candidate]) return output
def get_last_checkpoint(directory): """Obtain the name of the last checkpoint in a directory.""" import os checkpoint = "" if (not os.path.isdir(directory)): return checkpoint # Doing a search this way will treat first any checkpoint files # with seven digits, and then will fall bac...
def read_bert_table(file): """Reads BERT Table and BERT Table Data binary files and returns as a binary object""" try: with open(file, "rb") as f: bert_table_binary = f.read() f.close() except OSError as err: print("OS error: {0}".format(err)) return None ...
def coloca_peca(tab, peca, pos): # tabuleiro x peca x posicao -> tabuleiro """ Coloca uma peca na posicao desejada, alterando destrutivamente o tabuleiro. :param tab: tabuleiro :param peca: peca :param pos: posicao :return: tabuleiro """ tab[pos[1]][pos[0]] = peca return tab
def get_video_type(link): """ Takes a url and decides if it's Vimeo or YouTube. Returns None for unkown types. """ if 'vimeo.com/' in link: return 'vimeo' elif 'youtube.com/' in link or 'youtu.be' in link: return 'youtube' return None
def hoopCount(n): """ hoop_count == PEP8 (forced mixedCase by CodeWars) """ return 'Great, now move on to tricks' if n >= 10 else\ 'Keep at it until you get it'
def hora(campo): """ Procesa un campo que representa una hora en HHMMSS y lo devuelve como un string HH:MM:SS """ return ':'.join((campo[:2], campo[2:4], campo[4:])) if not campo.isspace() else ''
def distinct(l, lists): """ return 1 if every list of 'lists' contains an item that does not belong to l. The return value should then be converted to bool. (mostly useful when comparing the route set in a graph search) :param l: a list :param lists: list of lists or sets :return: n>0 if every l...
def string_fix(string, encode='utf-8'): """Fix the byte<->string problem in python 3""" if isinstance(string, bytes): string = string.decode('utf-8') elif isinstance(string, str): string = string else: string = str(string) return string
def returnVRNsForDriver(parking_lot, driver_age): """Returns all Vehicle Registration numbers for all drivers of a particular age""" if not isinstance(driver_age, int) or driver_age < 18: print("Driver Age Should be atleast 18") return -1 vrn_list = [] for i in range(1, len(parking_lo...
def pyBoolToSQL(inBool: bool): """ Simple function for converting a python bool to a database insertable integer(bit). :param inBool: The bool to insert to the database. :return: The integer(bit) to insert to the database. note:: Author(s): Mitch """ if inBool: re...
def merge(a, b, path=None): """ Recursively merges two dictionaries b into a. Duplicate keys, b overrides a """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge(a[key], b[key], path + [st...
def getbitlen(bint): """ Returns the number of bits encoding an integer """ if bint == 0: # Zero is encoded on one bit return 1 else: return int(bint).bit_length()
def _transform_vendor_trust(data: bytes) -> bytes: """Byte-swap and bit-invert the VendorTrust field. Vendor trust is interpreted as a bitmask in a 16-bit little-endian integer, with the added twist that 0 means set and 1 means unset. We feed it to a `BitStruct` that expects a big-endian sequence where...
def round_to_dec(value, decimals=None, unit=None): """Round to selected no of decimals.""" try: return round(value, decimals) except TypeError: pass return value
def binarysearch(arr,ser)->int: """ Binary Search In Sorted Array """ first=0 second=len(arr)-1 mid=(first+second)//2 while first<=second: if arr[mid]==ser: return mid+1 elif arr[mid]>ser: second=mid-1 elif arr[mid]<ser: first=mid+1 mid=(first+second)//2 return -1