content
stringlengths
42
6.51k
def fake_download(server): """Mock out download from server, such that connect works offline""" return "Test Stub", []
def read_markdown(raw_md): """ Reads the raw MarkDown and return the table and callback strings """ read_table = False read_callback = False data = [] data_callback = [] for line in raw_md.split(b'\n'): line = line.decode('UTF-8') if line == '| Option | Data-Attr | Defaults | Type | Description |': read_table = True if read_table: data.append([col.strip().strip('`') for col in line.split('|') if col]) if line == '## Description of data passed to callbacks (onChange and etc.)': read_table=False if line == '## Description of data passed to callbacks (onChange and etc.)': read_callback = True if read_callback: data_callback.append(line) if line == '## Creating slider (all params)': read_callback = False data = [row for row in data[:-1] if row] data_callback = [row for row in data_callback[4:-4] if row] return data, data_callback
def is_valid(point_x, point_y, grid, width, height): """see if a point is valid""" if not grid[int(point_y)][int(point_x)]: return False if point_y < 0 or point_x < 0: return False if point_y > height or point_x > width: return False return True
def undo_move(board, col, piece): """removes the topmost piece from that column(undoing move)""" for row in range(6): if board[row][col] == piece: board[row][col] = " " break return board
def _urljoin(*args): """ Joins given arguments into a url. Both trailing and leading slashes are stripped before joining. """ return "/".join(map(lambda x: str(x).strip("/"), args)) + "/"
def cm2inch(*values): """Convert from centimeter to inch Parameters ---------- *values Returns ------- tuple Examples -------- >>> cm2inch(2.54, 5.08) (1.0, 2.0) """ return tuple(v / 2.54 for v in values)
def _evaluate_features(features_name: list, features_index: list, config_features_available: bool): """ This ensures that (1) if feature names are provided in the config file, one and only one of the arguments, `features_name` or `features_index`, might be given, and (2) if feature names are NOT provided in the config file, one and only one of the arguments MUST be given. :param features_name: See the same argument in `do_extraction`. :param features_index: See the same argument in `do_extraction`. :param config_features_available: `True` if the key `STATISTICAL_FEATURES` in the config file, is associated with a list of features, and `False` otherwise. :return: True, if no exception was raised. """ if features_index is None: features_index = [] if features_name is None: features_name = [] given_by_list, given_by_index = False, False if len(features_name) > 0: given_by_list = True if len(features_index) > 0: given_by_index = True if not config_features_available: # if features in config file are not provided if given_by_list and not given_by_index: return True else: # if (1) both args are given, or (2) if none of them are provided, or (3) if # params_index is given raise ValueError( """ If a list of feature names is not provided by the config file, the arg `features_name` and only that MUST be given. """ ) else: if given_by_list + given_by_index > 1: # if both args are provided raise ValueError( """ Both of the arguments, `features_name` and `features_index`, cannot be given at the same time. """ ) return True
def assure_list(s): """Given not a list, would place it into a list. If None - empty list is returned Parameters ---------- s: list or anything """ if isinstance(s, list): return s elif s is None: return [] else: return [s]
def emoji_remove_underscope(text: str) -> str: """cleans text from underscops in emoji expressions and <> in annotations""" tokens = [] for token in text.split(): if len(token) > 3 and '_' in token: token = token.replace('_', ' ') if token[0] == '<' and token[-1] == '>': token = token[1:-1] tokens.append(token) return ' '.join(tokens)
def capitalize_or_join_words(sentence): """ If the given sentence starts with *, capitalizes the first and last letters of each word in the sentence, and returns the sentence without *. Else, joins all the words in the given sentence, separating them with a comma, and returns the result. For example: - If we call capitalize_or_join_words("*i love python"), we'll get "I LovE PythoN" in return. - If we call capitalize_or_join_words("i love python"), we'll get "i,love,python" in return. - If we call capitalize_or_join_words("i love python "), we'll get "i,love,python" in return. Hint(s): - The startswith() function checks whether a string starts with a particualr character - The capitalize() function capitalizes the first letter of a string - The upper() function converts all lowercase characters in a string to uppercase - The join() function creates a single string from a list of multiple strings """ # your code here if sentence.startswith("*"): sentence = result = sentence.title() result = "" for word in sentence.split(): result += word[:-1] + word[-1].upper()+ " " k = result[:-1] l = k.strip("*") m=''.join(l) return m else: s = ','.join(sentence.split()) return s
def valid_statement(source): """ Is source a valid statement? >>> valid_statement('x = 1') True >>> valid_statement('x = print foo') False """ try: compile(source, '', 'single') return True except SyntaxError: return False
def applyRule(x): """ x: an int output: an int after applying the rule """ if x % 2 is 0: # x is even return int(x/2) return int(3*x+1)
def user_pub(users): """User jbenito (restricted/restricted).""" return users["pub"]
def wraparound_calc(length, gran, minLen): """ HELPER FUNCTION Computes the number of times to repeat a waveform based on generator granularity requirements. Args: length (int): Length of waveform gran (int): Granularity of waveform, determined by signal generator class minLen: Minimum wfm length, determined by signal generator class Returns: (int) Number of repeats required to satisfy gran and minLen requirements """ repeats = 1 temp = length while temp % gran != 0 or temp < minLen: temp += length repeats += 1 if repeats > 1: print(f"Information: Waveform repeated {repeats} times.") return repeats
def calculate_from_string(math_string): """Solve equation from string, using "calculate_mathematical_expression" function""" divided_str = math_string.split(" ") num1 = float(divided_str[0]) num2 = float(divided_str[2]) sgn = divided_str[1] if sgn == "+": return num1 + num2 elif sgn == "-": return num1 - num2 elif sgn == "/": if num2 != 0: return num1 / num2 else: return None elif sgn == "*": return num1 * num2 else: return None
def _is_hex(content): """ Make sure this is actually a valid hex string. :param content: :return: """ hex_digits = '0123456789ABCDEFabcdef' for char in content: if char not in hex_digits: return False return True
def decode_bytes(data): """ Helper function to decode bytes into string, I think it ends up being called per character """ lines = "" try: lines = data.decode("ascii") except UnicodeDecodeError as e: try: lines = data.decode("utf-8") # last option: try to decode as cp1252 except UnicodeDecodeError as e: lines = data.decode("cp1252") return lines
def get_valid_post_response(data): """ Returns success message correct processing of post/get request :param str data: message :return: response :rtype: object """ response = {"status": 201, "message": "Created", "data": data} return response
def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest common subsequence between the two strings Note: my_lcs only gives length of the longest common subsequence, not the actual LCS """ if (len(string) < len(sub)): sub, string = string, sub lengths = [[0 for _ in range(0, len(sub) + 1)] for _ in range(0, len(string) + 1)] for j in range(1, len(sub) + 1): for i in range(1, len(string) + 1): if string[i - 1] == sub[j - 1]: lengths[i][j] = lengths[i - 1][j - 1] + 1 else: lengths[i][j] = max(lengths[i - 1][j], lengths[i][j - 1]) return lengths[len(string)][len(sub)]
def makescalar(origlist): """Recursive function to make all elements of nested lists into floats. To accommodate array inputs, all the functions here first broadcast to numpy arrays, generating nested lists of arrays. When the inputs are floats, these 0-d arrays should be cast back into floats. This function acts recursively on nested lists to do this. Arguments: origlist (list): List of elements to be converted. Elements are either numpy arrays or another list. These lists are modified in-place. Returns None. """ for (i, elem) in enumerate(origlist): if isinstance(elem, list): makescalar(origlist[i]) else: origlist[i] = float(elem) return None
def removeMacColons(macAddress): """ Removes colon character from Mac Address """ return macAddress.replace(':', '')
def parse_apg_url(apg_url): """Return the method, url and browser from an apg_url.""" method = apg_url.split("/apg/")[1].split("/?url=")[0] url = apg_url.split("/?url=")[1].split("&browser")[0] try: browser = apg_url.split("&browser=")[1].split("&")[0] except IndexError: browser = None return method, url, browser
def insert_ordered(value, array): """ This will insert the value into the array, keeping it sorted, and returning the index where it was inserted """ index = 0 # search for the last array item that value is larger than for n in range(0,len(array)): if value >= array[n]: index = n+1 array.insert(index, value) return index
def rivers_with_station(stations): """Given list of stations (MonitoringStation object), return the names of the rivers that are being monitored""" # Collect all the names of the rivers in a set to avoid duplicate entries rivers = {station.river for station in stations} # Return a list for convenience return list(rivers)
def translate_rich_to_termcolor(*colors) -> tuple: """ Translate between rich and more_termcolor terminology. This is probably prone to breaking. """ _colors = [] for c in colors: _c_list = [] ### handle 'bright' c = c.replace('bright_', 'bright ') ### handle 'on' if ' on ' in c: _on = c.split(' on ') _colors.append(_on[0]) for _c in _on[1:]: _c_list.append('on ' + _c) else: _c_list += [c] _colors += _c_list return tuple(_colors)
def sort_data_by_cloud(data): """ sort_data_by_cloud data: list of dictionaries one dictionary per PanDA schedresource (computingsite) keys: cloud computingsite and a bunch of other keys by job status, see STATELIST returns: input data sorted by cloud, computingsite """ res = sorted(data, key=lambda x: (str(x['cloud']).lower(), \ str(x['computingsite']).lower())) return res
def _format_input_label(input_label): """ Formats the input label into a valid configuration. """ return { 'name': input_label['name'], 'color': (input_label['color'][1:] if input_label['color'].startswith('#') else input_label['color']), 'description': input_label['description'] if 'description' in input_label else '' }
def rhonfw(re,alpha): """ NAME: rhonfw PURPOSE: Calculate the ratio of the NFW and soliton sections. USAGE: x = rhonfw(re,alpha) ARGUMENTS: alpha is a positive parameter, re is the transition radius. RETURNS: The value of the ratio of the sections. WRITTEN: Antonio Herrera Martin, U of Glasgow, 2017 """ return alpha*re*(1.+alpha*re)**2/(1.+re**2)**8;
def get_ip_prefix_from_adapters(local_ip, adapters): """Find the network prefix for an adapter.""" for adapter in adapters: for ip_cfg in adapter.ips: if local_ip == ip_cfg.ip: return ip_cfg.network_prefix
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ if type(input_list)!=list: return "Inappropriate input type" next0,next2 = 0, len(input_list)-1 # helper indices, init: next 0 at the beginning, next 2 at the end i = 0 # index, used for A SINGLE TRAVERSAL # O(n) AND A SINGLE LIST TRAVERSAL while i <= next2: if input_list[i] == 0: # if at current index we have 0, then... input_list[i]=input_list[next0] # at current index store the value that is replacing 0 input_list[next0]=0 # place 0 at the next 0'th position next0+=1 # and increment both counters i+=1 elif input_list[i] == 2: input_list[i]=input_list[next2] input_list[next2] = 2 next2-=1 else: # we have 1, so leave it, as sorting only 0s and 2s, will place 1s in place i+=1 return input_list
def get_numeric_log_level(log_level): """Return a number that will calculate to the verbosity level""" if log_level.lower() == "debug": return 4 elif log_level.lower() == "info": return 3 elif log_level.lower() == "warning": return 2 elif log_level.lower() == "error": return 1 elif log_level.lower() == "critical": return 0 else: return 2
def get_data_view_status(data_view_id): """ URL for retrieving the statuses of all services associated with a data view. :param data_view_id: The ID of the desired data views :type data_view_id: str """ return "data_views/{}/status".format(data_view_id)
def my_location(state): """ Get the location of the current player. :param state: The current game state. :returns: tuple (x, y) """ return state['gladiators'][state['current_player']]['pos']
def bbox_hflip(bbox, rows, cols): """Flip a bounding box horizontally around the y-axis.""" x_min, y_min, x_max, y_max = bbox return [1 - x_max, y_min, 1 - x_min, y_max]
def predict_score(predicts, actuals): """ Find the number of correct cell predictions. :param predicts: a list of predictions. :param actuals: a list of actual cells. :return: # correct predictions, # cells """ len_preds = len(predicts) len_actuals = len(actuals) shorter_len = min(len_preds, len_actuals) gap_predict = 0 gap_actual = 0 num_correct = 0 # print (shorter_len) for i in range(shorter_len): # print (i) # print (gap_predict) # print (gap_actual) # print () if predicts[i + gap_predict] == actuals[i + gap_actual]: num_correct += 1 else: if len_preds < len_actuals: gap_actual += 1 len_preds += 1 elif len_preds > len_actuals: gap_predict += 1 len_actuals += 1 return num_correct, len(actuals)
def mean(container): """Averages all elements in container Args: container: a container of sum()able elements Returns: The mean value of all elements """ return sum(container)/len(container)
def fibonacci(number): """ Returns True if number is fibonacci """ if number == 1: return True f1 = 1 f2 = 2 while f2 < number: f3 = f1 + f2 f1 = f2 f2 = f3 return f2 == number
def spCheck(diffs, sp_buf): """Quick function to check if events land within the spatial window.""" checks = [e for e in diffs if abs(e) < sp_buf] if any(checks): check = True else: check = False return check
def indent(level) : """Return indentation string for specified level""" x = "" for i in range(0, level) : x += " " # FIXME : make this stuff faster return x
def _remove_device_types(name, device_types): """Strip device types from a string. August stores the name as Master Bed Lock or Master Bed Door. We can come up with a reasonable suggestion by removing the supported device types from the string. """ lower_name = name.lower() for device_type in device_types: device_type_with_space = f" {device_type}" if lower_name.endswith(device_type_with_space): lower_name = lower_name[: -len(device_type_with_space)] return name[: len(lower_name)]
def validate_gateway_response_type(response_type): """ Validate response type :param response_type: The GatewayResponse response type :return: The provided value if valid """ valid_response_types = [ "ACCESS_DENIED", "API_CONFIGURATION_ERROR", "AUTHORIZER_FAILURE", "AUTHORIZER_CONFIGURATION_ERROR", "BAD_REQUEST_PARAMETERS", "BAD_REQUEST_BODY", "DEFAULT_4XX", "DEFAULT_5XX", "EXPIRED_TOKEN", "INVALID_SIGNATURE", "INTEGRATION_FAILURE", "INTEGRATION_TIMEOUT", "INVALID_API_KEY", "MISSING_AUTHENTICATION_TOKEN", "QUOTA_EXCEEDED", "REQUEST_TOO_LARGE", "RESOURCE_NOT_FOUND", "THROTTLED", "UNAUTHORIZED", "UNSUPPORTED_MEDIA_TYPES" ] if response_type not in valid_response_types: raise ValueError( "{} is not a valid ResponseType".format(response_type) ) return response_type
def get_comp_pairs(mut_ids): """Get pairs of compensated IDs.""" ans = [] if len(mut_ids) == 2: pair = (mut_ids[0], mut_ids[1]) ans.append(pair) else: pair_1 = (mut_ids[0], mut_ids[1]) pair_2 = (mut_ids[1], mut_ids[2]) ans.append(pair_1) ans.append(pair_2) return ans
def f90str(s): """Convert string repr of Fortran string to Python string.""" assert type(s) == str f90quotes = ["'", '"'] if s[0] in f90quotes and s[-1] in f90quotes: return s[1:-1] raise ValueError
def segregate(str): """3.1 Basic code point segregation""" base = bytearray() extended = set() for c in str: if ord(c) < 128: base.append(ord(c)) else: extended.add(c) extended = sorted(extended) return bytes(base), extended
def find( s, target, i=0 ): """Version fo find which returns len( s ) if target is not found""" result = s.find( target, i ) if result == -1: result = len( s ) return result
def swap(s): """Swaps ``s`` according to GSM 23.040""" what = s[:] for n in range(1, len(what), 2): what[n - 1], what[n] = what[n], what[n - 1] return what
def not_roca(version): """ROCA affected""" return not ((4, 2, 0) <= version < (4, 3, 5))
def getBetween(myString, startChunk, endChunk): """ returns a string between two given chunks. @param myString @param startChunk: substring that bounds the result string from left @param startChunk: substring that bounds the result string from right >>> getBetween('teststring', 'st','in') 'str' >>> getBetween('teststring', 'st','te') '' >>> getBetween('teststring', 'te','te') '' """ p1 = myString.find(startChunk) if p1 < 0: return '' else: p2 = myString.find(endChunk, p1 + len(startChunk)) if p2 < 0: return '' else: return myString[p1 + len(startChunk):p2]
def parabolic(a, x): """ Parabolic fit function. :param a: Coefficients array of length 3 :param x: free parameter :return: float """ return a[0] + a[1] * x + a[2] * x ** 2
def D_c_to_D_a(D_c, redshift): """calculate the angular diameter distance (D_a) from comoving distance (D_c) and redshift ( redshift)""" return D_c/(1 + redshift)
def padNumber(number, pad): """pads a number with zeros """ return ("%0" + str(pad) + "d") % number
def read_dficts_coords_to_details(dficts, dficts_details, calib=False): """ Parsable details: 1. read test coords to get test details: 1.1 measurement volume: z min, z max 1.2 # of particles: p_num :param dficts: :param dficts_details: :return: """ for name, df in dficts.items(): if calib: zmin = df.z.min() zmax = df.z.max() else: zmin = df.z_true.min() zmax = df.z_true.max() meas_vol = zmax - zmin p_num = len(df.id.unique()) # update dictionary dficts_details[name].update({ 'zmin': zmin, 'zmax': zmax, 'meas_vol': meas_vol, 'p_num': p_num }) return dficts_details
def hmean(a, b): """Return the harmonic mean of two numbers.""" return float(2*a*b) / (a + b) # return harmonic_mean([a, b])
def _get_output_filename(dataset_dir, split_name): """Creates the output filename. Args: dataset_dir: The directory where the temporary files are stored. split_name: The name of the train/test split. Returns: An absolute file path. """ return '%s/mnist_artificial_%s.tfrecord' % (dataset_dir, split_name)
def limit_length(s, length): """ Add ellipses to overly long strings """ if s is None: return None ELLIPSES = '...' if len(s) > length: return s[:length - len(ELLIPSES)] + ELLIPSES return s
def num_from_str(string, base=0): """ Accept a string. Return as an integer if possible, else as a float, else raise. """ try: return int(string, base=base) except ValueError: return float(string)
def find_index(segmentation, stroke_id): """ >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 0) 0 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 1) 0 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 5) 2 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 6) 2 """ for i, symbol in enumerate(segmentation): for sid in symbol: if sid == stroke_id: return i return -1
def argmin_list(seq, func): """ Return a list of elements of seq[i] with the lowest func(seq[i]) scores. >>> argmin_list(['one', 'to', 'three', 'or'], len) ['to', 'or'] """ best_score, best = func(seq[0]), [] for x in seq: x_score = func(x) if x_score < best_score: best, best_score = [x], x_score elif x_score == best_score: best.append(x) return best
def build_repository(pharses): """ Build the bible repository as a dict from identifier to context Jhn 3:10 --> text in John chapter 3 pharse 10 """ repository = {} for pharse in pharses: book, _, other = pharse.partition(' ') locator, _, context = other.partition(' ') repository[' '.join([book, locator])] = context return repository
def datetime64_(name="date", format="%Y-%m-%d"): """Return a date category with format""" return "datetime64(" + name + "," + format + ")"
def nested_map(x, f): """Map the function f to the nested structure x (dicts, tuples, lists).""" if isinstance(x, list): return [nested_map(y, f) for y in x] if isinstance(x, tuple): return tuple([nested_map(y, f) for y in x]) if isinstance(x, dict): return {k: nested_map(x[k], f) for k in x} return f(x)
def deserialize_utf8(value, partition_key): """A deserializer accepting bytes arguments and returning utf-8 strings Can be used as `pykafka.simpleconsumer.SimpleConsumer(deserializer=deserialize_utf8)`, or similarly in other consumer classes """ # allow UnicodeError to be raised here if the decoding fails if value is not None: value = value.decode('utf-8') if partition_key is not None: partition_key = partition_key.decode('utf-8') return value, partition_key
def common_neighbors(set_one: list, set_two: list) -> int: """ Calculate Common neighbors score for input lists :param set_one: A list of graph nodes -> part one :param set_two: A list of graph nodes -> part two :return: Common neighbours score """ return len(set(set_one) & set(set_two))
def isSuffixOf(xs, ys): """ isSuffixOf :: Eq a => [a] -> [a] -> Bool The isSuffixOf function takes two lists and returns True iff the first list is a suffix of the second. The second list must be finite. """ return xs == ys[-len(xs):]
def step(nodes, outputs, edges): """Return updated state in the form of a collection of nodes, a collection of outputs, and a collection of edges, given a collection of nodes, a collection of outputs, and a collection of edges. A node only propagates values if it has two values. Parameters ---------- nodes : dict each key is a node name each value is a 2-tuple containing up to two values flowing through the node outputs : dict each key is an output name each value is the tuple of values at that output name edges : dict each key is a node name each value is a 2-tuple of 2-tuples: ((low_dictionary, low_node_name), (high_dictionary, high_node_name)) the low dictionary and low node name pair denotes where the low value in the node named in the key goes, while the high dictionary and high node name specify where the high value goes Returns ------- nodes : dict nodes, transformed by propagated flows outputs : dict outputs, transformed by propagated flows edges : dict edges passed into the function """ flowed = [] for node_name in nodes.copy(): if node_name in flowed: continue if len(nodes[node_name]) == 2: if node_name in flowed: continue node = [int(value) for value in nodes[node_name]] low_value, high_value = min(node), max(node) low_flow, high_flow = edges[node_name] low_dictionary, low_node_name = low_flow high_dictionary, high_node_name = high_flow low_node = low_dictionary.get(low_node_name, tuple()) high_node = high_dictionary.get(high_node_name, tuple()) low_dictionary[low_node_name] = low_node + (str(low_value),) high_dictionary[high_node_name] = high_node + (str(high_value),) nodes[node_name] = tuple() if low_dictionary is nodes: flowed.append(low_node_name) if high_dictionary is nodes: flowed.append(high_node_name) return nodes, outputs, edges
def dict_repr(obj): """ Creates an unambiguous and consistent representation of a dictionary. Args: obj: The dictionary to produce the representation of Returns: The string representation """ result = '{' for key in sorted(obj): elem = obj[key] if isinstance(elem, dict): result += repr(key) + ': ' + dict_repr(elem) + ', ' else: result += repr(key) + ': ' + repr(elem) + ', ' if result.endswith(', '): result = result[0:-2] result += '}' return result
def add(curvelist): """ Add one or more curves. >>> curves = pydvif.read('testData.txt') >>> c = pydvif.add(curves) :param curvelist: The list of curves :type curvelist: list :returns: curve -- the curve containing the sum of the curves in curvelist """ numcurves = len(curvelist) if numcurves > 1: name = curvelist[0].name sendline = 'curvelist[' + str(0) + ']' for i in range(1, numcurves): name += ' + ' + curvelist[i].name sendline += '+ curvelist[' + str(i) + ']' c = eval(sendline) c.name = name if c.x is None or len(c.x) < 2: print('Error: curve overlap is insufficient') return 0 return c elif numcurves == 1: return curvelist[0] else: return curvelist
def build_ex(config, functions): """Additional BIOS build function :param config: The environment variables to be used in the build process :type config: Dictionary :param functions: A dictionary of function pointers :type functions: Dictionary :returns: config dictionary :rtype: Dictionary """ print("build_ex") return None
def convert_str_to_int(str_list, keys): # converts labels from string to intege """"converts string to integer per appliance dictionary""" list_int = [] for i in str_list: list_int.append(keys[i]) return list_int
def get_sample(partition, index): """retrieve the sample name """ # para partition: which partition, train/dev/test # para index: the index of sample if index < 0: print("\nINCORRECT INDEX INPUT") return sample_name = '' if partition == 'train': if index > 104: print("\nSAMPLE NOT EXIST") else: sample_name = 'train_' + str(index).zfill(3) elif partition == 'dev': if index > 60: print("\nSAMPLE NOT EXIST") else: sample_name = 'dev_' + str(index).zfill(3) elif partition == 'test': if index > 54: print("\nSAMPLE NOT EXIST") else: sample_name = 'test_' + str(index).zfill(3) else: print("\nINCORRECT PARTITION INPUT") return sample_name
def comb(n, k, combs={}): """Combination nCk with memo.""" if k > n - k: k = n - k if k == 0: return 1 if k == 1: return n if (n, k) in combs: return combs[n, k] num = den = 1 for i in range(k): num *= n - i den *= i + 1 res = num // den combs[n, k] = res return res
def pending_order(order_list, period): """Return the order that arrives in actual period""" indices = [i for i, order in enumerate(order_list) if order.sent] sum = 0 for i in indices: if period - (i + order_list[i].lead_time + 1) == 0: sum += order_list[i].quantity return sum
def _prefix(str): """Prefixes a string with an underscore. Args: str (str): The string to prefix. Returns: str: The prefixed string. """ return str if str.startswith("_") else "_%s" % str
def word_for_char(X, character): """ Diagnostic function, collect the words where a character appears :param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :param character: :return: >>> word_for_char( [['the', 'quick', 'brown'],['how', 'now', 'cow']], 'n') ['brown', 'now'] """ return [word for sentence in X for word in sentence if character in word]
def distinct(collection: list) -> int: """ Checks for the distinct values in a collection and returns the count Performs operation in nO(nlogn) time :param collection: Collection of values :returns number of distinct values in the collection """ length = len(collection) if length == 0: return 0 # performs operation in O(nlogn) collection.sort() result = 1 for x in range(1, length): if collection[x - 1] != collection[x]: result += 1 return result
def lib_utils_oo_list_to_dict(lst, separator='='): """ This converts a list of ["k=v"] to a dictionary {k: v}. """ kvs = [i.split(separator) for i in lst] return {k: v for k, v in kvs}
def _get_port_to_string(iface): """Simple helper which allows to get string representation for interface. Args: iface(list): Which IXIA interface to use for packet sending (list in format [chassis_id, card_id, port_id]) Returns: str: string in format "chassis_id/card_id/port_id" """ return "/".join(map(str, iface))
def is_number(text): """ Checking if the text is a number :param text: text we want to examine :type text: str :return: whether this is a number or not :rtype: bool """ try: float(text.strip()) except ValueError: return False return True
def netstring_from_buffer(buff): """ Reads a netstring from a buffer, returning a pair containing the content of the netstring, and all unread data in the buffer. Note that this assumes that the buffer starts with a netstring - if it does not, then this function returns ``(b'', buff)``. >>> netstring_from_buffer(b'0:,') (b'', b'') >>> netstring_from_buffer(b'5:hello,') (b'hello', b'') >>> netstring_from_buffer(b'5:hello,this is some junk') (b'hello', b'this is some junk') >>> netstring_from_buffer(b'11:with a nul\\x00,junk') (b'with a nul\\x00', b'junk') >>> netstring_from_buffer(b'5:hello no comma') (b'', b'5:hello no comma') >>> netstring_from_buffer(b'x:malformed length') (b'', b'x:malformed length') >>> netstring_from_buffer(b'500:wrong size,') (b'', b'500:wrong size,') >>> netstring_from_buffer(b'999:incomplete') (b'', b'999:incomplete') """ length = b'' colon_idx = buff.find(b':') if colon_idx == -1: return (b'', buff) else: str_size, data = buff[:colon_idx], buff[colon_idx + 1:] try: size = int(str_size) netstring = data[:size] if len(netstring) < size: # If the length specifier is wrong, then it isn't a valid # netstring return (b'', buff) if data[size] != ord(b','): # If the netstring lacks the trailing comma, then it isn't a # valid netstring return (b'', buff) # The extra 1 skips over the comma that terminates the netstring rest = data[size + 1:] return (netstring, rest) except ValueError: # If we can't parse the numerals, then it isn't a valid netstring return (b'', buff)
def _get_source_url(pypi_name, filename): """get the source url""" # example: https://files.pythonhosted.org/packages/source/u/ujson/ujson-1.2.3.tar.gz return 'https://files.pythonhosted.org/packages/source/{}/{}/{}'.format( pypi_name[0], pypi_name, filename)
def long_substr(data): """ http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python """ substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): for j in range(len(data[0]) - i + 1): if j > len(substr) and all(data[0][i:i + j] in x for x in data): substr = data[0][i:i + j] return substr
def _extract_match_id(match_json): """ Extract the match_id from json response. { "matches": [ { "id": "0000...", "match_id": 1313, "similarity": "001000" } ] } """ matches = match_json.get('matches', []) if len(matches) == 1: return matches[0].get('match_id', None) return None
def sorted_names(queue): """Sort the names in the queue in alphabetical order and return the result. :param queue: list - names in the queue. :return: list - copy of the queue in alphabetical order. """ new_queue = queue[:] new_queue.sort() return new_queue
def title(text, level=0): """Given a title, format it as a title/subtitle/etc.""" return '\n' + text + '\n' + '=-~_#%^' [level] * len(text) + '\n\n'
def price_change_color_red_green(val: str) -> str: """Add color tags to the price change cell Parameters ---------- val : str Price change cell Returns ------- str Price change cell with color tags """ val_float = float(val.split(" ")[0]) if val_float > 0: return f"[green]{val}[/green]" return f"[red]{val}[/red]"
def _no_spaces(string, replace_with='_'): """ Remove whitespace from a string, replacing chunks of whitespace with a particular character combination (replace_with, default is underscore) """ return replace_with.join(string.split())
def duplicate_check(file): """Checks the potfiles for duplicate lines/hashes""" seen = set() duplicates = 0 try: with open(file, "r") as source: line = source.readline() while line is not '': if line in seen: duplicates += 1 else: seen.add(line) line = source.readline() except FileNotFoundError: print("Potfile {} not found, could not check for duplicates".format(file)) return 0 return duplicates
def _fmt_unique_name(appname, app_uniqueid): """Format app data into a unique app name. """ return '{app}-{id:>013s}'.format( app=appname.replace('#', '-'), id=app_uniqueid, )
def translate_list_02(char_list): """Working on a list. CPU-acceleration with Numba.""" num_list = [] for word in char_list: if word == 'A': num = 1 elif word == 'B': num = 2 elif word == 'C': num = 3 elif word == 'D': num = 4 else: num = 5 num_list.append(num) return num_list
def tag_handler(tag, separator, post_html): """ This function switches from a specific {tag} to a specific markdown {separator} Example 1: <em>text</em> => *text* Example 2: <strong>text</strong> => **text** """ old_tag = tag close_tag = "</{0}>".format(tag) tag = "<{0}".format(tag) start = post_html.find(tag) end = post_html.find(close_tag) + len(close_tag) start_text = post_html.find(">", post_html.find(tag)) + 1 end_text = post_html.find(close_tag) text = post_html[start_text:end_text] new_text = "{1}{0}{1}".format(text, separator) post_html = post_html[:start] + new_text + post_html[end:] if (post_html.find(tag) >= 0): post_html = tag_handler(old_tag, separator, post_html) return post_html
def calc_tcp(gamma, td_tcd, eud): """Tumor Control Probability / Normal Tissue Complication Probability 1.0 / (1.0 + (``td_tcd`` / ``eud``) ^ (4.0 * ``gamma``)) Parameters ---------- gamma : float Gamma_50 td_tcd : float Either TD_50 or TCD_50 eud : float equivalent uniform dose Returns ------- float TCP or NTCP """ return 1.0 / (1.0 + (td_tcd / eud) ** (4.0 * gamma))
def identical_aa(x,y): """ Compare two amino acids :param x: :param y: :return: """ if x == y: return True if x == 'X' or y == 'X': return True return False
def run_program(codes, noun = None, verb = None): """ >>> run_program([1, 0, 0, 0, 99]) [2, 0, 0, 0, 99] >>> run_program([2, 3, 0, 3, 99]) [2, 3, 0, 6, 99] >>> run_program([2, 4, 4, 5, 99, 0]) [2, 4, 4, 5, 99, 9801] >>> run_program([1, 1, 1, 4, 99, 5, 6, 0, 99]) [30, 1, 1, 4, 2, 5, 6, 0, 99] """ ip = 0 prog = codes.copy() prog[1] = noun if noun != None else prog[1] prog[2] = verb if verb != None else prog[2] while prog[ip] != 99: if prog[ip] == 1: prog[prog[ip+3]] = prog[prog[ip+1]] + prog[prog[ip+2]] elif prog[ip] == 2: prog[prog[ip+3]] = prog[prog[ip+1]] * prog[prog[ip+2]] ip += 4 return prog
def mergeuniques(xs, ys): """ merge lists xs and ys. Return a sorted result """ result = [] xi = 0 yi = 0 xs.sort() # sort clause unneeded if lists already sorted (as in instructions), but added for generalising ys.sort() while True: if xi >= len(xs): # If xs list is finished, result.extend(ys[yi:]) # Add remaining items from ys return result # And we're done. if yi >= len(ys): # Same again, but swap roles result.extend(xs[xi:]) return result # Both lists still have items, copy smaller item to result. if xs[xi] < ys[yi]: result.append(xs[xi]) xi += 1 if xs[xi] == ys[yi]: # if equal, skip the identical ys[yi], so that only one is appended result.append(xs[xi]) xi += 1 yi += 1 else: result.append(ys[yi]) yi += 1
def matrix_matrix_product(A, B): """Compute the matrix-matrix product AB as a list of lists.""" m, n, p = len(A), len(B), len(B[0]) return [[sum([A[i][k] * B[k][j] for k in range(n)]) for j in range(p) ] for i in range(m) ]
def project_use_silo(project_doc): """Check if templates of project document contain `{silo}`. Args: project_doc (dict): Project document queried from database. Returns: bool: True if any project's template contain "{silo}". """ templates = project_doc["config"].get("template") or {} for template in templates.values(): if "{silo}" in template: return True return False
def normalize_float(f): """Round float errors""" if abs(f - round(f)) < .0000000000001: return round(f) return f
def day_num(x): """function returning the next compass point in the clockwise direction""" res = {"Sunday":0, "Monday":1, "Tuesday":2, "Wednesday":3, "Thursday":4, "Friday":5, "Saturday":6} ans = res.get(x, None) return ans
def teams(organization, no_teams, teams_and_members): """A fixture that returns a list of teams, which are all returned by the github.Organization.Organization.get_teams function.""" team_names = teams_and_members.keys() for name in team_names: organization.create_team(name, permission="push") return no_teams
def build_api_url(latitude: str, longitude: str) -> str: """ Build a URL to send to the API :param latitude: A string representing the latitude :param longitude: A string representing the longitude :return: A formatted URL string """ url = "https://api.open-meteo.com/v1/forecast?" url += f"latitude={latitude}" url += f"&longitude={longitude}" url += "&hourly=" # These are the parameters pulled from the API params = [ "temperature_2m", "relativehumidity_2m", "dewpoint_2m", "pressure_msl", "cloudcover", "precipitation", "weathercode" ] url += ",".join(params) return url