content
stringlengths
42
6.51k
def emptyfn(body: str, return_type: str="u1") -> str: """Wrap body inside of an empty function""" return f"fn test() -> {return_type} {{{body}}}"
def __get_int(section, name): """Get the forecasted int from json section.""" try: return int(section[name]) except (ValueError, TypeError, KeyError): return 0
def format_transaction(timestamp: float, address: str, recipient: str, amount: int, operation: str, openfield: str): """ Returns the formatted tuple to use as transaction part and to be signed This exact formatting is MANDATORY - We sign a char buffer where every char counts. """ str_timestamp = '%.2f' % timestamp str_amount = '%.8f' % float(amount) transaction = (str_timestamp, address, recipient, str_amount, operation, openfield) return transaction
def roman_to_int(s): """ https://www.tutorialspoint.com/roman-to-integer-in-python :type s: str :rtype: int """ roman = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900 } i = 0 num = 0 while i < len(s): if i + 1 < len(s) and s[i:i + 2] in roman: num += roman[s[i:i + 2]] i += 2 else: # print(i) num += roman[s[i]] i += 1 return num
def sortedSquares(nums): """ :type nums: List[int] :rtype: List[int] """ l = 0 r = len(nums) - 1 i = len(nums) - 1 result = [0] * len(nums) while l <= r: if nums[l]**2 < nums[r]**2: result[i] = nums[r]**2 i -= 1 r -= 1 else: result[i] = nums[l]**2 i -= 1 l += 1 return result
def make_project(id): """ return a template project """ return { "type": "Project", "metrics": [], "tags": [], "id": id, "description": "", "applicant": "", }
def evaluate_g3( kappa, nu, sigma, mu, s3 ): """ Evaluate the third constraint equation and also return the jacobians :param float kappa: The value of the modulus kappa :param float nu: The value of the modulus nu :param float sigma: The value of the modulus sigma :param float mu: The value of the modulus mu :param float s3: The constraint value """ return ( kappa + nu - 2 * sigma ) * mu - 2 * sigma**2 - s3**2,\ {'kappa':mu, 'nu':mu, 'sigma':-2 * mu - 4 * sigma, 'mu':( kappa + nu - 2 * sigma), 's3':-2 * s3 }
def is_true(v) -> bool: """ Check if a given bool/str/int value is some form of ``True``: * **bool**: ``True`` * **str**: ``'true'``, ``'yes'``, ``'y'``, ``'1'`` * **int**: ``1`` (note: strings are automatically .lower()'d) Usage: >>> is_true('true') True >>> is_true('no') False :param Any v: The value to check for truthfulness :return bool is_true: ``True`` if the value appears to be truthy, otherwise ``False``. """ v = v.lower() if type(v) is str else v return v in [True, 'true', 'yes', 'y', '1', 1]
def expand_video_segment(num_frames_video: int, min_frames_seg: int, start_frame_seg: int, stop_frame_seg: int): """ Expand a given video segment defined by start and stop frame to have at least a minimum number of frames. Args: num_frames_video: Total number of frames in the video. min_frames_seg: Target minimum number of frames in the segment. start_frame_seg: Current start frame of the segment. stop_frame_seg: Current stop frame of the segment. Returns: Tuple of start frame, stop frame, flag whether the segment was changed. """ num_frames_seg = stop_frame_seg - start_frame_seg changes = False if min_frames_seg > num_frames_video: min_frames_seg = num_frames_video if num_frames_seg < min_frames_seg: while True: if start_frame_seg > 0: start_frame_seg -= 1 num_frames_seg += 1 changes = True if num_frames_seg == min_frames_seg: break if stop_frame_seg < num_frames_video: stop_frame_seg += 1 num_frames_seg += 1 changes = True if num_frames_seg == min_frames_seg: break return start_frame_seg, stop_frame_seg, changes
def f(x): """ A function for testing on. """ return -(x + 2.0)**2 + 1.0
def app_name(id): """Convert a UUID to a valid Heroku app name.""" return "dlgr-" + id[0:8]
def rename_keys(dist, keys): """ Rename all the dictionary keys *in-place* inside a *dist*, which is a nested structure that could be a dict or a list. Hence, I named it as dist... which is much better than lict. >>> test = {"spam": 42, "ham": "spam", "bacon": {"spam": -1}} >>> rename_keys(test, ("spam", "eggs")) {"eggs": 42, "ham": "spam", "bacon": {"eggs": -1}} """ if isinstance(dist, list): for item in dist: rename_keys(item, keys) elif isinstance(dist, dict): oldkey, newkey = keys if oldkey in dist: dist[newkey] = dist.pop(oldkey) for value in dist.values(): rename_keys(value, keys) return dist
def put_comma(alignment, min_threshold: float = 0.5): """ Put comma in alignment from force alignment model. Parameters ----------- alignment: List[Dict[text, start, end]] min_threshold: float, optional (default=0.5) minimum threshold in term of seconds to assume a comma. Returns -------- result: List[str] """ r = [] for no, row in enumerate(alignment): if no > 0: if alignment[no]['start'] - alignment[no-1]['end'] >= min_threshold: r.append(',') r.append(row['text']) r.append('.') return r
def parse_geofence(response): """Parse the json response for a GEOFENCE and return the data.""" hue_state = response['state']['presence'] if hue_state is True: state = 'on' else: state = 'off' data = {'name': response['name'], 'model': 'GEO', 'state': state} return data
def intersect(ch_block, be_block): """Return intersection size.""" return min(ch_block[1], be_block[1]) - max(ch_block[0], be_block[0])
def complement_color(r, g, b): """Get complement color. https://stackoverflow.com/questions/40233986/python-is-there-a-function-or-formula-to-find-the-complementary-colour-of-a-rgb :param r: _description_ :type r: _type_ :param g: _description_ :type g: _type_ :param b: _description_ :type b: _type_ """ def hilo(a, b, c): # Sum of the min & max of (a, b, c) if c < b: b, c = c, b if b < a: a, b = b, a if c < b: b, c = c, b return a + c k = hilo(r, g, b) return tuple(k - u for u in (r, g, b))
def _pnpoly(x, y, coords): """ the algorithm to judge whether the point is located in polygon reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation """ vert = [[0, 0]] for coord in coords: for node in coord: vert.append(node) vert.append(coord[0]) vert.append([0, 0]) inside = False i = 0 j = len(vert) - 1 while i < len(vert): if ((vert[i][0] > y) != (vert[j][0] > y)) and (x < (vert[j][1] - vert[i][1]) * (y - vert[i][0]) / (vert[j][0] - vert[i][0]) + vert[i][1]): inside = not inside j = i i += 1 return inside
def get_habituation_folder(s): """Get the type of maze from folder""" names_part = ["habituation", "hab", "hab1", "hab2", "hab3", "hab4", "hab5"] temp = s.split("/") for name in temp: for parts in names_part: if parts in name: return 1 return 0
def good_public_function_name(good_arg_name): """This is a perfect public function""" good_variable_name = 1 return good_variable_name + good_arg_name
def ComputeLabelY(Array): """Compute label y coordinate""" Y = min(Array)+ (max(Array)-min(Array))/2 return Y
def indef2def(indefs, a, b): """ Use the stored polynomial indefinite integral coefficients to calculate the definite integral of the polynomial over the interval [a,b]. """ # Evaluate a, b contributions using Horner's algorithm. aval = indefs[-1] for c in indefs[-2::-1]: aval = c + a*aval aval *= a # since const term dropped bval = indefs[-1] for c in indefs[-2::-1]: bval = c + b*bval bval *= b # since const term dropped return bval - aval
def ListToText(txtlst,sep=','): """ Convert list to a string :param lst txtlst: list (element shoud be string) :param str sep' character(s) :return: text(str) - 'elemnet+sep+element...' """ text='' if sep == '': sep=' ' for s in txtlst: text=text+s+sep n=text.rfind(sep) if n >= 0: text=text[:n] text='['+text+']' return text
def getPodStatus(pod): """ get pod status for display """ #logger.debug("getPodStatus()") if not pod: return "no pod" if not pod['status']: return "no pod status" return "%s %s" % (pod['metadata']['name'], pod['status']['phase'])
def penn_to_wn(tag): """ Convert between a Penn Treebank tag to a simplified Wordnet tag """ if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None
def max_sum_subarray(arr): """ :param - arr - input array return - number - largest sum in contiguous subarry within arr """ sumArray = sum(arr) maxSum = sumArray while len(arr) > 1: if arr[0] > arr[len(arr)-1]: arr = arr[:-1] else: arr = arr[1:] if sum(arr) > maxSum: maxSum = sum(arr) return maxSum # def max_sum_subarray(arr): # max_sum = arr[0] # current_sum = arr[0] # print("BEFORE IT ALL BEGINS | Array is {}, max_sum is {}, current_sum is {}". format(arr, max_sum, current_sum)) # for num in arr[1:]: # current_sum = max(current_sum + num, num) # max_sum = max(current_sum, max_sum) # print("num is {}, max_sum is {}, current_sum is {}". format(num, max_sum, current_sum)) # return max_sum
def init(i): """ Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ return {'return': 0}
def replaceAdjacent_cells(freePlaceMap, x, y, count): """ Checks every Cell surrounded by the current Cell if its free and has no Value. Then the Current count will be the new Value and this new Cell will be Added to the List to be checked :param freePlaceMap: The Current FreePlaceMap :param x: The Current X Coordinate to check the Neighbours of :param y: The Current Y Coordinate to check the Neighbours of :param count: The Current Area-Index :return: The List with every valid Neighbour """ list = [] if freePlaceMap is None or len(freePlaceMap) <= 1 or len(freePlaceMap[0]) <= 1: return # Check Left Cell if x > 0 and freePlaceMap[y][x - 1] != -1 and freePlaceMap[y][x - 1] != count: freePlaceMap[y][x - 1] = count list.append((x - 1, y)) # Check Right Cell if x < len(freePlaceMap[0]) - 1 and freePlaceMap[y][x + 1] != -1 and freePlaceMap[y][x + 1] != count: freePlaceMap[y][x + 1] = count list.append((x + 1, y)) # Check Cell Underneath if y > 0 and freePlaceMap[y - 1][x] != -1 and freePlaceMap[y - 1][x] < count: freePlaceMap[y - 1][x] = count list.append((x, y - 1)) # Check Upper Cell if y < len(freePlaceMap) - 1 and freePlaceMap[y + 1][x] != -1 and freePlaceMap[y + 1][x] != count: freePlaceMap[y + 1][x] = count list.append((x, y + 1)) return list
def find_disagreement(first_term, second_term): """Finds the disagreement set of the terms.""" term_pair_queue = [(first_term, second_term)] while term_pair_queue: first_term, second_term = term_pair_queue.pop(0) if isinstance(first_term, tuple) and isinstance(second_term, tuple): if first_term[0] == second_term[0]: term_pair_queue.extend(zip(first_term[1], second_term[1])) continue return False if first_term == second_term: continue return (first_term, second_term) return True
def split_multimac(devices): """ Router can group device that uses dynamic mac addresses into a single device. This function splits them into separate items. """ split_devices = [] for device in devices: if ',' not in device['mac']: split_devices.append(device) continue split_ds = [device.copy() for i in range(len(device['mac'].split(',')))] for key, val in device.items(): if ',' not in val or key not in ('mac', 'activity_ip', 'activity_ipv6', 'activity_ipv6_ll', 'ip', 'port'): continue for i, split_val in enumerate(val.split(',')): split_ds[i][key] = split_val for split_d in split_ds: split_d['activity'] = split_d['activity_ip'] split_devices.append(split_d) return split_devices
def check_alphabet(sequence): """Function that takes as input a sequence and it will check that there is at least a letter matching the alphabet in the sequence, returning true.""" code = "ATCG" for base in sequence: if base in code: return(True) return(False)
def str2dict(string): """Transform a string to a dictionary""" dictionary = {} string_list = string.split(',') for item in string_list: result = item.split('=') dictionary.update({result[0]: result[1]}) return dictionary
def _to_rv_feature(annotation: dict, class_map: dict) -> dict: """Convert the geojson from Raster Foundry's API into the minimum dict required by Raster Vision """ return { "geometry": annotation["geometry"], "properties": {"class_id": class_map[annotation["properties"]["label"]]}, }
def shortest_mesh_path_length(source, destination): """Get the length of a shortest path from source to destination without using wrap-around links. Parameters ---------- source : (x, y, z) destination : (x, y, z) Returns ------- int """ x, y, z = (d - s for s, d in zip(source, destination)) # When vectors are minimised, (1,1,1) is added or subtracted from them. # This process does not change the range of numbers in the vector. When a # vector is minimal, it is easy to see that the range of numbers gives the # magnitude since there are at most two non-zero numbers (with opposite # signs) and the sum of their magnitudes will also be their range. return max(x, y, z) - min(x, y, z)
def puzzle_to_list(puzzle): """ Converts a two dimensional puzzle to a one dimensional puzzle. [[1, 2, 3], [4, 5, 6], [7, 8, 9]] --> [1, 2, 3, 4, 5, 6, 7, 8, 0] """ lst = [] for row in puzzle: lst.extend(row) return lst
def _vec_vec_elem_mul_fp(x, y): """Multiply two vectors element wise.""" return [a * b for a, b in zip(x, y)]
def normalize(reg_string, prefer_spaces=True, ret_string=False): """Make sure everything is lowercase and remove _ and -""" space = " " if prefer_spaces else "" result = [ x for x in reg_string.lower() .replace("_", " ") .replace("/", " ") .replace("-", space) .replace("s.py", "") .replace(".py", "") .split() ] return "".join(result) if ret_string else result
def import_object(name): """Imports an object by name. import_object('x.y.z') is equivalent to 'from x.y import z'. """ parts = name.split('.') m = '.'.join(parts[:-1]) attr = parts[-1] obj = __import__(m, None, None, [attr], 0) try: return getattr(obj, attr) except AttributeError as e: raise ImportError("'%s' does not exist in module '%s'" % (attr, m))
def get_query_param_set(params): """ Strip, lowercase, and remove empty params to be used in a query """ param_set = params.strip().lower().split(" ") param_set = [p for p in param_set if len(p) > 0] return param_set
def exp_requirement(level): """ EXP required to level up from level. """ return 1000 * (level + 1)
def _normalize_module_set(argument): """ Split up argument via commas and make sure they have a valid value """ return set([module.strip() for module in argument.split(',') if module.strip()])
def print_all(k): """Print all arguments of repeated calls. >>> f = print_all(1)(2)(3)(4)(5) 1 2 3 4 5 """ print(k) return print_all
def _listToPhrase(things, finalDelimiter, delimiter=', '): """ Produce a string containing each thing in C{things}, separated by a C{delimiter}, with the last couple being separated by C{finalDelimiter} @param things: The elements of the resulting phrase @type things: L{list} or L{tuple} @param finalDelimiter: What to put between the last two things (typically 'and' or 'or') @type finalDelimiter: L{str} @param delimiter: The separator to use between each thing, not including the last two. Should typically include a trailing space. @type delimiter: L{str} @return: The resulting phrase @rtype: L{str} """ if not isinstance(things, (list, tuple)): raise TypeError("Things must be a list or a tuple") if not things: return '' if len(things) == 1: return str(things[0]) if len(things) == 2: return "%s %s %s" % (str(things[0]), finalDelimiter, str(things[1])) else: strThings = [] for thing in things: strThings.append(str(thing)) return "%s%s%s %s" % (delimiter.join(strThings[:-1]), delimiter, finalDelimiter, strThings[-1])
def get_host_context(resp_host): """ Prepare host context data as per Demisto's standard. :param resp_host: response from host command. :return: Dictionary representing the Demisto standard host context. """ return { 'ID': resp_host.get('id', ''), 'Hostname': resp_host.get('hostName', ''), 'IP': resp_host.get('ipAddress', ''), 'OS': resp_host.get('operatingSystemScanner', {}).get('name', '') }
def dataToBit(val, invert): """Return string representation of bit value. Converts common text values to their bit equivalents, inverting them as required by the feed. Keyword arguments: val -- string value to convert invert -- boolean check for whether to invert truthiness of value """ val = str(val).strip().upper() midVal = 0 if val == 'YES': midVal = 1 elif val == 'TRUE': midVal = 1 elif val == '1': midVal = 1 if invert: if midVal == 1: finVal = str(0) else: finVal = str(1) else: finVal = str(midVal) return finVal
def admin_command(sudo, command): """ If sudo is needed, make sure the command is prepended correctly, otherwise return the command as it came. :param sudo: A boolean representing the intention of having a sudo command (or not) :param command: A list of the actual command to execute with Popen. """ if sudo: if not isinstance(command, list): command = [command] return ['sudo'] + [cmd for cmd in command] return command
def compute_checksum(byte_array): """Compute FNV-1 checksum. Args: byte_array: list (int) Each element represents a a byte Returns: integer Computed checksum Raises: Nothing """ checksum = 2166136261 for b in byte_array: checksum = ((checksum ^ b) * 16777619) & 0xffffffff return checksum
def parse_awards(movie): """ Convert awards information to a dictionnary for dataframe. Keeping only Oscar, BAFTA, Golden Globe and Palme d'Or awards. :param movie: movie dictionnary :return: well-formated dictionnary with awards information """ awards_kept = ['Oscar', 'BAFTA Film Award', 'Golden Globe', 'Palme d\'Or'] awards_category = ['won', 'nominated'] parsed_awards = {} for category in awards_category: for awards_type in awards_kept: awards_cat = [award for award in movie['awards'][category] if award['category'] == awards_type] for k, award in enumerate(awards_cat): parsed_awards['{}_{}_{}'.format(awards_type, category, k+1)] = award["award"] return parsed_awards
def pad(text, min_width, tabwidth=4): """ Fill the text with tabs at the end until the minimal width is reached. """ tab_count = ((min_width / tabwidth) - (len(text) / tabwidth)) + 1 return text + ('\t' * int(tab_count))
def mask_x_by_z(x, z): """ Given two arrays x and z of equal length, return a list of the values from x excluding any where the corresponding value of z is 0. :param x: Output values are taken from this array :type x: :class:`~numpy.ndarray` :param z: x[i] is excluded from the output if z[i] == 0 :type z: :class:`~numpy.ndarray` """ assert len(x) == len(z) return [xi for xi, zi in zip(x, z) if zi != 0]
def list_to_dict(lista): """ Argument: list of objects. Output: Dict where key is the ID, and value the hole object. """ ret = {} try: for obj in lista: clave = obj.get('id') if clave: ret[clave] = obj return ret except Exception as err: # pylint: disable=unused-variable # return ret raise Exception("[list_to_dict] Error processing data.")
def count_nucleotides(dna, nucleotide): """ (str, str) -> int Return the number of occurrences of nucleotide in the DNA sequence dna. >>> count_nucleotides('ATCGGC', 'G') 2 >>> count_nucleotides('ATCTA', 'G') 0 """ return dna.count(nucleotide)
def parsimony_informative_or_constant(numOccurences): """ Determines if a site is parsimony informative or constant. A site is parsimony-informative if it contains at least two types of nucleotides (or amino acids), and at least two of them occur with a minimum frequency of two. https://www.megasoftware.net/web_help_7/rh_parsimony_informative_site.htm A site is constant if it contains only one character and that character occurs at least twice. https://www.megasoftware.net/web_help_7/rh_constant_site.htm Arguments --------- argv: numOccurences dictionary with sequence characters (keys) and their counts (values) """ # create a dictionary of characters that occur at least twice d = dict((k, v) for k, v in numOccurences.items() if v >= 2) # if multiple characters occur at least twice, the site is parsimony # informative and not constant if len(d) >= 2: parsimony_informative = True constant_site = False # if one character occurs at least twice and is the only character, # the site is not parismony informative but it is constant elif len(d) == 1 and len(numOccurences) == 1: parsimony_informative = False constant_site = True else: parsimony_informative = False constant_site = False return parsimony_informative, constant_site
def to_list(obj, key=None): """ to_list(obj) returns obj if obj is a list, else [obj, ]. to_list(obj, key) returns to_list(obj[key]) if key is in obj, else []. """ if key is None: return obj if isinstance(obj, list) else [obj] else: return to_list(obj[key]) if key in obj else []
def op_has_scalar_output(input_shapes, optype, attr): """ TFLite uses [] to denote both scalars and unknown output shapes. Return True if an op can have scalar outputs despite having non-scalar inputs. Otherwise, we will replace [] with None """ if optype in ["TFL_STRIDED_SLICE", "StridedSlice"]: inp_rank = len(input_shapes[0]) return attr['shrink_axis_mask'] == 2 ** inp_rank - 1 if (optype.startswith("TFL_REDUCE") or optype in ['All']) and len(input_shapes) == 2: inp_rank = len(input_shapes[0]) keep_dims = attr.get('keep_dims', True) # axes input can be a scalar for a single axis num_axes = 1 if input_shapes[1] == [] else input_shapes[1][0] return not keep_dims and inp_rank == num_axes if optype == "TFL_RESHAPE": return input_shapes[1] == [0] if optype == "Size": # Op from TF return True return False
def bin_to_int(x: str) -> int: """ Convert from a binary string to a integer. Parameters ---------- x: str Binary string to convert. Returns ------- int Corresponding integer. """ return int(x, 2)
def collided_with_level(player_state, previous_position): """ Called whenever the player bumps into a wall. Usually, you just want to set player_state["position"] = previous_position :param player_state: Our state :param previous_position: Where were we before be bumped into the wall? :return: the new PlayerState """ player_state["position"] = previous_position return player_state
def collect_like_terms(term_matrix): """ input is polynomial in form of term_matrix from poly_parser.py output is another term_matrix with terms collected term_matrix = [[" ", variable1, variable2...], [coefficient, exponent1, exponent2...],...] """ t = [term[:] for term in term_matrix] for i, term in enumerate(t, start=1): if i < len(t) - 1: for j in range(i+1, len(t)): if t[i][1:] == t[j][1:]: t[i] = [t[i][0] + t[j][0]] + t[i][1:] t[j][0] = 0 # get rid of 0 terms t = [u for u in t if u[0] != 0] # get rid of extra variables if len(t[0]) > 0: for i in reversed(range(len(t[0]))): # in reverse so deletion doesn't affect index of subsequent variables extra = True if len(t) > 0: for term in t[1:]: try: if term[i] != 0: extra = False except IndexError: extra = True if extra: for term in t: try: del term[i] except IndexError: pass if t == [[]]: return [['constant']] return t
def _error_matches_criteria(error, criteria): """ Check if an error matches a set of criteria. Args: error: The error to check. criteria: A list of key value pairs to check for in the error. Returns: A boolean indicating if the provided error matches the given criteria. """ for key, value in criteria: if error.get(key) != value: return False return True
def has_phrase(message: str, phrases: list): """ returns true if the message contains one of the phrases e.g. phrase = [["hey", "world"], ["hello", "world"]] """ result = False for i in phrases: # if message contains it i = " ".join(i) if i in message: result = True return result
def reverse(sequence, keep_nterm=False): """ Create a decoy sequence by reversing the original one. Parameters ---------- sequence : str The initial sequence string. keep_nterm : bool, optional If :py:const:`True`, then the N-terminal residue will be kept. Default is :py:const:`False`. Returns ------- decoy_sequence : str The decoy sequence. """ if keep_nterm and sequence: return sequence[0] + reverse(sequence[1:], False) return sequence[::-1]
def area_triangle(base, height): """ Calculate the area of a triangle. param "base": width of the triangle base param "height": height of the trianble """ return base*height/2
def _GetTimeDenom(ms): """Given a list of times (in milliseconds), find a sane time unit for them. Returns the unit name, and `ms` normalized to that time unit. >>> _GetTimeDenom([1, 2, 3]) ('ms', [1.0, 2.0, 3.0]) >>> _GetTimeDenom([.1, .2, .3]) ('us', [100.0, 200.0, 300.0]) """ ms_mul = 1000 * 1000 units = [('us', 1000), ('ms', ms_mul), ('s', ms_mul * 1000)] for name, mul in reversed(units): normalized = [float(t) * ms_mul / mul for t in ms] average = sum(normalized) / len(normalized) if all(n > 0.1 for n in normalized) and average >= 1: return name, normalized normalized = [float(t) * ms_mul for t in ms] return 'ns', normalized
def apply_step_decay(params, t): """ Reduces the learning rate by some factor every few epochs. Args: params: parameters for the annealing t: iteration number (or you can use number of epochs) Returns: Updated learning rate """ lr = params['curr_lr'] # current learning rate k = params['k'] # decay factor period = params['period'] # period used to anneal if (t % period) == 0 and (t != 0): return lr * 1. / k return lr
def susceptibility_two_linear_known(freq_list, interaction_strength, decay_rate): """ In the linear regime for a two-level system, the suecpetibility is known analytically. This is here for useful comparison, as good agreement between a simulated weak field in a two-level system tells us that the model is accurate in the linear regime, which gives us confidence in the scheme for going beyond the weak field limit. Notes: See TP Ogden Thesis Eqn(2.61) """ return 1j * interaction_strength / (decay_rate / 2 - 1j * freq_list)
def is_greetings(text): """ Checks if user is saying hi. Parameters: text (string): user's speech Returns: (bool) """ state = False keyword = [ "hey", "hello", "hi", "good morning", "good afternoon", "greetings" ] for word in keyword: if ((text.lower()).find(word.lower()) != -1): state = True return state
def month_to_foldername(month): """group months for folder structure""" folder_name = " " if month in [1,2,3]: folder_name = "1-3" if month in [4,5,6]: folder_name = "4-6" if month in [7,8,9]: folder_name = "7-9" if month in [10,11,12]: folder_name = "10-12" return folder_name
def is_pretty_name_line(line): """Line from symbol table defines a simple symbol name (a pretty name).""" return line.startswith('Pretty name')
def inferGroup(titlebuffer): """infers the function prefix""" if titlebuffer: if titlebuffer[0] == "*": return "*var*" if titlebuffer[0] in ["-", "_"]: #["*", "-", "_"] #strip first letter titlebuffer = titlebuffer[1:] if titlebuffer.startswith("glfw"): return "glfw:" idx = titlebuffer.rfind(":") # print(idx, titlebuffer[:idx+1]) if idx >= 0: return titlebuffer[:idx+1] return ""
def isinstance_namedtuple(obj) -> bool: """ Based on https://stackoverflow.com/a/49325922/7127824 and https://github.com/Hydrospheredata/hydro-serving-sdk/pull/51 The main use is to check for namedtuples returned by pandas.DataFrame.itertuples() :param obj: any object :return: bool if object is an instance of namedtuple """ return (isinstance(obj, tuple) and hasattr(obj, '_asdict') and hasattr(obj, '_fields'))
def split(path): """Parse a full path and return the collection and the resource name If the path ends by a '/' that's a collection :param path: a path in the collection :type path: str :return: a pair with the collection name and the resource/collection name :type: tuple """ if path == '/': return tuple(('/', '.')) if path.endswith('/'): pi = path[:-1].rfind('/') else: pi = path.rfind('/') coll_name = path[:pi+1] resc_name = path[pi+1:] # root collection if coll_name == '': coll_name = '/' return tuple((coll_name, resc_name))
def plural(x): """ Returns an 's' if plural Useful in print statements to avoid something like 'point(s)' """ if x > 1: return 's' return ''
def str_to_bool(v): """ From http://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python """ return v.lower() in ["yes", "true", "t", "1"]
def to_num(text): """ Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. """ try: return int(text) except ValueError: try: return float(text) except ValueError: return text
def _verify_rank_feature(value, low, high): """ Rank features must be a positive non-zero float. Our features are scaled from 0 to 100 for fair comparison. """ if value is None or value == 0: return None ceiling = min(value, high) floor = max(low, ceiling) return floor
def _shape_repr(shape): """Return a platform independent representation of an array shape Under Python 2, the `long` type introduces an 'L' suffix when using the default %r format for tuples of integers (typically used to store the shape of an array). Under Windows 64 bit (and Python 2), the `long` type is used by default in numpy shapes even when the integer dimensions are well below 32 bit. The platform specific type causes string messages or doctests to change from one platform to another which is not desirable. Under Python 3, there is no more `long` type so the `L` suffix is never introduced in string representation. >>> _shape_repr((1, 2)) '(1, 2)' >>> one = 2 ** 64 / 2 ** 64 # force an upcast to `long` under Python 2 >>> _shape_repr((one, 2 * one)) '(1, 2)' >>> _shape_repr((1,)) '(1,)' >>> _shape_repr(()) '()' """ if len(shape) == 0: return "()" joined = ", ".join("%d" % e for e in shape) if len(shape) == 1: # special notation for singleton tuples joined += ',' return "(%s)" % joined
def _get_ending_key(e): """ Generate a key to store repeats temporarily """ return ('ending',)
def pv_grow_perpetuity(c,r,q): """Objective : estimate present value of a growthing perpetuity r : discount rate q : growth rate of perpetuity c : period payment formula : c/(r-g) e.g., >>>pv_grow_perpetuity(30000,0.08,0.04) 750000.0 """ return(c/(r-q))
def sort_ascending(p_files): """Sort files by file basename instead of file path. Added March 2021 by P. de Dumast """ from operator import itemgetter import os path_basename = [] for f in p_files: path_basename.append((os.path.basename(f), f)) path_basename = sorted(path_basename, key=itemgetter(0)) return [f[1] for f in path_basename]
def commafy(s): """ Returns a copy of s, with commas every 3 digits. Example: commafy('5341267') = '5,341,267' Parameter s: string representing an integer Precondition: s a string with only digits, not starting with 0 """ if len(s) <= 3: return s left = commafy(s[0:-3]) right = s[-3:] return left + ',' + right
def _gettypenames(operands): """ helper function to obtain type name dict from an input dict of operands """ return dict([(arg, type(operand).__name__) for arg, operand in operands.items()])
def underscore_escape(text): """ This function mimics the behaviour of underscore js escape function The html escaped by jinja is not compatible for underscore unescape function :param text: input html text :return: escaped text """ html_map = { '&': "&amp;", '<': "&lt;", '>': "&gt;", '"': "&quot;", '`': "&#96;", "'": "&#x27;" } # always replace & first for c, r in sorted(html_map.items(), key=lambda x: 0 if x[0] == '&' else 1): text = text.replace(c, r) return text
def parse_proc_load_avg(stdout:str, stderr:str, exitcode:int) -> dict: """ 0.12 0.22 0.25 1/1048 16989 """ if exitcode != 0: raise Exception() ret = stdout.strip().split(" ") return { "load1": float(ret[0]), "load5": float(ret[1]), "load15": float(ret[2]), "processes_runnable": int(ret[3].split("/")[0]), "processes_total": int(ret[3].split("/")[1]), }
def _convert_old_aldb_status(old_status): """Convert insteonplm ALDB load status to new ALDB load status. Old status values: EMPTY = 0 LOADING = 1 LOADED = 2 FAILED = 3 PARTIAL = 4 New status values: EMPTY = 0 LOADED = 1 LOADING = 2 FAILED = 3 PARTIAL = 4 """ if old_status in [0, 3, 4]: return old_status if old_status == 1: return 2 if old_status == 2: return 1
def add_commas(number): """ input: 4500 output: "4,500" """ number = str(number) number = number[::-1] # Reverse number se we can add the commas #ugliness if len(number) < 4: #Less than a thousand return number[::-1] if len(number) < 7: #one comma to be added at number[3] return str(number[:3] + "," + number[3:])[::-1] if len(number) < 10: #Two commas added at number[3] and number[6] return str(number[:3] + "," + number[3:6] + "," + number[6:])[::-1] if len(number) < 13: raise NotImplementedError
def format_exception(e): """ Returns a string which includes both exception-type and its str() """ try: exception_str = str(e) except Exception: try: exception_str = repr(e) except Exception: exception_str = '(error formatting exception)' return '%s - %s' % (e.__class__.__name__, exception_str)
def safe_divide(x, y): """Compute x / y, but return 0 if y is zero.""" if y == 0: return 0 else: return x / y
def factorial_iter(n): """Nth number of factorial series by bottom-up DP w/ optimized space. - Time complexity: O(n). - Space complexity: O(1). """ f = 1 for k in range(2, n + 1): f *= k return f
def bind(x, f): """ A monadic bind operation similar to Haskell's Maybe type. Used to enable function composition where a function returning None indicates failure. :param x: The input value passed to callable f is not None. :param f: A callable which is passed 'x' :return: If 'x' is None on input, None otherwise the result of calling f(x). """ if x is None: return None return f(x)
def count_by(iterable, iteratee): """ Think of it like a harry potter sorting hat, tells you final number of students in every group. Similar to group_by, instead of returning a list with every grouped_key, returns count of grouped elements only. params: array, iteratee iterable-> list, set, generator iteratee-> a function or a lambda for grouping the elements Examples >>> _.count_by([1, 2, 3, 4, 5], lambda x: 'even' if x % 2 == 0 else 'odd') >>> {"odd": 3, "even": 2} """ from collections import defaultdict d = defaultdict(lambda: 0) for item in iterable: key = iteratee(item) d[iteratee(item)] += 1 return dict(d)
def Status(state, health, health_rollup=None): """ Status based on Resource.Status in Resource.0.9.2 (Redfish) """ status = {'State': state, 'Health': health} if health_rollup is not None: status['HealthRollup'] = health_rollup return status
def get_bit(num: int, index: int) -> bool: """ Get the index-th bit of num. """ mask = 1 << index return bool(num & mask)
def PopulationDynamics(population, fitness): """Determines the distribution of species in the next generation.""" n = list(population) L = len(population) f = fitness(population) for i in range(L): n[i] *= f[i] N = sum(n) if N == 0.0: return population for i in range(L): n[i] /= N return tuple(n)
def there_are_only_spaces(string): """ Check string for any character that is not a space. """ slist = list(string) while len(slist) > 0: char = slist.pop(0) if char != ' ': return False return True
def param_nully(value) -> bool: """Determine null-like values.""" if isinstance(value, str): value = value.lower() return value in [None, '', 'undefined', 'none', 'null', 'false']
def fitler_errors_from_input_data(data_to_valid,errors): """ filter errors from the input data dict list Parameters ---------- data_to_valid : list A list of dict. It's the input_data that need validation errors : dict A dictinnary containing Schema.ValidationError error messages. The keys are the indexes in the input_data list of dictinaries and the values are the error messages. Returns ------- data_to_valid : list a list of dictionaries without the dict with Schema.ValidationError """ indexes = errors.keys() for idx in indexes: del data_to_valid[idx] return data_to_valid
def blend_color(a, b, ratio) -> tuple: """Blends and returns the mix of colors a and b to a given ratio. Note: ratio argument must be a 3-float sequence.""" return ( int(a[0] + (b[0] - a[0]) * ratio[0]), int(a[1] + (b[1] - a[1]) * ratio[1]), int(a[2] + (b[2] - a[2]) * ratio[2]) )
def split_dir_file(path): """ This function separates file path and file name Parameters: ----------- path: string path of a file with file name Returns: -------- tuple Returns a tuple of directory path and file name Examples: --------- >>> split_dir_file('data/clean/banking.csv') ('data/clean','banking.csv') """ path_list = path.split('/') file_name = path_list[-1] dir_path = path_list[0] for i in path_list[1:-1]: dir_path = dir_path+"/"+i return (dir_path,file_name)
def list_partial_strings(circuit): """ List the parial strings of circuit, that is, the strings that are the slices circuit[0:n] for 0 <= l <= len(circuit). Parameters ---------- circuit : tuple of operation labels or Circuit The operation sequence to act upon. Returns ------- list of Circuit objects. The parial operation sequences. """ ret = [] for l in range(len(circuit) + 1): ret.append(tuple(circuit[0:l])) return ret
def sort(seq): """ Takes a list of integers and sorts them in ascending order. This sorted list is then returned. :param seq: A list of integers :rtype: A list of sorted integers """ gap = len(seq) swap = True while gap > 1 or swap: gap = max(1, int(gap / 1.25)) swap = False for i in range(len(seq) - gap): if seq[i] > seq[i + gap]: seq[i], seq[i + gap] = seq[i + gap], seq[i] swap = True return seq
def check_citation_type(citation, violation_description): """A helper function used in filter_citations_by_type to extract the citation by desciprtion. """ #### EXERCISE: Implement boolean conditional checking against violation_description here if citation['Violation Description']: return citation else: return {}