content
stringlengths
42
6.51k
def add_up(n): """ Adds up all numbers from 1 to n. """ numbers = range(1, n + 1) return sum(numbers)
def serial_to_chamber(x: int) -> int: """Convert serialized chamber id to chamber number.""" return (x & 0x0000003F) + 1
def _to_list(obj): """Make object into a list""" return [obj] if not isinstance(obj, list) else obj
def u_func(c, h, mp): """ Calculates utility of chosen (consumption, housing) bundle. Args: c (float): consumption h (float): housing mp (dict): model parameters. Returns: (float): utility of bundle """ return (c**(1-mp['phi']))*(h**mp['phi'])
def JsonString_to_JsonFile(json_string,file_name="test.json"): """Transforms a json string to a json file""" out_file=open(file_name,'w') out_file.write(json_string) out_file.close() return file_name
def _py_assert_stmt(expression1, expression2): """Overload of assert_stmt that executes a Python assert statement.""" assert expression1, expression2() return None
def do_the_diff(defaults, overrides): """Diff two yaml loaded objects, returning diffs in a namedtuple :param defaults: File you wish to compare against, the base. :param overrides: File you wish to compare, the mask. :return: stuff :rtype: dict """ new_combined_diff = {} for key in overrides.keys(): if key not in defaults.keys(): new_combined_diff[key] = overrides[key] else: if defaults[key] == overrides[key]: pass else: if 'NEW_DEFAULTS' not in new_combined_diff.keys(): new_combined_diff['NEW_DEFAULTS'] = {} if 'OLD_OVERRIDES' not in new_combined_diff.keys(): new_combined_diff['OLD_OVERRIDES'] = {} new_combined_diff['NEW_DEFAULTS'][key] = defaults[key] new_combined_diff['OLD_OVERRIDES'][key] = overrides[key] return new_combined_diff
def pad(l, until=0, fillvalue=None): """ Pad a list. """ for _ in range(until - len(l)): l.insert(0, fillvalue) return l
def convert (number): """ :param number: int :return: str - as requested """ result = '' if (number % 3) == 0: result = 'Pling' if (number % 5) == 0: result += 'Plang' if (number % 7) == 0: result += 'Plong' if len (result) == 0: return f'{number}' return result
def get_total_colors(color_frequencies: dict) -> int: """Count total amount of colors""" return len([p for p in color_frequencies.values() if p])
def generate_variable(r, c, n): """Creates a label for the coordinates and contents of a cell.""" return f'{r},{c}_{n}'
def merge_timelines(timeline_a, timeline_b): """Takes two timelines, both of which must contain a list of times and a list of values, and combines them into a single timeline containing a list of times and added values, so that if an interval in both timelines overlap, then the returned timeline will show the sum of the two values during that interval.""" combined_times = [] combined_values = [] # Reverse the timelines so that we pop the earliest values first. times_a = timeline_a[0] values_a = timeline_a[1] times_b = timeline_b[0] values_b = timeline_b[1] times_a.reverse() values_a.reverse() times_b.reverse() values_b.reverse() # Track the a and b values independently current_a_value = 0 current_b_value = 0 # Returns the next time from either timeline to appended to the output. def get_next_smallest_time(): if (len(times_a) == 0) and (len(times_b) == 0): raise Exception("Internal error combining timelines.") if (len(times_a) == 0): return times_b[-1] if (len(times_b) == 0): return times_a[-1] if times_a[-1] <= times_b[-1]: return times_a[-1] return times_b[-1] # Run the update_output() closure until all of the original timeline values # have been combined into the output. while (len(times_a) > 0) or (len(times_b) > 0): t = get_next_smallest_time() # It's possible that both timelines have a change in value at the same # time. if (len(times_a) != 0) and (times_a[-1] == t): times_a.pop() current_a_value = values_a.pop() if (len(times_b) != 0) and (times_b[-1] == t): times_b.pop() current_b_value = values_b.pop() combined_times.append(t) combined_values.append(current_a_value + current_b_value) return [combined_times, combined_values]
def nexus_infile(myid,itwist): """ nexus style input name Args: myid (str): prefix itwist (int): twist index Returns: str: input filename """ prefix = myid.split('.')[0] infile = '.'.join([prefix,'g%s'%str(itwist).zfill(3),'twistnum_%d'%itwist,'in','xml']) return infile
def xlen(seq): """ Returns the length of a sequence or None. Parameters ---------- seq : iterable or None Returns ------- int or None """ if (seq is None): return seq return len(seq)
def divider_row(sizes): """ Create a one line string of '-' characters of given length in each column """ s = '' for i in range(len(sizes)): s = s + '-'.ljust(sizes[i], '-') + ' ' return s
def isempty(s): """return if string is empty """ if s is None or s == "" or s == "-": return True else: return False
def count_vowels(s): """ (str) -> int Return the number of vowels (a, e, i, o, and u) in s. >>> count_vowels('Happy Anniversary!') 5 >>> count_vowels('xyz') 0 """ num_vowels = 0 for char in s: if char in 'aeiouAEIOU': num_vowels = num_vowels + 1 return num_vowels
def should_force_reinit(config): """Configs older than 2.0.0 should be replaced""" ver = config.get("cli_version", "0.0.0") return int(ver.split(".")[0]) < 2
def extract_features(document, word_features): """ Used to get a word vector required by the naive bayes classifier for training and during streaming :param document: tokens :param word_features: all words :return: """ document_words = set(document) features = [] for word in word_features: features.append(word in document_words) return features
def get_errors_from_serializer(serializer_errors): """ Extracts the errors from the serializer errors into a list of strings. """ errors = [] for key, details in serializer_errors.items(): for error in details: errors.append(str(error)) return errors
def check_parameter_string(candidate, param): """Checks that a parameter is a string or a list of strings. """ parameters = { "site": "NWIS station id(s) should be a string or list of strings," + "often in the form of an eight digit number enclosed in quotes.", "parameterCd": "NWIS parameter codes are five-digit strings that specify " + "the parameter that is being measured at the site. Common " + "codes are '00060' for stream stage in feet, '00065' for " + "stream discharge in cubic feet per second, and '72019' for " + "groundwater levels. Not all sites collect data for all " + "parameters. See a complete list of physical parameters here: " + "https://help.waterdata.usgs.gov/parameter_cd?group_cd=PHY " + "You may request multiple parameters by submitting a comma-" + "delimited string of codes with no spaces, or by submitting " + "a list of codes, like this: parameterCd = '00065,00060' or " + "parameterCd = ['00065', '00060'] ", "county": "The NWIS county parameter accepts a five-digit string or " + "a list of five-digit strings to select all of the sites " + "within a county or list of counties. " + "Example: '51059' or ['51059', '51061'] are acceptable.", "state": "This parameter uses US two-letter postal codes " + "such as 'MD' for Maryland or 'AZ' for Arizona.", "default": "This parameter should be a string or a list of strings.", } if param in parameters: msg = parameters[param] + " Actual value: {}".format(candidate) else: msg = ( "This parameter should be a string or a list of strings." + " Actual value: {}".format(candidate) ) if candidate is None: return None elif isinstance(candidate, str) and candidate: return candidate elif (isinstance(candidate, list) or isinstance(candidate, tuple)) and candidate: for s in candidate: if not isinstance(s, str): raise TypeError(msg + " bad element: {}".format(s)) return ",".join([str(s) for s in candidate]) else: raise TypeError(msg)
def scalar_mul(eta, x): """Scalar multiplication. Return a list with the same dimensions as `x` where each element in `x` is multiplied by `eta`. Args: eta (float) Scalar to apply to `x`. x (list): Vector to scale. 1 or 2 dimensional. Returns: list: A scaled list. Same dimensions as `x`. """ if isinstance(x[0], list): # 2 dimensional return [[eta * x_ij for x_ij in x_i] for x_i in x] else: # 1 dimensional return [eta * x_i for x_i in x]
def calc_lcoe_om(fom, vom, cf=1): """ :param fom: Fixed operation and maintentance costs as CURR/KWY :param vom: Variable cost in the form of CURR/ KWH :param cf: Capacity factor assumed for the plant, default is 1 :return: LCOE O&M component in CURR per KWh """ fixed = fom / (cf * 8600) om_lcoe = fixed + vom return om_lcoe
def process_funql(funql): """Remove quotes and unnecessary spaces.""" funql = funql.replace("'", "") funql = funql.replace(", ", ",") funql = funql.replace(", ", ",") funql = funql.replace(" ,", ",") return funql
def intersection(L1, L2): """ Find the intersection point of the two lines A1 * x + B1 * y = C1 A2 * x + B2 * y = C2 The intersection point is: x = Dx/D y = Dy/D The determinant D A1 B1 which is L1[0] L1[1] A2 B2 L2[0] L2[1] Dx: C1 B1 which is L1[2] L1[1] C2 B2 L2[2] L2[1] and Dy: A1 C1 which is L1[0] L1[2] A2 C2 L2[0] L2[2] Input: Line1, Line2 the two intersecting lines Output: x, y the point of intersection """ D = L1[0] * L2[1] - L1[1] * L2[0] Dx = L1[2] * L2[1] - L1[1] * L2[2] Dy = L1[0] * L2[2] - L1[2] * L2[0] if D != 0: x = Dx / D y = Dy / D return x, y else: return False
def parse_line(line): """Parse a line of instructions and return a (step, requires) tuple""" assert line.startswith("Step ") and line.endswith(" can begin.") word = line.split() return word[7], word[1]
def quantize(rgb, quanta): """map a tuple (r,g,b) each between 0 and 255 to our discrete color buckets""" r,g,b = rgb r = max([q for q in quanta if q <= r]) g = max([q for q in quanta if q <= g]) b = max([q for q in quanta if q <= b]) return (r,g,b)
def create_word_vocab(input_data): """create word vocab from input data""" word_vocab = {} for sentence in input_data: words = sentence.strip().split(' ') for word in words: if word not in word_vocab: word_vocab[word] = 1 else: word_vocab[word] += 1 return word_vocab
def list_merger(base_list, overlay_list): """It is important to note we expect both arg lists to be non-repeating. Merges lists such that the `base_list` is preserved and the `overlay_list` is overlaid onto it. Example: source = ['Node', 'Node1'] target = ['Node', 'Jack'] returns = ['Node', 'Jack', 'Node1'] :param base_list: Source list of object we want to overlay. :param overlay_list: Target list of object we want overlay onto. :return: Non-repeating list of object. """ merged_list = base_list[:] result_len = len(merged_list) if base_list == overlay_list: return merged_list src_set = set(base_list) tgt_set = set(overlay_list) tgt_order = overlay_list[:] src_order = base_list[:] if not tgt_set.intersection(src_set): only_source = [n for n in src_order if n not in tgt_order] else: only_source = [] if tgt_set.issubset(src_set): return merged_list idx = 0 for item in tgt_order: if item not in src_order: offset = 0 try: _ = src_order[idx] valid = True except IndexError: valid = False if valid: prev_idx = max(0, idx - 1) match = src_order[prev_idx] == tgt_order[prev_idx] if prev_idx >= 0 and match: offset = 0 elif match: offset = prev_idx else: next_idx = idx + 1 try: match = src_order[next_idx] == tgt_order[next_idx] if match: offset = next_idx except IndexError: pass insert = idx + offset if insert >= 0 or result_len < 3: merged_list.insert(insert, item) else: merged_list.append(item) else: merged_list.insert(idx, item) result_len += 1 idx += 1 for item in reversed(only_source): merged_list.remove(item) merged_list.insert(0, item) return merged_list
def point_sub(a, b): """ Subtract two 2d vectors (Inline this if you can, function calls are slow) """ return (a[0] - b[0], a[1] - b[1])
def unwrap(mappings): """Remove the set() wrapper around values in component-to-team mapping.""" for c in mappings['component-to-team']: mappings['component-to-team'][c] = mappings['component-to-team'][c].pop() return mappings
def choice_id(choice): """ Returns Choice type field's choice id for form rendering """ try: resp = choice[0] except IndexError: resp = '' pass return resp
def camel_case(name): # type: (str) -> str """Return a camelCased version of a string.""" return name[0:1].lower() + name[1:]
def _validate(validation_func, err, *args): """Generic validation function that returns default on no errors, but the message associated with the err class otherwise. Passes all other arguments into the validation function. :param validation_func: The function used to perform validation. :param err: The error class to catch. :param args: The arguments to pass into the validation function. :return: Validation error message, or empty string if no error. """ try: validation_func(*args) except err as validation_err: return str(validation_err) return ''
def sort_by(comparator, list): """Sorts the list according to the supplied function""" return sorted(list, key=comparator)
def gcd_recursive_by_divrem(m, n): """ Computes the greatest common divisor of two numbers by recursively getting remainder from division. :param int m: First number. :param int n: Second number. :returns: GCD as a number. """ if n == 0: return m return gcd_recursive_by_divrem(n, m % n)
def sort_and_print(body, num): """ Sorts the values of dictionaries and prints respective top sentences :param body: list of dictionaries of 'sentence': score :param num: no of sentences to be printed :return: prints """ result = [] rank = [] for sentdict in body: for sent in sentdict: rank.append(sentdict[sent]) rank = list(set(rank)) # remove duplicates rank = sorted(rank, reverse=True) count = 0 # print top 'num' sentences in same order as of original document for sentdict in body: for sent in sentdict: if count == num: break for r in rank[:num]: if sentdict[sent] == r: result.append(sent) count += 1 return result
def _clean_message(output: str) -> str: """Strips the succeeding new line and carriage return characters.""" return output.rstrip("\n\r")
def time_is_hh_mm_ss_ms(str_hh_mm_ss_ms): """test if time value is format hh:mm:ss.ms Args: str_hh_mm_ss_ms (str): time value Raises: Exception: incorrrect format Returns: bol: True if valid """ try: hr, min, sec = map(float, str_hh_mm_ss_ms.split(':')) return True except: raise Exception(f'The time value "{str_hh_mm_ss_ms} "' + 'need to be in format: hh:mm:ss.ms')
def reverse_dict(dct): """ Reverse the {key:val} in dct to {val:key} """ newmap = {} for (key, val) in dct.items(): newmap[val] = key return newmap
def _get_interior_years(from_year, to_year, start_year, end_year): """Return the Rule years that overlap with the Match[start_year, end_year]. """ years = [] for year in range(start_year, end_year + 1): if from_year <= year and year <= to_year: years.append(year) return years
def ctd_sbe37im_preswat(p0, p_range_psia): """ Description: OOI Level 1 Pressure (Depth) data product, which is calculated using data from the Sea-Bird Electronics conductivity, temperature and depth (CTD) family of instruments. This data product is derived from SBE 37IM instruments and applies to CTDMO instruments, all series, and specifically processes telemetered and recovered_host (not recovered_instrument) data. Implemented by: 2014-02-05: Russell Desiderio. Initial Code Usage: p = ctd_sbe37im_preswat(p0, p_range_psia) where p = sea water pressure (PRESWAT_L1) [dbar] p0 = raw pressure (PRESWAT_L0) [counts] p_range_psia = pressure range calibration coefficient [psia] References: OOI (2012). Data Product Specification for Pressure (Depth). Document Control Number 1341-00020. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-00020_Data_Product_SPEC_PRESWAT_OOI.pdf) """ # compute pressure range in units of dbar p_range_dbar = (p_range_psia - 14.7) * 0.6894757 # compute pressure in dbar and return p_dbar = p0 * p_range_dbar / (0.85 * 65536.0) - 0.05 * p_range_dbar return p_dbar
def M_from_t(t,n,M0,t0): """ find mean anomaly at time t Parameters ---------- t time to find M for n mean motion M0 reference mean anomaly at time t0 t0 reference time t0 Note that M = 0 at pericentre so if t0 = pericentre passage time then M0 = 0 """ M = M0 + (n*(t-t0)) return M
def decode_cp1252(string): """ CSV files look to be in CP-1252 encoding (Western Europe) Decoding to ASCII is normally fine, except when it gets an O umlaut, for example In this case, values must be decoded from cp1252 in order to be added as unicode to the final XML output. This function helps do that in selected places, like on author surnames """ if not string: return string try: # See if it is not safe to encode to ascii first string.encode("ascii") except (UnicodeEncodeError, UnicodeDecodeError): # Wrap the decode in another exception to make sure this never fails try: string = string.decode("cp1252") except (UnicodeEncodeError, UnicodeDecodeError, AttributeError): pass return string
def count_mismatches(aligned_seq1, aligned_seq2): """ :param seq1, aligned_seq2: aligned sgRNA and genomic target (seq+PAM) :return: """ cnt = 0 ending = len(aligned_seq1) - 3 for i in range(ending): cnt += int(aligned_seq1[i] != aligned_seq2[i] and aligned_seq1[i] != "-" and aligned_seq2[i] != "-") return cnt
def decimal_to_binary_util(val): """ Convert 8-bit decimal number to binary representation :type val: str :rtype: str """ bits = [128, 64, 32, 16, 8, 4, 2, 1] val = int(val) binary_rep = '' for bit in bits: if val >= bit: binary_rep += str(1) val -= bit else: binary_rep += str(0) return binary_rep
def get_catalog_record_embargo_available(cr): """ Get access rights embargo available date as string for a catalog record. :param cr: :return: """ return cr.get('research_dataset', {}).get('access_rights', {}).get('available', '')
def _damerau_levenshtein(a, b): """Returns Damerau-Levenshtein edit distance from a to b.""" memo = {} def distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: d = min( distance(x[1:], y) + 1, # correct an insertion error distance(x, y[1:]) + 1, # correct a deletion error distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]: # Correct a transposition. t = distance(x[2:], y[2:]) + 1 if d > t: d = t memo[x, y] = d return d return distance(a, b)
def itb(num: int, length: int): #print(num) """ Converts integer to bit array Someone fix this please :D - it's horrible :param num: number to convert to bits :param length: length of bits to convert to :return: bit array """ if num >= 2**length: num = 2**length - 1 if num < 0: num = 0 num = int(num) if length == 13: return [int(i) for i in '{0:013b}'.format(num)] if length == 16: return [int(i) for i in '{0:016b}'.format(num)] if length == 17: return [int(i) for i in '{0:017b}'.format(num)] if length == 23: return [int(i) for i in '{0:023b}'.format(num)]
def get_filesize_est(n_regions): """ Get a filesize estimate given the number of regions in grid encoding. Parameters ---------- n_regions: int number of regions encoded by grid encoding Returns ------- float Estimated filesize """ return 0.00636654 * n_regions + 3.392864597
def sext(binary, bits): """ Sign-extend the binary number, check the most significant bit """ neg = binary & (1 << (bits - 1)) if neg: mask = 0 for i in range(bits, 16): mask |= (0b1 << i) return (mask | binary) else: return binary
def zfp_precision_opts(precision): """Create a compression options for ZFP in fixed-precision mode The float precision parameter is the number of uncompressed bits per value. """ zfp_mode_precision = 2 return zfp_mode_precision, 0, precision, 0, 0, 0
def schur_representative_from_index(i0, i1): """ Simultaneously reorder a pair of tuples to obtain the equivalent element of the distinguished basis of the Schur algebra. .. SEEALSO:: :func:`schur_representative_indices` INPUT: - A pair of tuples of length `r` with elements in `\{1,\dots,n\}` OUTPUT: - The corresponding pair of tuples ordered correctly. EXAMPLES:: sage: from sage.algebras.schur_algebra import schur_representative_from_index sage: schur_representative_from_index([2,1,2,2], [1,3,0,0]) ((1, 2, 2, 2), (3, 0, 0, 1)) """ w = [] for i, val in enumerate(i0): w.append((val, i1[i])) w.sort() i0 = [] i1 = [] for pair in w: i0.append(pair[0]) i1.append(pair[1]) return (tuple(i0), tuple(i1))
def get_qualified_name(_object): """Return the Fully Qualified Name from an instance or class.""" module = _object.__module__ if hasattr(_object, '__name__'): _class = _object.__name__ else: _class = _object.__class__.__name__ return module + '.' + _class
def is_valid(x, y, grid, x_max, y_max): """Check the bounds and free space in the map""" if 0 <= x < x_max and 0 <= y < y_max: return grid[x][y] == 0 return False
def keys_of(d): """ Returns the keys of a dict. """ try: return list(d.keys()) except: raise ValueError('keys_of(d) must be passed a dict')
def sint(mixed, default=None): """Safe int cast.""" try: return int(mixed) except: return default
def quick_exponent_with_mod(base, power, modulo): """Compute quickly the exponent within a given modulo range. Will apply a modulo with the specified base at every iteration of the exponentiation algorithm, making sure the result is in the given range.""" # 'powers' will be a list of the base with powers of two applied, i.e.: # with base==3, powers==[3, 3^2, 3^4, 3^8, 3^16, ...] powers = [base] # for each power of two i = 2 while i <= power: # compute base^(2^i) and add it to the list powers.append((powers[-1] * powers[-1]) % modulo) # next power of two i *= 2 # list of booleans corresponding to which powers of two to include to make # up the whole exponent powers_to_include = list(bool(int(digit)) for digit in bin(power)[2:][::-1]) # accumulator for the product accumulator = 1 # for each factor==base^(2^index) for index, factor in enumerate(powers): # if this power should be included if powers_to_include[index]: # multiply and apply modulo accumulator *= factor accumulator %= modulo # return the product accumulator return accumulator
def list_to_string(list_to_convert): """ list_to_convert -> List that should be converted into string e.g. '[1,2,False,String]' returns string """ list_to_string = '[' for j in range(len(list_to_convert)): list_to_string += str(list_to_convert[j]) + ',' # remove last ',' list_to_string = list_to_string[:-1] list_to_string += ']' return list_to_string
def compute_U(Sigma_sfr, Sigma_g): """ Ionizaton parameter as a function of star formation and gas surface densities. reference: Eq. 38 Ferrara et al. 2019 inputs: Sigma_sfr in Msun/yr/kpc^2 Sigma_g in Msun/kpc^2 """ out= (1.7e+14)*(Sigma_sfr/(Sigma_g*Sigma_g)) return out
def _coerce_ascii(c): """ coerce an ASCII value into the alphabetical range """ while True: if c > 127: c -= 128 if c < 64: c += 64 if (c >= 65 and c <= 90) or (c >= 97 and c <= 122): return c c += 7
def status_8bit(inp): """ Return the status of each bit in a 8 byte status """ idx = 7 matches = {} for num in (2 ** p for p in range(idx, -1, -1)): if ((inp - num) > 0) or ((inp - num) == 0): inp = inp - num matches[idx] = True else: matches[idx] = False idx -= 1 return matches
def query_url(namespace, cls_version, extension=''): """ """ url = 'https://kg.humanbrainproject.org/query/%s/%s/fg' %\ (namespace.lower(), cls_version) return url+extension
def prune_position(step): """Keep only ``left`` and ``top`` keys in step position.""" return {k: v for k, v in step.get('position', {}).items() if k in ('left', 'top')}
def _header_name(channel_name: str, i_bin: int, unique: bool = True) -> str: """Constructs the header name for a column in a yield table. There are two modes: by default the names are unique (to be used as keys). With ``unique=False``, the region names are skipped for bins beyond the first bin (for less redundant output). Args: channel_name (str): name of the channel (phase space region) i_bin (int): index of bin in channel unique (bool, optional): whether to return a unique key, defaults to True Returns: str: the header name to be used for the column """ if i_bin == 0 or unique: header_name = f"{channel_name}\nbin {i_bin+1}" else: header_name = f"\nbin {i_bin+1}" return header_name
def pack_message_other(code, data): """ Method by which other modules messages are (re-)packed :param code: the code of the message :param data: the data to pack :return: dict, code and data """ b_data = bytes(data, 'ascii') return {'code': code, 'data': b_data}
def solution(N): """ DINAKAR convert to binary and find gap by just knowing the entry of 1 and remember the last index of 1 also remember the longest in each iteration when 1 is encountered """ longest = -1 last_longest_index = 0 ar = bin(N).replace("0b", "") print(ar) for i in range(len(ar)): if ar[i] == "1": print("1 found...at index " + str(i)) longest = max(longest, i - last_longest_index - 1) last_longest_index = i print("current longest " + str(longest)) return 0 if longest == -1 else longest
def get_item_safe(sequence, index=0, default=""): """ Retrives the item at index in sequence defaults to default if the item des not exist """ try: item = sequence[index] except IndexError: item = default return item
def merge_datasets(datasets): """ Merge a list of datasets into one dataset """ dataset = datasets[0] for i in range(1, len(datasets)): dataset.extend(datasets[i]) return dataset
def get_subdict(d, param): """ Get a subdictionary d : key -> value in a dictionary of form d : key -> (d : param -> value) """ return dict([(key, d[key][param]) for key in d.keys()])
def check_correlation_method(method): """Confirm that the input method is currently supported. Parameters ---------- method : str The correlation metric to use. Returns ------- str Correctly formatted correlation method. """ method = method.lower() avail_methods = ["pearson", "spearman", "kendall"] assert method in avail_methods, "method {} not supported, select one of {}".format( method, avail_methods ) return method
def get_label_from_iri_list(iri_list, iri2label_dict): """ Helper for getting labels of a df with IRI lists as values using an iri2label dict""" label_list = [iri2label_dict[iri] for iri in iri_list] return label_list
def StripComments(lines): """strip comments and empty lines """ result = [] found_comment = 0 for line in lines: if not line.strip(): continue if found_comment: if line.startswith(" */"): found_comment = 0 else: if line.startswith(" //"): continue elif line.startswith(" /*"): found_comment = 1 else: result.append(line) return result
def _number(string): """ Extracts an int from a string. Returns a 0 if None or an empty string was passed. """ if not string: return 0 else: try: return int(string) except ValueError: return float(string)
def next_month_is(year, month): """ Short function to get the next month given a particular month of interest :param year: year of interest :param month: month of interest :type year: integer :type month: integer """ next_year = year next_month = month + 1 if next_month > 12: next_month = 1 next_year = year + 1 return next_year, next_month
def example_func(parameter): """ This is an example function """ try: var = int(parameter) result = var * var except ValueError: result = 'Nan' return result
def removeTags(fileStr): """ Removes all tags from the chat that start with '<xyz' and end with '</xyz'. """ current = 0 while True: #print("Next char:",fileStr[current]) openAngleBracketIndex = fileStr.find('<',current) if openAngleBracketIndex == -1: break spaceIndex = fileStr.find(' ', openAngleBracketIndex+1) if spaceIndex == -1: break else: current = spaceIndex endStr = "</"+fileStr[openAngleBracketIndex+1:spaceIndex]+'>' endIndex = fileStr.find(endStr, spaceIndex) if endIndex == -1: current = spaceIndex else: endIndex = endIndex+len(endStr) #print(openAngleBracketIndex, endStr, endIndex+len(endStr)) fileStr = fileStr[:openAngleBracketIndex]+ \ fileStr[endIndex:] #print(fileStr) current = openAngleBracketIndex return fileStr
def class_ldap(log): """An error classifier. log the console log text Return None if not recognized, else the error type string. """ if 'failed to bind to LDAP server' in log: return 'LDAP failure' return None
def array_chunk_loop(array, size): """Return an array containing chunks of the specified array with the specified size, using a loop.""" result = [] chunk = [] for i, value in enumerate(array): chunk.append(value) if len(chunk) == size or i + 1 == len(array): result.append(chunk[:]) chunk.clear() return result
def flatten(data): """ Flatten a list/tuple/set of any nestedness. """ result = [] for item in data: if isinstance(item, (tuple, list, set)): result.extend(flatten(item)) else: result.append(item) return result
def check_line_for_error(line,errormsg): """ Parse given line for VASP error code Args: line (string): error statement Returns: errormsg (string): VASP error code """ if 'inverse of rotation matrix was not found (increase SYMPREC)' in line: errormsg.append('inv_rot_mat') elif 'WARNING: Sub-Space-Matrix is not hermitian in DAV' in line: errormsg.append('subspacematrix') elif 'Routine TETIRR needs special values' in line: errormsg.append('tetirr') elif 'Could not get correct shifts' in line: errormsg.append('incorrect_shift') elif ('REAL_OPTLAY: internal error' in line or 'REAL_OPT: internal ERROR' in line): errormsg.append('real_optlay') elif 'ERROR RSPHER' in line: errormsg.append('rspher') elif 'DENTET' in line: errormsg.append('dentet') elif 'TOO FEW BANDS' in line: errormsg.append('too_few_bands') elif 'BRIONS problems: POTIM should be increased' in line: errormsg.append('brions') elif 'internal error in subroutine PRICEL' in line: errormsg.append('pricel') elif 'One of the lattice vectors is very long (>50 A), but AMIN' in line: errormsg.append('amin') elif ('ZBRENT: fatal internal in' in line or 'ZBRENT: fatal error in bracketing' in line): errormsg.append('zbrent') elif 'ERROR in subspace rotation PSSYEVX' in line: errormsg.append('pssyevx') elif 'WARNING in EDDRMM: call to ZHEGV failed' in line: errormsg.append('eddrmm') elif 'Error EDDDAV: Call to ZHEGV failed' in line: errormsg.append('edddav') elif 'EDWAV: internal error, the gradient is not orthogonal' in line: errormsg.append('grad_not_orth') elif 'ERROR: SBESSELITER : nicht konvergent' in line: errormsg.append('nicht_konv') elif 'ERROR EDDIAG: Call to routine ZHEEV failed!' in line: errormsg.append('zheev') elif 'ELF: KPAR>1 not implemented' in line: errormsg.append('elf_kpar') elif 'RHOSYG internal error' in line: errormsg.append('rhosyg') elif 'POSMAP internal error: symmetry equivalent atom not found' in line: errormsg.append('posmap') elif 'internal error in subroutine IBZKPT' in line: errormsg.append('ibzkpt') elif 'internal error in subroutine SGRCON' in line: errormsg.append('sgrcon') return errormsg
def auc(points): """Calulate the area under the curve using trapezoid rule.""" return sum((p[0]-lp[0])/100*(lp[1]+(p[1]-lp[1])/2.0)/100 for p, lp in zip(points[1:], points[:-1]))
def learner_stats_id(ctr_info): """Assemble stats id.""" broker_id = ctr_info.get('broker_id') explorer_id = ctr_info.get('explorer_id') agent_id = ctr_info.get('agent_id') return "_".join(map(str, (broker_id, explorer_id, agent_id)))
def isSet(input): """ This function check input is a set object. :param input: unknown type object """ return isinstance(input, set)
def pascal_triangle(n): """pascal triangle""" if (n <= 0): return [] init = [[1]] for i in range(1, n): if (i == 1): init.append([1, 1]) else: init.append([0] * (i + 1)) init_point = 0 for num in range(i + 1): if (num == 0): init[i][num] = 1 continue elif (num == i): init[i][num] = 1 continue if (init_point != i - 1): val = init[i - 1][init_point] + init[i - 1][init_point + 1] init[i][num] = val init_point += 1 return(init)
def fnSeconds_To_Hours(time_period): """ Convert from seconds to hours, minutes and seconds. Date: 16 October 2016 """ num_hrs = int(time_period/(60.*60.)); time_period =time_period - num_hrs*60.*60.; num_mins = int(time_period/60.); num_secs = time_period - num_mins*60.; return num_hrs,num_mins,num_secs
def with_subfolder(location: str, subfolder: str): """ Wrapper to appends a subfolder to a location. :param location: :param subfolder: :return: """ if subfolder: location += subfolder + '/' return location
def merge(dict1, dict2, def1, def2, func): """Merge two nested dictionaries, using default values when it makes sense""" assert isinstance(dict1, dict) assert isinstance(dict2, dict) toReturn = {} keys1 = set(dict1.keys()) keys2 = set(dict2.keys()) for key in keys1 | keys2: # change this to | val1 = dict1.get(key, None) val2 = dict2.get(key, None) if isinstance(val1,dict) or isinstance(val2,dict): toReturn[key] = merge(val1 or {}, val2 or {}, def1, def2, func) else: toReturn[key] = func(val1 or def1, val2 or def2) return toReturn
def create_mute_list(time_list): """ Args: subs (tuple): a list of tuples (start,end) Returns: """ muteTimeList = [] for timePair in time_list: lineStart = timePair[0] lineEnd = timePair[1] muteTimeList.append("volume=enable='between(t," + format(lineStart-.1, '.3f') + "," + format(lineEnd+.1, '.3f') + ")':volume=0") return muteTimeList
def is_convolution_or_linear(layer): """ Return True if `layer` is a convolution or a linear layer """ classname = layer.__class__.__name__ if classname.find('Conv') != -1: return True if classname.find('Linear') != -1: return True return False
def ngram(max_ngram_size: int, s1: str, s2: str, *, weighted: bool = False, any_mismatch: bool = False, longer_worse: bool = False) -> int: """ Calculates how many of n-grams of s1 are contained in s2 (the more the number, the more words are similar). Args: max_ngram_size: n in ngram s1: string to compare s2: string to compare weighted: substract from result for ngrams *not* contained longer_worse: add a penalty when second string is longer any_mismatch: add a penalty for any string length difference FIXME: Actually, the last two settings do NOT participate in ngram counting by themselves, they are just adjusting the final score, but that's how it was structured in Hunspell. """ l2 = len(s2) if l2 == 0: return 0 l1 = len(s1) nscore = 0 # For all sizes of ngram up to desired... for ngram_size in range(1, max_ngram_size + 1): ns = 0 # Check every position in the first string for pos in range(l1 - ngram_size + 1): # ...and if the ngram of current size in this position is present in ANY place in second string if s1[pos:pos+ngram_size] in s2: # increase score ns += 1 elif weighted: # For "weighted" ngrams, decrease score if ngram is not found, ns -= 1 if pos == 0 or pos + ngram_size == l1: # ...and decrease once more if it was the beginning or end of first string ns -= 1 nscore += ns # there is no need to check for 4-gram if there were only one 3-gram if ns < 2 and not weighted: break # longer_worse setting adds a penalty if the second string is longer than first if longer_worse: penalty = (l2 - l1) - 2 # any_mismatch adds a penalty for _any_ string length difference elif any_mismatch: penalty = abs(l2 - l1) - 2 else: penalty = 0 return nscore - penalty if penalty > 0 else nscore
def get_audio_args(name, data, sample_rate=None, step=None, **kwargs): """ Wrapper to parse args """ return (name, data, step, sample_rate)
def _crossing(n_x, n_y, n, shift): """tells you if the shift crosses PBC in the x or why direction :param n_x: system size in x :type n_x: int :param n_y: system_size in y :type n_y: int :param n: what index you are currently at :type n: int :param shift: whoch way you want to shift to :type shift: list """ x = n%n_x y = n // n_x x_new = x + shift[0] x_looped = x//n_x != x_new //n_x y_new = y + shift[1] y_looped = y//n_y != y_new //n_y return([shift[0]*x_looped, shift[1]*y_looped])
def qmul(q1, q2): """ Return quaduple (4 tuple) result of quaternion multiplation of q1 * q2 Quaternion multiplication is not commutative q1 * q2 != q2 * q1 Quaternions q1 and q2 are sequences are of the form [w, x, y, z] """ w = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3] x = q1[0] * q2[1] + q1[1] * q2[0] + q1[2] * q2[3] - q1[3] * q2[2] y = q1[0] * q2[2] + q1[2] * q2[0] + q1[3] * q2[1] - q1[1] * q2[3] z = q1[0] * q2[3] + q1[3] * q2[0] + q1[1] * q2[2] - q1[2] * q2[1] return (w, x, y, z)
def build_placements(shoes): """ (list of str) -> dict of {str: list of int} Return a dictionary where each key is a company and each value is a list of placements by people wearing shoes made by that company. >>> result = build_placements(['Saucony', 'Asics', \ 'Asics', 'NB', 'Saucony', 'Nike', 'Asics', 'Adidas', \ 'Saucony', 'Asics']) >>> result == {'Saucony': [1, 5, 9], \ 'Asics': [2, 3, 7, 10], 'NB': [4], 'Nike': [6], \ 'Adidas': [8]} True """ placements = {} position = 1 for brand in shoes: if brand not in placements: placements[brand] = [] placements[brand].append(position) position = position + 1 return placements
def get_path(obj, *keys): """Extract a value from a JSON data structure.""" for key in keys: if not obj: return obj if isinstance(key, int): try: obj = obj[key] except IndexError: return None elif isinstance(key, str): obj = obj.get(key) else: raise TypeError(f"Invalid key type: {type(key).__qualname__}") return obj
def decimal_to_string(decimal): """ """ # Don't love this problem_fractions = {0.13: "1/8", 0.67: "2/3", 0.33: "1/3"} if decimal in problem_fractions: return problem_fractions.get(decimal) ratio = float(decimal).as_integer_ratio() return "/".join(str(d) for d in ratio)
def key_to_list(key): """make a list that contains primaryKey of this ingredient""" return [x.strip() for x in key.split(',')]
def formatannotation_fwdref(annotation, base_module=None): """the python 3.7 _formatannotation with an extra repr() for 3rd party modules""" if getattr(annotation, "__module__", None) == "typing": return repr(annotation).replace("typing.", "") if isinstance(annotation, type): if annotation.__module__ in ("builtins", base_module): return annotation.__qualname__ return repr(annotation.__module__ + "." + annotation.__qualname__) return repr(annotation)
def prod(iterator): """Product of the values in this iterator.""" p = 1 for v in iterator: p *= v return p