content
stringlengths
42
6.51k
def isnum(x): """Test whether an object is an instance of a built-in numeric type.""" for T in int, float, complex: if isinstance(x, T): return 1 return 0
def prefix_keys(d: dict, prefix: str, sep: str = "_") -> dict: """ dict: Returns the input dictionary with prefixed keys. Examples: >>> a = {"k": "val"} >>> prefix_keys(d=a, prefix="demo") {"demo_k": "val"} """ keys = [prefix + sep + str(k) for k in d.keys()] return {key...
def rescale(frac, mult): """ frac: fraction positives mult: negative multiplier End cases 0 and 1 work here. Doing the math: wlog, p+n=1, so frac=p=1-n (for p=%pos, n=%neg) """ #return p/(p+(1-p)*n) # to show similarity to wrong version below return frac / (frac + (1-frac) * mult)
def _smallest_change(h, alpha): """ find the smallest point not fixed by `h` """ for i in range(alpha, len(h)): if h[i] != i: return i
def instances(doc): """ Only return XFormInstances, not duplicates or errors """ return doc["doc_type"] == "XFormInstance"
def strict_update(d1, d2): """For two dicts `d1` and `d2`, works like `d1.update(d2)`, except without adding any new keys to `d1` (only values of existing keys updated). Dictonaries are copied, so that this does not have an 'inplace' effect. """ assert type(d1) == type(d2) == dict, 'Only for dictio...
def parse_credit_card(txt): """ Returns None or True. """ if txt.startswith('korttitapahtuma'): return True return None
def _converter_func(slope, intercept): """Return a function for linear transform of data.""" if type(slope) is str: return slope def func(val): return slope * val + intercept return func
def info_convertor(info,): """ [Transform the original kitti info file] """ seqs = info.keys() #['cat']# seq_lengths = [len(info[i]) for i in seqs] data = [] for seq in seqs: print(seq) data.append(info[seq]) new_infos = { "seqs": list(seqs), "seq_le...
def bin_categorize(distance: float) -> int: """Binary hypothesis binning method to be referenced across data analysis files and classifiers. Args: distance (float): The premeasured distance, in meters. Returns: 1 if the distance is less than 2 meters, 0 otherwise. """ if distance ...
def obscure_string(input_string): """ Obscures the input string by replacing all but the last 4 characters in the string with the character '*'. Useful for obscuring, security credentials, credit card numbers etc. Args: input_string A string of characters Returns: A new string where all but the l...
def gcd(a, b): """Return greatest common divisor using Euclid's Algorithm.""" while b: a, b = b, a % b return a
def get_groups_by_identifier(database, group_identifiers, identifier_name): """Returns a list of (group, group_identifier) tuples based a previously made grouping""" groups = [] for group_identifier in group_identifiers: # Get all sections in this group group = [] for section in dat...
def truncate_long_string(data, maxlen=75): """ Truncates strings longer than maxlen """ return (data[:maxlen] + "...") if len(data) > maxlen else data
def _make_divisible(v, divisor, min_value=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param di...
def find_repetition(input_str): """ Removes repetitions from string. Optionally specify minimum number of repetitions to keep before removing the rest :param input_str: String to be processed. :return: string with repetitions removed """ lines = input_str.split('\n') duplicates = [] ...
def correct_time_string(timeString): """ Returns a valid string version of the time of departure/arrival based on given argument value If no-value is given, "ALL_DAY" will be returned :param timeString: String to correct :return: Corrected string value """ if timeString == "BEFORE_NOON...
def epoch_timestamp_to_ms_timestamp(ts: int) -> int: """ Converts an epoch timestamps to a milliseconds timestamp :param ts: epoch timestamp in seconds :return: timestamp in milliseconds """ return int(ts * 1000)
def remove_last(target, remove_me): """ Returns string `target` with last occurence of `remove_me` removed >>> remove_last('evacuate valorous vampires', 'va') 'evacuate valorous mpires' """ before = target[:target.rfind(remove_me)] after = target[target.rfind(remove_me) + len(remove_me):] ...
def initial_keypath(keypath: str) -> str: """Get the initial keypath component from the keypath. Args: keypath (str): The keypath to fetch the initial component from. Returns: str: The initial keypath component or empty string. """ return keypath.split('.')[0]
def dict_to_prop_array(my_dict): """ Take a dictionary and return a MOF prop array """ names = [] values = [] for key, value in my_dict.items(): names.append(key) values.append(value) return names, values
def jars_from_output(output): """ Collect jars for ide-resolve-files from Java output. """ if output == None: return [] return [jar for jar in [output.class_jar, output.ijar, output.source_jar] if jar != None and not jar.is_source]
def compare_to(x, y): """return the sign bit of x-y""" if x < y: return 1 return 0
def doNestedGroup(indata, group_key_func, group_element_func=None): """Group the indata based on the keys that satisfy group_key_func (applied to the value) Return a dict of dictionaries created by group_element_func Each each value of the dictionaries returned by group_element_func must be a dictionary...
def _compare_state(desired_state, current_state, ignore=None): """Compares desired state to current state. Returns true if objects are equal Recursively walks dict object to compare all keys :param desired_state: The state user desires. :param current_state: The state that currently exists. :param...
def xgcd(a, b): """ Returns g, x, y such that g = x*a + y*b = gcd(a,b). Input: a -- an integer b -- an integer Output: g -- an integer, the gcd of a and b x -- an integer y -- an integer Examples: >>> xgcd(2,3) (1, -1, 1) >>> xgcd(10, 12) (2, -...
def get_value(value, value_type=None): """ This function return the value of the specified key else `None` For `strings`, the default value is the empty string. For `bytes`, the default value is empty bytes. For `bools`, the default value is false. For `numeric` types, the default value is zero...
def sample_func(arg0, args1="name", *args, **kwargs): """This is a sample module function.""" f_var = arg0 + 1 return f_var
def parse_address(address): """Convert host:port or port to address to pass to connect.""" if ':' not in address: return ('', int(address)) host, port = address.rsplit(':', 1) return (host, int(port))
def enforce_key_consistency(key): """ Forces all keys to lowercase and replaces spaces with underscores """ return str(key.replace(' ', '_').lower())
def delete_duplicates(a_list): """This function recives a list, it returns a new list based on the original list but without the duplicate elements of it""" new_list = [] for i in a_list: if not i in new_list: new_list.append(i) return new_list
def _translate_work_type(parameters_json: dict) -> str: """ translates workType based on level and value of "hasModel" (workType) """ part_of = parameters_json.get('partOf', '') while isinstance(part_of, list): part_of = part_of[0] if "zp38w953h0s" in part_of and parameters_json.get('hasModel', ...
def RobustBellmanOp(P, Sigma, state, action, gamma): """Represent R(s,a) + gamma * Sigma Notice that R(s,a) is the expected cost of execute |a| at state s. Returns float value Ve is the estimated robust value function. Returns ------- value function of state: float The value function o...
def first(iterable, condition=lambda x: True): """ Returns the first element that satisfies `condition`. \n Returns `None` if not found. """ return next((x for x in iterable if condition(x)), None)
def f(L): """ list[alpha] -> alpha + NoneType """ if len(L) > 0: return L[0]
def PDMS2Dec (st): """ Convert a declination in degrees, min, seconds to degrees t st = Declination as "dd mm ss.ss". """ ################################################################ p = st.split() h = abs(int(p[0])) m = abs(int(p[1])) s = abs(float(p[2])) dec = (float(h) + fl...
def is_sentence(sentence): """ Evaluates if the input is a sentence (more than one word) """ return len(sentence.split(' ')) > 1
def convert_to_formatted_time(seconds): """ Converts an int into minutes and seconds. from: https://www.geeksforgeeks.org/python-program-to-convert-seconds-into-hours-minutes-and-seconds/ :param seconds: The time to convert :return: A string representation in minutes and seconds """ seconds...
def local_energy_bound(local_energy, mean, threshold): """Try to suppress rare population events by imposing local energy bound. See: Purwanto et al., Phys. Rev. B 80, 214116 (2009). Parameters ---------- local_energy : float Local energy of current walker mean : float Mean val...
def patch_string_from_method(method: str) -> str: """Get the string that indicates the method to be patched for a calling method.""" switch_dict = { "get": "tentaclio_gs.clients.GSClient._get", "put": "tentaclio_gs.clients.GSClient._put", "remove": "tentaclio_gs.clients.GSClient._remove"...
def parse_dependency(value): """ Basic support for version expression. Right now it just parses mypackage==1.0.0 -> ('mypackage', '1.0.0') mypackage -> ('mypackage', None) """ # Split into parts parts = value.split('==') # We always have name name = parts[0] # Pull out th...
def column_index_to_integer(col): """Convert XLS-style column index into equivalent integer Given a column index e.g. 'A', 'BZ' etc, converts it to the integer equivalent using zero-based counting system (so 'A' is equivalent to zero, 'B' to 1 etc). """ # Convert column index e.g. 'A', 'BZ' et...
def splitProjectInfo(value: str): """Split a comma-separated list of 3 values (hub,group,project)""" tokens = value.split(",") if len(tokens) != 3: raise RuntimeError(f"Invalid project: {value}") return tokens
def sort_variables(variables): """Sort variables based on their rank and shift. Note that this relies on all variables having a unique rank. """ return tuple(sorted(variables, key=lambda v: (v.rank, v.shift)))
def adapt_PEPformat(x): """ PEPred-Suite jar input format :param x: id that starts with '>' :return: id that starts with '>' and ends with '|0' """ if '|' not in x: x = x + '|0' return x
def null_observation_model(arg): """ A callable that returns ``arg`` directly. It works as an identity function when observation models need to be disabled for a particular experiment. """ import warnings warnings.warn( "`null_observation_model` is deprecated. " "Use `<Measu...
def mat33_mat31_mult(A, b): """Multiply a 3x3 matrix with a 3x1 matrix. Parameters ---------- A : 'list' ['list' ['float']] 3x3 matrix. b : 'list' ['float'] 3x1 matrix. Returns ------- res : 'list' ['float'] 3x1 matrix. """ res = [0, 0, 0] r3 = range...
def rename_var(v, rs): """Renames a variable v, iff v occurs in a variable conversion list. Otherwise, v is returned unmodified""" for r,s in rs: if v == r: return s return v
def hamdist(str1, str2): """Count the # of differences between equal length strings str1 and str2""" diffs = 0 for ch1, ch2 in zip(str1, str2): if ch1 != ch2: diffs += 1 return diffs
def _idices2slices(a, a0=0, a1=99): """Converts an iterable of split-point indices into an array of range indices. E.g., [] --> [(a0,a1)] [4] --> [(a0, 3), (4, a1)] [2,3,6] --> [(a0, 1), (2, 2), (3, 5), (6, a1)] """ if a is None or len(a) == 0: return [(a0,a1)]...
def sample_time(times): """ Returns the mean sample time of the array of time instants given params: - times : array of instants """ n = len(times) diffs = [times[i+1] - times[i] for i in range(n - 1)] return sum(diffs)/len(diffs)
def get_scores(student): """ get_scores(student) -> tuple student = {'name1' : score1, 'name2' : score2, ...} ret tuple(score) """ return tuple(student.values())
def findAnEven(l): """ Assumes l is a list of ints Returns the first even num in l Raises ValueError if l doesn't contain an even num """ first_even_n = 0 for num in l: if num % 2 == 0: first_even_n = num break if first_even_n == 0: raise ValueError("l doesn't contain an eve...
def findMedianSortedArrays(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ m = len(nums1) n = len(nums2) x = m + n i = 0 j = 0 kk = [] while i + j < int(x / 2) + 1 and i < m and j < n: if nums1[i] <= nums2[j]: kk.appe...
def wrapto360(angle): """ Wrap a value on -180, 180 to 360. :param degrees: float :return: float """ if angle >= 0: return angle else: return 360 + angle
def _resolution_to_timedelta(res_text): """ Convert an Entsoe resolution to something that pandas can understand Parameters ---------- res_text : str Returns ------- str """ if res_text == 'PT60M': delta = '60min' elif res_text == 'P1Y': delta = '12M' el...
def maybe_float(string): """Convert string to a float and return the float or None.""" try: return float(string) except ValueError: return None
def hex_to_byte(hexStr): """ Convert hex strings to bytes. """ bytes = [] hexStr = ''.join(hexStr.split(" ")) for i in range(0, len(hexStr), 2): bytes.append(chr(int(hexStr[i:i + 2], 16))) return ''.join(bytes)
def effective_prior(p_tar, c_miss, c_fa): """This function adjusts a given prior probability of target p_targ, to incorporate the effects of a cost of miss, cmiss, and a cost of false-alarm, cfa. Args: p_tar: target prior c_miss: cost of miss c_fa: cost of false alarm Returns: ...
def tokenize_text(text): """ Fake tokenizer; Return a list of words """ return text.split()
def int_to_cohort(index, base=16): """int_to_cohort(index[, base]) Converts a sequential ID to a cohort tuple. Positional arguments: index (int) - integer ID Keyword arguments: base (int) - base year to treat as 0 Returns: (tuple) - (year, season) tuple """ retur...
def add_smoke_events(esdr_json): """ Given a dictionary in the ESDR file format, compute and add the smoke events Here is an example of the ESDR format: {"channel_names": ["smoke_probability", "activation_ratio", "event"], "data": [[1546520585, 1.0, 0.067, 0], [1546520675, 1.0, 0.063, 0]]} For...
def mean(array): """ get mean of list, returns None if length is less than 1 """ if not array: return None return float(sum(array))/float(len(array))
def const_in_binop(v): """ >>> const_in_binop(-1) 1 >>> const_in_binop(0) 0 >>> const_in_binop(1 << 32) 1 >>> const_in_binop(1 << 32 - 1) 0 """ if v < 0 or v >= (1 << 32): return 1 else: return 0
def pad(value,size): """ pad a string with spaces to the size provided """ if len(value) < size: value += ' '*(size-len(value)) return value
def normalise_card_fields(cards): """ Adds XSOAR-like variations of card fields. """ fields = { "id": "ID", "name": "Name", "url": "URL", "due": "Due", "labels": "Labels" } for card in cards: for k, v in fields.items(): if k in card: ...
def dms2dd(degrees, minutes, seconds, direction): """ http://en.proft.me/2015/09/20/converting-latitude-and-longitude-decimal-values-p/ Args: degrees: minutes: seconds: direction: Returns: """ dd = float(degrees) + float(minutes)/60 + float(seconds)/(60*60) ...
def construct_rss_url(root_url, rss_feed_path): """ Construct URL for the RSS feed. Args root_url: Blog's root URL. rss_feed_path: String or Path object describing the path to the RSS feed under the blog's root directory. Returns The RSS feed URL as a string. ...
def factorial(m): """Returns `m!`. """ if not m: return 1 k = m while m > 1: m -= 1 k *= m return k
def rectangles_collide(pos1, size1, pos2, size2): """ Return True if the rectangles collide Rectangles are supplied in [x,y], [xsize, ysize] form with the left corner and size. Assumes positions and sizes to be sorted :param pos1: top left corner of the first rectangle, as (x, y) 2-tuple :par...
def ch_company_dict(obj): """Creates dictionary from a company with id and company_number keys.""" if obj is None: return None return { 'id': str(obj.id), 'company_number': obj.company_number, }
def sum_digits(n: int, base: int = 10) -> int: """Sums the digits of a non-negative integer in a given base. Args: n: A non-negative integer value. base: The base in which ``n`` will be represented. Must be at least 2. """ digit_sum = 0 while n != 0: n, digit = divmod(n, bas...
def basic(s, coeffs): """Performs the "standard" de Casteljau algorithm.""" r = 1.0 - s degree = len(coeffs) - 1 pk = list(coeffs) for k in range(degree): new_pk = [] for j in range(degree - k): new_pk.append(r * pk[j] + s * pk[j + 1]) # Update the "current" valu...
def get_alert(paramalertLS, paramalertLQ, parampopLS, parampopLQ, hazbinLS=[1., 10., 100.], popbinLS=[100, 1000, 10000], hazbinLQ=[10., 100., 1000.], popbinLQ=[100, 1000, 10000]): """ Get alert levels Args: paramalertLS (float): Hazard statistic of preferred landslide mo...
def _reshape_full_data(full_data: dict) -> dict: """Reshape full data into simple keys/values. Output example: { "2021-08-16": None, "2021-08-17": "Chicken Teriyaki", "2021-08-18": "Taco Soup", } """ data = {} for day in full_data.get("days", []): key = day...
def merge_user_settings(settings): """Return the default linter settings merged with the user's settings.""" default = settings.get('default', {}) user = settings.get('user', {}) if user: linters = default.pop('linters', {}) user_linters = user.get('linters', {}) for name, dat...
def get_first_geolocation(messages): """ return the first geotagged message lat and long as tuple """ try: return [(m.latitude, m.longitude) for m in messages if m.has_geolocation()][0] except: # pylint: disable=W0702 return ()
def cure_weight(refrxn, refeq, rrat, xi=0.2): """ :param refeq: value of benchmark for equilibrium Reaction :param rrat: ratio of intermonomer separation for Reaction to equilibrium Reaction :param xi: parameter :return: weight for CURE """ sigma = xi * abs(refeq) / (rrat ** 3) weight =...
def node_name(name): """Get node name without io#.""" pos = name.find(":") if pos >= 0: return name[:pos] return name
def to_int(val): """ Convert a string to int number from https://github.com/longld/peda """ try: return int(str(val), 0) except: return None
def primes(n): """ # Z. Returns a list of primes < n """ sieve = [True] * n for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i]: sieve[i * i::2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1) return [2] + [i for i in range(3, n, 2) if sieve[i]]
def find_role(member, key): """ Find and return the role to pass the message to. :param server: The server to find the role for. :param key: The role to select """ if not member: return None for role in member.roles: if role.name == key: return role return ...
def blue_star(c1): """ The relation between the color1 and color2 in BLUE stars assuming that the BLUE stars are 2 times brighter in color1 ---------- c1: flux in color1 ---------- Returns - flux in color2 """ c2 = 0.5*c1 return c1, c2
def unpack(trace, mapping): """ Takes a Grayscale trace JSON object and a response mapping object (see extract_mapping above) and returns a JSON string for an equivalent PDM trace. """ history = trace["clickTrackers"]["clickTracker"]["eventHistory"] decisions = [] for event in history: if event["event...
def format_headers(headers, excludes=[]): """Returns a dictionary after excluding blacklisted headers""" _h = {} for k, v in headers.items(): if k not in excludes: _h[k] = v return _h
def get_file_ext(filename): """Returns the lowercase extension part of filename, without the dot. """ pos = filename.rfind('.') if pos > -1: return filename[pos + 1:].lower() else: return ''
def enum_to_string(enum): """ Convenience method that converts an IntEnum/Enum to string Parameters ---------- enum: Enum The enum to convert Returns ------- name: str The stringified enum """ enum = str(enum) return enum[enum.index('.') + 1:]
def render_label(label, inits={}): """Slightly more flexible way to render labels. >>> from sympy.physics.quantum.circuitplot import render_label >>> render_label('q0') '$\\\\left|q0\\\\right\\\\rangle$' >>> render_label('q0', {'q0':'0'}) '$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\...
def UsersInvolvedInAmendments(amendments): """Return a set of all user IDs mentioned in the given Amendments.""" user_id_set = set() for amendment in amendments: user_id_set.update(amendment.added_user_ids) user_id_set.update(amendment.removed_user_ids) return user_id_set
def hello(friend_name): """Return "Hello, World!" >>> hello("Rowan") 'Hello, Rowan!' """ return "Hello, {}!".format(friend_name)
def equal_project_access(d1, d2): """ Check whether d1 and d2 are equal regardless of the order of list values. Args: d1, d2 (dict): { project1: [permission1, permission2], project2:...} Returns: boolean: True if d1 and d2 contain the same set of permissions for each project, F...
def ms2smp(ms, fs): """ Parameters ---------- ms: float Time in milliseconds fs: float Sampling rate in Hz. """ # return corresponding length in samples return int(float(fs) * float(ms) / 1000.0)
def p1(x, s): """ Smoothed L1 penalization. """ return (x-s/2)*(x>s) - (x+s/2)*(-x>s) + ((x**2)/(2*s))*(x<=s and -x<=s)
def get_build_params(test, params=[], strseparator="&", str_boolean=False): """ function to process params of url `test` contain the view description/ instance `params` contain the array list to send on params `strseparator` string separator of url params. Default= & `str_boolean` bo...
def safe_str(obj): """ return the byte string representation of obj """ try: return str(obj) except UnicodeEncodeError: return obj
def get_names(feat_list): """ feat_list: list of feature defined in 'feature_object' Returns list of the feature names. """ names = [] for el in feat_list: if el.size != 1: for it in range(el.size): names.append(el._return_name()[it]) else: ...
def fix(text): """Repairs encoding problems.""" # NOTE(Jonas): This seems to be fixed on the PHP side for now. # import ftfy # return ftfy.fix_text(text) return text
def findNextOpr(txt): """ >>> findNextOpr(' 3* 4 - 5') 3 >>> findNextOpr('8 4 - 5') 6 >>> findNextOpr('89 4 5') -1 """ # decide whether the data type is correct if not isinstance(txt, str) or len(txt) <= 0: return "error: findNextOpr" # use for ...
def calculate_ngram_freqs_solution(ngrams): """Calculate the frequency of a subsequent word given a sequence of ngrams :param ngrams: [['i', 'will', 'be'], ['will', 'be', 'leaving'], ['be', 'leaving', 'florida']] """ freqs = {} for ngram in ngrams: # Differentiate successor (= lastWord) ...
def find(label, equivList): """ Find the neighbor with the smallest label and assign it to the current element. Parameters: label, label number; equivList, equivalence relatioship list. Returns: minVal, smallest label. """ minVal = min(equivList[label]) while label != minV...