content
stringlengths
42
6.51k
def validKey(key, pkeys): """ Helper function """ if key in pkeys and len(pkeys[key]) > 0: return True return False
def _parse_ids(ids, info_dict): """Parse different formats of ``ids`` into the right dictionary format, potentially using the information in ``info_dict`` to complete it. """ if ids is None: # Infer all id information from info_dict return {outer_key: inner_dict.keys() for outer_key, inner_dict in info_dict.items()} if isinstance(ids, str): # ids only provides a single argument name but no parameter indices return {ids: info_dict[ids].keys()} if not isinstance(ids, dict): # ids only provides argument names but no parameter indices return {_id: info_dict[_id].keys() for _id in ids} return ids
def __get_params(argv): """Function to manage input parameters.""" # Correct syntax syntax = '%s pcap_input csv_output format' % argv[0] # Not enough parameters if len(argv) != 4: print('Usage: %s' % syntax) exit() # Return the parameters return argv[1], argv[2], argv[3]
def get_hosts(path, url): """ Creates windows host file config data :param path: :param url: :return: string """ info = """ # host for %%path%% 127.0.0.1\t%%url%% """.replace("%%url%%", url).replace("%%path%%", path) return info
def coerce_to_list(value): """Splits a value into a list, or wraps value in a list. Returns: value, as a sorted list """ if isinstance(value, list): return sorted(value) for split_char in (",", ";", ":", "|", " "): if split_char in value: return sorted([val.strip() for val in value.split(split_char)]) return [value]
def compare_fw_versions( v1, v2 ): """ :param v1: left FW version :param v2: right FW version :return: 1 if v1 > v2; -1 is v1 < v2; 0 if they're equal """ v1_list = v1.split( '.' ) v2_list = v2.split( '.' ) if len(v1_list) != 4: raise RuntimeError( "FW version (left) '" + v1 + "' is invalid" ) if len(v2_list) != 4: raise RuntimeError( "FW version (right) '" + v2 + "' is invalid" ) for n1, n2 in zip( v1_list, v2_list ): if int(n1) > int(n2): return 1 if int(n1) < int(n2): return -1 return 0
def return_statement(evaluator, ast, state): """Evaluates "return expr;".""" if ast.get("expr"): res = evaluator.eval_ast(ast["expr"], state) else: res = None return res, True
def split_by_max_length(sentence, max_text_length=128): """Standardize n_sentences: split long n_sentences into max_text_length""" if len(sentence) < max_text_length: return [sentence] split = sentence.split() new_n_sentences, text = [], [] for x in split: support_text = " ".join(text) if len(support_text) + len(x) < max_text_length: text.append(x) else: new_n_sentences.append(support_text) text = [x] text = " ".join(text) if len(text) > 2: new_n_sentences.append(text) return new_n_sentences
def axis_helper(y_shape, x_shape): """ check which axes the x has been broadcasted Args: y_shape: the shape of result x_shape: the shape of x Return: a tuple refering the axes """ res = [] j = len(x_shape)-1 for i in range(len(y_shape)-1, -1, -1): if j < 0 or x_shape[j] != y_shape[i]: res.append(i) j-=1 return tuple(res[::-1])
def choice_text(val, choices): """Returns the display text associated with the choice value 'val' from a list of Django character field choices 'choices'. The 'choices' list is a list of two-element tuples, the first item being the stored value and the second item being the displayed value. Returns None if val is not found inthe choice list. """ for choice in choices: if choice[0]==val: return choice[1] return None
def keep_step(metrics, step): """ Only keeps the values of the metrics for the step `step`. Default to None for each metric that does not have the given `step`. Args: metrics (dict): keys are metric names, values are lists of (step, value) pairs e.g. { "loss": [(1, 0.1), (100, 0.01), ...], "acc": [(1, 0.9), (100, 0.91), ...] } step (int): the step we want to keep Returns: metrics (dict): keys are metric names, values have the flatten result for the given `step` e.g. { "loss": 0.01, "acc": 0.91 } """ result = {} for metric, values in metrics.items(): result[metric] = None for s, v in values: if s == step: result[metric] = v break return result
def aprs_to_redis(ts, par): """ change aprslib par onbject to a hash table redis can store """ return { "latitude":par.get("latitude", None), "longitude": par.get("longitude", None), "last_heard": ts, "symbol": par["symbol_table"]+par["symbol"], "from": par["from"] }
def hex_no_0x(i): """ Return the equivalent of the C PRIx64 format macro. The removal of the extra L is to ensure Python 2/3 compatibility. """ tmp = str(hex(i)[2:]) if tmp[-1] == 'L': tmp = tmp[:-1] return tmp
def sum_numerator_fraction_expansion_e(x): """ Returns the digit sum of the numerator of the x-th continued fraction of e """ numerator = 1 if x % 3 == 2: denominator = 2*(x//3 + 1) else: denominator = 1 while x > 1: if x % 3 == 0: numerator += 2*(x//3)*denominator else: numerator += denominator numerator, denominator = denominator, numerator x -= 1 numerator += 2*denominator digits = [int(i) for i in str(numerator)] return(sum(digits))
def solve_capcha(capcha_str): """Function which calculates the solution to part 1 Arguments --------- capcha_str : str, a string of numbers Returns ------- total : int, the sum of adjacent matches """ capcha = [int(cc) for cc in list(capcha_str)] total = 0 for ii in range(len(capcha)): if capcha[ii] == capcha[ii - 1]: total += capcha[ii] return total
def number_formatter(number, pos=None): """Convert a number into a human readable format.""" magnitude = 0 while abs(number) >= 100: magnitude += 1 number /= 100.0 return '%.1f%s' % (number, ['', '', '', '', '', ''][magnitude])
def is_string(val): """ Return True iff this is a string """ return isinstance(val, str)
def get_sent_id(corpus_id, doc_id, naf_sent_id, fill_width=8): """ :param corpus_id: :param doc_id: :param naf_sent_id: :return: """ nltk_sent_id = '' for id_ in [corpus_id, doc_id, naf_sent_id]: id_filled = str(id_).zfill(fill_width) nltk_sent_id += id_filled return nltk_sent_id
def check_historical(previous_downs, current_downs): """ Runs a comparison check between two failed ping test dictionaries to determine whether the tests have recently failed, recovered or in a recent warning state. Parameters: previous_downs - dictionary of previously failed and warn status tests current_downs - dictionary of currently failed and warn status tests Return: history - recent test status dictionary """ print("Previous Downs", previous_downs) print("Current Downs:", current_downs) history = {"recent_fail" : [i for i in current_downs["DOWN"] if i not in previous_downs["DOWN"]]} print("Recently Failed:", history["recent_fail"]) history["recent_warn"] = [i for i in current_downs["WARN"] if i not in previous_downs["WARN"]] print("Recently Warn:", history["recent_warn"]) # Looks through all WARN and DOWN Instances history["recovered"] = [h for i in previous_downs for h in previous_downs[i] if h not in current_downs[i]] print("Recently Recovered:", history["recovered"]) return history
def extract_y(lst): """ Extract y coordinate from list with x, y, z coordinates :param lst: list with [[x, y, z], ..., [x, y, z]] :return: list with y coordinates [x, ..., x] """ return [item[1] for item in lst]
def pad_with_zeros(hist_list): """ For each year which doesn't exist here, put 0 """ last_year = hist_list[0][0] - 1 # initialize to be less than the first year i = 0 while i < len(hist_list): year_item = hist_list[i] if year_item[0] - last_year > 1: # fill the gap while year_item[0] - last_year > 1: last_year += 1 hist_list.insert(i, (last_year, 0)) i += 1 last_year += 1 i += 1 return hist_list
def triangle_coordinates(i, j, k): """ Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangles are parallel to the lower axis on the lower side. Parameters ---------- i,j,k: enumeration of the desired triangle Returns ------- A numpy array of coordinates of the hexagon (unprojected) """ return [(i, j, k), (i + 1, j, k - 1), (i, j + 1, k - 1)]
def convert_attribute(aim_attribute, to_aim=True): """Convert attribute name from AIM to ACI format converts from this_format to thisFormat :param aim_attribute: :return: """ if to_aim: # Camel to _ (APIC to AIM) result = [] for x in aim_attribute: if x.isupper(): result.append('_') result.append(x.lower()) return ''.join(result) else: # _ to Camel (AIM to APIC) parts = aim_attribute.split('_') result = parts[0] for part in parts[1:]: result += part[0].upper() + part[1:] return result
def send_message(service, user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Sent Message. """ try: message = (service.users().messages().send(userId=user_id, body=message) .execute()) print('Message Id: %s' % message['id']) return message except Exception as e: print('An error occurred: %s' % e)
def split_list_email(str_email): """ return list to emails """ if not isinstance(str_email, list): return [e.strip() for e in str_email.split(",")] return str_email
def merge(root_config, *args): """Merge two configuration dictionaries together.""" root = root_config.copy() for arg in args: clean = {k: v for k, v in arg.items() if v is not None} root.update(clean) return root
def get_patches_per_dimension(dimension: int, size: int, stride: int) -> int: """ Returns the number of patches that can be created in the given dimension without going over the dimension bounds. """ assert size % stride == 0 overlapping = (size // stride) - 1 if stride != size else 0 return (dimension // stride) - overlapping
def check_url(url): """ Check if exist a well-formed url""" if url[:8] == "https://" or url[:7] == "http://": return True else: return False
def migrate_packetbeat(line): """ Changes things like `interfaces:` to `packetbeat.interfaces:` at the top level. """ sections = ["interfaces", "protocols", "procs", "runoptions", "ignore_outgoing"] for sec in sections: if line.startswith(sec + ":"): return ["packetbeat." + line] return [line]
def is_strong_subclass(C, B): """Return whether class C is a subclass (i.e., a derived class) of class B and C is not B. """ return issubclass (C, B) and C is not B
def worst_resident_index(hospital, hospital_prefs_dict, matched_dict): """ returns the index of worst resident assigned to the hospital based on hospital's prefrences list. """ idxs = [] for res in hospital_prefs_dict[hospital]: if res in matched_dict[hospital]: idxs.append(hospital_prefs_dict[hospital].index(res)) return max(idxs)
def strip(line): """Removes any \r or \n from line and remove trailing whitespaces""" return line.replace('\r\n', '').strip()
def hash_add(element, table_size): """ Hash by adding the ascii values of the letters in the string. Return an integer. """ char_val_list = list(map(lambda x: ord(x), str(element))) hash_val = 0 for val in char_val_list: hash_val += val index = hash_val % table_size return index
def map_traps(prev_pat, row_limit): """Work out the number of safe tiles in a trapped room.""" safe = prev_pat.count('.') row = 1 while row < row_limit: next_row = '' trap_patterns = ('^^.', '.^^', '^..', '..^') pattern = '.{}{}'.format(prev_pat[0], prev_pat[1]) if pattern in trap_patterns: next_row += '^' else: next_row += '.' i = 1 while i < len(prev_pat) - 1: pattern = '{}{}{}'.format(prev_pat[i-1], prev_pat[i], prev_pat[i+1]) if pattern in trap_patterns: next_row += '^' else: next_row += '.' i += 1 pattern = '{}{}.'.format(prev_pat[i-1], prev_pat[1+1]) if pattern in trap_patterns: next_row += '^' else: next_row += '.' safe += next_row.count('.') prev_pat = next_row row += 1 return safe
def shortest_angle_interpolation(start, end, amount): """ This interpolation method considers the 'start' and 'end' as angles in a circumference where the objective is to find the smallest arch between two angles. param start: Start angle with values in the range of [0 to 360[ param end: Final angle with values in the range of [0 to 360[ param amount: Value between [0, 1] which determines how close the interpolated angle will be placed from the Start angle (0) or from the Final angle (1), being 0.5 the middle. return interpolated_angle: Interpolated angle between 'start' and 'end'. """ shortest_angle = ((end-start) + 180) % 360 - 180 interpolated_angle = (start + shortest_angle * amount) % 360 return interpolated_angle
def make_creator(child): """Generate code-block for creating sub-resources""" if child.get("creator") is None: return "" class_ = child["class"] name = child["name"] creator_name = child["creator"]["name"] path = child['json_path'] path = path.rstrip('.*') return ( f""" def {creator_name}(self, name: str, data: dict) -> {class_}: self.set_jsonpath("{path}" + name, data) new_object = {class_}(self, "{path}." + name, data) self.__{name}.append(new_object) return new_object """)
def is_p2sh(script: bytes) -> bool: """ Determine whether a script is a P2SH output script. :param script: The script :returns: Whether the script is a P2SH output script """ return len(script) == 23 and script[0] == 0xa9 and script[1] == 0x14 and script[22] == 0x87
def convertObjectsToXml(result_set): """ Convert a set of objects to XML using the get_xml method of those objects. result_set must be an object capable of being iterated over. """ xmlstream = [] for result in result_set: xmlstream.append(result.get_xml()) xmlstream = map(lambda x: str(x), xmlstream) return '\n\n'.join(xmlstream)
def scales_from_voices_per_octave(nu, range): """Returns the list of scales based on the voices per octave parameter """ return 2 ** (range / nu)
def WendlandC6_2D(u: float, h_inv: float): """ Evaluate the WendlandC6 spline at position u, where u:= x*h_inv, for a 2D projection. Values correspond to 295 neighbours. """ norm2D = 78. / (7. * 3.1415926) if u < 1.0: n = norm2D * h_inv**2 u_m1 = (1.0 - u) u_m1 = u_m1 * u_m1 # (1.0 - u)^2 u_m1 = u_m1 * u_m1 # (1.0 - u)^4 u_m1 = u_m1 * u_m1 # (1.0 - u)^8 u2 = u*u return ( u_m1 * ( 1.0 + 8*u + 25*u2 + 32*u2*u )) * n else: return 0.
def cell_multiply(c, m): """ Multiply the coordinates (cube or axial) by a scalar.""" return tuple( m * c[i] for i in range(len(c)) )
def number(value, minimum=None, maximum=None, cut=False, pad=False): """Returns back an integer from the given value""" value = int(value) if minimum is not None and value < minimum: if pad: return minimum raise ValueError( "Provided value of {} is below specified minimum of {}".format(value, minimum) ) if maximum is not None and value > maximum: if cut: return maximum raise ValueError( "Provided value of {} is above specified maximum of {}".format(value, maximum) ) return value
def sum(data): """ Get sum of list elements. """ result = 0 for value in data: result += value return result
def decode(x: bytes) -> str: """Decode a string like done in `os._createenviron` (hard-coding utf-8)""" return x.decode("utf-8", errors="surrogateescape")
def _amzs(pHI,pFA): """recursive private function for calculating A_{MZS}""" # catch boundary cases if pHI == pFA == 0 or pHI == pFA == 1: return .5 # use recursion to handle # cases below the diagonal defined by pHI == pFA if pFA > pHI: return 1 - _amzs(1-pHI, 1-pFA) # upper left quadrant # Mueller, Zhang (2006) if pFA <= .5 <= pHI: return .75 + (pHI-pFA)/4 - pFA*(1-pHI) # cases above the diagonal defined by pHI == pFA # and not in the upper left quadrant elif pHI <= (1-pFA): if pHI == 0: return (3 + pHI - pFA)/4 else: return (3 + pHI - pFA - pFA/pHI)/4 else: if pFA == 1: return (3 + pHI - pFA)/4 else: return (3 + pHI - pFA - (1-pHI)/(1-pFA))/4
def check_inputs(input1, input2): """ Checks the inputs given to ensure that input1 is a list of just numbers, input2 is a number, and input2 is within input1. Raises an exception if any of the conditions are not true. >>> check_inputs([1, 2.0, 3.0, 4], 4) 'Input validated' >>> check_inputs([], 1) Traceback (most recent call last): ... TypeError: input2 not in input1 >>> check_inputs(1, 1) Traceback (most recent call last): ... TypeError: input1 is not the correct type >>> check_inputs([1, 2, 'hi'], 4) Traceback (most recent call last): ... TypeError: The element at index 2 is not numeric >>> check_inputs([1.0, 2.0, 3.0], 'hello') Traceback (most recent call last): ... TypeError: input2 is not the correct type # MY DOCTESTS """ if not isinstance(input1, list): raise TypeError('input1 is not the correct type') numeric = [isinstance(i, int) or isinstance(i, float) for i in input1] if not all(numeric): raise TypeError('The element at index ' + str(numeric.index(False)) + ' is not numeric') if not type(input2) in [float, int]: raise TypeError('input2 is not the correct type') if input2 not in input1: raise TypeError('input2 not in input1') return 'Input validated'
def prepend_license(license_text, src_text, file_extension): """Prepend a license notice to the file commented out based on the extension. Args: src_text (str): The text which will have the license prepended. file_extension (str): The relevant file extension. Returns: str: The full text of the prepended file. """ # opening, new line prepend, closing comment_symbols = { ".css": ("/*", " * ", " */"), ".html": ("<!--", " ", "-->"), ".js": ("/*", " * ", " */"), } ext = file_extension.lower() if ext not in comment_symbols: return src_text com = comment_symbols[ext] lic = "\n".join(("".join((com[1], line)) for line in license_text)) lic = "\n".join((com[0], lic, com[2])) if ext == ".html": lic = "\n".join(("{#", lic, "#}")) src_text = "\n".join((lic, src_text)) return src_text
def batch_image(im_list, batch_size): """ to put the image into batches """ bs = batch_size fnames = [] fname = [] for _, im_name in enumerate(im_list): bs -= 1 fname.append(im_name) if bs == 0: fnames.append(fname) fname = [] bs = batch_size if len(fname) > 0: fnames.append(fname) return fnames
def calc_chi_square_distance(counts_sim, counts_real): """Returns the chi-square-distance for the two histograms of simulator and quantum computer""" coefficient = 0 for key in counts_real.keys(): # add missing keys from quantum computer to simulator if key not in counts_sim.keys(): counts_sim[key] = 0 for key in counts_sim.keys(): # add missing keys from simulator to quantum computer if key not in counts_real.keys(): counts_real[key] = 0 # calculate chi square distance coefficient = coefficient + ((counts_real[key] - counts_sim[key]) ** 2 / (counts_real[key] + counts_sim[key])) return coefficient / 2
def _best_art(arts): """Return the best art (determined by list order of arts) or an empty string if none is available""" return next((art for art in arts if art), '')
def find_largest_digit_helper(n, max_digit_now): """ :param n: int, the number which user wants to find max digit now :param max_digit_now: int, the max digit now :return: int, the max digit of n Reduce one digit in each recursive case to approach base case(n<10) """ if n < 0: # Negative number, should plus -1 to be positive n = -n if n % 10 > max_digit_now: # Explore and assign right max_digit max_digit_now = n % 10 if n < 10: # Base Case return max_digit_now else: # Recursive Case return find_largest_digit_helper(n // 10, max_digit_now)
def merge(prevArtifacts, nextArtifacts): """Merge artifact lists with nextArtifacts masking prevArtifacts""" artifactList = list(nextArtifacts.copy()) artifactList.extend(prevArtifacts) merged = [] excludedNames = set() for artifact in artifactList: if artifact.name not in excludedNames: merged.append(artifact) excludedNames.add(artifact.name) return merged
def isTheOnlyOne(elements): """ Checks whether there is the only one true positive object or not. @param {Array.<*>} elements. @return {boolean} True, if there is the only one element, which is not None, empty or 0. False if it's not. """ count = 0 for element in elements: if element: count += 1 if count == 1: return True return False
def _check_value(value): """Convert the provided value into a boolean, an int or leave it as it.""" if str(value).lower() in ["true"]: value = True elif str(value).lower() in ["false"]: value = False elif str(value).isdigit(): value = int(value) return value
def swap_key_val_dict(a_dict): """ swap the keys and values of a dict """ return {val: key for key, val in a_dict.items()}
def GCS(string1, string2): """ Returns: (str): The greatest (longest) common substring between two provided strings (returns empty string if there is no overlap) """ # this function copied directly from: # https://stackoverflow.com/a/42882629 answer = "" len1, len2 = len(string1), len(string2) for i in range(len1): for j in range(len2): lcs_temp=0 match='' while ((i+lcs_temp < len1) and (j+lcs_temp<len2) and string1[i+lcs_temp] == string2[j+lcs_temp]): match += string2[j+lcs_temp] lcs_temp+=1 if (len(match) > len(answer)): answer = match return answer
def set_verbosity(level=1): """Set logging verbosity level, 0 is lowest.""" global verbosity verbosity = level return verbosity
def _swap(x): # pylint: disable=invalid-name """Helper: swap the top two elements of a list or a tuple.""" if isinstance(x, list): return [x[1], x[0]] + x[2:] assert isinstance(x, tuple) return tuple([x[1], x[0]] + list(x[2:]))
def _get_baseline_options(site): """ Extracts baseline options from ``site["baseline"]``. """ # XXX default for baseline_beta currently set here options_dict = site["baseline"].copy() options_tuple = (options_dict.pop('nn_baseline', None), options_dict.pop('nn_baseline_input', None), options_dict.pop('use_decaying_avg_baseline', False), options_dict.pop('baseline_beta', 0.90), options_dict.pop('baseline_value', None)) if options_dict: raise ValueError("Unrecognized baseline options: {}".format(options_dict.keys())) return options_tuple
def longestPalindrome2(s): """ :type s: str :rtype: str """ dp=[[False for col in range(len(s))] for row in range(len(s))] res=[0,0]; for i in range(len(s)): dp[i][i]=True if i>1 and s[i]==s[i-1]: dp[i-1][i]=True res[0]=i-1 res[1]=i for length in range(3,len(s)+1): for i in range(len(s)-length+1): j=i+length-1 if s[i]==s[j] and dp[i+1][j-1]: dp[i][j]=True res[0]=i res[1]=j return s[res[0]:res[1]+1]
def dkeys(dict): """ Utility function to return the keys of a dict in sorted order so that the iteration order is guaranteed to be the same. Blame python3 for being FUBAR'd.""" return sorted(list(dict.keys()))
def get_units(name, attr_dict): """ """ try: units = attr_dict[name]["units"] if not isinstance(units, str): units = "{0}".format(units) except KeyError: units = None if units in [None, "None", "none"]: return None return units
def all_in(sequence1, sequence2): """ Confirm that all elements of one sequence are definitely contained within another """ return all(elem in sequence2 for elem in sequence1)
def object_type_repr(obj): """Returns the name of the object's type. For some recognized singletons the name of the object is returned instead. (For example for `None` and `Ellipsis`). """ if obj is None: return "None" elif obj is Ellipsis: return "Ellipsis" cls = type(obj) # __builtin__ in 2.x, builtins in 3.x if cls.__module__ in ("__builtin__", "builtins"): name = cls.__name__ else: name = cls.__module__ + "." + cls.__name__ return "%s object" % name
def type_name(value): """ Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name """ cls = value.__class__ if cls.__module__ in set(['builtins', '__builtin__']): return cls.__name__ return '%s.%s' % (cls.__module__, cls.__name__)
def mult_values(*values): """Return the product of values, considering only elements that are not None. An item v,w in values can be anything that contains __mul__ function such that v*1 and v*w is defined. """ current = 1 for v in values: if v is not None: current = v * current return current
def _trace_level(master): """Returns the level of the trace of -infinity if it is None.""" if master: return master.level return float('-inf')
def is_inside_image(xp, yp, r): """ Description of is_inside_image Returns True if the point is inside the image, False otherwise Args: xp (undefined): x pixel yp (undefined): y pixel r (undefined): radius of image """ return ((xp - r)**2 + (yp - r)**2) <= r**2
def num_to_str(num): """ Convert an int or float to a nice string. E.g., 21 -> '21' 2.500 -> '2.5' 3. -> '3' """ return '{0:0.02f}'.format(num).rstrip('0').rstrip('.')
def break_words(stuff: str) -> list: """This function will break up words for us""" words = stuff.split(' ') return words
def zoo(total_head, total_legs, animal_legs=[2, 4]): """ Find the number of kangaroo and tiger in a zoo. For example: zoo(6, 16) -> (4, 2) zoo(8, 20, [4, 2, 2]) -> (2, 0, 6) Parameters ---------- total_head: int Total number of animals total_legs: int Total number of animals'legs animal_legs: list A list of animal legs. The length of the list is either 2 or 3. Returns ------- tuple The number of animals in each animal type (based on the given animal_legs). Return None if there is no solution. """ animal_num = len(animal_legs) if animal_num == 2: animal_0_leg = animal_legs[0] animal_1_leg = animal_legs[1] for animal_0_num in range(total_head + 1): animal_1_num = total_head - animal_0_num animal_total_legs = animal_0_leg * animal_0_num \ + animal_1_leg * animal_1_num if animal_total_legs == total_legs: return animal_0_num, animal_1_num return None, None elif animal_num == 3: animal_0_leg = animal_legs[0] animal_1_leg = animal_legs[1] animal_2_leg = animal_legs[2] for animal_0_num in range(total_head + 1): for animal_1_num in range(total_head + 1 - animal_0_num): animal_2_num = total_head - animal_0_num - animal_1_num animal_total_legs = animal_0_leg * animal_0_num \ + animal_1_leg * animal_1_num \ + animal_2_leg * animal_2_num if animal_total_legs == total_legs: return animal_0_num, animal_1_num, animal_2_num return None, None, None else: print("The allowed number of animal types is 2 or 3 only.")
def likelihood(sensor_valuesA, sensor_valuesB): """ 1. compare A and B A,and B must be same range list of integers. 2. return likelihood. if A is completely equaly as B, then likelihood is 1.0(Max) if A is completely different as B, likelihood is 0.0(Min) In almost cases, likelihood is between 1.0 and 0.0 """ if(type(sensor_valuesA) is list and type(sensor_valuesB) is list and len(sensor_valuesA) == len(sensor_valuesB) ) : l = 1.0 n = len(sensor_valuesA) for i in range(n): if sensor_valuesA[i] != sensor_valuesB[i]: l -= (1.0 / n) return l else: print(""" Error in likelihood(function) these arguments are incorrect types """)
def natural_list_parse(s, symbol_only=False): """Parses a 'natural language' list, e.g.. seperated by commas, semi-colons, 'and', 'or', etc...""" tokens = [s] seperators = [',', ';', '&', '+'] if not symbol_only: seperators += [' and ', ' or ', ' and/or ', ' vs. '] for sep in seperators: newtokens = [] for token in tokens: while len(token) > 0: before, found, after = token.partition(sep) newtokens.append(before) token = after tokens = newtokens return [x for x in [x.strip() for x in tokens] if len(x) > 0]
def get_name_from_seq_filename(seq_filename): """Get sequence name from the name of an individual sequence fasta filename. Args: seq_filename: string. Of the form 'sequence_name'.fasta, like OLF1_CHICK/41-290.fasta. Returns: string. Sequence name. """ return seq_filename.split('.')[0]
def translate_format_item_value(a: str): """ Preprocess: we replace all marks like %1$s to regex capture group (\S+) param a: The string to be processed. :return: The processed string. """ i = 1 pattern = '%{i}$s' desired = r'(\[.+\]|\S+)' while pattern.format(i=i) in a: a = a.replace(pattern.format(i=i), desired) i += 1 return a
def build_creative_name(order_name, creative_num): """ Returns a name for a creative. Args: order_name (int): the name of the order in DFP creative_num (int): the num_creatives distinguising this creative from any duplicates Returns: a string """ return 'HB {order_name}, #{num}'.format( order_name=order_name, num=creative_num)
def count_bulls_cows(user_string, comp_string): """ Function compare two strings and count bulls and cows :param user_string: string which has the same length as comp_string :param comp_string: string which has the same length as user_string :return: tuple with number of cows and bulls """ bulls = 0 cows = 0 for index, num in enumerate(user_string): if comp_string[index] == user_string[index]: bulls += 1 if num in comp_string and comp_string[index] != user_string[index]: cows += 1 return bulls, cows
def get_grid(rows, columns): """Get grid with number of rows and columns.""" return [[0 for _ in range(columns)] for _ in range(rows)]
def lucas_mod(n, mod): """ Compute n-th element of Fibonacci sequence modulo mod. """ P, Q = 1, -1 x, y = 0, 1 # U_n, U_{n+1}, n=0 for b in bin(n)[2:]: x, y = ((y - P * x) * x + x * y) % mod, (-Q * x * x + y * y) % mod # double if b == "1": x, y = y, (-Q * x + P * y) % mod # add return x
def div_growth_rate(t, dt, d0): """ Calculates the growth rate of a dividend using the dividend growth rate valuation model. parameters: ----------- t = time dt = current price of dividend d0 = price of dividend t years ago """ growth_rate = (((dt/d0) ** (1/t)) - 1) * 100 return round(growth_rate, 4)
def bytecount(numbytes): #---------------------------------------------------<<< """Convert byte count to display string as bytes, KB, MB or GB. 1st parameter = # bytes (may be negative) Returns a short string version, such as '17 bytes' or '47.6 GB' """ retval = '-' if numbytes < 0 else '' # leading '-' for negative values absvalue = abs(numbytes) if absvalue < 1024: retval = retval + format(absvalue, '.0f') + ' bytes' elif 1024 <= absvalue < 1024*100: retval = retval + format(absvalue/1024, '0.1f') + ' KB' elif 1024*100 <= absvalue < 1024*1024: retval = retval + format(absvalue/1024, '.0f') + ' KB' elif 1024*1024 <= absvalue < 1024*1024*100: retval = retval + format(absvalue/(1024*1024), '0.1f') + ' MB' elif 1024*1024*100 <= absvalue < 1024*1024*1024: retval = retval + format(absvalue/(1024*1024), '.0f') + ' MB' else: retval = retval + format(absvalue/(1024*1024*1024), ',.1f') + ' GB' return retval
def get_raw_times(times, starttime, endtime): """ Return list of times covering only the relevant time range. times - all times in input file starttime, endtime - relevant time range """ i_min, i_max = 0, len(times) - 1 for (i, time) in enumerate(times): if time < starttime: i_min = i elif time > endtime: i_max = i break return times[i_min: i_max + 1]
def json_str_list_to_int_list(json_list,json_number_base=16): """ returns a json list to a list of ints with base 'json_number_base' [default 16] """ return [int(k,json_number_base) for k in json_list]
def sturm_liouville_function(x, y, p, p_x, q, f, alpha=0, nonlinear_exp=2): """Second order Sturm-Liouville Function defining y'' for Lu=f. This form is used because it is expected for Scipy's solve_ivp method. Keyword arguments: x -- independent variable y -- dependent variable p -- p(x) parameter p_x -- derivative of p_x wrt x q -- q(x) parameter f -- forcing function f(x) alpha -- nonlinear parameter nonlinear_exp -- exponent of nonlinear term """ y_x = y[1] y_xx = -1*(p_x/p)*y[1] + (q/p)*y[0] + (q/p)*alpha*y[0]**nonlinear_exp - f/p return [y_x, y_xx]
def convert_keys_to_string(dictionary): """Recursively converts dictionary keys to strings.""" if not isinstance(dictionary, dict): return dictionary return dict((str(k), convert_keys_to_string(v)) for k, v in dictionary.items())
def get_natoms_element(formula): """ Converts 'Be24W2' to {'Be': 24, 'W' : 2}, also BeW to {'Be' : 1, 'W' : 1} """ import re elem_count_dict = {} elements = re.findall('[A-Z][^A-Z]*', formula) #re.split('(\D+)', formula) for i, elm in enumerate(elements): elem_count = re.findall(r'\D+|\d+\.\d+|\d+', elm) #print(elem_count) if len(elem_count) == 1: elem_count_dict[elem_count[0]] = 1 else: elem_count_dict[elem_count[0]] = float(elem_count[1]) return elem_count_dict
def update_position(dir, x, y): """Returns the updated coordinates depending on the direction of the path""" if dir == 'DOWN': return x, y + 1 elif dir == 'UP': return x, y - 1 elif dir == 'LEFT': return x - 1, y elif dir == 'RIGHT': return x + 1, y
def deriveRefinedCollisionData(model): """This function collects all collision bitmasks in a given model. Args: model(dict): The robot model to search in. Returns: : dict -- a dictionary containing all bitmasks with corresponding element name (key). """ collisiondata = {} for linkname in model['links']: for elementname in model['links'][linkname]['collision']: element = model['links'][linkname]['collision'][elementname] data = { key: element[key] for key in (a for a in element.keys() if a not in ['geometry', 'name', 'pose']) } if data: data['name'] = model['links'][linkname]['collision'][elementname]['name'] data['link'] = linkname collisiondata[elementname] = data return collisiondata
def primes_sieve3(n): """ Sieve method 3: Returns a list of primes < n >>> primes_sieve3(100) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] """ # begin half-sieve, n>>1 == n//2 sieve = [True] * (n>>1) upper = int(n**0.5)+1 for i in range(3, upper, 2): if sieve[i>>1]: sieve[i*i>>1::i] = [False] * ((n-i*i-1)//(2*i)+1) return [2] + [2*i+1 for i in range(1, n>>1) if sieve[i]]
def _policy_dict_at_state(callable_policy, state): """Turns a policy function into a dictionary at a specific state. Args: callable_policy: A function from `state` -> lis of (action, prob), state: the specific state to extract the policy from. Returns: A dictionary of action -> prob at this state. """ infostate_policy_list = callable_policy(state) if isinstance(infostate_policy_list, dict): infostate_policy = infostate_policy_list legal_actions = state.legal_actions() for action in infostate_policy.keys(): assert action in legal_actions for action in legal_actions: if action not in infostate_policy: infostate_policy[action] = 0.0 else: infostate_policy = {} for ap in infostate_policy_list: infostate_policy[ap[0]] = ap[1] return infostate_policy
def is_valid_vpsaos_account_id(account_id): """ :param account_id: Account ID to check validity :return: True iff VPSAOS account is valid """ valid_set = set('0123456789abcdef') return all(c in valid_set for c in account_id)
def xstr(s): """ Converts None types to an empty string, else the same string """ if s is None: return '' return str(s)
def EvaluateOnePotential(position,potential): """Defines a function that evaluate the potential at a certain point x. This function will be vectorized with np.vectorize to evaluate the potential on a list of position [x1,x2,...] Parameters: ----------- position (float) : a float that defines the x position where we want to evaluate the potential potential (str) : a string that defines the mathematical expression of the potential Returns: -------- EvalPotential (float) : the potential value at the x position """ x = position EvalPotential = eval(potential) return EvalPotential
def char_fun(A, b): """ Returns True if dictionary b is a subset of dictionary A and False otherwise. """ result = b.items() <= A.items() return result
def _ensure_is_list(obj): """ Return an object in a list if not already wrapped. Useful when you want to treat an object as a collection,even when the user passes a string """ if obj: if not isinstance(obj, list): return [obj] else: return obj else: return None
def abs(i): """ https://docs.mongodb.com/manual/reference/operator/aggregation/abs """ return f"{{'$abs' :{i}}}"
def _total(data): """Sum all downloads per category, regardless of date""" # Only for lists of dicts, not a single dict if isinstance(data, dict): return data totalled = {} for row in data: try: totalled[row["category"]] += row["downloads"] except KeyError: totalled[row["category"]] = row["downloads"] data = [] for k, v in totalled.items(): data.append({"category": k, "downloads": v}) return data
def epochJulian2JD(Jepoch): """ ---------------------------------------------------------------------- Purpose: Convert a Julian epoch to a Julian date Input: Julian epoch (nnnn.nn) Returns: Julian date Reference: See JD2epochJulian Notes: e.g. 1983.99863107 converts into 2445700.5 Inverse of function JD2epochJulian ---------------------------------------------------------------------- """ return (Jepoch-2000.0)*365.25 + 2451545.0
def reverse_dictionary(d): """ Reverses the key value pairs for a given dictionary. Parameters ---------- d : :obj:`dict` dictionary to reverse Returns ------- :obj:`dict` dictionary with keys and values swapped """ rev_d = {} [rev_d.update({v:k}) for k, v in d.items()] return rev_d
def removeStopwords(terms,stopwords): """ This function removes from terms all occurrences of words in the list stopwords. """ """ This will be provided for the student. """ output = [] for x in terms: if x not in stopwords: output.append(x) return output