content
stringlengths
42
6.51k
def get_filename(n_gram_val, pca_val, cv_val, oversampling_val, base_output_directory): """ Finds and returns the filename for the output file to be saved as, based on input parameters given by user :param n_gram_val: 1-gram, 2-gram, 3-gram :param pca_val: enabling or disabling dimensionality reduction ...
def f_shrink(x): """ half value """ a = 0.5 return x * a
def first_word(text: str) -> str: """ returns the first word in a given text. """ # your code here pindex = text.find(" ") if pindex == -1: return text else: return text[:pindex]
def _strip_namespace(value_or_map): """ Remove the namespace part from the given cache key(s). """ def _strip(value): return value.split(":", 1)[-1] if hasattr(value_or_map, "keys"): return {_strip(k): v for k, v in value_or_map.items()} elif hasattr(value_or_map, "__iter__"): ...
def get_worker_name(worker_id): """Returns `/job:tpu_worker/task:{worker_id}`.""" return f'/job:tpu_worker/task:{worker_id}'
def add_article(name): """ Returns a string containing the correct indefinite article ('a' or 'an') prefixed to the specified string. """ if name[:1].lower() in "aeiou": return "an " + name return "a " + name
def iphexval(ip): """ Retrieve the hexadecimal representation of an IP address .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' network.iphexval 10.0.0.1 """ a = ip.split(".") hexval = ["%02X" % int(x) for x in a] # pylint: disable=E1321 return "".j...
def format_tag(tag): """ Splits tags on ':' and removes enclosing quotes if present and returns returns both sides of the split as strings Example: >>> format_tag('user:foo') 'user', 'foo' >>>format_tag('user:"foo bar"'') 'user', 'foo bar' """ idx = tag.index(":") key = tag[...
def dict_value_of(dict_data, key): """ usage example {{ your_dict|dict_value_of:your_key }} """ if key: return dict_data.get(key)
def add_video_parameters(json_metadata, should_use_native_video): """ Add necessary video parameters to the metadata of the video """ processing_parameters = json_metadata.get('processingParameters', {}) video_parameters = [('shouldKeepNativeFrameRate', should_use_native_video), ( 'framesPla...
def string_encode(key): """Encodes ``key`` with UTF-8 encoding.""" if isinstance(key, str): return key.encode("UTF-8") else: return key
def is_pos_float(number): """ Returns True if a number is a positive float. """ return type(number) == float and number >= 0.0
def pprint(matrix: list) -> str: """ Preety print matrix string Parameters ---------- matrix : list Square matrix. Returns ------- str Preety string form of matrix. """ matrix_string = str(matrix) matrix_string = matrix_string.replace('],', '],\n') retu...
def uppercase(string): """Return string converted to uppercase.""" return string.upper()
def mp_curl_ratio(gamma, a_tension, b_tension): # <<< """The curl ratio subroutine has three arguments, which our previous notation encourages us to call gamma, 1/alpha, and 1/beta. It is a somewhat tedious program to calculate [(3-alpha)alpha^2 gamma + beta^3] / [alpha^3 gamma + (3-beta)beta^2], ...
def parse_addr(addr, port=20000): """ Parse IP addresses and ports. Works with: IPv6 address with and without port; IPv4 address with and without port. """ if addr == '': # no address given (default: localhost IPv4 or IPv6) return "", port, 0 elif ']:' in ...
def fibonacci(n): """ fibonacci :param n: :return: """ return n if n < 2 else fibonacci(n - 2) + fibonacci(n - 1)
def ror(x, n, p=1): """Bitwise rotation right p positions n is the bit length of the number """ return (x >> p) + ((x & ((1 << p) - 1)) << (n - p))
def _event(title, subtitle, icon): """Build a event used as returned item :param str title: the title of this item :param str subtitle: the subtitle of this item :icon: the icon for this item :returns: a list of dict, actually just one entry """ return [dict(title=title, subtitle=subtitle,...
def convert_file_timestamp_strftime(file_time: float): """Takes a given file timestamp and converts it to a human-readable format. Examples: >>> import os\n >>> mtime = os.stat('.').st_mtime\n >>> mtime\n 1635892055.433207 >>> convert_file_timestamp_strftime(mtime)\n ...
def format_tags(tags): """ Reformats tags :param dict tags: dict of data pipeline tags (e.g. {key1: val1, key2: val2, key3: val3}) :returns: list of dicts (e.g. [{key: key1, value: val1}, {key: key2, value: val2}, {key: key3, value: val3}]) """ return [dict(key=k, value=v) for k, v in tags.items()...
def splice_s(array, *args): """Implementation of splice function in scalar context""" offset = 0; if len(args) >= 1: offset = args[0] length = len(array) if len(args) >= 2: length = args[1] if offset < 0: offset += len(array) total = offset + length if ...
def search_for_attr_value(obj_list, attr, value): """ Finds the first (not necesarilly the only) object in a list, where its attribute 'attr' is equal to 'value', returns None if none is found. :param obj_list: list, of objects to search :param attr: string, attribute to search for :param value: mixed types, valu...
def GetValueString(val): """ Return the string representation of |val| expected by GN. """ if isinstance(val, bool): if val: return 'true' else: return 'false' elif isinstance(val, int): return val else: return '"%s"' % val return val
def config_oli_box(oli_box_id, project_id, device_type): """ Basic information about OLI box. """ obj = {} obj['oli_box_id'] = oli_box_id obj['project_id'] = project_id obj['device_type'] = device_type return (obj)
def get_matrix_with_quiet_zone(matrix, quiet_zone_size=4): """ Create new matrix with quiet zone and copy matrix into it """ if quiet_zone_size < 0: raise Exception('Quiet zone size must be positive') size = len(matrix) res_matrix = [] for y in range(size + quiet_zone_size * 2): line...
def karatsuba(x, y, b=10): """ returns product of x, y. Uses base b in karatsuba algorithm Gives running time of O(n^1.585) as opposed to O(n^2) of naive multiplication >>> karatsuba(1234223123412323, 1234534213423333123) 1523690672850721578619752112274729L """ if x < 1000 or y < 1000: ...
def seq_iter(iterable): """ helper function to handle iterating over a dict or list should iterate using: for idx in iterable: value = iterable[idx] ... Args: iterable: an iterable object Returns: key to access iterable """ return iterable if isinst...
def bond_energy(r, fc, r0): """ Calculate the bond energy using the harmonic potential. Args: r (float): distance between atoms [angstrom] fc (float): force constant [kcal/mol] r0 (float): equilibrium distance [angstrom] Returns: e_bond (float): energy of bond [kcal/mol] ...
def columns(thelist, n): """ Break a list into ``n`` columns, filling up each column to the maximum equal length possible. For example:: >>> l = range(10) >>> columns(l, 2) [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] >>> columns(l, 3) [[0, 1, 2, 3], [4, 5, 6, 7],...
def _as_list(arr): """Make sure input is a list of mxnet NDArray""" if not isinstance(arr, (list, tuple)): return [arr] return arr
def selectBit(val, bitNo): """ select bit from integer """ return (val >> bitNo) & 1
def allVowelsA(word): """ allVowelsA is a function that changes all vowels to A. This function is a building block for a function that will count syllables by counting vowels. For that purpose, all vowels are equivalent. But, we want to remove consecutive duplicate vowels. Converting all...
def manhattan(x1, y1, x2, y2): """ Return the Manhattan distance between (x1, y1) and (x2, y2). (number, number, number, number) -> number """ return abs(x1 - x2) + abs(y1 - y2)
def linearize_term(term, n_orbitals): """Function to return integer index of term indices. Args: term(tuple): The term indices of a one- or two-body FermionOperator. n_orbitals(int): The number of orbitals in the simulation. Returns: index(int): The index of the term. """ #...
def execute_event_artists_queries(event_id, artist_id, cursor, db): """Executes event artists queries to insert the event artists into the linking table""" if artist_id != 0: try: cursor.execute("SELECT event_id from event_artists WHERE event_id = '{}'".format(event_id)) db.commi...
def bbox_rot90(bbox, factor, rows, cols): # skipcq: PYL-W0613 """Rotates a bounding box by 90 degrees CCW (see np.rot90) Args: bbox (tuple): A bounding box tuple (x_min, y_min, x_max, y_max). factor (int): Number of CCW rotations. Must be in set {0, 1, 2, 3} See np.rot90. rows (int): I...
def omit_falsy(collection: list): """ Removes falsy entries from a list, returning None if no entries remaining """ new_list = list(filter(lambda entry: entry, collection)) return new_list or None
def urljoin(*parts): """Combines parts of a URL into a fully path. Removes any additional trailing or leading "/" characters. Example: urljoin('abc.com', 'path/', 'file.txt) -> 'abc.com/path/file.txt' Args: *parts: Any sequence of parts of a URL to join Returns: Concatenate...
def __parse(string): """Parses a given string into a float if it contains a dot, into integer otherwise. :param string: Given string to parse. :return: Integer or float representation of the given string. """ if "." in string: return float(string) return int(string)
def _rank2(a, b, c, d): """Return rank of 2x2 boolean matrix.""" if (a & d) ^ (b & c): return 2 if a or b or c or d: return 1 return 0
def _row_apply_map(mapper, x_row): """Function applying mapper (list of lambdas) to vector of values.""" return [transform(x_row, i) for i, transform in enumerate(mapper)]
def any2unicode(text, encoding='utf8', errors='strict'): """Convert `text` (bytestring in given encoding or unicode) to unicode. Parameters ---------- text : str Input text. errors : str, optional Error handling behaviour if `text` is a bytestring. encoding : str, optional ...
def bool_or_none(value): """Return boolean equivalent or None for a given value. :param value: value to be parsed returns: None if value=None, else True if truthy or False otherwise """ if value is None: return None return str(value).lower() in ["true", "1", "y", "yes", "on"]
def getDataPoint(quote): """ Produce all of the needed values to generate a datapoint """ """ ------------- Update this function ------------- """ stock = quote['stock'] bid_price = float(quote['top_bid']['price']) ask_price = float(quote['top_ask']['price']) price = (bid_price + ask_price) / 2 return stock, bid...
def to_http_url(list): """convert [hostname, port] to a http url""" str = '' str = "http://%s:%s" % (list[0], list[1]) return str
def is_multiple(n: int, m: int) -> bool: """Returns True if n is a multiple of m and False otherwise.""" if n % m == 0: return True return False
def decode(digits, base): """Decode given digits in given base to number in base 10. digits: str -- string representation of number (in given base) base: int -- base of given number return: int -- integer representation of number (in base 10)""" answer = 0 rev_digits = digits[::-1] for i in...
def playfair_put_into_pairs(text): """takes a list of strings and puts them in to pairs, adds extra X on the end incase where len text is odd Args: text ([list]): [lsit of strings e.g ["A","B","C","D"] Returns: [list]: [that will go to ["AB","CD]] """ if len(text)...
def proportional(raw_value, factor, unit=None): """Applies a proportional factor.""" return (float(raw_value) * factor, unit)
def c_is_fun(text): """ Prints a Message when /c is called """ return "C " + text.replace('_', ' ')
def create_guac_connection(workout_id, config): """ Creates a guacamole connection ready for inserting into the student entry server configuration. @param workout_id: ID of the workout being created @type workout_id: string @param config: Specification string for a student guacamole connection @...
def hasUserForecastForFixture(results, fixtureid): """ return True if a result object matches the required fixture id, return False if no forecast is found for the fixture id """ for result in results: if result.fixture_id == fixtureid: return True return False
def ns2nsfit(ns, num): """ Returns a list of distances or ps for performing fits. If ds == 5 and num == 3: -> [5, 5, 5] If ds == [3, 5, 7] and num == 3: -> [3, 3, 3, 5, 5, 5, 7, 7, 7] Likewise for ps. Args: ds: num: Returns: """ if isinstance(ns,...
def vehicle_map(veh): """Maps a vehicle type id to a name :param veh: vehicle type id :return: vehicle type name """ if veh == 2: return "Tram" elif veh == 6: return "Metro" elif veh == 7: return "Ferry" elif veh == 12: return "Train" else: ret...
def find_smallest_positive(items) -> int: """ Returns the smallest positive integer that does not exist in the given int array. :param items: array of ints :return: the smallest positive int not in the array """ # Create boolean array to hold if an integer is found # Maps index of array to the integer in items ...
def create_dict_keyed_by_field_from_items(items, keyfield): """ given a field and iterable of items with that field return a dict keyed by that field with item as values """ return {i.get(keyfield): i for i in items if i and keyfield in i}
def translate_version_str2list(version_str): """Translates a version string in format 'x[.y[.z[...]]]' into a list of numbers""" if version_str is None: ver = [0, 0] else: ver = [] for i in version_str.split(".")[:2]: try: i = int(i) except...
def sqrt(x): """ Calculate the square root of argument x """ # Check that x is positive if x < 0: print("Error negative value supplied") return -1 else: print("Here we go..") # Initial guess for the square root z = x / 2.0 # Continuously improve the guess ...
def max_pow_2(number_peers): """Return the powers of 2 >= to the number of peers""" powers = [] x = 0 while 2**x < number_peers: powers.append(2**x) x += 1 return powers + [2**x]
def _preprocess(statement: str): """Preprocess the input statement.""" statement = statement.strip() # Replace any occourance of " with '. statement = statement.replace('"', "'") if statement[-1] != ";": statement += ";" return statement
def uniqify(seq): # Dave Kirby """ Return only unique items in a sequence, preserving order :param list seq: List of items to uniqify :return list[object]: Original list with duplicates removed """ # Order preserving seen = set() return [x for x in seq if x not in seen and not seen.add...
def getForecastRun(cycle, times): """ :param cycle: Forecast cycle reference time :param times: All available times/cycles :return: DataTime array for a single forecast run """ fcstRun = [] for t in times: if str(t)[:19] == str(cycle): fcstRun.append(t) return fcstRun
def comparator(order, item_stats, mode): """Checks if the item satisfies the conditions.""" if mode: return order["platinum"] < (sum([c["platinum"] for c in item_stats[0:3]]) / 3 * 0.7) return order["platinum"] < item_stats["lowest_2d_average"] * 0.7
def best_known_date_variation (date_var_1digit): """ Best known date variation usaged by airline (often not specified in the IATA guideline """ if date_var_1digit in ['A', 'J']: return -1 elif date_var_1digit in ['1', '2']: return int (date_var_1digit) else: return 0
def _tf_string_replace(_str): """ Replace chars that are not accepted by tensorflow namings (eg. variable_scope) :param _str: :return: """ return ( _str.replace("[", "p") .replace("]", "q") .replace(",", "c") .replace("(", "p") .replace(")", "q") ...
def align_address_to_size(address: int, align: int) -> int: """Align the address to the given size.""" return address + ((align - (address % align)) % align)
def _list_of_countries(value): """ Parses a comma or semicolon delimited list of ISO 3166-1 alpha-2 codes, discarding those which don't match our expected format. We also allow a special pseudo-country code "iso". Returns a list of lower-case, stripped country codes (plus "iso"). """ from ...
def aspectRatioFix(preserve,anchor,x,y,width,height,imWidth,imHeight): """This function helps position an image within a box. It first normalizes for two cases: - if the width is None, it assumes imWidth - ditto for height - if width or height is negative, it adjusts x or y and makes them pos...
def better_get_first_model_each_manufacturer(car_db): """Uses map function and lambda to avoid code with side effects.""" result = map(lambda x: x[0], car_db.values()) # convert map to list return list(result)
def get_icon_from_type(type): """ A helper function to obtain icon from type name of the object. """ t = """<img src = "/style/img/%s_icon.png" width = "16" height = "16" alt = "%s" />""" return t % (type.lower(), type.lower())
def assign_only_product_as_production(db): """Assign only product as reference product. Skips datasets that already have a reference product or no production exchanges. Production exchanges must have a ``name`` and an amount. Will replace the following activity fields, if not already specified: * 'na...
def lowercase_words(words): """ Lowercases a list of words Parameters ----------- words: list of words to process Returns ------- Processed list of words where words are now all lowercase """ return [word.lower() for word in words]
def dms_to_sex(d, m, s): """Converts degrees, minutes and decimal seconds to sexagesimal seconds. Example: (41, 24, 12.2) -> 149052.2 :param int d: degrees :param int m: minutes :param float s: decimal seconds :rtype: float """ return (d * 3600) + (m * 60) + s
def GetOutputFileName(test, name, lang): """Creates the output file name based on the language and the name of the app. Args: test: Whether the input file name starts with TEST. name: The name of the application. I.e. Chrome, GoogleGears. lang: The language of the installer. Returns: The output fi...
def get_list_from_lines(lines): """Convert a string containing a series of lines into a list of strings.""" return [line.rstrip() for line in lines.splitlines()]
def get_rotation_from_version(version): """ Given a version number from `scripts/calibrate_onearm.py`, we figure out the rotation. Right now this is a lot of trial and error, but there isn't much of an alternative. Replaces the old method of `get_average_rotation`. """ print("WARNING: this metho...
def solar_elevation_angle(solar_zenith_angle): """Returns Solar Angle in Degrees, with Solar Zenith Angle, solar_zenith_angle.""" solar_elevation_angle = 90 - solar_zenith_angle return solar_elevation_angle
def unique(list): """ Creates a list with unique entries, sorted by their appearance in the list (to make an ordered set) :param list: :return: """ existing = set() return [x for x in list if not (x in existing or existing.add(x))]
def time_str_to_seconds(time): """Convert a time intervall specified as a string like ``dd-hh:mm:ss'`` into seconds. Accepts both '-' and ':' as separators at all positions.""" intervals = [1, 60, 60 * 60, 60 * 60 * 24] return sum( iv * int(t) for iv, t in zip(intervals, reversed(time.replace('...
def make_keys_lowercase(dct) -> dict: """Change uppercase keys in dictionary to lowercase, if key is string""" return {key.lower() if type(key) == str else key: value for key, value in dct.items()}
def pretty_printer(form): """ Remove blank lines """ return '\n'.join((line.strip() for line in form.splitlines() if line and not line.isspace()))
def load_initial_grid(state_slice, dimensions): """Make initial grid from the state_slice depending on number of dimensions.""" grid = [] initial_slice = [ [column for column in row] for row in state_slice ] if dimensions == 4: initial_slice = [initial_slice] grid.app...
def basic_dict_get(dic): """Return the value of the key "value" from the dict.""" return dic["value"]
def clean_number(number_string): """ Cleans non-numeric characters from entered string and converts and returns the new number. """ cleaned_number_string = "" for char in number_string: if char in "0123456789": cleaned_number_string += char return int(cleaned_number_strin...
def db200final_cfg(db200final): """Return a configuration dict (as needed by pony.person etc.) containing a database with with 200 factids. Do not write to this database (select queries only) """ return {"db": db200final}
def _broadcast_shapes(shape1, shape2): """ Given two shapes (i.e. tuples of integers), return the shape that would result from broadcasting two arrays with the given shapes. Examples -------- >>> _broadcast_shapes((2, 1), (4, 1, 3)) (4, 2, 3) """ d = len(shape1) - len(shape2) ...
def apply_backspaces_and_linefeeds(text): """ Interpret backspaces and linefeeds in text like a terminal would. Interpret text like a terminal by removing backspace and linefeed characters and applying them line by line. If final line ends with a carriage it keeps it to be concatenable with next ...
def compute_slope(x1,y1,x2,y2): """ Computes the slope from x and y co-ordinates of two points @x1: x-intercept of line1 @y1: y-intercept of line1 @x2: x-intercept of line2 @y2: y-intercept of line2""" if x2!=x1: return ((y2-y1)/(x2-x1))
def force_str(x): """ Force string """ try: return str(x) except: try: return "".join(i for i in x if ord(i)<128) except: return ""
def repr_object(o): """ Represent an object for testing purposes. Parameters ---------- o Object to represent. Returns ------- result : str The representation. """ if isinstance(o, (str, bytes, int, float, type)) or o is None: return repr(o) return "...
def div(A, B): """ Function to divide two values A and B (A / B), use as "div(A, B)" """ if (B == 0): raise Exception("Don't divide by zero!") return A / B
def get_default(dct, key, default=None, fn=None): """Get a value from a dict and transform if not the default.""" value = dct.get(key, default) if fn is not None and value != default: return fn(value) return value
def normal_diffusion(times, diffusion_coefficient, dimensions=2): """Models the relationship between mean squared displacement and time during a normal (Brownian) diffusion process. During normal diffusion the mean squared displacement increases linearly with time according to the Einstein relation. ""...
def save_dct_to_txt(data_dict): """Saves the key-value pairs of a dictionary to text files on local disk, with each key as a filename and its value(s) as the contents of that file. Parameters ---------- data_dict : dict dictionary containing keys as filenames and values as the contents to be sa...
def net_in_sol_rad(sol_rad, albedo=0.23): """ Calculate net incoming solar (or shortwave) radiation from gross incoming solar radiation, assuming a grass reference crop. Net incoming solar radiation is the net shortwave radiation resulting from the balance between incoming and reflected solar radiat...
def get_oidc_auth(token=None): """ returns HTTP headers containing OIDC bearer token """ return {'Authorization': token}
def _format_content(password, salt, encrypt=True): """Format the password and salt for saving :arg password: the plaintext password to save :arg salt: the salt to use when encrypting a password :arg encrypt: Whether the user requests that this password is encrypted. Note that the password is sav...
def base_dict_to_string(base_dict): """ Converts a dictionary to a string. {'C': 12, 'A':4} gets converted to C:12;A:4 :param base_dict: Dictionary of bases and counts created by find_if_multibase :return: String representing that dictionary. """ outstr = '' # First, sort base_dict so that m...
def _clean(sentence): """Performs some basic cleanup of the sentence. """ cleaned = sentence.replace("&quot;", "\"").replace("&apos;", "'") cleaned = cleaned.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">") return cleaned