content
stringlengths
42
6.51k
def estimate_random_rewards(arms, N): """Returns the estimated obtained rewards with a random strategy""" return N * (sum(arms) / len(arms))
def dict_of_lists_to_list_of_dicts(dl): """ Thanks to Andrew Floren from https://stackoverflow.com/a/33046935/142712 :param dl: dict of lists :return: list of dicts """ return [dict(zip(dl, t)) for t in zip(*dl.values())]
def quote_spaces(arg): """Generic function for putting double quotes around any string that has white space in it.""" if ' ' in arg or '\t' in arg: return '"%s"' % arg else: return str(arg)
def color_rgb(r,g,b): """r,g,b are intensities of red, green, and blue in range(256) Returns color specifier string for the resulting color""" return "#%02x%02x%02x" % (r,g,b)
def RepresentsInt(val): """ Takes string and checks if value represents int number >>> RepresentsComplex('10') True >>> RepresentsComplex('Not Int!') False """ if type(val) == int: return True try: if val[0] in ("-", "+"): return val[1:].isdigit() ...
def ising_energy(sample, h, J, offset=0.0): """Calculate the energy for the specified sample of an Ising model. Energy of a sample for a binary quadratic model is defined as a sum, offset by the constant energy offset associated with the model, of the sample multipled by the linear bias of the variable...
def _lookup(config_dict, search_key): """ lookup will search the given collection for a specified key and return its value. :param search_key: key in specified collection. :param config_dict: dictionary which contains the search key. :return: value of search_key. """ if search_key in con...
def craft_url(cryptocurrency, start_date, end_date): """ Constructs the coinmarketcap url for the specified cryptocurrency, start date, and end date params --------- cryptocurrency: String * The cryptocurrency to construct URL for start_date: String * The start date for data col...
def _assert_type(data, key, tpe, default=None): """Extract and verify if a key in a dictionary has a given type""" value = data.get(key, default) if not isinstance(value, tpe): raise ValueError("Config error: {}: expected {}, found {}".format( key, tpe, type(value))) return value
def flatten_imports(imports): """ Go from a two level dict to a single level dict """ flat_imports = {} for mod_name, funcs in imports.items(): for func_name, func in funcs.items(): flat_imports['{}_{}'.format(mod_name, func_name)] = func return flat_imports
def _mobius_to_interval(M): """Convert a Mobius transform to an open interval.""" a, b, c, d = M s, t = a/c, b/d return (s, t) if s <= t else (t, s)
def validate_row(row): """ Helper function to validate a row read in from CSV. If validation fails, returns tuple of (False, error message). If validation succeeds, returns tuple of (True, (username, field_name, score)) """ if not isinstance(row, list): return (False, "Badly...
def seconds_to_frames(frame_rate, number_of_seconds): """Converts number_of_seconds to the equivalent number of frames.""" return int(number_of_seconds * frame_rate)
def _rst_to_html_filter(value): """ Converts RST text to HTML ~~~~~~~~~~~~~~~~~~~~~~~~~ This uses docutils, if the library is missing, then the original text is returned Loading to environment:: from jinja2 import Environment env = Environment() env.filter...
def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split())
def _median(data): """Return the median (middle value) of numeric data. When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values: >>> median([1, 3, 5]) 3 >>> median...
def is_prime(num): """Returns True if num is prime""" if num <= 1: return False if num <= 3: return True count = 2 while count ** 2 <= num: if num % count == 0: return False count += 1 return True
def update_input_image_size(net, input_size): """ Update input image size for model. Parameters: ---------- net : Module Model. input_size : int Preliminary value for input image size. Returns: ------- tuple of 2 ints Spatial size...
def most_common(words, n=10): """ Returnes the most common words in a document Args: words (list): list of words in a document n (int, optional): Top n common words. Defaults to 10. Returns: list: list of Top n common terms """ from collections import Counter bow = ...
def combine_glob_and_spc_dct(glob_dct, spc_dct): """ stuff """ new_dct = glob_dct.copy() for skey, sval in spc_dct.items(): if skey in glob_dct: new_dct[skey] = sval return new_dct
def rollup_resources(resources): """Rollup resources together: if a resource include multiple separate ones (i.e. is a rollup) and all the separate ones are included the rollup will be used instead. """ # keep track of rollups: rollup key -> set of resource keys potential_rollups = {} for re...
def first_upper(string): """ Return a string with the first character capitalized. Empty strings are supported. The original string is not changed. """ return string[:1].upper() + string[1:]
def toChoices(object_list): """A function to format a list of objects to a list of two-element tuples expected by django select widgets. Of the form ('value','display')""" if len(object_list[0]) == 2: return [(x[1], x[1]) for x in object_list] else: return [(x[1], x[2]) for x in object_...
def greeting(title, name): # pylint: disable=unused-argument """Print a greeting message. This command print "Good morning, <title> <name>.". Args: title: title of the person say greetings to. name: name of the person say greetings to. """ print("Good morning, {title} {name}.".format(*...
def abs_even(num): """Make even number absolute in value >>> abs_even(-4) 4 >>> abs_event(-7) -7 """ if num % 2 == 0 and num < 0: return -num return num
def is_dict(text: str) -> bool: """ Does the given type represent a dictionary? """ return text[:8] == "HashMap<"
def signed_nibble(x) -> int: """Converts an unsigned nibble to a signed nibble.""" return (x | ~7) if (x & 8) else (x & 7)
def _create_text_labels(classes, scores, class_names=None): """ Args: classes (list[int] or None): scores (list[float] or None): class_names (Dict[int: str] or None): Returns: list[str] or None """ labels = None if classes is not None and class_names is not None:...
def getCardValue(cards): """Returns the value of the cards. Face cards are worth 10, aces are worth 11 or 1 (this function picks the most suitable ace value).""" value = 0 numberOfAces = 0 # Add the value for the non-ace cards: for card in cards: rank = card[0] # card is a tuple like (...
def f_to_k(tf): """ Convierte temperaturas de Fahrenheit a Kelvin Parameters: tf : Temperatura en grados Fahrenheit Returns: tk : Temperatura en grados Kelvin """ if tf is not None: tk = 273.5 + ((tf - 32.0) * (5.0 / 9.0)) ...
def as_unsigned_int32_array(byte_array): """Interprets array of byte values as unsigned 32 bit ints.""" def uint32(a, b, c, d): return a + (b << 8) + (c << 16) + (d << 24) return [uint32(*byte_array[i:i + 4]) for i in range(0, len(byte_array), 4)]
def _opt_content(darwin): """Return the content of the opt specific section of the CROSSTOOL file.""" return { "compiler_flag": [ # No debug symbols. # Maybe we should enable https://gcc.gnu.org/wiki/DebugFission for opt or # even generally? However, that can't happen here, as it...
def deep_sort_lists(obj): """Sort lists nested in dictionaries """ if isinstance(obj, dict): return {k: deep_sort_lists(obj[k]) for k in obj} if isinstance(obj, list): return [deep_sort_lists(v) for v in sorted(obj)] return obj
def get_label_mapped_to_positive_belief(query_result): """Return a dictionary mapping each label_id to the probability of the label being True.""" return {label_id: belief[1] for label_id, belief in query_result.items()}
def new_size_keep_aspect_ratio(original_size, target_size, resize_type='inner'): """Return a new size included (if resize_type='inner') or excluded (if resize_type='outer') in the targeted one by resizing and keeping the original image's aspect ratio. """ # Get current and desired ratio for the images ...
def _format_recipients(recipients): """Take a list of recipient emails and format it nicely for emailing.""" return ", ".join(recipients)
def _removeDuplicatesOneLevel(aList): """ Remove first level duplicates. """ result = [] if aList == []: return if type(aList) != type([]): return aList for elem in aList: if elem not in result: result.append(elem) return result
def lists(iters): """Create a sequence of lists from a mapping / iterator / generator.""" return list(map(list, iters))
def roi2origin(x, y, coordiBBOX, padded=True): """ Coordinates transformation from ROI to original large image """ if padded: x_origin = x + coordiBBOX[0] - 1 y_origin = y + coordiBBOX[2] - 1 else: x_origin = x + coordiBBOX[0] y_origin = y + coordiBBOX[2] retu...
def init_bitstring_groundstate(occ_num: int) -> int: """Occupy the n lowest orbitals of a state in the bitstring representation Args: occ_num (integer): number of orbitals to occupy Returns: (integer): bitstring representation of the ground state """ return (1 << occ_num) - 1
def index_finder(line): """Searches the water output line for alignment position indexes. """ index = 0 if len(line.split()) > 1: if line.split()[1] == 'al_start:': index = int(line.split()[2]) elif line.split()[1] == 'al_stop:': index = int(line.split()[2]) ...
def validate_ints(data): """ Method to validate data of type integer :params: data :response: True, False """ if not isinstance(data, int): return False return True
def _snake_to_camel_case(value): """Convert snake case string to camel case.""" words = value.split("_") return words[0] + "".join(map(str.capitalize, words[1:]))
def raw_data_paths(eclipse): """ Construct a query that returns a data structure containing the download paths :param eclipse: GALEX eclipse number. :type flag: int :returns: str -- The query to submit to the database. """ return 'https://mastcomp.stsci.edu/portal/Mashup/MashupQuery.a...
def calculate_area_per_pixel(resolution): """ Takes a resolution in metres and return the area of that pixel in square kilometres. """ pixel_length = resolution # in metres m_per_km = 1000 # conversion from metres to kilometres area_per_pixel = pixel_length**2 / m_per_km**2 return...
def header(token): """ returns a generic header used for insert and update Deployment manader API calls. :param token: bearer token :return: header dict as expected by requests """ return { 'Metadata-Flavor': 'Google', 'Authorization': f'Bearer {token}', 'Accept': 'applic...
def xor_lists(l1, l2): """Xor l1 and l2 element by element.""" res = [] for i, _ in enumerate(l1): res.append(l1[i] ^ l2[i]) return res
def resolve(name, try_import=True): """ Resolve a string of the form X.Y...Z to a python object by repeatedly using getattr, and __import__ to introspect objects (in this case X, then Y, etc. until finally Z is loaded). """ symbols = name.split('.') try: builder = __import__(symbols[0])...
def getBundleKey(bundlePath): """ Return all parts of a bundle's "key" as used in a timestamp file, given its full filename. >>> getBundleKey("/bundleinfo/tor-browser/win32/some-file-name.txt") '/bundleinfo/tor-browser/win32/' """ # No, we can't use "os.path.directory" or "os.pa...
def convert_checkbox(policy_params): """ Replace param_checkbox with param-indexed. """ params = {} # drop checkbox parameters. for param, data in policy_params.items(): if param.endswith("checkbox"): base_param = param.split("_checkbox")[0] params[f"{base_param}-...
def doc_prep(docstring): """ Splits a docstring by newlines, and finds the minimum indent level, then lstrips that much indentation off each line of the docstring. :param docstring: :return: Docstring linesplit. :rtype: list """ if not docstring: return [] doclines = docstri...
def parseJobString(jstr): """ Parse a Slurm-style job string in the form "1-3,5,8,10-11" """ def parseInterval(interval): i = [int(j) for j in interval.split('-')] if len(i) == 1: return i if len(i) == 2: return range(i[0], i[1] + 1) raise Exception('Invalid task interval...
def write(file_path, new_contents): """ Write the contents of a file. """ with open(file_path, "wb") as f: return f.write(new_contents)
def mergeVariables(variables, envVariables): """ Merge new variables with existing environment variables Args: variables (dict): variables to merge envVariables (dict): existing environment variables Returns: envVariables (dict) """ print("") for var in variables: ...
def has_gaps(gaps): """Returns True if gaps dictionary has gaps in it. Parameters ---------- gaps: dictionary Dictionary of Channel:gaps arrays """ for channel in gaps: if len(gaps[channel]): return True return False
def parse_args(argv): """Confirm params are correct""" return len(argv) == 1
def _first_multiple_of(num: int, above: int) -> int: """ Returns first multiple of num >= above """ return above + ((num-(above%num)) % num)
def IteratedCompareMixed (lhs, rhs): """Tuple comparison that permits C{None} as lower than any value, and defines other cross-type comparison. @return: -1 if lhs < rhs, 0 if lhs == rhs, 1 if lhs > rhs.""" li = iter(lhs) ri = iter(rhs) while True: try: (lv, rv) = (next(li), ...
def uniq(seq): """Return unique elements in the input collection, preserving the order. :param seq: sequence to filter :return: sequence with duplicate items removed """ seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
def remove_newlines(text): """Remove all newline characters from a piece of text. Args: text (str): Any piece of text. Returns: str: That text without newline characters. """ text = text.replace("\n", " ") text = text.replace("\t", " ") text = text.replace("\r", " ") return(text)
def tanimoto(a,b): """ returns the similarity between sets a and b, between 0 and 1 """ c = [v for v in a if v in b] return float(len(c))/(len(a)+len(b)-len(c))
def per_device_batch_size(batch_size, num_gpus): """For multi-gpu, batch-size must be a multiple of the number of GPUs. Note that this should eventually be handled by DistributionStrategies directly. Multi-GPU support is currently experimental, however, so doing the work here until that feature is in place. ...
def get_selected_runs(sub, ref): """ Returns the positions in ref, which are covered by the subsequence sub. Returns None if sub is not a subsequence of ref """ indices = [] sub_pos = 0 for ref_pos in range(len(ref)): if sub_pos >= len(sub): break if ref[ref_pos] ...
def power_time_series(series, scalar): """ Multiply a series by itself X times where X is a scalar """ s = str(series) return f"multiply([{','.join([s for _ in range(scalar)])}])"
def permutation_non_recursion(lst): """Simple, ugly and no recursive, soution.""" if len(lst) <= 1: return lst r = [[]] for i in range(len(lst)): r = [[a] + b for a in lst for b in r if a not in b] return r
def get_metric_name(metric_label): """Returns pushgateway formatted metric name.""" return 'ib_message_flow_{0}'.format(metric_label)
def uniquefy(seq): """ duplicated members only keep one copy. [1,2,2,3,3,4] => [1,2,3,4]. """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
def parse_isEnable(configs): """ Set isEnable=False to each parameter isEnable if its parent (SNMP device) isEnable key ,equal to False. :param configs: SNMP configurations. :return: Applied isEnable from SNMP device config to each SNMP parameters. """ for conf in configs: if not con...
def softsignDerivative(x): # DOES NOT WORK WITH NN """This function returns the softsign derivative of x (Note: Not Real Derivative) """ return 1.0/(1+abs(x))**2
def exclude_options(string, list_to_exclude): """Confirm input is not in a given list. Return the input if yes; raise an error if not. Case sensitive. """ try: assert string not in list_to_exclude except AssertionError: raise RuntimeError(f"Input may not be one of {list_to_excl...
def mult3(v, d): """Multiplies a 3D vector to a scalar""" return [v[0] * d, v[1] * d, v[2] * d]
def get_option_or_default(options, option_name, default_value=None): """ Gets the first option's value from options or returns the default value :param options: the parsed options :param option_name: the name of the option for which get the value :param default_value the value to return if the param...
def overlaps(a, b): """ Return the amount of overlap, in bp between a and b. If >0, the number of bp of overlap If 0, they are book-ended. If <0, the distance in bp between them """ return min(a[1], b[1]) - max(a[0], b[0])
def is_float(text): """Tests if the specified string represents a float number. Args: text(str): text to check Returns: : bool -- True if the text can be parsed to a float, False if not. """ try: float(text) return True except (ValueError, TypeError): return F...
def ReverseComplement(Pattern): """Find the reverse complement of a DNA string.""" thisdict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} complement = [] for i in Pattern: complement.append(thisdict[i]) return "".join(complement)[::-1]
def convertWavelength(wavelength) -> str: """ Convert wavelength into string in nano meter. Parameters ---------- wavelength : str, int, float Wavelength in nano meters or micro meters Returns ------- str Wavelength as string Raises ------ ValueError ...
def readtxt(filepath): """ read file as is""" with open(filepath, 'rt') as f: lines = f.readlines() return ''.join(lines)
def isPrime(n: int)->bool: """ Give an Integer 'n'. Check if 'n' is Prime or Not :param n: :return: bool - True or False A no. is prime if it is divisible only by 1 & itself. 1- is neither Prime nor Composite - check for n being a even number i.e divisble by 2 - check for n being divisi...
def check_lhn_has_min_two_build(ind, do_correction=True): """ Checks if individuum dict has, at least, two buildings. If not, erases LHN system. Parameters ---------- ind : dict Individuum dict for GA run do_correction : bool, optional Defines, if ind dict should be modified...
def default_charge_set(i: int) -> set: """Set of defect charge states. -1 (1) is included for positive (negative) odd number. E.g., default_charge_set(3) = [-1, 0, 1, 2, 3] default_charge_set(-3) = [-3, -2, -1, 0, 1] default_charge_set(2) = [0, 1, 2] default_charge_set(-4) = [...
def parse_message(input_bytes): """ decoode byte into utf-8 string until 0x00 is found""" n_bytes = len(input_bytes) start_offset = 0 end_offset = 0 msg_str = "" while start_offset < n_bytes and start_offset < n_bytes: while end_offset < n_bytes and input_bytes[end_offset] != 0x00: ...
def split_genotype(genotype): """ Split genotype to rel and alt. :param genotype: :return: """ if len(genotype) == 2: return genotype[0], genotype[1] else: return genotype, None
def get_luminance(r, g, b, a=1) -> float: """Gets luminance from an RGB value. Source: https://github.com/CuteFwan/Koishi""" return (0.299 * r + 0.587 * g + 0.114 * b) * a
def build_http_array(post, name): """ builds a dictionary of dictionaries out of flat HTTP field data used for arrays like user[2][first_name] etc. by Herman Schaaf, ironzebra.com """ dic = {} for k in post.keys(): if k.startswith(name): rest = k[len(name):] ...
def remove_doubles(fs): """Returns a list of elements from iterable fs, without double values""" toReturn = [] for f in fs: if all(f != g for g in toReturn): toReturn.append(f) return toReturn
def control_1_11_password_policy_expire(passwordpolicy): """Summary Args: passwordpolicy (TYPE): Description Returns: TYPE: Description """ result = True failReason = "" offenders = [] offenders_links = [] control = "1.11" description = "Ensure IAM password poli...
def is_pgn(filename): """Tells if a filename is a pgn.""" return filename[-4:] == ".pgn"
def _assess(dat1, dat2, thresh): """ Assess if two sets of values are within some numerical threshold """ cond = True for val1, val2 in zip(dat1, dat2): cond = bool((abs(val1 - val2) / val1) * 100.0 < thresh) return cond
def padSize(raw_value, pad): """Calculate the needed padding size for the given value. Args: raw_value (int): raw value to be padded pad (int): padding that should be used Return Value: Number of padding bytes that should be used for the padding """ return (pad - (raw_value...
def refs_should_be_omitted(ref: str): """ Determine if a ref should be completely omitted from json output, we do not want to show origin @param ref: string containing the ref @return: True if this ref should be omitted from the list """ return ref.startswith("origin/")
def as_time(arg): """Defines the custom argument type TIME. Converts its input into an integer if it lacks a unit suffix, otherwise a float. Args: arg (str): A command line argument. Returns: Value of arg converted to a float (duration) or integer (integrations). Raises: ...
def getObjectName(o): """ Return the name of an host object @type o: hostObject @param o: an host object @rtype: string @return: the name of the host object """ if type(o) is str : return o return o.name()
def transform_version_string_into_int(version_string: str) -> int: """ Transforming a version string into a number. (example_version = "1.2.3") :param version_string: :return: """ version_numbers = [int(x) for x in version_string.split(".")] assert len(version_numbers) == 3 return ((vers...
def extract_scores_from_record(record): """ Extract subjective scores from a record """ ratings = {} # go through each record to find actual ratings for key, val in record.items(): # skip columns like MOS etc. if key.lower() in ["pvs_id", "mos", "ci", "n"]: continue ...
def get_mac_str(valve_index, port_num): """Gets the mac address string for the valve/port combo Args: valve_index (int): The internally used id of the valve. port_num (int): port number Returns: str """ two_byte_port_num = ("%04x" % port_num) two_byte_port_num_formatted ...
def bytes_to_str(string): """ Convert from bytes to str. """ if string is None: return None return string.decode('utf-8')
def w(q2: float, m_parent: float, m_daughter: float) -> float: """ Calculates the recoil variable w, which runs from 1 (zero recoil) to the maximum value (depends on daughter). :param q2: Momentum transfer to the lepton-neutrino system. :param m_parent: Mass of the parent meson, e.g. the B meson. :p...
def get_parameter_for_dev_mode(dev_mode_setting): """Return parameter for whether the test should be running on dev_mode. Args: dev_mode_setting: bool. Whether the test is running on dev_mode. Returns: str. A string for the testing mode command line parameter. """ return '--params....
def reverse(text): """Returns a text in reversed order of characters Arguments: text {string} -- any kind of text Returns: string -- text with reversed order of characters """ if text is None: return None result = [] for char in text: result.insert(0...
def detect_tachycardia(heart_rate, age): """ This function makes best guess as to whether tachycardia is being exhibited :param float heart_rate: heart rate in bpm :param int age: age of user/patient :return ble tachycardia: whether or not tachycardia detected """ import logging as log ...