content
stringlengths
42
6.51k
def find_output_shape(inputs, shapes, output): """Find the output shape for given inputs, shapes and output string, taking into account broadcasting. Examples -------- >>> oe.parser.find_output_shape(["ab", "bc"], [(2, 3), (3, 4)], "ac") (2, 4) # Broadcasting is accounted for >>> oe.pa...
def map_llc_history_result_to_dictionary_list(land_charge_history): """Produce a list of jsonable dictionaries of an alchemy result set""" if not isinstance(land_charge_history, list): return list(map(lambda land_charge: land_charge.to_dict(), [land_charge_history])) else: ...
def getname(obj): """ Abstracts the common pattern of allowing both an object or an object's NAME as a parameter when dealing with relationships. """ try: return obj.name except AttributeError: return obj
def unstable_phases(compstr): """ hard-coded list of unstable phases phases are considered unstable for reasons listed in the documentation these phases shall not appear in the energy analysis """ unstable_list = ["Na0.5K0.5Mo1O", "Mg1Co1O", "Sm1Ag1O", ...
def is_min_bracket(triple): """For a triple of positive numbers (a,b,c), returns a triple (boolean, index, error) where: boolean is True if a > b < c (this brackets a minimum value); index is 1 (middle) if input brackets a minimum value, otherwise index indicates which end of the bracket has t...
def convert_object_info(converters, obj_info): """ Convert object information """ for key, transform in converters.items(): if key in obj_info: obj_info[key] = transform(obj_info[key]) return obj_info
def expand(polymer, pair_insertion_dict): """Expand a polymer once using the dict""" new_polymer = "" for pair in zip(polymer, polymer[1:]): new_polymer += pair[0] if pair[1] in pair_insertion_dict[pair[0]]: new_polymer += pair_insertion_dict[pair[0]][pair[1]] new_polymer += ...
def position_of_blanks(state): """ Takes a state and returns the position of the first blank entry. position_of_blanks(str) -> int """ for i in range(0,len(state)): if state[i] == "_": return i break else: None
def partition(boxes, balls): """Create all nonnegative tuples of length d which sum up to n. """ # <https://stackoverflow.com/a/36748940/353337> # See <https://stackoverflow.com/a/45348441/353337> for an alterative # solution. def rec(boxes, balls, parent=tuple()): if boxes > 1: ...
def ppfUniform(p, a, b): """Returns the evaluation of the percent point function (inverse cumulative distribution) evaluated at the probability p for a Uniform distribution with range (a,b). Usage:\n ppfUniform(a,b)""" return a+p*(b-a)
def clean_text(text): """ Remove most punctuation from string and make it lowercase :param text: String :return: String with cleaned up text """ text = text.lower() text = text.replace("!", " ") text = text.replace("?", " ") text = text.replace(";", " ") text = text.replace('"', ...
def get_and_reset_metric_from_dict(metric_dict): """Convert metric to dict of results and reset""" if not metric_dict: return {} metric_result = {name: metric.result().numpy() for name, metric in metric_dict.items()} for _name, metric in metric_dict.items(): metric.reset_states() ret...
def approximate_fst(desired_fst, simulated_fst, parameter_fst, max_run_fst = 1, min_run_fst = 0, limit = 0.005): """Calculates the next Fst attempt in order to approximate a desired Fst. """ if abs(simulated_fst - desired_fst) < limit: return parameter_fst, max_run_fst, min_ru...
def gnome_sort(t_input): """ Gnome Sort Algorithm Simple and slow algorithm http://en.wikipedia.org/wiki/Gnome_sort Best case performance: O(n^2) Worst case performance: O(n) Worst Case Auxiliary Space Complexity: O(1) :param t_input: [list] of numbers :return: [list] - sorte...
def ignoreErrors(func, *args, **kwargs): """ >>> ignoreErrors(int, '3') 3 >>> ignoreErrors(int, 'three') """ try: return func(*args, **kwargs) except Exception: return None
def hamdist(str1, str2): """ Count the # of diferences between equal length strings str1 and str2 """ diffs = 0 for ch1, ch2 in zip(str1, str2): if ch1 != ch2: diffs += 1 return diffs
def first(a, fn): """ Example: first([3,4,5,6], lambda x: x > 4) :param a: array :param fn: function to evaluate items :return: None or first item matching result """ return next((x for x in a if fn(x)), None)
def problem_5_5(a, b): """ Write a function to determine the number of bits required to convert integer A to integer B. Input: 31, 14 Output: 2 Solution: compute (a XOR b) and produce the number of 1 bits in the result. """ def num_set_bits(n): count = 0 while n != 0: ...
def del_nones(doc): """ Delete keys with the value ``None`` in a dictionary, recursively. This alters the input so you may wish to ``copy`` the dict first. """ for key, value in list(doc.items()): if value is None: del doc[key] elif isinstance(value, dict): d...
def is_unknown_county(fips: str) -> bool: """Checks if fips is an unknown county. Args: fips: fips code to check. Returns: True if unkown, false otherwise. """ return len(fips) == 5 and fips.endswith("999")
def _matches_billing(price, hourly): """Return True if the price object is hourly and/or monthly.""" return any([hourly and price.get('hourlyRecurringFee') is not None, not hourly and price.get('recurringFee') is not None])
def _get_artifact_version(f_path: str) -> str: """ Retrieve version of artifact from given file path Args: f_path: str Returns: str """ begin_idx = f_path.rfind('artifact/json/') + 14 version = f_path[begin_idx: len(f_path)].split('/')[0] ...
def split_tasks(task_l, n): """Split tasks into equal lenght chunks.""" return [task_l[_i::n] for _i in range(n)]
def pretty_dict_string(d, indent=0): """Pretty output of nested dictionaries. """ s = '' for key, value in sorted(d.items()): s += ' ' * indent + str(key) if isinstance(value, dict): s += '\n' + pretty_dict_string(value, indent+1) else: s += '=' + str...
def merge_lists(orig: list, new: list, key_attr: str) -> list: """merge two lists based on a unique property""" combined = [] new_by_key = {getattr(item, key_attr): item for item in new} seen = set() # add original items, or their replacements if present for item in orig: key = getattr(i...
def _point(x,index=0): """Convert tuple to a dxf point""" return '\n'.join([' %s\n%s'%((i+1)*10+index,float(x[i])) for i in range(len(x))])
def _get_remaining_header_list(keyword_list, key_amount): """ Captures and repeats a partial sdrf header """ part_header = [] for key, value in key_amount.items(): _found = False for keyword in keyword_list: if key.startswith(keyword): _found = True if not...
def search_engine(encoded_query, inverted_idx): """takes an encoded query and the inverted_idx, searches in the inverted_idx and returns a list of the documents that contain all the tokens in the query Args: encoded_query (list): a textual query, encoded in integer inverted_idx (dict): a...
def get_attr(attrs, key): """ Get the attribute that corresponds to the given key""" path = key.split('.') d = attrs for p in path: if p.isdigit(): p = int(p) # Let it raise the appropriate exception d = d[p] return d
def is_intel_company(company): """Checks that company contains intel""" return company and 'intel' in company.lower()
def wikipedia_about_page(langcode: str) -> str: """Returns the Wikipedia "About" page for the language given by `langcode`. :param langcode: The language code of the desired language """ return "https://{}.wikipedia.org/wiki/Wikipedia:About".format(langcode)
def splinter_window_size(splinter_webdriver, splinter_window_size): """ Prevent pytest-splinter from crashing with Chrome. """ if splinter_webdriver == 'chrome': return None return splinter_window_size
def int_from_bytes(b): """Creates integer from little-endian bytes.""" return int.from_bytes(b, byteorder="little")
def create_ch_mapping(ch_names, name_addition): """Create a name mapping funtion to generate distinguishable channel names.""" ch_mapping = {} for ch_name in ch_names: ch_mapping[ch_name] = name_addition + "_" + ch_name return ch_mapping
def is_batch(code, shape, axes): """Method to check if given axis code belongs to a batch dimension. Parameters ---------- code : str shape : tuple axes : str Returns ------- bool """ # special case: if len(shape) == 3 and 'X' in axes and 'Y' in axes and 'I' == code: ...
def compare_filenames(file_list1, file_list2): """ Compare elements in 2 lists. :param file_list1: :param file_list2: :return: """ return set(file_list1).difference(file_list2)
def is_equal_or_sub_url(request_url, checked_url): """Stupidly simple method to check for URLs equality""" if request_url == checked_url: return True request_url = request_url.rstrip('/') checked_url = checked_url.rstrip('/') return request_url.startswith(checked_url)
def github_disable_required_pull_request_reviews(rec): """ author: @mimeframe description: Setting 'Require pull request reviews before merging' was disabled. When enabled, all commits must be made to a non-protected branch and submitted via a pull request with at ...
def parseDbDummyFname(dbDummyFname): """given user data item which is dummy database name used for remesh and restart purposes, pull out the base name (minus -s0002, -sXXXX, etc.) and return the base name and extension (extension in an empty string if appropriate)""" remeshRestartTagIndex = dbDummyFn...
def get_method_color(method): """ Return color given the method name. """ color = {} color['Random'] = 'blue' color['Target'] = 'cyan' color['Minority'] = 'cyan' color['Loss'] = 'yellow' color['BoostIn'] = 'orange' color['LeafInfSP'] = 'brown' color['TREX'] = 'green' colo...
def move_up(t): """ A method that takes coordinates of bomb's position and returns coordinates of neighbour located above the bomb. It returns None if there isn't such a neighbour """ x, y = t if x == 0: return None else: return (x - 1, y)
def jwt_response_payload_handler(token, user=None, request=None): """ Returns the response data for both the login and refresh views. Override to return a custom response such as including the serialized representation of the User. Example: def jwt_response_payload_handler(token, user=None, re...
def get_summary_table(valid): """Optimize the summary table we potentially use. Args: valid (datetime with time zone): Datetime Returns: str table to query """ if valid is None: return "summary" if (valid.month == 12 and valid.day >= 30) or ( valid.month == 1 and va...
def set_db(url, db): """useful for unit testing, where you want to use a local database """ global mydao mydao = None return mydao
def goodbye(name): # pylint: disable=unused-argument """Print a goodbye message. This command print "Goodbye, <name>.". Args: name: name of the person say goodbye to. """ print("Goodbye, {name}".format(**locals())) return 0
def get_positive_values(x): """Return a list of values v from x where v > 0.""" result = [] for _x in x: if _x > 0: result.append(_x) else: return result return result
def perimeterSqr(side: float) -> float: """Finds perimeter of square""" perimeter: float = 4 * side return perimeter
def crop(img, xmin, xmax, ymin, ymax): """Crops a given image.""" if len(img) < xmax: print('WARNING') patch = img[xmin: xmax] patch = [row[ymin: ymax] for row in patch] return patch
def get_json_value(obj, key): """Recursively fetch values for given key from JSON .""" result_array = [] def search(obj, result_array, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict): for k, v in obj.items(): if isinstance(...
def join(*args): """Like posixpath.join""" return "/".join(args)
def unique(l): """Filters duplicates of iterable. Create a new list from l with duplicate entries removed, while preserving the original order. Parameters ---------- l : iterable Input iterable to filter of duplicates. Returns ------- list A list of elements of `l`...
def calc_freq_from_interval(interval, unit='msec'): """ given an interval in the provided unit, returns the frequency :param interval: :param unit: unit of time interval given, valid values include ('msec', 'sec') :return: frequency in hertz """ if interval <= 0: print('Invalid inter...
def _get_elements_and_boundaries(flows): """filter out elements and boundaries not used in this TM""" elements = {} boundaries = {} for e in flows: elements[e] = True elements[e.source] = True elements[e.sink] = True if e.source.inBoundary is not None: boundar...
def get_workflowType(decision): """ Given a polling for decision response from SWF via boto, extract the workflowType from the json data """ try: return decision["workflowType"]["name"] except KeyError: # No workflowType found return None
def is_catalogue_link(link): """check whether the specified link points to a catalogue""" return link['type'] == 'application/atom+xml' and 'rel' not in link
def num_check(poss_int): """ Check whether string is feasibly an integer value of zero or greater """ try: if int(poss_int) >= 0: return True else: return False except ValueError: return False
def parse_ab(branch_dict): """ Extract 'ahead/behind' counts from Git status lines. Arguments --------- branch_dict: dict branch meta data dictionary Returns ------- list a list of two counts: [num_ahead, num_behind] """ if 'branch.ab' not in branch_dict: ...
def str2bool(s): """Convert str to bool.""" return s.lower() not in ['false', 'f', '0', 'none', 'no', 'n']
def pack_vals(a, b, c, d, offset=0): """Packs 4 byte values into a 32-bit word offset is subtracted from the values before storing """ return (((a - offset) & 0xff) + (((b - offset) & 0xff) << 8) + (((c - offset) & 0xff) << 16) + (((d - offset) & 0xff) << 24))
def difference_of_list(value, other_value): """ Compare two value lists and return a set for each list that does not include shared values, RETURN ONE LIST Parameters ---------- value: List[str] list to be compared to other list (most often some certain properties) other_value: List[str...
def compress_towards_affordability(cost_of_living, affordability): """Decrease differences between expensive and cheap locations.""" if cost_of_living == affordability: return cost_of_living else: return ((cost_of_living - affordability) * 0.33) + affordability
def moving_average(a_list, frame): """ moving_average(a_list, frame) performes a moving average smoothing on a given list of values Parameters ---------- a_list: array_like list of values to smooth frame: integer ...
def get_nonref_alleles(GT_string): """Take a VCF genotype (GT) string and return a set containing all non-reference alleles""" alleles = set(GT_string.split('/')) try: alleles.remove('.') # remove missing genotypes except KeyError: pass try: alleles.remove('0') # remove refer...
def _recognized(x, dict): """ If atom type is recognized, return it. Else, return empty string. """ if x in dict.keys(): return x else: return ''
def stringLengthCompare(a, b): """ _stringLengthCompare_ Sort comparison function to sort strings by length from longest to shortest. """ if len(a) > len(b): return -1 if len(a) == len(b): return 0 else: return 1
def show_type(type_name): """ Pretty-print a Python type or internal type name. Args: type_name: a Python type, or a string representing a type name Returns: a string representation of the type """ if isinstance(type_name, str): return type_name elif isinstance...
def factor(i, j, k, l): """Based on the orbitals indices return the factor that takes into account the index permutational symmetry.""" if i == j and k == l and i == k: return 1.0 elif i == j and k == l: return 2.0 elif ( (i == k and j == l) or (i == j and i == k) ...
def lastaccessed_sort(d1, d2): """ sort dictionaries in descending order based on last access time """ m1 = d1.get('_last_accessed', 0) m2 = d2.get('_last_accessed', 0) if m1 == m2: return 0 if m1 > m2: return -1 # d1 is "less than" d2 return 1
def _normalize_base_url(_base_url): """This function normalizes the base URL (i.e. top-level domain) for use in other functions. .. versionadded:: 3.0.0 :param _base_url: The base URL of a Khoros Community environment :type _base_url: str :returns: The normalized base URL """ _base_url = _...
def find_bound_of_bounds(bounds_list): """Find the bounding box of a list of bounds. Parameters ---------- bounds_list: list List containing bounds to find bounding box of. """ # Set initial guess x_min = bounds_list[0][0][0] y_min = bounds_list[0][0][1] x_max = bounds_list[...
def lat_lng_error_message(value: str, param: str) -> str: """ Defines an error message when lat or long are not in good format - value: str. Latitude or longitude value as a string - param: str. Name of the param (either latitude or longitude) """ error_msg = "Incorrect " + param + "...
def create_data_descriptor(collection_id: str, var_id: str, spatial_extent: dict, temporal_extent: list) -> dict: """ """ # Create WEkEO 'data descriptor' data_descriptor = { "datasetId": collection_id, "boundingBoxValues": [ { "name": "bbox", "bb...
def make_attr_string(attr): """Returns an attribute string in the form key="val".""" attr_string = ' '.join('%s="%s"' % (k, v) for k, v in attr.items()) return '%s%s' % (' ' if attr_string != '' else '', attr_string)
def force_line_char_limit(line, indent): """ If line is longer than limit then create new line at a space in the text :param line: :return: """ clim = 120 if len(line) <= clim: return line rem = line oline = '' for i in range(clim): j = clim - i if rem[j]...
def merge(a: dict, b: dict) -> dict: """Deep merge of 2 dict objects. Take the values in dict "b" and merge them into dict "a". If a key exists in both inputs the value from "b" will be used. """ queue = list() ret = dict() queue.append((ret, a, b)) while len(queue) > 0: roo...
def check_for_Ns(seq): """Doc string here..""" nCount = seq.count('N') if( nCount > 0 ): return nCount else: return 0
def _ChopEar(face, i): """Return a copy of face (of length n), omitting element i.""" return face[0:i] + face[i + 1:]
def remove_quotes(string: str) -> str: """ Removes quotes from around a string, if they are present. :param string: The string to remove quotes from. :return: The string without quotes. """ # If starts and ends with double-quotes, remove them if string.startswith('\"') and string.e...
def move_down(loc): """increments the location for downward movement. """ return (loc[0], loc[1] - 1)
def xsthrow_format(formula): """formats the string to follow the xstool_throw convention for toy vars """ return (formula. replace('accum_level[0]', 'accum_level[xstool_throw]'). replace('selmu_mom[0]', 'selmu_mom[xstool_throw]'). replace('selmu_theta[0]', 'selmu_thet...
def selectionsort(list, descending=False): """ Takes in a list as an argument, and sorts it using a "Selection Sort"-algorithm. --- Args: - list (list): The list to be sorted - descending (bool): Set true if the list be sorted high-to-low. Default=False Raises: - T...
def wordlist2set(input_list, save_order = False): """ converts list of phrases to set if save_order == False, n-grams like 'word1 word2' and 'word2 word1' will be equal in result set """ if save_order: return set(input_list) return set([' '.join(sorted(words.split())) for words in inp...
def gate_infidelity_to_irb_decay(irb_infidelity, rb_decay, dim): """ For convenience, inversion of Eq. 4 of [IRB]. See irb_decay_to_infidelity :param irb_infidelity: Infidelity of the interleaved gate. :param rb_decay: Observed decay parameter in standard rb experiment. :param dim: Dimension of the...
def swap_possible(board): """ Optional Challenge: helper function for swap Returns True if a swap is possible on the given board and False otherwise """ print("Not implemented yet!") return False
def bubble_sort(list_): """Bubble sort.""" list_length = len(list_) - 1 sorted_ = False while not sorted_: sorted_ = True for i in range(list_length): if list_[i] > list_[i + 1]: list_[i], list_[i + 1] = list_[i + 1], list_[i] sorted_ = False ...
def merge(left, right): """ Merges two lists (arrays), sorting them in the process Returns a new merged list Takes overall O(n) time """ l = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: l.append(left[i]) i...
def find_item(item_to_find, items_list): """ Returns True if an item is found in the item list. :param item_to_find: item to be found :param items_list: list of items to search in :return boolean """ is_found = False for item in items_list: if item[1] == item_to_find[1]: ...
def tuple_plus_schema_2_dict(data, schema): """ :param data: :param schema: :return: """ rdata = {} for schema_item, value in zip(schema, data): if schema_item.field_type == 'RECORD': ldata = [] if schema_item.mode == 'REPEATED': llist = value ...
def unicodetoascii(s, encoding='ascii', rplc=None): """A crude str encoder. Replaces '?' from s.encode with rplc (if not None). Bytes returned unchanged.""" # Another choice: encoding='latin-1'. # ??? Is this sane: just to have a different replacement char than '?'? if not isinstance(s, str): ...
def Camel2Const(camel: str) -> str: """Convert from Camel to Const format. e.g. HogeTitle -> HOGE_TITLE :type camel: str :rtype: str """ return camel[0] + ''.join(['_' + c if c.isupper() else c.upper() for c in camel[1:]])
def tanh_backward(dout, cache): """ backward of tanh, dx = 1 - (tanh(x))^2 :param dout: :param cache: :return: """ tanh_x = cache return (1 - tanh_x ** 2) * dout
def ord_seq_upper(ordseq): """Upper for [ord] sequence.""" return [c - 32 if c <= 122 and c >= 97 else c for c in ordseq]
def byLength(word1, word2): """ Compars two strings by their length Returns: Negative if word2 > word1 Positive if word1 > word2 Zero if word1 == word 2 """ return len(word1) - len(word2)
def prod(num_iter): """ returns product of all elements in this iterator *'ed together""" cumprod = 1 for el in num_iter: cumprod *= el return cumprod
def product(*args): """This method returns the product of items passed as arguments Returns product of the arguments passed. If args length is zero then ti will return 0 """ if len(args) == 0: return 0 result = 1 for arg in args: result *= arg return result
def largest_sum_contiguous_subarray(arr): """ Find the subarray with maximum sum from all subarrays. :param arr: List of numbers to form subarray from. :return: The maximum sum in all subarrays. """ max_now = 0 max_next = 0 for i in arr: max_next += i max_now = max(max_n...
def intersection(lst1, lst2): """ Intersection of two sets :param lst1: first input list :param lst2: second input list :return: intersection in list format """ return list(set(lst1) & set(lst2))
def update_time(p_dict, uuid): """Updates time by uuid""" updated_param = { "duration": p_dict["duration"] if "duration" in p_dict else 18, "user": p_dict["user"] if "user" in p_dict else "example-user", "activities": p_dict["activities"] if "activities" in p_dict else ( ["qa...
def old_vertex_from_dummy(dummy: int, key: int, biggest) -> int: """Old vertex ID from the dummy vertex ID""" if dummy < 0: return -(dummy + (biggest + 1) * (key - 1) + 1) return dummy
def stations_by_town(stations): """This function maps river names to a list of stations on a given river""" dict = {} for s in stations: if s.town not in dict: dict[s.town]=[s] elif s.town in dict: dict[s.town] += [s] return dict