content
stringlengths
42
6.51k
def addUser(name): """Registers a new user with this computer. Returns true if the user was successfully added. Returns None and an error message otherwise.""" return None, 'Not implemented.'
def solfege(title_hymn): """Partitions the input string to (an optional) title, ': ', and the hymn, takes a sublist starting from the first string, skipping always two other strings, and ending 3 strings from the end, returns the result as a string with ', ' as a separator >>> solfege('Hymn of St. John: Ut queant laxis re sonare fibris mi ra gestorum fa muli tuorum sol ve polluti la bii reatum Sancte Iohannes') 'Ut, re, mi, fa, sol, la' >>> solfege('Ut queant laxis re sonare fibris mi ra gestorum fa muli tuorum sol ve polluti la bii reatum Sancte Iohannes') 'Ut, re, mi, fa, sol, la' """ # the input string partitioned to the title (if given) and the actual hymn possible_title, hymn = title_hymn.split(': ') if ': ' in title_hymn else ('', title_hymn) # vase reseni # the hymn as a list of strings separated by ' ' hymn_list = hymn.split(' ') # vase reseni # skipping always two strings, and ending 3 strings from the end skip2 = hymn_list[:-3:3] # vase reseni # the skip2 list as a string, ', ' as a separator skip2_str = ", ".join(skip2) # vase reseni return skip2_str
def stringify(obj): """Converts all objects in a dict to str, recursively.""" if isinstance(obj, dict): return {str(key): stringify(value) for key, value in obj.items()} elif isinstance(obj, list): return [stringify(value) for value in obj] else: return str(obj)
def replace_only_nums(preprocessed_log): """ Replace nuemeric tokens with a wildcard :param preprocessed_log: resultant log message after pre-processing :return: input text after replacing numeric tokens with a wildcard """ for i, token in enumerate(preprocessed_log): if token.isnumeric(): preprocessed_log[i] = '<*>' return preprocessed_log
def parse_import_line(line): """ @import "app_window_params.h" {md_id=DockingParams} """ def get_string_between(s, after_what, before_what): end = s[s.index(after_what) + len(after_what):] middle = end[0 : end.index(before_what)] return middle imported_file = get_string_between(line, '@import "', '"') md_id = get_string_between(line, "md_id=", "}") return imported_file, md_id
def convert_list_objs(log): """ Deserializes Crop objects to dict format """ return [obj.to_dict() for obj in log]
def calc_offset(previous: tuple, index: int) -> int: """ Function ---------- Given the previous insertions and the current insertion index, the necessary offset is calculated Paramters ---------- previous : [(int, int),] A list of tuples with: tuple[0] : previous insertion index tuple[1] : length of previous insertion index : int The location of the current insertion into the list Returns ---------- int An integer representing the number of slices to offset the insertion Notes ---------- When we have multiple nested structures, we need to compute what the potential offset is when placing into the sorted list. We cannot do this in the original list because then future structures may map to a newly inserted structure as opposed to the exterior polygon """ offset = 0 for item in previous: idx, n_pts = item if index > idx: offset += n_pts return offset
def constructTableQuery(ch, index): """helper function for characterInTableName""" payload = "' OR EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='test' AND TABLE_NAME LIKE '" tableStr = "" if(index == "no index"): tableStr += "%" + ch + "%" elif(index >= 0): tableStr += index * "_" + ch + "%" else: index *= -1 index -= 1 tableStr += "%" + ch + "_" * index payload += tableStr + "') AND ''='" #do I even need the AND ''=' part? it evaluates to '' = '' which is true so true/false AND true? Seems redundant return payload
def build_j_type(joints): """ Builds the joint type (R or P) list. """ num_j = len(joints) j_type = [] for i in range(num_j): j_type.append(joints[i].j_type) return j_type
def truncate(string, length=255, killwords=False, end='...'): """Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. .. sourcecode:: in views.py context['my_string'] = 'foo bar baz' in template &truncate($my_string,5) -> "foo ..." &truncate($my_string,5,killwords=True) -> "foo ba..." """ if len(string) <= length: return string elif killwords: return string[:length - len(end)] + end result = string[:length - len(end)].rsplit(' ', 1)[0] if len(result) < length: result += ' ' return result + end
def correct_eval_poly(d): """This function evaluates the polynomial poly at point x. Poly is a list of floats containing the coeficients of the polynomial poly[i] -> coeficient of degree i Parameters ---------- poly: [float] Coefficients of the polynomial, where poly[i] -> coeficient of degree i x : float Point Returns ------- float Value of the polynomial at point x Example ------- >>> eval_poly( [1.0, 1.0], 2) 3.0 """ poly, x = d["poly"], d['x'] result = 0.0 power = 1 degree = len(poly) - 1 i = 0 while i <= degree: result = result + poly[i] * power power = power * x i = i + 1 return (d,result)
def str2bool(s): """Convert string to bool for argparse """ values={'true': True, 't': True, 'yes': True, 'y': True, 'false': False, 'f': False, 'no': False, 'n': False} if s.lower() not in values: raise ValueError('Need bool; got %r' % s) return values[s.lower()]
def sub(*args): """Subtracts a list of numbers from the first number entered""" """check for length of array""" return args[0] - sum(args[1:])
def safe_bytes(s): """Accepts a bytes or str and returns the utf-8 bytes if it's a str.""" if isinstance(s, str): return s.encode('utf-8') elif isinstance(s, bytes): return s raise TypeError("unknown string type {0}".format(type(s)))
def lget(l, idx, default): """Safely get a list object""" try: return l[idx] except IndexError: return default
def _ins(source: str, insert: str, position: int) -> str: """inserts value at a certain position in the source""" return source[:position] + insert + source[position:]
def get_totals(sorted_user_list): """Given a sorted user list, get the totals for ways and nodes. :param sorted_user_list: User dicts sorted by number of ways. :type sorted_user_list: list :returns: Two-tuple (int, int) containing way count, node count. :rtype: (int, int) """ way_count = 0 node_count = 0 for user in sorted_user_list: way_count += user['ways'] node_count += user['nodes'] return node_count, way_count
def offbySwaps(s1,s2): """Input: two strings s1,s2 Process: to check if s2 can be obtained by swapping/arranging characters in s1(or vice versa) Output: return True when above condition is met otherwise return False""" extra1='' extra2='' if len(s1)==len(s2): for x in s1: if x not in s2: extra1=extra1+x for y in s2: if y not in s1: extra2=extra2+y if extra1=='' and extra2=='': return True else: return False else: return False
def get_portals(entries): """Create mapping of portal entrances from entries.""" portals = {} for portal_name, locations in entries.items(): if len(locations) == 2: (location1, level_change1), (location2, level_change2) = locations portals[location1] = location2, level_change2 portals[location2] = location1, level_change1 return portals
def int_or_str(val, encoding=None): """ simple format to int or string if not possible """ try: return int(val) except ValueError: if encoding is None: if isinstance(val, bytes): return val return str(val) elif isinstance(val, bytes): return val.decode(encoding).strip()
def build_coreference(reference_id: int) -> dict: """Build a frame for a coreference structure""" return { 'id': reference_id, 'representative': { 'tokens': [] }, 'referents': [] }
def Escaped(Location, Width): """ This function will return a true if the particle has esacped the cubic geometry defined by Width: The width of the cube Location: A tuple defining where the particle is located """ for coordinate in Location: if coordinate < 0 or coordinate > Width: return True return False # Return this if particle is still in cube
def serial_number(unique_id): """Translate unique ID into a serial number string.""" serial_number = str(unique_id) return serial_number[:4] + '-' + serial_number[4:]
def list_to_str(input_list: list, delimiter: str = ',') -> str: """ Concatenates a list elements, joining them by the separator `delimiter`. Parameters ---------- input_list : list List with elements to be joined. delimiter : str, optional The separator used between elements, by default ','. Returns ------- str Returns a string, resulting from concatenation of list elements, separeted by the delimiter. Example ------- >>> from pymove.utils.conversions import list_to_str >>> list = [1,2,3,4,5] >>> print(list_to_str(list, 'x'), type(list_to_str(list))) 1x2x3x4x5 <class 'str'> """ return delimiter.join( [x if isinstance(x, str) else repr(x) for x in input_list] )
def get_language_code_from_domain_path(file_path) -> str: """ this works nice for me @param file_path: @return: """ folder_names = file_path.split("/") return folder_names[folder_names.index("lang") + 1]
def filtered_icon(options, filter): """Returns btn-primary if the filter matches one of the filter options """ for option in options: if filter == option[1]: return "btn-primary" return ""
def getnamedargs(*args, **kwargs): """allows you to pass a dict and named args so you can pass ({'a':5, 'b':3}, c=8) and get dict(a=5, b=3, c=8)""" adict = {} for arg in args: if isinstance(arg, dict): adict.update(arg) adict.update(kwargs) return adict
def modpos(pos, L, move): """very similar to modcoord, but only for a LxL. takes as input walk[i][0] or walk[i][1] returns the pos modified with the move, accounting for PBCs.""" pos += move if pos == L: # moved off right or bottom return(0) if pos == -1: # moved off top or left return(L - 1) return(pos)
def getSumOf3Numbers(array , target): """ Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should find all triplets in the array that sum up to the target sum and return a two-dimensional array of all these triplets. The numbers in each triplet should be ordered in ascending order, and the triplets themselves should be ordered in ascending order with respect to the numbers they hold. If no three numbers sum up to the target sum, the function should return an empty array. """ #sort the array array.sort() NumSums = [] for i in range(len(array)-2): right = len(array)-1 left = i+1 while left < right: # print(right , left) currSum = array[i]+array[left]+array[right] if currSum == target: NumSums.append([array[i],array[left],array[right]]) left +=1 right -=1 elif currSum < target: left +=1 elif currSum > target: right -=1 else: print("passs") pass return NumSums
def db_error_needs_new_session(driver, code): """some errors justify a new database connection. In that case return true""" if code == "ConnectionResetError": return True return False
def farey(v, lim): """ determine closest fraction for floating point value v such that lim is the maximum denominator the function returns a (numerator, denominator) tuple """ if v < 0: n, d = farey(-v, lim) return -n, d # gives a zero z of the same type as the lim argument z = lim - lim lower, upper = (z, z+1), (z+1, z) while True: mediant = (lower[0] + upper[0]), (lower[1] + upper[1]) if v * mediant[1] > mediant[0]: if lim < mediant[1]: return upper lower = mediant elif v * mediant[1] == mediant[0]: if lim >= mediant[1]: return mediant if lower[1] < upper[1]: return lower return upper else: if lim < mediant[1]: return lower upper = mediant
def _get_schema_type(schema): """Retrieve schema type either by reading 'type' or guessing.""" # There are a lot of OpenAPI specs out there that may lack 'type' property # in their schemas. I fount no explanations on what is expected behaviour # in this case neither in OpenAPI nor in JSON Schema specifications. Thus # let's assume what everyone assumes, and try to guess schema type at least # for two most popular types: 'object' and 'array'. if "type" not in schema: if "properties" in schema: schema_type = "object" elif "items" in schema: schema_type = "array" else: schema_type = None else: schema_type = schema["type"] return schema_type
def add_default_field(pv_name, default_field): """ Add a default field to a pv name if pv_name does not already have a field and the default field makes sense. This is useful for example to add a VAL field to pvs for the archive Args: pv_name: the pv name default_field: default field to add Returns: pvname with the default field added """ if default_field is None or default_field == "": return pv_name if pv_name is None or pv_name == "" or "." in pv_name: return pv_name return "{0}.{1}".format(pv_name, default_field)
def STR_LEN_BYTES(expression): """ Returns the number of UTF-8 encoded bytes in the specified string. https://docs.mongodb.com/manual/reference/operator/aggregation/strLenBytes/ for more details :param expression: The string or expression of the string :return: Aggregation operator """ return {'$strLenBytes': expression}
def _format_buffer(buf): """ example: [0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88] -> "11-22-33-44-55-66-77-88" :param list buf: :rtype: str """ return '-'.join(["%.2x"%i for i in buf])
def _medgen_url(cui): """ URL linkout the NCBI MedGen website. :param cui: concept unique identifier :return: str url """ return 'http://www.ncbi.nlm.nih.gov/medgen/' + str(cui)
def is_gzip(filename): """ Uses the file contents to check if the file is gzip or not. The magic number for gzip is 1f 8b See KRONOS-8 for details """ with open(filename) as f: file_start = f.read(4) if file_start.startswith("\x1f\x8b\x08"): return True return False
def list_attributes(any_class): """List all public methods and attributes of a class sorted by definition order """ return [x for x in any_class.__dict__.keys() if not x.startswith("_")]
def lzip(*args): """ Zip, but returns zipped result as a list. """ return list(zip(*args))
def ugly(n): """if number is 0, or number is divisible by one of 2, 3, 5 or 7. >>> ugly(0) # by definition True >>> ugly(4) True >>> ugly(13) False >>> ugly(39) True >>> ugly(121) False >>> ugly(-14) True >>> ugly(-39) True """ return not n or not(n % 2) or not(n % 3) or not(n % 5) or not(n % 7)
def arduino_version(ARDUINO): """ Example: 105 -> 1.0.5 """ return '.'.join(str(ARDUINO))
def classify_dict_f(a_dict, *filters): """Classfy a dict like object. Multiple filters in one loop. - a_dict: dict like object - filters: the filter functions to return True/False Return multiple filter results. Example: data = {'a': 1, 'b': 2} dm1 = lambda k, v: v > 1 dm2 = lambda k, v: v > 2 classify_dict_f(data, dm1, dm2) -> {'b': 2}, {} """ results = tuple({} for i in range(len(filters))) for key, value in a_dict.items(): for filter_func, result in zip(filters, results): if filter_func(key, value): result[key] = value return results
def make_entity_base_url(url): """ Returns an entity URL with a trailing "/" so that it can be used consistently with urljoin to obtain URLs for specific resources associated with the entity. >>> make_entity_base_url("/example/path/") == '/example/path/' True >>> make_entity_base_url("/example/path") == '/example/path/' True """ return url if url.endswith("/") else url + "/"
def ramp(phi, A): """ Ramps linearly between A[0] and A[1] according to phi, such that phi=1 => A(phi) = A[0], phi=-1 => A(phi) = A[1] """ return A[0]*0.5*(1.+phi) + A[1]*0.5*(1.-phi)
def vargs(args): """ Conform function args to a sequence of sequences. """ n = len(args) if n == 1: return args[0] elif n == 0: raise TypeError("no arguments given") else: return args
def _parse_placeholder_types(values): """Extracts placeholder types from a comma separate list.""" values = [int(value) for value in values] return values if len(values) > 1 else values[0]
def validateDir(value): """ Validate direction. """ msg = "Direction must be a 3 component vector (list)." if not isinstance(value, list): raise ValueError(msg) if 3 != len(value): raise ValueError(msg) try: nums = map(float, value) except: raise ValueError(msg) return value
def combined_prefix(cluster_bin_index, isoform_type, sample_name): """Return i{cluster_bin_index}_{isoform_type}_{sample_name}""" assert isoform_type in ["HQ", "LQ", "ICE"] return "i{i}_{t}_{s}".format(i=cluster_bin_index, t=isoform_type, s=sample_name)
def expected_cuts(cut_coords): """Expected cut with test_demo_mosaic_slicer.""" if cut_coords == (1, 1, 1): return {'x': [-40.0], 'y': [-30.0], 'z': [-30.0]} if cut_coords == 5: return {'x': [-40.0, -20.0, 0.0, 20.0, 40.0], 'y': [-30.0, -15.0, 0.0, 15.0, 30.0], 'z': [-30.0, -3.75, 22.5, 48.75, 75.0] } return {'x': [10, 20], 'y': [30, 40], 'z': [15, 16]}
def dist_to_char(distance): """ * Convert the distance to the mine into a character * @param d * @return """ if 1 <= distance <= 26: # in range a - z return chr(distance + 96) elif 26 <= distance <= 52: # in range A - Z return chr(distance + 38) return '*'
def render(line, prefix_arg=None, color=-1): """ Turn a line of text into a ready-to-display string. If prefix_arg is set, prepend it to the line. If color is set, change to that color at the beginning of the rendered line and change out before the newline (if there is a newline). :param str line: Output line to be rendered :param str prefix_arg: Optional prefix to be stuck at the beginning of the rendered line :param int color: If 0-255, insert escape codes to display the line in that color """ pretext = '' if prefix_arg is None else prefix_arg if -1 < color < 256: pretext = "\x1b[38;5;{}m{}".format(str(color), pretext) if line[-1] == "\n": line = "{}\x1b[0m\n".format(line[:-1]) else: line = "{}\x1b[0m".format(line) return "{}{}".format(pretext, line)
def generate_gateway_url(project, gateway): """Format the resource name as a resource URI.""" return 'projects/{}/global/gateways/{}'.format(project, gateway)
def dont_give_me_five(start: int, end: int) -> int: """This function returns the count of all numbers except numbers with a 5.""" count = 0 for item in range(start, end+1): if '5' not in str(item): #print (item) count += 1 return count
def inverse(phi, e): """ Use the Bezout law to calculate the inverse of e to the modulus of phi. :param phi: :param e: :return: an integer d st. d*e = 1 (mod phi) """ s, t, sn, tn, r = 1, 0, 0, 1, 1 while r != 0: q = phi // e r = phi - q * e st, tt = sn * (-q) + s, tn * (-q) + t s, t = sn, tn sn, tn = st, tt phi = e e = r return t
def ext_gcd(a, b): """ calculate the greatest common denominator or return integers if b is 0 or a is an integer multiple of b. """ if b == 0: return 1, 0 elif a % b == 0: return 0, 1 else: x, y = ext_gcd(b, a % b) return y, x - y * (a // b)
def is_hypervisor_image(plat): """Checks if platform is a hypervisor. Returns true for hypervisor, false for cloud.""" hypervisor_list = ["vmware", "qcow2", "vhd"] if plat in hypervisor_list: return True return False
def _winfix(s): """clean up the string on Windows""" return s.replace('2L', '2').replace('3L', '3').replace('4L', '4').replace('5L', '5')
def get_label_font_size(max_dim): """ Find standardised font size that can be applied across all figures. Args: max_dim: The number of rows or columns, whichever is the greater """ label_font_sizes = {1: 8, 2: 7} return label_font_sizes[max_dim] if max_dim in label_font_sizes else 6
def right(state): """move blank space right on the board and return new state.""" new_state = state[:] index = new_state.index(0) if index not in [2, 5, 8]: temp = new_state[index + 1] new_state[index + 1] = new_state[index] new_state[index] = temp return new_state else: return None
def dataset_names(val=False): """ Returns list of data set names :param val: Whether or not to include the validation set :return: List of strings """ if val: return ["Q1", "Q2", "Q3", "Q4", "TEST", "VAL"] return ["Q1", "Q2", "Q3", "Q4", "TEST"]
def is_xpath_selector(selector): """ A basic method to determine if a selector is an xpath selector. """ if (selector.startswith('/') or selector.startswith('./') or selector.startswith('(')): return True return False
def prepare_show_ipv6_interface_output(data): """ Helper function to prepare show ipv6 interface output :param data: :return: """ output = dict() result = list() for ip_data in data: if output.get(ip_data["interface"]): output[ip_data["interface"]].append(ip_data) else: output[ip_data["interface"]] = [ip_data] if output: ip_keys = ["status", "neighborip", "ipaddr", "flags", "vrf", "neighbor", "interface"] for _, value in output.items(): result.append(value[0]) if len(value) > 1: for attr in ip_keys: value[1][attr] = value[1][attr] if value[1][attr] else value[0][attr] result.append(value[1]) return result
def valid_length_word(word, words_list): """Function to test the validity of the length of the input word. Args: word (str): input word words_list (list): list of words whose size must be the same as the word entered Returns: bool: whether or not the length of the word is valid """ if len(word)==len(words_list[-1]): return True else: return False
def get_gridline_bools(axis_gridlines): """If gridlines ON, return True else False""" if 'xaxis' in axis_gridlines: xaxis_gridlines = True else: xaxis_gridlines = False if 'yaxis' in axis_gridlines: yaxis_gridlines = True else: yaxis_gridlines = False return xaxis_gridlines, yaxis_gridlines
def parse_id_rank_pair(str): """ Parses a rank entry. Since protein labels are sometimes not included return -1 for protein id. """ if "=" not in str: return -1, float(str) id, rank = str.split("=") return int(id), float(rank)
def flett(liste1, liste2): """ Fletter 2 lister """ flettet_liste = [] index = 0 while index < max(len(liste1), len(liste2)): if index < len(liste1): flettet_liste.append(liste1[index]) if index < len(liste2): flettet_liste.append(liste2[index]) index += 1 return flettet_liste
def find_overlap(box1,box2): """Find the area of intersection between two boxes Parameters ---------- box1 : list A list of [x,y,width,height] where x,y in the top-left point coordinates of the first box box2 : list A list of [x,y,width,height] where x,y in the top-left point coordinates of the second box Returns ------- int The area of the intersection between the two boxes Examples -------- >>> find_overlap([0,0,10,5],[0,0,5,10]) 25 """ # box is : x,y,w,h x1 = set(range(box1[0],box1[0]+box1[2])) y1 = set(range(box1[1],box1[1]+box1[3])) x2 = set(range(box2[0],box2[0]+box2[2])) y2 = set(range(box2[1],box2[1]+box2[3])) return len(x1.intersection(x2))*len(y1.intersection(y2))
def _filter_layer_repr(filter_layer): """Functions returned by math_eval.compute() have docstrings that indicate what the function does. This recursively searches the keys_in and vals_in attributes of Filter and GlobalConstraint objects and make it so that the string representation of those compute() functions looks like "compute('x**2 + 3')" instead of '<function compute.<locals>.outfunc at 0x000002EEE5AAC160>'.""" out = [] for k in filter_layer: if isinstance(k, list): out.append(_filter_layer_repr(k)) continue try: if "compute.<locals>.outfunc" in repr(k): doc = k.__doc__.split("\n")[0] out.append('compute("{}")'.format(doc)) else: out.append(k) except: out.append(k) return out
def get_points_to_draw(f, x0: float, skip: int, n: int, r: float) -> list: """ Get the points to draw in the bifurcation diagram. Parameters ---------- f: Callable The map function x0: float The initial conidition of the map. skip: int The number of iteration values to skip after the initial condition to let the map reach its final state. n: int The number of points to generate (and to return for plotting) after reaching the final state configuation. r: float The bifurcation parameter. Returns ------- list A list of point pairs to plot in the bifurcation diagram for the given value `r` of the bifurcation parameters. """ x = x0 # skip the initial values for _ in range(skip): x = f(x, r) # store the values that should be plotted output = [] for _ in range(n): x = f(x, r) output.append((r, x)) return output
def check_location(loc): """Makes sure the location is valid. I'm just going to list the big ones. If this is stopping you from doing something cool, remove it yourself!""" valid_locations = ('smart', 'usny', 'ussf', 'usch', 'usda', 'usla2', 'usmi2', 'usse', 'cato', 'cato2') if loc in valid_locations: return loc elif loc == None: print('No location found, picking smart.') return 'smart' else: print('Invalid or unlisted location, reverting to smart.') return 'smart'
def get_email_template( plugin_configuration: list, template_field_name: str, default: str ) -> str: """Get email template from plugin configuration.""" for config_field in plugin_configuration: if config_field["name"] == template_field_name: return config_field["value"] or default return default
def mu_chi_var_chi_max_to_alpha_beta_max(mu_chi, var_chi, amax): """ Convert between parameters for beta distribution """ mu_chi /= amax var_chi /= amax**2 alpha = (mu_chi**2 * (1 - mu_chi) - mu_chi * var_chi) / var_chi beta = (mu_chi * (1 - mu_chi)**2 - (1 - mu_chi) * var_chi) / var_chi return alpha, beta, amax
def divisible_pairs(iterable, key): """ Divisible-pairs gives the total number of divisible pairs in which the sum of the numbers from a pair is divisible by the given key :param iterable: The iterable should be of type list or tuple containing numbers :param key: key should be a number :return: Returns the total number of divisible pairs whose sum is divisible by given key Eg: divisible_pairs([1, 0, 0, 2, 5, 3],3) returns 5 Here divisible pairs are {(0, 0), (0, 3), (0, 3), (1, 2}, (1, 5)} """ # To check whether the given iterable is list or tuple if type(iterable) == list or type(iterable) == tuple: pass else: raise TypeError("Iterable should be of either list or tuple") # To check whether all the given items in the iterable are numbers only for item in iterable: if not isinstance(item, int): raise ValueError("Only numbers are accepted in the iterable") # To check whether the given key is a number or not if not isinstance(key, int): raise ValueError("Key should be a number") # Dictionary to store all the remainders and their number of occurrences rem = {} for num in iterable: remainder = num % key if remainder in rem.keys(): rem[remainder] += 1 else: rem[remainder] = 1 pairs = 0 # selecting two numbers out of n numbers is n C 2 ways i.e. (n(n-1))/2 if 0 in rem.keys(): # since 0 is divisible by key pairs += (rem[0] * (rem[0] - 1)) // 2 end = key // 2 if key % 2 == 0: if end in rem.keys(): # since sum of two ends is equal to key pairs += (rem[end] * (rem[end] - 1)) // 2 else: end += 1 for i in range(1, end): # noinspection PyBroadException try: pairs += rem[i] * rem[key - i] except Exception: pass return pairs
def state_value(state, key_list): """Gets a value from the state variable stored in the RELEASE_TOOL_STATE yaml file. The key_list is a list of indexes, where each element represents a subkey of the previous key. The difference between this function and simply indexing 'state' directly is that if any subkey is not found, including parent keys, None is returned instead of exception. """ try: next = state for key in key_list: next = next[key] return next except KeyError: return None
def chain_2(d2f_dg2, dg_dx, df_dg, d2g_dx2): """ Generic chaining function for second derivative .. math:: \\frac{d^{2}(f . g)}{dx^{2}} = \\frac{d^{2}f}{dg^{2}}(\\frac{dg}{dx})^{2} + \\frac{df}{dg}\\frac{d^{2}g}{dx^{2}} """ return d2f_dg2*(dg_dx**2) + df_dg*d2g_dx2
def divide(first_term, second_term): """Divide first term by second term. This function divides ``first_term`` by ``second_term``. Parameters ---------- first_term : Number First term for the division. second_term : Number Second term for the division. .. warning:: Should not be zero! Returns ------- result : Number Result of the division. Raises ------ ZeroDivisionError If second term is equal to zero. See Also -------- add : Addition. subtract : Subtraction. multiply : Multiplication. Examples -------- >>> divide(1, 1) 1.0 >>> divide(1, -1) -1.0 >>> divide(4, 2) 2.0 >>> divide(1, 2) 0.5 """ result = first_term / second_term return result
def population_spread_fitness(input_phenotype, desired_population, population_weight, spread_weight): """ Reward high population of agents, punish high spread of disease. :param input_phenotype: :type input_phenotype: :param desired_population: Desired Population :type desired_population: Integer :param population_weight: The weight of the relative population. :type population_weight: Float :param spread_weight: The weight of the relative spread of disease. :type spread_weight: Float :return: :rtype: """ infected = input_phenotype["number_total_infected"] # Pc current_population = input_phenotype["parameters"]["number_of_agents"] relative_population = current_population / desired_population # infected = input_phenotype["number_currently_infected"] relative_spread = infected / current_population return population_weight * (1 - relative_population) + relative_spread * spread_weight # Minimization above # return 1 - (population_weight * (1 - relative_population) + relative_spread * spread_weight)
def set_node_value(data, path, value): """ Sets value to the node of the dictionary :param data: The dictionary to search :param path: The path to search Example - root.node1.node2.0.node3 :param value: The value to set :return: The value of the node specified in the path """ node = data path_list = path.split('.') for i in range(len(path_list) - 1): if path_list[i].isdigit(): item = int(path_list[i]) else: item = path_list[i] node = node[item] node[path_list[len(path_list) - 1]] = value return data
def build_already_running(builds, trigger_id): """ check to see if our build trigger is already running """ for build in builds: if trigger_id == build.build_trigger_id: return True return False
def identity(*args, **kwargs): """Return args, acting as identity for mocking functions.""" # pylint: disable=unused-argument # Here, kwargs will be ignored. if len(args) == 1: return args[0] return args
def debugMessages(key: str, print_msg: bool = False) -> str: """ Get debug details according to the key given. :param key: dict key :param print_msg: debug info. :return: debug (dict value) if True, otherwise None. """ msg_dict = { "START_SERVER": "Initializing server...", "SERVER_STARTED": "Server is up and running.", "GRAPHICS_LOAD": "Loading client graphices...", "CONNECT": "Establishing a connection to the server...", "CONNECTED": "Client is successfully connected to the server.", "AUTHENTICATED": "Client authenticated successfully!", "NOT_AUTHENTICATED": "Username or Password incorrect, please try again.", "DISCONNECTED": "Client disconnected from the server.", "TIMEOUT": "There is a problem connecting to the server, please try again later.", "DB_CONNECT": "Establishing a connection to database...", "DB_CONNECTED": "Server is successfully connected to the database.", "DB_CONNECTION_ERROR": "Connection to database could not be established.", "DB_OPERATION_ERROR": "Something went wrong with the database, try again later.", "CLIENT_DB_CONNECT": "Checking if database is up and running...", "CLIENT_DB_CONNECTED": "Everything is ready!", "DB_UPDATE_QUERY_SUCCESS": "Database record updated successfully.", "DB_UPDATE_QUERY_FAIL": "Database record could not be updated.", "AVATAR_UPDATED": "User requested to change the avatar, file overwrite successfully." } if print_msg: print(msg_dict[key]) return msg_dict[key]
def sanitize(string, safechars): """Sanitize the string according to the characters in `safe`.""" # First, get the function's cache dict. try: safecache = sanitize.safecache except AttributeError: safecache = sanitize.safecache = {} # Next, fetch or set a dict version of the safe string. safehash = safecache.get(safechars) if safehash is None: safehash = safecache[safechars] = {} for char in safechars: safehash[char.lower()] = 1 # Finally, sanitize the string. reslist = [] for char in string: lower = char.lower() if safehash.get(lower, 0): reslist.append(char) return ''.join(reslist)
def ts_grismc_sim(pixels): """ Simple analytic wavelength calibration for Simulated GRISMC data """ disp = 0.0010035 ## microns per pixel (toward positive X in raw detector pixels, used in pynrc) undevWav = 4.0 ## undeviated wavelength undevPx = 1638.33 wavelengths = (pixels - undevPx) * disp + undevWav return wavelengths
def euclidean_gcd_recursive(first, second): """ Calculates GCD of two numbers using the recursive Euclidean Algorithm :param first: First number :param second: Second number """ if not second: return first return euclidean_gcd_recursive(second, first % second)
def params(kernels, time, target, target_frame, observer, lat, lon, corr): """Input parameters from WGC API example.""" return { 'kernels': kernels, 'times': time, 'target': target, 'target_frame': target_frame, 'observer': observer, 'latitude': lat, 'longitude': lon, 'aberration_correction': corr, }
def _read_mtl_band_filenames(mtl_): """ Read the list of bands from an mtl dictionary. :type mtl_: dict of (str, obj) :rtype: dict of (str, str) >>> sorted(_read_mtl_band_filenames({'PRODUCT_METADATA': { ... 'file_name_band_9': "LC81010782014285LGN00_B9.TIF", ... 'file_name_band_11': "LC81010782014285LGN00_B11.TIF", ... 'file_name_band_quality': "LC81010782014285LGN00_BQA.TIF" ... }}).items()) [('11', 'LC81010782014285LGN00_B11.TIF'), ('9', 'LC81010782014285LGN00_B9.TIF'), ('quality', \ 'LC81010782014285LGN00_BQA.TIF')] >>> _read_mtl_band_filenames({'PRODUCT_METADATA': { ... 'file_name_band_9': "LC81010782014285LGN00_B9.TIF", ... 'corner_ul_lat_product': -24.98805, ... }}) {'9': 'LC81010782014285LGN00_B9.TIF'} >>> _read_mtl_band_filenames({'PRODUCT_METADATA': { ... 'file_name_band_6_vcid_1': "LE71140732005007ASA00_B6_VCID_1.TIF" ... }}) {'6_vcid_1': 'LE71140732005007ASA00_B6_VCID_1.TIF'} """ product_md = mtl_['PRODUCT_METADATA'] return dict([(k.split('band_')[-1], v) for (k, v) in product_md.items() if k.startswith('file_name_band_')])
def concat_tas_dict(tas_dict): """ Given a dictionary, create a concatenated TAS string. Arguments: tas_dict: dictionary representing the object with the TAS attributes Returns: concatenated TAS string of the current model """ tas1 = tas_dict['allocation_transfer_agency'] tas1 = tas1 if tas1 else '000' tas2 = tas_dict['agency_identifier'] tas2 = tas2 if tas2 else '000' tas3 = tas_dict['beginning_period_of_availa'] tas3 = tas3 if tas3 else '0000' tas4 = tas_dict['ending_period_of_availabil'] tas4 = tas4 if tas4 else '0000' tas5 = tas_dict['availability_type_code'] tas5 = tas5 if tas5 else ' ' tas6 = tas_dict['main_account_code'] tas6 = tas6 if tas6 else '0000' tas7 = tas_dict['sub_account_code'] tas7 = tas7 if tas7 else '000' tas = '{}{}{}{}{}{}{}'.format(tas1, tas2, tas3, tas4, tas5, tas6, tas7) return tas
def __ExtractBasePath(target): """Extracts the path components of the specified gyp target path.""" last_index = target.rfind('/') if last_index == -1: return '' return target[0:(last_index + 1)]
def is_appraisal(dictx): """ function to check if the application is Appraisal. """ for key in dictx.keys(): if 'appraisal' in key: return True return False
def del_nz_positions(prof1, prof2): """Set positions that are non-zero in both profiles to zero. A new profile is returned.""" prof1_len = len(prof1) assert prof1_len == len(prof2), "Activity Profiles must have the same length to be compared." result = [] for idx in range(prof1_len): if prof1[idx] != 0.0 and prof2[idx] != 0.0: result.append(0.0) else: result.append(prof1[idx]) return result
def reverse_complement(seq): """ Given a sequence it returns its reverse complementary """ alt_map = {'ins':'0'} complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} for k,v in alt_map.items(): seq = seq.replace(k,v) bases = list(seq) bases = reversed([complement.get(base,base) for base in bases]) bases = ''.join(bases) for k,v in alt_map.items(): bases = bases.replace(v,k) return bases
def get_consonants(text_string): """Given a string, return a list of unique consonants within that string""" found_consonants = [] if text_string: consonants = "bcdfghjklmnpqrstvwxyz" for char in text_string.lower(): if char in consonants: found_consonants.append(char) #remove duplicates return list(set(found_consonants))
def _index(key, sequence, testfn=None, keyfn=None): """Return the index of key within sequence, using testfn for comparison and transforming items of sequence by keyfn first. >>> _index('e', 'hello') 1 >>> _index('E', 'hello', testfn=_equalsIgnoreCase) 1 >>> _index('x', 'hello') """ index = 0 for element in sequence: value = element if keyfn: value = keyfn(value) if (not testfn and value == key) or (testfn and testfn(value, key)): return index index += 1 return None
def setNoneList(values): """ :param list/None values: :return list """ if values is None: return [] else: return values
def build_groups(mut_list, base_mut=None, out_list=None): """ Recursively propagates a binary tree of muts :param list base_mut: The base for the mutation :param list mut_list: The remaining mutations to add to the tree :param list out_list: The list to append values to :return: a list of lists containing all the possible mutations >>> build_groups(['a', 'b']) [('a', 'b'), ('a',), ('b',)] >>> build_groups(['a'], ['b']) [('b', 'a'), ('b',)] """ # Since we can't make mutables the default parameters if base_mut is None: base_mut = [] if out_list is None: out_list = [] if not mut_list: # base case if base_mut: out_list.append(tuple(base_mut)) return None else: new_base = [mut_list[0]] build_groups(mut_list[1:], base_mut + new_base, out_list) build_groups(mut_list[1:], base_mut, out_list) return out_list
def list_to_dict(l): """ Convert python list to python dictionary :param l: python type list >>> list = ["key1", 1, "key2", 2, "key3", 3] >>> list_to_dict(list) == {'key1': 1, 'key2': 2, 'key3': 3} True """ if l is None: return None return dict(zip(l[0::2], l[1::2]))
def link_generator(start: int, end: int, page: int) -> str: """ Generates links with appropriate query parameters. --- Args: start (int): start year of the query end (int): end year of the query page (int): page number Returns: link (str): final link for scrape requests """ link = f"https://www.1000plus.am/hy/compensation?full_name=&status=all&date_from={start}-01-01&date_to={end}-01-01&page={page}" return link
def bb_to_plt_plot(x, y, w, h): """ Converts a bounding box to parameters for a plt.plot([..], [..]) for actual plotting with pyplot """ X = [x, x, x+w, x+w, x] Y = [y, y+h, y+h, y, y] return X, Y
def unwrap_process_input_tuple(tup: tuple): """ Helper function that unwraps a tuple to its components and creates a unique key for the column combination Parameters --------- tup : tuple the tuple to unwrap """ names, quantile, intersection, tmp_folder_path = tup name_i, name_j = names k = (name_i, name_j) return name_i, name_j, k, quantile, intersection, tmp_folder_path
def digital_root(n: int) -> int: """ In this kata, you must create a digital root function. A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. :param n: :return: """ if len(str(n)) == 1: return n else: temp = 0 n_str = str(n) for char in n_str: temp += int(char) return digital_root(temp)