content
stringlengths
42
6.51k
def renorm_flux(flux, flux_err, star_fluxratio: float): """ Renormalizes light curve flux to account for flux contribution due to nearby stars. Args: flux (numpy array): Normalized flux of each data point. star_fluxratio (float): Proportion of flux that comes ...
def is_ab_band(band): """ Check if the default system for the provided band is AB. Parameters ---------- band : str Name of a photometric filter Returns ------- bool True if the default system for this band is AB """ ab_bands = ['u', 'g', 'r', 'i', 'z', 'y']...
def merge_attributions(match_list, attributions): """merge_attributions""" over_all = [] miss = 0 for i in match_list: over_all.extend(i[0]) attribution_dic = {} for i in range(len(attributions)): split_time = over_all.count(i) if split_time: attribution_dic[...
def new_feature_collection(features=None): """ :param features: :return: """ # set features to empty list by default if features is None: features = [] # build a geojson feature collection feature_collection = { "type": "FeatureCollection", "features": features...
def _isWindows(build): """Return build.is_windows in a backwards-compatible way.""" try: return build.is_windows except AttributeError: return False
def human_time(seconds: int) -> str: """convert seconds into human readable 00d00h00m00s format""" sign_string = "-" if seconds < 0 else "" seconds = abs(int(seconds)) days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) if ...
def _get_spectrum_header_offset(spectrum_number, srsi, nrps): """ Calculates the PCF header offset for spectrum. Inputs: spectrum_number: number of spectrum to obtain offset of header for. srsi: Spectral record start index. nrps: number of records per spectrum Returns: offs...
def clean_empty(d): """ Clean empty node in nested Dict or List. """ if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (clean_empty(v) for v in d) if v] return {k: v for k, v in ((k, clean_empty(v)) for k, v in d.items()) if v}
def group_objects_by_number(object_list, number_in_each_group=3): """ Accepts an object list and groups it into sets. Intended for displaying the data in a three-column grid. """ new_list = [] i = 0 while i < len(object_list): new_list.append([x for x in object_list[i:i+number_in_ea...
def kruskal_ALGraph(graph): """an algorithm for gengrate MST time complexity O(E * log2 E) Parameters: ALGraph Returns: set simple input: >>> graph = { ... 0: {1:1, 2:3, 3:4}, ... 1: {2:5}, ... 2: {3:2}, ... 3: set() ... } out...
def deescapify(name) : #--------------------------------------------------------------------------------------------------- """ A Python version of ncgen's deescapify() function (see genlib.c). The code here is a fairly literal translation of that function. I expect this could be recoded in a more pythonic way...
def _apply_post_effect_or_preset(effect_or_preset, tensor, shape, time, speed): """Helper function to either invoke a post effect or unroll a preset.""" if callable(effect_or_preset): return effect_or_preset(tensor=tensor, shape=shape, time=time, speed=speed) else: # Is a Preset. Unroll me. ...
def _ftr_tick(sub_features_config=None): """sub-feature converting parent to tick""" return { 'name': 'RunnerFeatureSub', 'kwargs': { 'value_processors_config': [{ 'name': 'value_processor_to_tick', }], 'sub_features_config': sub_features_confi...
def get_verts(voxel, g): """return list (len=8) of point coordinates (x,y,z) that are vertices of the voxel (i,j,k)""" (i, j, k) = voxel dx, dy, dz = g["dx"], g["dy"], g["dz"] v1_0, v1_1, v1_2 = g["xlo"] + i * dx, g["ylo"] + j * dy, g["zlo"] + k * dz vertices = [ (v1_0, v1_1, v1_2), ...
def S_id(v): """Fingerprints a potential value to a string identifier.""" return 'S{:07d}'.format(int(round(-v * 1e5)))
def roots(a, b, c): """ Return two roots of the quadratic algebraic equation ax^2 + bx + c = 0, where a, b, and c may be complex. """ import cmath # complex functions q = b*b - 4*a*c r1 = -(b - cmath.sqrt(q))/(2*a) r2 = -(b + cmath.sqrt(q))/(2*a) # r1 and r2 are complex because ...
def nb_of_answers(pop): """ Returns the number of possible answer given a population. """ return pop[0]*2 + pop[1] + pop[2]
def split(s): """split by newlines""" return s.split('\n')
def dice_coefficient(a, b): """ Creates a coefficient that shows how similar two strings are based on bigrams :param a: (String) String 1 :param b: (String) String 2 :return: (float) percentage match """ if not len(a) or not len(b): return 0.0 # quick case for true duplic...
def S(r, rc1, rc2, derivative=False): """ Calculate the switching function S(r) which decays continuously between 1 and 0 in the range from rc1 to rc2 (rc2>rc1): S(r) = (rc2^2 - r^2)^2 * (rc2^2 + 2*r^2 - 3*rc1^2) / (rc2^2-rc1^2)^3 I'm using the same smoothing/switching cutoff function used by the...
def __flatten(parent, visited): """ Return a flat list of all tree objects """ objs = [] if type(parent) in (list, tuple): for obj in parent: objs.extend(__flatten(obj, visited)) elif parent is not None: if parent not in visited: visited.append(parent) ...
def compute_tf(vector, bow): """ Computes the Term Frequency of a vector, where: tf(w) = (Number of times the word appears in a user story) / (Total number of words in the user story) """ tf_dict = {} bow_count = len(bow) for word, count in vector.items(): tf_dict[word] = count /...
def num_frames(length, fsize, fshift): """Compute number of time frames of spectrogram """ pad = (fsize - fshift) if length % fshift == 0: m = (length + pad * 2 - fsize) // fshift + 1 else: m = (length + pad * 2 - fsize) // fshift + 2 return m
def plural_obj_name_to_singular(obj_name, post_fix='', post_fix_used=None): """Convert plural object name to a singular name.""" acronyms = ['Ads', 'Nis'] # list of acronyms that end in 's' # if it's two 'ss' on the end then don't remove the last one if (obj_name not in acronyms and obj_name[-1] == 's'...
def get_root(database): """Load root folder from database.""" return list(database.keys())[0]
def _construct_license(fuel_metadata_dict): """Construct LICENSE string from an input Fuel metadata dictionary.""" return ("License: %s\n" "License URL: %s\n" "License Image: %s" % (fuel_metadata_dict.get("license_name", ""), fuel_metadata_dict.get("license_url...
def bisect_search1(L, e): """where L is list and e is element""" if L == []: return False elif len(L) == 1: return L[0] == e else: half = len(L) // 2 if L(half) > e: return bisect_search1(L[:half], e) else: return bisect_search1(L[half:], e...
def filter_stems_prob(stem_dic, CUTOFF_PROB): """ Function: filter_stems_prob() Purpose: Create new dictionary which stores stems with high probability. Input: A dictionary of stems. Return: An new dictionary of stems. """ stems_...
def heuristic(point1, point2): """ Returns the distance between two points. params: point1 (int tuple): first point point2 (int tuple): second point return: dist (int): Manhattan (aka L) distance between the points """ x1, y1 = point1 x2, y2 = point2 ...
def get_cluster_id_by_name(cluster_list, cluster_name): """Helper function to retrieve the ID and output bucket of a cluster by name.""" cluster = [c for c in cluster_list if c['clusterName'] == cluster_name][0] return cluster['clusterUuid'], cluster['config']['configBucket']
def russian(a, b): """ The Russian Peasant Algorithm: Multiply one integer by the other integer. Input: a, b: integers Returns: a*b """ c = 0 while a > 0: if a % 2 == 1: c = c + b b = b << 1 a = a >> 1 return c
def build_entity(key, value): """ build_entity return a dict that can be passed back to rasa as an entity using the given string key and value """ return {"entity": key, "value": value, "start": 0, "end": 0}
def database_url(url): """Parse a string as a Heroku-style database URL.""" # Heroku database URLs start with postgres://, which is an old and # deprecated dialect as far as sqlalchemy is concerned. We upgrade this # to postgresql+psycopg2 by default. if url.startswith('postgres://'): url = ...
def transform_keys(transform, d): """ Transforms the keys in a dict. :param transform: If method, calls with key and value, returns new key If dict, maps keys to key values for new key If list, only returns dict with specified keys Else retu...
def read_file(filename: str) -> str: """Read a file and return the text""" with open(filename, "r") as file: data = file.read() return data
def convert_millis(track_dur_lst): """ Convert milliseconds to 00:00:00 format """ converted_track_times = [] for track_dur in track_dur_lst: seconds = (int(track_dur)/1000)%60 minutes = int(int(track_dur)/60000) hours = int(int(track_dur)/(60000*60)) converted_time = '%...
def get_username_for_os(os): """Return username for a given os.""" usernames = {"alinux2": "ec2-user", "centos7": "centos", "ubuntu1804": "ubuntu", "ubuntu2004": "ubuntu"} return usernames.get(os)
def flatten(xss): """Flatten a list of lists Args: xss (list[list[T]]): A list of lists. Returns: list[T]: A flattened input. """ return [x for xs in xss for x in xs]
def PrettyString(val): """ BRIEF If it's a float, reduce to 2 digits """ if isinstance(val, list) or isinstance(val, tuple): return "({0})".format(', '.join([PrettyString(item) for item in val])) elif callable(val): return val.__name__ else: val = str(val) try: ...
def longest_sub_str_without_dup(string): """ :param string: string :return: max length of substr with out duplication """ cur_len = 0 max_len = 0 last_pos = [-1] * 26 for i in range(len(string)): curchr_pos_i = ord(string[i]) - ord('a') cur_chr_pre_i = last_pos[curchr_pos...
def read_bytes(buf, size): """ Reads bytes from a buffer. Returns a tuple with buffer less the read bytes, and the bytes. """ b = buf[0:size] return (buf[size:], b)
def growClusterForPoly( labels, threshold_array, P, NeighborPolys, C, weight, spatialThre ): """Grow one region from current area unit until threshold constraint is satisified Parameters ---------- labels : list, required A list of current region labels thresho...
def query_nearby( lat: float, lon: float, limit: int, radiusmetres: int ) -> dict: """query to get wiki pages near a coordinate options for geosearch are found here: https://en.wikipedia.org/w/api.php?action=help&modules=query+geosearch""" if not 10 <= radiusmetres <= 10000: raise Exception...
def nested_byte_values_to_strings(rule, keyname): """ currently valid nested byte values in statements array are - OrStatement - AndStatement - NotStatement """ if rule.get('Statement', {}).get(keyname): for idx in range(len(rule.get('Statement', {}).get(keyname, {}).get(...
def value(d): """Given either a dict or a list, returns one of the values. Intended for coldict2mat and rowdict2mat. """ return next(iter(d.values())) if isinstance(d, dict) else d[0]
def sender_is_bot(message): """Check if sender is bot to not reply to own msgs""" return message['sender_type'] == "bot"
def fizz_buzz_elif(n): """ Return the correct FizzBuzz value for n by testing divisibility in an if-elif. """ divisible_by_3 = n % 3 == 0 divisible_by_5 = n % 5 == 0 if divisible_by_3 and divisible_by_5: return "Fizz Buzz!" elif divisible_by_3: return "Fizz!" elif div...
def fixStringEnds(text): """ Shortening the note body for a one-line preview can chop two-byte unicode characters in half. This method fixes that. """ # This method can chop off the last character of a short note, so add a dummy text = text + '.' # Source: https://stackoverflow.com/a/3048717...
def rivers_with_station(stations): """Creates a list of rivers which have at least one station, with no duplicates""" rivers_list = [] for station in stations: if station.name == None: pass else: rivers_list.append(station.river) return set(rivers_list)
def seconds_to_hms(seconds): """ Return string 'hh:mm:ss' or 'mm:ss'. """ if not seconds: return "0" h = seconds / 3600 s = seconds - 3600 * h m = s / 60 s = s - 60 * m if not h: return "%02d:%02d" % (m, s) return "%02d:%02d:%02d" % (h, m, s)
def range_slider_select_tab1(value): """ :return: Tab 1 year range slider output years for density plot on tab 1. """ transformed_value = [v for v in value] return "Years Selected: {} to {}".format(transformed_value[0], transformed_value[1])
def retrieve_task_id_from_message(kwargs): """Helper to retrieve the `Task` identifier from the message `body`. This helper supports Protocol Version 1 and 2. The Protocol is well detailed in the official documentation: http://docs.celeryproject.org/en/latest/internals/protocol.html """ headers ...
def card_average(hand): """ :param hand: list - cards in hand. :return: float - average value of the cards in the hand. """ return sum(hand) / len(hand)
def cat(*strings): """Concatinates strings""" return "".join(strings)
def consistency_penalty_scheduler(step, n_anneal_steps, base_penalty_weight): """ Schedule the consistency penalty. """ if base_penalty_weight == 0: return 0. if step >= n_anneal_steps: return base_penalty_weight return 0.0
def check_matrix_empty(matrix, rows, cols): """ Return True if the matrix is made up of 0's""" for r in range(rows): for c in range(cols): if matrix[r][c] == 1: return False return True
def merge_dicts(dicts): """ Merges dictionaries :param dicts: :return: """ dres = {} for dc in dicts: dres.update(dc) return dres
def check_forms_validity(search_forms): """ Checks validity of search forms. :param search_forms: list of search forms :return: True if all forms are valid, otherwise False """ for search_form in search_forms: if not search_form.get('form').is_valid(): return False ret...
def _str_bool(v): """convert a string rep of yes or true to a boolean True, all else to False""" if (type(v) is str and v.lower() in ['yes', 'true']) or \ (type(v) is bool and bool(v)): return True return False
def has_tags(available, required): """ Helper method to determine if tag requested already exists """ for key, value in required.items(): if key not in available or value != available[key]: return False return True
def eiffel_c_define (line, hfilename): """Eiffel wrapper of C define in 'line'.""" items = line.split () if len (items) == 3: symbol = items[1] value = items[2] result = """ %s: INTEGER external "C [macro <%s>]" alias "%s" end""" % (...
def last(thing): """ LAST wordorlist if the input is a word, outputs the last character of the word. If the input is a list, outputs the last member of the list. """ return thing[-1]
def is_control(line, index, word): """ Return whether LINE[INDEX] is actual the start position of control statement WORD. It must be followed by an opening parantheses and only whitespace in between WORD and the '('. """ if index > 0: if not (line[index-1] in [' ', '\t', ';']): return False inde...
def use_keys_from(src, template): """ Create a new dictionary using whitelisted keys """ return {k: v for k, v in src.items() if k in template}
def get_files_by_id(list_of_files, date, numbers): """ Select and return filenames specified by ``date`` and ``numbers`` out of ``list_of_files``. Parameters ---------- list_of_files : iterable of strings. List of filenames in which to search. date : string. The date for all id...
def report_error(message): """ Return a dictionary with a command to display 'message' """ return {'mode': 'Error', 'status': message}
def convert_camel_case(s: str) -> str: """convert to camel case Args: s (str): str Returns: str: camel case str """ return s.title().replace("_", "").replace("-", "")
def missing_to_default(field, default): """ Function to convert missing values into default values. :param field: the original, missing, value. :param default: the new, default, value. :return: field; the new value if field is an empty string, the old value otherwise. :rtype: any ...
def json_tweet_parser(tweet, users, tweets_dict, users_dict): """Function to parse a tweet with bs Arguments: tweet {str} -- tweet result users {dict} -- dict with results tweets_dict {dict} -- dict to store tweets users_dict {dict} -- dict to store users Returns: d...
def update_db_query(translation, detected_language, news_id): """ :param translation: :param detected_language: :param news_id: :return: """ if translation and detected_language and news_id: return u"UPDATE news SET translated_content='%s', detected_language='%s' " \ ...
def _n_pow_w(n): """ return (1-w)**k """ x, y = divmod(n, 2) k1 = 3**x if y == 1: k2 = -k1 else: k2 = 0 return k1, k2
def get_reformatted_source_path(path: str): """Build source path without trailing '/'. Args: path (str): Original path. Returns: str: Reformatted path. """ if path.endswith("/"): path = path[:-1] return path
def keys2string(dictionary): """Recursive function which converts dictionary keys to strings""" if not isinstance(dictionary, dict): return dictionary return dict((str(k), keys2string(v)) for k, v in dictionary.items())
def nice_value(x): """Round x to nice value.""" exp = 1.0 sign = 1 if x < 0.0: x = -x sign = -1 while x >= 1.0: x /= 10.0 exp *= 10.0 while x < 0.1: x *= 10.0 exp /= 10.0 if x >= 0.75: return sign * 1.0 * exp if x >= 0.35: ...
def double_eights(n): """Return true if n has two eights in a row. >>> double_eights(8) False >>> double_eights(88) True >>> double_eights(2882) True >>> double_eights(880088) True >>> double_eights(12345) False >>> double_eights(80808080) False """ "*** YOUR ...
def add_zero(number): """ Add zero before number if number is smaller than 10. :param number: <string> -> number :return: <string> -> number """ if int(number) < 10: number = '0' + str(number) return number
def _replace_bool(s): """Replace booleans and before passing to ast.literal_eval.""" s = s.replace('true', 'True') s = s.replace('false', 'False') return s
def _state_preparation_pauli_words(num_wires): """Pauli words necessary for a state preparation. Args: num_wires (int): Number of wires of the state preparation Returns: List[str]: List of all necessary Pauli words for the state preparation """ if num_wires == 1: return ["X...
def remove_ambiguous_solutions(fn_in, db_lines, strict=True, verbose=True): """ Removes features with identical solutions. During solving, some tags may be tightly coupled and solve to the same solution. In these cases, those solutions must be dropped until disambiguating information can be found. ...
def only_action_date_type(time_period): """ if a date_type is last_modified_date, don't use the matview this applies to """ try: for v in time_period: if v.get("date_type", "action_date") != "action_date": return False except Exception: return False ...
def rjust(value, arg): """ Right-aligns the value in a field of a given width. Argument: field size. """ return value.rjust(int(arg))
def pool_to_HW(shape, data_frmt): """ Convert from NHWC|NCHW => HW """ if len(shape) != 4: return shape # Not NHWC|NCHW, return as is if data_frmt == 'NCHW': return [shape[2], shape[3]] return [shape[1], shape[2]]
def join_constraints_list(lst): """ Eliminates dublicated functions """ return ''.join(sorted(set(lst)))
def sign (n) : """Returns the sign of n. >>> sign (4) 1 >>> sign (-6.9) -1 >>> sign (0) 0 """ if n > 0 : return 1 elif n < 0 : return -1 else : return 0
def is_url(location): """ Check that a given location is an URL """ return location and "://" in location
def time_formatter(seconds: float) -> str: """ humanize time """ minutes, seconds = divmod(int(seconds),60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ((str(days) + "d, ") if days else "") + \ ((str(hours) + "h, ") if hours else "") + \ ((str...
def unique1(s): """Return True if there are no duplicate elements in sequence s.""" for j in range(len(s)): for k in range(j + 1, len(s)): if s[j] == s[k]: return False # found duplicate pair return True
def create_guess_char_indices_dict(guesses): """ Loops over each guess, and then loops over each character in the guess. This method finds the index of the character in the guess and then appends it to a list of indices which are set as the value of the character (key) in the result map. Each non-unders...
def build_container_sas_uri(storage_acc_url: str, container: str, sas: str) -> str: """ Create a container SAS URL in the format of: {account-url}/{container}?{SAS} Note that this method is not responsible for the generation of the SAS token. :param storage_acc_url: Base URL to the storage account ...
def replace_bibtex_cite_name(bibtex, current_name, new_name): """replaces the cite_name in a bibtex file with something else :param: string of bibtex to do the replacing on :param current_name: current cite name in the bibtex :param new_name: name to replace it with """ new_bibtex = bibtex.rep...
def frame_convert(frame, cals): """ Convert the frame to a wavelength using a starting value and delta (in microns). Parameters ---------- frame : int Datacube frame to convert to a wavelength. cals : list of floats Calibration values for the input datacube; ...
def atoms(gra): """ atoms, as a dictionary """ atm_dct, _ = gra return atm_dct
def aero_force(rho, V, C, A): """ Aerodynamic lift/drag equation Input variables: rho : Fluid density V : Fluid velocity C : Lift/drag coefficient A : Reference area """ F = 0.5 * rho * (V**2) * C * A return F
def check_ip(ip): """ check_ip is called from all_check. check_ip takes arguments src_ip and dst_ip from acl_data one at a time and parses through both variables to make sure they are correct ip addresses. Returns True if IP is correct, returns False if IP is wrong format. """ ip = ip.split...
def check_step_length(step_length): """Validate window length""" if step_length is not None: if not is_int(step_length) or step_length < 1: raise ValueError( f"`step_length` must be a positive integer >= 1 or None, " f"but found: {step_length}") return ste...
def chksum(rom): """Compute the Atari Diagnostics Cartridge checksum. This is a plain 16-bit modular sum. """ return sum(rom)&0xFFFF
def list_contains_only_xs(lst): """Check whether the given list contains only x's""" for elem in lst: if elem != "X": return False return True
def create_category_index(categories): """Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representin...
def _hex_to_float(color): """Convert hex value to tuple of type float with values between 0.0 and 1.0 """ a = color.lstrip('#') return tuple(int(a[i:i+2], 16)/255.0 for i in (0, 2, 4, 6))
def convert_hex_to_rgb_tuple(hexstring): """ """ hexstring = hexstring.replace("#", "") return tuple([int(hexstring[i:i+2], 16) for i in range(0, len(hexstring), 2)])