content
stringlengths
42
6.51k
def set_default_site(site): """Set the default site""" global _default_site _default_site = site return _default_site
def favorite_animal(users_animal): """Display a message to the user that changes based on their favorite animal.""" return f'Wow, {users_animal} is my favorite animal, too!'
def is_prolog_list(json_term): """ True if json_term is Prolog JSON representing a Prolog list. See `swiplserver.prologserver` for documentation on the Prolog JSON format. """ return isinstance(json_term, list)
def random_edge_limits(vertex_index, min_edge, max_edge, degree_dict): """ Calculate random_edge parameter limits. :param vertex_index: vertex index :type vertex_index: int :param min_edge: minimum edge number :type min_edge: int :param max_edge : maximum edge number :type max_edge : in...
def place_move(board, move, symbol): """Place symbol in-place.""" x, y = move return tuple(tuple(symbol if j == y else cell for j, cell in enumerate(row)) if i == x else row for i, row in enumerate(board))
def group_by(l, col=None): """Example: >>> l = [{"a":1},{"a":2}] >>> utils.group_by(l,"a") {1: [{'a': 1}], 2: [{'a': 2}]} """ out_dict = {} for i in l: if col != None: out_dict.setdefault(i[col],[]).append(i) else: out_dict.setdefault(i,[]).append(i) ...
def get_chemblids_of_user_entity_ids(cursor, unification_table, user_entity_ids): """ Get the chemblids using their BIANA user entity ids """ query_chemblid = ("""SELECT CH.value FROM externalEntityCHEMBL CH, {} U WHERE U.externalEntityID = CH.extern...
def pg_varchar(size=0): """ Returns the VARCHAR declaration for the provided size: * If no size (or an empty or negative size is provided) return an 'infinite' VARCHAR * Otherwise return a VARCHAR(n) :type int size: varchar size, optional :rtype: str """ if size: if not isins...
def RPL_SUMMONING(sender, receipient, message): """ Reply Code 342 """ return "<" + sender + ">: " + message
def cm2inch(*tupl): """Convert input cm to inches (width, hight) """ inch = 2.54 if isinstance(tupl[0], tuple): return tuple(i/inch for i in tupl[0]) else: return tuple(i/inch for i in tupl)
def generate_mock_perf_log(*args) -> list: """build facility for unit test used to generate webdriver Performance Log GA hits will get values in argument Returns: list: performance log example : generate_mock_perf_log_ga("A") -> [{ "level": "INFO", ...
def create_data(apikey): """Creates the data.""" data = {} data['API_key'] = apikey data['addresses'] = ['Essen+Germany', #0 'Dusseldorf+Germany', #1 'Stuttgart+Germany', #2 'Berlin+Germany', #3 'Hamburg+Germany', #4 ...
def unescape(s): """Revert escaped characters back to their special version. For example, \\n => newline and \\t => tab """ return s.replace('\\n', '\n').replace('\\t', '\t').replace('\\r', '\r')
def version_to_dec(a_version_string): """ Converts a version string to a number to allow for quick checks on the versions of specific components. :param a_version_string: The version string under test (e.g. '3.4.0') :type a_version_string: str :return: An integer representation of the string versio...
def find_extension(ext_type: bytes, types, values): """ Matching cipher extensions to values :param ext_type: :param types: :param values: :return: """ iter = 0 #For the APLN extension, grab the value in ASCII if ext_type == b"\x00\x10": while iter < len(types): ...
def tupleize(obj): """ Converts into or wraps in a tuple. If `obj` is an iterable object other than a `str`, converts it to a `tuple`. >>> tupleize((1, 2, 3)) (1, 2, 3) >>> tupleize([1, 2, 3]) (1, 2, 3) >>> tupleize(range(1, 4)) (1, 2, 3) Otherwise, wraps `obj` in ...
def the(it): """If the given iterator produces just one unique value, return it. Otherwise, raise ValueError.""" first = True out = None for v in it: if first: out = v first = False else: if out != v: raise ValueError("More than o...
def quad_func2(x, a, b, c): """a*(x-b)**2 + c""" return a*(x-b)**2 + c
def extract_user_v1(data): """For Private API """ return { "pk": int(data["pk"]), "username": data["username"], "full_name": data["full_name"], "is_private": data["is_private"], "profile_pic_url": data["profile_pic_url"], "is_verified": data.get("is_verified")...
def binary_search(search_list, item): """ Finds the middle of the list, checks where that number is relative to item, and then splits on the side where item is supposed to be and repeats this process until item is the middle index. List must be sorted O log(n) time complexity ...
def https_in_url(url): """ Check if url startswith https :param url: str: The url to check :return: True if url startswith https else False """ return True if url.startswith('https://') else False
def get_analytics_from_object(_object): """Get analytics response payload""" if not _object: return None analytics = _object.analytics return [analytics] if analytics else None
def chunks(xs, n): """ Split list to evenly sized chunks >> chunks(range(10), 4) [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]] :param xs: arbitrary list :param n: chunk size :return: list of lists """ return [xs[i : i + n] for i in range(0, len(xs), n)]
def count_substring(string, sub_string): """ This is a simple function that returns a List Comprehension to find the substrings within character strings, outputing the total number of occurrences of the substring in the original string """ # List Comprehension return(sum([1 for i in range(0, le...
def convert_none_to_empty_list(value): """Convert value to an empty list if it's None. :param value: The value to convert. :returns: An empty list of 'value' is None, otherwise 'value'. """ return [] if value is None else value
def create_message_request(service, token, title, body): """ Dynamically creates the request paylod to send push notifications based on the input provided """ action = 'OPEN_APP' priority = 'normal' silent = False ttl = 30 if service == "GCM": message_request = { 'Addresses': { t...
def youngs_modulus_saenopy(youngs_modulus): """ Defines the material properties for a linear-elastic hydrogel (such as Matrigel) hydrogel with a poission ratio of 0.25 (see [Steinwachs,2015], in this case Youngsmodulus equals K_0/6). Use None in saenopy Args: youngs_modulus(float) : Yo...
def sort_keys(key): """ Temporary function. See https://github.com/plotly/python-api/issues/290. :param (str|unicode) key: The attribute we're sorting on. :return: (bool, str|unicode) The naturally-sortable tuple. """ is_special = key in 'rtxyz' return not is_special, key
def getLen(elem): """This function is used to Sort the fileds by possibilities.""" leng=len(elem[0]) if leng!=0: return leng return 99
def get_json_login(username, password): """ Function to return the login json given a username and password """ return { "usernameOrEmailAddress": username, "password": password }
def _calc_reward_stats(fn, hist, arm_id): """ Args: arm_id (int): if specified only use the bandit with the given `arm_id`. """ if arm_id is None: return fn([reward for _, reward in hist]) else: return fn([reward for id_, reward in hist if id_ == arm_id])
def binary_search_hi(a,d,lo,hi): """ Created for leetcode prob 34 """ if d!=a[lo]: raise Exception("d should be a[lo]") while hi>lo: mid=(lo+hi)//2+1 if a[mid]==d: lo=mid else: hi=mid-1 if a[hi]==d: return hi else: retur...
def _preprocess_sgm(line, is_sgm): """Preprocessing to strip tags in SGM files.""" if not is_sgm: return line # In SGM files, remove <srcset ...>, <p>, <doc ...> lines. if line.startswith("<srcset") or line.startswith("</srcset"): return "" if line.startswith("<doc") or line.startswith("</doc"): r...
def type_from_column(col_name, col_definitions): """Transform a column name to its standardized form.""" for definition in col_definitions: if col_name.lower() in definition: return definition[0] return None
def _check_trajectory_inputs(init_cond, threshold, trajectory_len): """ This function checks for the type and range of the 3 hyperparameters for the skew-tent map. These are the input to the function compute_trajectory from the module chaotic_sampler.py Parameters ---------- init_cond : sca...
def Arity(n): """Returns the English name of the given arity.""" if n < 0: return None elif n <= 3: return ['nullary', 'unary', 'binary', 'ternary'][n] else: return '%s-ary' % n
def create_abbrevlist(wiki_abbrevs, add_abbrevs, remove_abbrevs): """Creates a final abbreviations list for abbreviations.txt Function adds and removes abbreviations from those retrieved on Wiktionary as per the contents of the arguments. Args: wiki_abbrevs (list): abbreviations from wiktiona...
def pluralize(value, arg='s', arg2=None): """ Adapted from django.template.defaultfilters: https://github.com/django/django/blob/master/django/template/defaultfilters.py Returns a plural suffix if the value is not 1. By default, 's' is used as the suffix: * If value is 0, vote{{ value | plural...
def get_card_names(cards): """ :param cards: List of card JSONs :return: List of card names (str) """ names = [] for card in cards: name = card.get("name") names.append(name) return names
def latest_version(*names, **kwargs): """ Return the latest version of the named fileset/rpm package available for upgrade or installation. If more than one fileset/rpm package name is specified, a dict of name/version pairs is returned. If the latest version of a given fileset/rpm package is alrea...
def line_filter(line): """ Filter lines with specific words """ # If any of these strings are int the line, do not output that line blacklist = ['** Device', '--Performing ', 'Tests Included', 'No difference', 'jnpr.jsnapy', 'ID gone missing', 'ID list', 'Difference in pre '] skip_line ...
def _is_number(s): """Check if an element can be converted to a float, returning True if it can and False if it can't""" if((s is False) or (s is True)): return(False) try: float(s) except(ValueError, TypeError): return(False) else: return(True)
def linear_func(W,X): """ General form of a 2-d linear function with w0 as intercept """ return W[0]+W[1]*X[0]+W[2]*X[1]
def _build_command_options(options): """Build a list of flags from given pairs (option, is_enabled). Each option is prefixed with a single '-'. Include only options for which is_enabled=True. """ return ['-' + item[0] for item in options if item[1]]
def check_game_state(current_word: str, hangman_state: int) -> bool: """Check if there are any _ left in the word or if hangman_state >= 9. Args: current_word (str): The current state of the word that the user sees. hangman_state (int): The state of the hangman. Returns: bool: True...
def make_key(args, kwargs): """Generate hash from arguments. Based on: https://github.com/python/cpython/blob/cd3c2bdd5d53db7fe1d546543d32000070916552/Lib/functools.py#L448 """ key = args if kwargs: key += (object(),) for item in kwargs.items(): key += item retur...
def _van_der_corput(n_sample, base=2): """Van der Corput sequence. :param int n_sample: number of element of the sequence. :param int base: base of the sequence. :return: sequence of Van der Corput. :rtype: list (n_samples,) """ sequence = [] for i in range(n_sample): n_th_number...
def strip_words(text): """ When multiple words (separated by '|') are used to describe emojis, we need to remove the '|' in order to create edges for each word. This function takes out the '|' and puts all the words into a list. """ return text.split(' | ')
def bb_iou_dice(boxa, boxb): """IoU and Dice for bbox""" x_min = max(boxa[0], boxb[0]) y_min = max(boxa[1], boxb[1]) x_max = min(boxa[2], boxb[0] + boxb[2]) y_max = min(boxa[3], boxb[1] + boxb[3]) inter_area = (x_max - x_min) * (y_max - y_min) boxa_area = (boxa[2]-boxa[0]) * (boxa[3] - box...
def get_bnumber_from_user_input(user_input): """ The key used in the Sierra adapter VHS is the seven-digit form of a b-number. This function takes the user input, which could include the 'b' prefix or the check digit, and reduces it to the seven-digit form. """ if ( len(user_input) == l...
def get_users(passwd: str) -> dict: """Split password output by newline, extract user and name (1st and 5th columns), strip trailing commas from name, replace multiple commas in name with a single space return dict of keys = user, values = name. """ output = {} for line in passwd...
def hgdate(text): """:hgdate: Date. Returns the date as a pair of numbers: "1157407993 25200" (Unix timestamp, timezone offset). """ return "%d %d" % text
def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type ...
def make_raster_list_for_mosaic(csv_data): """Extract the names of the rasters for the CSV data.""" raster_path_index = 0 rasters = [] for record in csv_data: if record[raster_path_index] is not None: rasters.append(record[raster_path_index]) return rasters
def get_dict_key_by_value(source_dict: dict, dict_value): """Return the first key of the ``source_dict`` that has the ``dict_value`` as value.""" for k, v in source_dict.items(): if v == dict_value: return k return
def get_pollutant_label(pollutant): """Gets the formated label for the pollutant""" if pollutant == "co2": return "CO$_2$" elif pollutant == "co": return "CO" elif pollutant == "pm2p5_mass" or pollutant == "pm2p5_number" or pollutant == "pm2p5p": return "PM$_{2.5}$" elif poll...
def convert_to_float(frac_str): """ It wouldn't be the oilfield without a healthy mix of units and fractions. This function attempts to deal with fractions care of someone on stack overflow (thank you). Parameters ---------- frac_str: string Returns ------- result: float E...
def diameter_to_capacity(pipe_diameter_mm): """Calculate pipe capacity in MW based on diameter in mm. 20 inch (500 mm) 50 bar -> 1.5 GW CH4 pipe capacity (LHV) 24 inch (600 mm) 50 bar -> 5 GW CH4 pipe capacity (LHV) 36 inch (900 mm) 50 bar -> 11.25 GW CH4 pipe capacity (LHV) 48 inch (1200 ...
def invert_z_coordinates(positions): """ Given a list of coordinates, invert the z coordinates. This is used when converting particle coordinates from the raw tiltseries to the final reconstruction's coordinate system for simulated data. Args: positions: A list of [x, y, z] coordina...
def landingpage_filters(context, request, filters_form=None): """Landing page filters form""" return dict( filters_form=filters_form, )
def hierarchy_depth(hierarchy, path=()): """ Create a mapping of every path in the hierarchy to the node living at that path in the hierarchy. """ base = {} for key, inner in hierarchy.items(): down = tuple(path + (key,)) if isinstance(inner, dict): base.update(hier...
def get_entities_bios(seq): """Gets entities from sequence. note: BIOS Args: seq (list): sequence of labels. Returns: list: list of (chunk_type, chunk_start, chunk_end). Example: # >>> seq = ['B-PER', 'I-PER', 'O', 'S-LOC'] # >>> get_entity_bios(seq) [['PER', ...
def generate_uncrypted_record(timestamp, input_template_text, key): """Generates formatted individual record and returns the iv and the record as a tuple. Keyword arguments: timestamp -- the timestamp for the record input_template_text -- the input template text key -- the key for the id plaint...
def KJKGtoBTULB(hkjkg): """ Convertie l'enthalpie en kJ/kg vers btu/lb Conversion: 1 kJ/kg = 0.429923 Btu/lb :param hkjkg: Enthalpie [kJ/kg] :return hbtulb: Enthalpie [btu/lb] """ hbtulb = hkjkg * 0.429923 return hbtulb
def get_parameters_nodes(input_nodes): """Find operations containing the parameters of the model. Args: input_nodes (:obj:`list` of :obj:`Node`): the input operations of the model. Returns: parameters (:obj:`list` of :obj:`Node`): the operations containing the par...
def createList(r1, r2): """Create a list from a range.""" return list(range(r1, r2 + 1))
def value_to_wep(confidence_value): """ This method will transform an integer value into the WEP scale string representation. The scale for this confidence representation is the following: .. list-table:: STIX Confidence to WEP :header-rows: 1 * - Range of Values - WEP ...
def checkUse(use): """ Determines whether to take an action, based on system configuration @param use: Flags telling whether to take action @type use: None, boolean, or tuple of booleans """ if use is None: return True if type(use) is not tuple: use = (use,) for usevar in...
def is_number(testValue): """Returns True if testValue is an number and False otherwise.""" isNumber = True charactersDone = 0 currentCharacter = 0 positiveNegative = 0 decimal = 0 testValueString = str(testValue) testValueString = testValueString.strip() totalCharacters = len(testV...
def calculate_bypass_armour(hit_limit): """ Method to calculate the minimum value the attacking player needs to roll on a D20 dice to bypass the target player's armour and hit them directly :param hit_limit: the hit limit value calculated as the minimum value the attacking player needs to roll on a D20...
def str2float2int(x): """ :param x: :return: x as an int mostly a convenience function for argparse of large numbers e.g. "1e10" """ return int(float(x))
def get_hs_used_kb(node): """ Receives a node monitor JSON string and returns a list containing the used disk space in KB for each hyperstore disk. :param node: an iterable object :type node: dict :rtype: list """ if 'disksInfo' not in node: r...
def count_fish(days, fish): """Return the number of fish after days, given the initial state fish.""" for _ in range(days): newfish = fish[0] for i in range(1, len(fish)): fish[i - 1] = fish[i] fish[8] = newfish fish[6] += newfish return sum(fish)
def fun(arg1: int) -> str: # comment """_summary_ :param arg1: _description_ :type arg1: int :raises FileExistsError: _description_ :return: _description_ :rtype: str """ if arg1 > 1: raise FileExistsError() # comment return "abc"
def cast_to_str_or_int(text, cast_to_str): """ A helper function to convert a given input to either a string or an integer. :param text: Input text :type text: int or str :param cast_to_str: When True, input text is cast to a string. When False, input is cast to an integer. :type cast_to_str: b...
def replace_parentheses_with_list(list_x): """ Input: A list with entries within parentheses Output: A list with entries within the parentheses replaced with entries within lists 1. Detect the parentheses in the list, e.g., ['(', 'A', 'or', 'B', ')', 'and', 'C'] 2. Put the entries within the parentheses into anot...
def scrape_images(url): """Scrape images from a website. Parameters: url (str): url to a website Returns: image_container (list): list of pd.DataFrame object containing the table data Raises: None """ image_container = None return image_container
def expand_gids_in_list(e, L): """ Return list L with all gids replaced by their cid-list equivalent. Here L is a list of mixed cid and gid identifiers. Duplicates removed in output, of course. The operation preserves the order of the portions (like a contest-free grammar, if there are no cycl...
def auto_line_fitting_filter(param, i1, i2): """A filter function for fitting of a single calibration line. Args: param (): i1 (int): i2 (int): Return: bool: """ if param[0] <= 0.: # line amplitdue too small return False if param[1] < i1 or param...
def is_tag(obj): """Determines if `obj` is a tuple of two strings. Examples: >>> is_tag(('hello', 'yes')) True >>> is_tag(('hi', 22)) False """ try: return isinstance(obj, tuple) and len(obj) == 2 and all((isinstance(x, str) or x == None) for x in obj) except: retu...
def some_funky_spot(ilist,bitpos): """Return true if some pattern has a nonterminal or operand decider""" for i in ilist: if bitpos < len(i.ipattern.bits): if i.ipattern.bits[bitpos].is_nonterminal(): return True if i.ipattern.bits[bitpos].is_operand_decider(): retu...
def shardAnnotate(s, iter, shard) : """Append iteration and shard number to str""" return s+".i"+str(iter).zfill(2) +".s"+str(shard).zfill(2)
def booth(X, Y): """constraints=10, minimum f(1, 3)=0""" return ((X)+(2.0*Y)-7.0)**2+((2.0*X)+(Y)-5.0)**2
def format_datetime(value, format="%d.%b.%y, %H:%M"): """Format a date time""" if value is None: return "" return value.strftime(format)
def DigitSum(DigitString): """Returns the sum of the digits for DigitString. DigitString: a string whose characters are integers.""" i = 0 Sum = 0 while i < len(DigitString): Sum += int(DigitString[i]) i +=1 return Sum
def case_insensitive_name(package_name): """Convert a package name to a case-insensitive name. Appends the hash of the input string, and converts the whole string to lower case. Note, the appended hash value is represented in decimal, and may be negative. Args: name: string: A potentially case-sensitive...
def standardise_force_name(name): """use lower case with hyphens as per the filenames in the bulk crime data""" mapping = { "Avon & Somerset": "avon-and-somerset", "Avon and Somerset": "avon-and-somerset", "Bedfordshire": "bedfordshire", "Cambridgeshire": "cambridgeshire", "Cheshire": "cheshire"...
def google_analytic(api_key=None): """ generate google analytic html example: {% load google_analytic %} {% google_analytic "UA-111111111" %} """ if not api_key: raise Exception('google api key is required.') return { 'api_key': api_key }
def spot_is_free(spot, candles, light): """ A spot is NOT free if the horizontal and vertical distance between that and the light is less than the light strength """ for candle in candles: x_dist = abs(candle[0] - spot[0]) y_dist = abs(candle[1] - spot[1]) if x_dist < light a...
def _create_chunks_from_list(lst, n): """Creates chunks of list. Args: lst: list of elements. n: size of chunk. """ chunks = [] for i in range(0, len(lst), n): chunks.append(lst[i:i + n]) return chunks
def lookup(obj, key, default=None): """Looks up a property within an object using a dotted path as key. If the property isn't found, then return the default value. """ keys = key.split(".") value = default for key in keys: value = obj.get(key) if value is None: ret...
def _convert_input_source(source): """Convert input source to proper denon conform name. :param source: name of the source :return: source name adapted to protocol """ source = source.upper() if "SATCBL" in source: source = "SAT/CBL" return source
def str_list(input_list): """ Convert all the elements in a list to str Args: input_list: list of any elements Returns: list of string elements """ return ['{}'.format(e) for e in input_list]
def common_start(sa, sb): """ Returns the longest common substring from the beginning of sa and sb """ def _iter(): for a, b in zip(sa, sb): if a == b: yield a else: return return ''.join(_iter())
def parse_time(timestamp): """ Parses timestamps like 12:34.56 and 2s into seconds """ if ":" in timestamp: parts = timestamp.split(":") result = float(parts[-1]) if len(parts) >= 2: result += float(parts[-2]) * 60 if len(parts) >= 3: result += f...
def is_string(value): """Return True if value is a string.""" try: return isinstance(value, basestring) # type: ignore except NameError: return isinstance(value, str)
def findExtremeDivisor(n1, n2): """ Assumes that n1 and n2 are positive ints Return a tuple containing the smallest common divisor > 1 and the largest common divisor of n1 and n2""" divisors = () minVal, maxVal = None, None for i in range(2, min(n1, n2) + 1): if n1%i == 0 and n2%...
def filter_fname(fname): """ Take an input title string that was extracted from a filename, and if there are more periods or underscores than spaces, then replace them (underscores or periods) with spaces. """ # Count number of spaces, periods, and underscores spc = fname.count(' ') spd ...
def pluck(d, *args): """ pluckr """ # print("hello pluckr"); sys.stdout.flush() out = [None] * len(args) for i, key in enumerate(args): # print("key: " + key); sys.stdout.flush() try: out[i] = d[key] except KeyError: raise RuntimeError("no such key...
def f(x): """Define function f(x)= 1/(1+x^2)""" return 1.0/(1+x**2)