content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def getRuleCount( lstRules, policy_name ): """ This function return the rule count for a given policy indicated by policy_name Parameters: - IN : 1. List containing all the rules 2. Name of the policy - Out: # of rules in the policy. """ count = 0 for x in lstRules: if x.split(',')[0] == policy_name: count +=1 return count
b4956b0a5af91f1834ee4d463414df2cc02c8796
701,858
def send_format(catfact): """ Format's the catfact into a the message to send content string """ return """ Thank you for subscribing to CatFacts™ Did you know: ``` {}``` Type "UNSUBSCRIBE" to unsubscribe from future catfacts. """.format(catfact)
208605f35db4505bb0037cae23088c89e6b1475f
701,859
def effect_from_model(model, ref, ref_rc, alt, alt_rc, methods, mutation_positions, out_annotation_all_outputs, extra_args=None, **argv): """Convenience function to execute multiple effect predictions in one call # Arguments model: Keras model ref: Input sequence with the reference genotype in the mutation position ref_rc: Reverse complement of the 'ref' argument alt: Input sequence with the alternative genotype in the mutation position alt_rc: Reverse complement of the 'alt' argument methods: A list of prediction functions to be executed, e.g.: from concise.effects.ism.ism. Using the same function more often than once (even with different parameters) will overwrite the results of the previous calculation of that function. mutation_positions: Position on which the mutation was placed in the forward sequences out_annotation_all_outputs: Output labels of the model. extra_args: None or a list of the same length as 'methods'. The elements of the list are dictionaries with additional arguments that should be passed on to the respective functions in 'methods'. Arguments defined here will overwrite arguments that are passed to all methods. **argv: Additional arguments to be passed on to all methods, e.g,: out_annotation. # Returns Dictionary containing the results of the individual calculations, the keys are the names of the executed functions """ assert isinstance(methods, list) if isinstance(extra_args, list): assert(len(extra_args) == len(methods)) else: extra_args = [None] * len(methods) main_args = {"model": model, "ref": ref, "ref_rc": ref_rc, "alt": alt, "alt_rc": alt_rc, "mutation_positions": mutation_positions, "out_annotation_all_outputs": out_annotation_all_outputs} pred_results = {} for method, xargs in zip(methods, extra_args): if xargs is not None: if isinstance(xargs, dict): for k in argv: if k not in xargs: xargs[k] = argv[k] else: xargs = argv for k in main_args: xargs[k] = main_args[k] res = method(**xargs) pred_results[method.__name__] = res return pred_results
27c528da568d257d129ae219f504ecf4f23b93f2
701,860
def get_pronoun(pronoun, gender='MALE', sep='_'): """ Gets the correct gender pronoun Arguments: pronoun {str} -- HE_SHE pronoun that needs to be converted Keyword Arguments: gender {str} -- [description] (default: {'MALE'}) sep {str} -- [description] (default: {'_'}) Returns: str -- [description] """ m, f = pronoun.split(sep) if gender == 'MALE': return m else: return f
a9f3d7aa3f09af305ac110e1cc8c9ac977051d8b
701,861
def is_fill_compute_el(obj): """Object contains executable methods 'fill' and 'compute'.""" return hasattr(obj, 'fill') and hasattr(obj, 'compute') \ and callable(obj.fill) and callable(obj.compute)
18f1825947852f6dd307e0a2ab07c8d95f213151
701,862
def addstr(str1, str2): """Concatenate strings str1 & str2""" return str(str1) + str(str2)
209c932bca262a458013afcafd6899e6cf02b3b6
701,863
import difflib def get_name_similarities(name_pairs): """Get char LCS similarity for each signature pair.""" return [difflib.SequenceMatcher(None, sig1, sig2).ratio() for sig1, sig2 in name_pairs]
a124e36387d4a72968985967fde0c48dc4d3b21d
701,864
import subprocess def run_cmd(cmd_args, cwd=None, shell=False): """Runs a command and returns output as a string.""" process = subprocess.Popen( cmd_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell, cwd=cwd) output = process.communicate() if process.wait() != 0: print("Error while running the command!") print("\nOUTPUT:\n============") print(output[1].decode("utf-8")) print("============\n") raise Exception("cmd invocation FAILED: " + " ".join(cmd_args)) return output[0]
792d966bffac12aada63e5c36795cd7043ead4ec
701,865
import sys def extract_ut_args(): """Extract unittest specific arguments from sys.argv""" # -h -v -q -f -c -b # --locals # anything not starting with a - newargs = [] for i in range(1, len(sys.argv)): # must ignore progname in argv[0] arg = sys.argv[i] if arg in ["-h", "-v", "-q", "-f", "-c", "-b", "--locals"]: newargs.append(arg) elif arg[0] != "-": newargs.append(arg) for arg in newargs: if arg in sys.argv: i = sys.argv.index(arg) del sys.argv[i] newargs.insert(0, sys.argv[0]) return newargs
a899dee319466e9e91c727f00be6f7a130127c8f
701,866
def parse_predictions_dict(predictions, num_growths): """Parses predictions dictionary to remove graph generated suffixes. Args: predictions: dict, predictions dictionary directly from SavedModel inference call. num_growths: int, number of model growths contained in export. Returns: List of num_growths length of dictionaries with fixed keys and predictions. """ predictions_by_growth = [{} for _ in range(num_growths)] for k in sorted(predictions.keys()): key_split = k.split("_") if key_split[-1].isnumeric() and key_split[-2].isnumeric(): idx = 0 if num_growths == 1 else int(key_split[-2]) predictions_by_growth[idx].update( {"_".join(key_split[3:-2]): predictions[k]} ) else: idx = 0 if num_growths == 1 else int(key_split[-1]) predictions_by_growth[idx].update( {"_".join(key_split[3:-1]): predictions[k]} ) del predictions return predictions_by_growth
fbb1789cf317e7c4d0015271bf8690ea4bddf0ef
701,867
import os def create_idx_to_path(lfw_dir): """ Create a dictionary where the key is the image index and the value is the path to the image. """ labels = sorted(os.listdir(lfw_dir)) idx = 0 idx_to_path = {} for label in labels: for img in sorted(os.listdir(os.path.join(lfw_dir, label))): idx_to_path[idx] = os.path.join(lfw_dir, label, img) idx += 1 return idx_to_path
7e9e475a04c04637902103f7ba4e7cc181d8ab88
701,868
import subprocess def create_movie(name, folder): """ Creates the movie with all the images present in the given directory :param name: :param folder: :return: result of subprocess """ cmd = ["ffmpeg", "-framerate", "1", "-i", folder + "/pic%04d.png", "-c:v", "libx264", "-r", "30", "-pix_fmt", "yuv420p", name] return subprocess.call(cmd)
392f5b88d1da63ad241402e313ab8f601ebe997c
701,869
def get_word_pattern(word: str) -> str: """ Get word pattern. This pattern is useful to break substitution cipher. :param word: Word to get pattern for. :return: Word pattern. """ # There is no ordered set type in Python, but we can get that behaviour using # dict keys because since python 3.7 dict keys are guaranteed to be ordered. char_order = {} for char in word: char_order[char] = None chars_indexed = list(char_order.keys()) pattern = list(map(lambda char: chars_indexed.index(char), (char for char in word))) return ".".join(map(str, pattern))
ce81624bd3690c2037c5b570e19ba2340907a24a
701,871
def _run_op_1(task): """Test function using the function decorator.""" return task.run()
b2d3b220dcd1371f9140859b4ffe025f8231b4da
701,872
def create_df(dass_words, dfcp_words): """ this function creates a dictionary, that keeps track of each occurance of a word in a 'dass' context and 'dfcp' context it returns this dictionary """ dass = {} dfcp = {} data = [dass, dfcp] for listed_values in dass_words: # access single list for value in listed_values: # access single value if value not in data[0].keys(): # if this value is not in the dictionary data[0][value] = 0 # create a key value pair data[0][value] += 1 # and increment else: # if it already is in the dictionary data[0][value] += 1 # increment for listed_values in dfcp_words: # access single list for value in listed_values: # access sinlge value if value not in data[1].keys(): # if this value is not in the dictionary data[1][value] = 0 # create a key value pair data[1][value] += 1 # and increment else: # if it already is in the dictionary data[1][value] += 1 # increment return data
43e5715808247d726a353e7841a5dbc2aa117740
701,873
def q_in_valid_range(q): """ Asserts that q is either 1, 2 or 3. For other values, the formulas have not been implemented. """ assert 1 <= q <= 3, "Please enter q in {1,2,3}" return True
6ef79efde7376f0743bc840fe394707a8f9b213f
701,874
import hashlib def sha512_first_half(message: bytes) -> bytes: """ Returns the first 32 bytes of SHA-512 hash of message. Args: message: Bytes input to hash. Returns: The first 32 bytes of SHA-512 hash of message. """ return hashlib.sha512(message).digest()[:32]
591a0096e643af32326ae051f9a993db82a758c5
701,875
def median(arr: list): """ Returns the median and its index in the array. """ indices = [] list_size = len(arr) median = 0 if list_size % 2 == 0: indices.append(int(list_size / 2) - 1) # -1 because index starts from 0 indices.append(int(list_size / 2)) median = (arr[indices[0]] + arr[indices[1]]) / 2 else: indices.append(int(list_size / 2)) median = arr[indices[0]] return median, indices
639a6d4efbc91457520ef1411ef7b935fb477b82
701,876
import os def get_abs_path(in_path): """ Given a relative or absolute path, return the absolute path. :param in_path: :return: """ if os.path.isabs(in_path): return in_path else: return os.path.abspath(in_path)
6d732d563bef61dbde058110addc5fa91fea4a5d
701,877
def is_(a: object, b: object) -> bool: """ Return `a is b`, for _a_ and _b_. Example: >>> is_(object())(object()) False Args: a: left element of is expression b: right element of is expression Return: `True` if `a is b`, `False` otherwise """ return a is b
6edda9af046f6a45f37578c073ed0e21e3320778
701,878
import logging import os import sys def get_logger(name, path, fname): """create a logger and return """ logger = logging.getLogger(name) file_log_handler = logging.FileHandler(os.path.join(path, fname)) stderr_log_handler = logging.StreamHandler(sys.stdout) logger.addHandler(file_log_handler) logger.addHandler(stderr_log_handler) logger.setLevel("INFO") formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s","%Y-%m-%d %H:%M:%S") file_log_handler.setFormatter(formatter) stderr_log_handler.setFormatter(formatter) sys.stdout.flush() return logger
4f2b99074944b73e4d4f43620f2f0d933a845dbf
701,879
def _set_default_contact_rating(contact_rating_id: int, type_id: int) -> int: """Set the default contact rating for mechanical relays. :param contact_form_id: the current contact rating ID. :param type_id: the type ID of the relay with missing defaults. :return: _contact_rating_id :rtype: int """ if contact_rating_id > 0: return contact_rating_id return {1: 2, 2: 4, 3: 2, 4: 1, 5: 2, 6: 2}[type_id]
e39f5f9701d4314cd19109ce08c599b3737cd064
701,880
import json def _read_color_map(path, object_hook=None): """ Read a color map as json. :param path (str): The path to read the map from. :param object_hook (func): A Function to manipulate the json. :return: A dictionary of color map. """ with open(path) as f: return json.load(f, object_hook=object_hook)
34c627443cd418d84b19bd54b3e79427d8168b1e
701,881
def convertd2b(amount, x_pow, y_pow): """Apply the equation to get the result. Decimal to binary.""" res = amount * (10 ** x_pow / 2 ** y_pow) return res
8a6c7ca98a351b9a6f6c499954f7d8a533559122
701,882
def task_3_list_customers_in_germany(cur) -> list: """ List the customers in Germany Args: cur: psycopg cursor Returns: 11 records """ cur.execute("""SELECT * FROM Customers WHERE country='Germany'""") return cur.fetchall()
bf6465cc590cfe7d45817eff02e0dbaacb02e195
701,883
def find_page(pages, limit, value): """ Function to calculate and return the current page of a paginated result. :param pages: :param limit: :param value: :return: """ page_range = [limit * page for page in range(1, pages + 1)] for index, my_range in enumerate(page_range): if value <= my_range: return index + 1 return None
d1b97fb0c6c54c85b748922fb6df3d96121ea3c7
701,884
def dict_to_str(d): """Represent dictionary as string. Represents a dictionary as a string. This is useful when a representation for a filename is desired. The function will unroll all keys and join their parameters with '_', yielding a single string for the dictionary. Parameters ---------- d: Input dictionary Returns ------- String-based representation. As an example, suppose the input consists of: ``` { 'p': 2, 'd': 3 } ``` The function will then return the string `p2_d3`. """ tokens = [] for key in sorted(d.keys()): tokens.append(key + str(d[key])) return '_'.join(tokens)
4279cbc08dde9ef4e513cd562c66f63f09c866fa
701,885
def compare(guess, answer): """ Compare guess and answer Arguments: guess -- a 4-digital number string of the guess. answer -- a 4-digital number string of right answer. Returns: cow -- a number of the user guessed correctly in the correct place. bull -- a number of the user guessed correctly in the wrong place. """ cow = 0 bull = 0 for i in range(len(guess)): if guess[i] == answer[i]: cow += 1 if guess[i] in answer: bull += 1 bull = bull - cow return cow, bull
f615f4ebd555c0c4119d0fcbf9ae581146fe7816
701,886
def _get_parent_node_by_pred(node, pred, search_current=False): """Find the first parent node that satisfies a predicate function.""" if not search_current: node = node.parent while node is not None: if pred(node): return node node = node.parent return None
a69be92c468758ea1faf366c2881588e8f6fd688
701,888
import json import click def maybe_print_as_json(opts, data, page_info=None): """Maybe print data as JSON.""" if opts.output not in ("json", "pretty_json"): return False root = {"data": data} if page_info is not None and page_info.is_valid: meta = root["meta"] = {} meta["pagination"] = page_info.as_dict(num_results=len(data)) if opts.output == "pretty_json": dump = json.dumps(root, indent=4, sort_keys=True) else: dump = json.dumps(root, sort_keys=True) click.echo(dump) return True
5c84deb086001e0406dc8df9df4510ddc301e0e8
701,889
def float_like(x, /) -> bool: """ Tests if an object could be converted to a float. Args: x (Any): object to test Returns: bool: Whether the object can be converted to a float. """ try: float(x) return True except ValueError: return False
ed34d52e34bc7c09242fde6cd0890381df297325
701,890
def get_structure_numbers(structure, momenta_dict): """Return the number of the parent and children of a given structure according to some momenta dictionary. """ legs = structure.get_all_legs() children = frozenset((leg.n for leg in legs)) if structure.name() == "S": return None, children, None else: parent = momenta_dict.inv[children] is_legs = tuple( leg.n for leg in legs if leg.state == leg.INITIAL ) if not is_legs: return parent, children, None is_leg = is_legs[0] fs_children = frozenset((child for child in children if child != is_leg)) return parent, fs_children, is_leg
db9548b1e26402bb38e9c33741ca38aa866fd217
701,891
def check_bin(number, index): """ 用于某些二进制标志位的场景 返回一个 int 类型变量的某一二进制位的值,index 从 1 开始,即 >>> check_bin(2, 1) 0 >>> check_bin(2, 2) 1 """ try: return int(bin(number)[2:][-index]) except IndexError: return 0
d5c54f3121f56c028fb20e6bfcd51395cd58aa05
701,892
def parse_exclusion_file(exclusion_file, exclusion_column): """ Reads in the specified column of the specified file into a set. """ exclusion_list = set() with open(exclusion_file) as infile: for line in infile: to_exclude = line.split('\t')[exclusion_column] exclusion_list.add(to_exclude) return exclusion_list
3ae8430a96ed1883691cd63b86cd26d24c6f7652
701,893
def min_sum_space_improved(arr): """ A method that calculates the minimum difference of the sums of 2 arrays consisting of all the elements from the input array. Wrong problem description (as it talks about sets): https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0 Correct problem description: task.md time complexity: O(n*sum) space complexity: O(sum) Parameters ---------- arr : int[] a list of int values Returns ------- x : int the minimum (absolute) difference between the sums of 2 arrays consisting of all the elements from the input array """ n = len(arr) if n == 0: return 0 if n == 1: return arr[0] sum_of_all = sum(arr) matrix = [ [abs(sum_of_all - i - i) for i in range(sum_of_all+1)], [None for _ in range(sum_of_all+1)] ] for i in range(1, n): for j in range(sum_of_all, -1, -1): matrix[1][j] = matrix[0][j] if j+arr[i] <= sum_of_all: if matrix[0][j+arr[i]] <= matrix[1][j]: matrix[1][j] = matrix[0][j+arr[i]] matrix[0] = [e for e in matrix[1]] return matrix[1][0]
b8eb4f22e44d2d5104b2f4436908aa85ee07ac2d
701,894
from typing import Dict def encode_token_tx(token_tx: Dict) -> bytes: """ Creates bytes representation of token transaction data. args: token_tx: Dictionary containing the token transaction data. returns: Bytes to be saved as token value in DB. """ token_tx_str = '' token_tx_str += token_tx['tokenAddress'] + '\0' token_tx_str += token_tx['addressFrom'] + '\0' token_tx_str += token_tx['addressTo'] + '\0' token_tx_str += token_tx['value'] + '\0' token_tx_str += token_tx['transactionHash'] + '\0' token_tx_str += token_tx['timestamp'] + '\0' return token_tx_str.encode()
4100d4dacdeea4a588906151a02f9adef874aaec
701,895
def distance(strand_a, strand_b): """ Compare two strings and count the differences. :param strand_a string - String representing a strand of DNA. :param strand_b string - String representing a different strand of DNA. :return int - number of differences between 2 strands. """ if len(strand_a) != len(strand_b): raise ValueError("The Hamming distance is only defined for sequences of equal length, " " so an attempt to calculate it between sequences of different lengths should not work.") dna_compared = zip(strand_a, strand_b) num_differences = 0 for sequence in dna_compared: if sequence[0] != sequence[1]: num_differences += 1 return num_differences
012e0b1640e738b17dc6a4fb4a01c1f53e0e7639
701,896
import sys def unzscore(im_norm, zscore_median, zscore_iqr): """ Revert z-score normalization applied during preprocessing. Necessary before computing SSIM :param im_norm: Normalized image for un-zscore :param zscore_median: Image median :param zscore_iqr: Image interquartile range :return im: image at its original scale """ im = im_norm * (zscore_iqr + sys.float_info.epsilon) + zscore_median return im
aa74e5a2b8e757d569003b4a4f21675e97875a01
701,897
def values_to_rgb(ranges, values): """ Converts a three dimensional tuple to a RGB map @param ranges The mininum and maximum of each dimension @param values The value to transform """ r_color = (float(values[0]) - float(ranges[0][0])) / float(ranges[0][1]) g_color = (float(values[1]) - float(ranges[1][0])) / float(ranges[1][1]) b_color = (float(values[2]) - float(ranges[2][0])) / float(ranges[2][1]) return r_color, g_color, b_color
2dabe98b78e873e1aaff91577461e0991402ec64
701,898
def lam(m, f, w): """Compute lambda""" s = 0 for i in range(len(f)): s += f[i] * w[i] return float(m)/float(s)
6a71eb0020a5c2d86d88504f9867150c0fa7e248
701,899
import numpy def in_domain(X, a_array, c_array): """ Check is a given point is inside or outside the design domain """ flag = 1 for n in range(numpy.shape(a_array)[0]): a = a_array[n] c = c_array[n] dist = numpy.dot(X-c,a) if(dist > 0.7): flag = 0 if(abs(dist)<0.7): flag = 2 return flag
e39e779b456ea8df4f217d1c2ed5eaddf498881a
701,900
def clamp(x, inf=0, sup=1): """Clamps x in the range [inf, sup].""" return inf if x < inf else sup if x > sup else x
42c178afc0bdfc02fd31fe3f211f23cc04b40d2e
701,901
def _get_item_kind(item): """Return (kind, isunittest) for the given item.""" try: itemtype = item.kind except AttributeError: itemtype = item.__class__.__name__ if itemtype == 'DoctestItem': return 'doctest', False elif itemtype == 'Function': return 'function', False elif itemtype == 'TestCaseFunction': return 'function', True elif item.hasattr('function'): return 'function', False else: return None, False
c597db3de4447c68f3d8187e2f988e6c81e19d00
701,902
def mapattr(value, arg): """ Maps an attribute from a list into a new list. e.g. value = [{'a': 1}, {'a': 2}, {'a': 3}] arg = 'a' result = [1, 2, 3] """ if len(value) > 0: res = [getattr(o, arg) for o in value] return res else: return []
34e45bcf804d37feb5995b88534cca78679d8cfb
701,904
def _rxcheck(model_type, interval, iss_id, number_of_wind_samples): """Gives an estimate of the fraction of packets received. Ref: Vantage Serial Protocol doc, V2.1.0, released 25-Jan-05; p42""" # The formula for the expected # of packets varies with model number. if model_type == 1: _expected_packets = float(interval * 60) / ( 2.5 + (iss_id-1) / 16.0) -\ float(interval * 60) / (50.0 + (iss_id-1) * 1.25) elif model_type == 2: _expected_packets = 960.0 * interval / float(41 + iss_id - 1) else: return None _frac = number_of_wind_samples * 100.0 / _expected_packets if _frac > 100.0: _frac = 100.0 return _frac
610fa2c2aa83e6d0c9cf9c93961ba8aa6b496188
701,905
def string_in_list(str, substr_list): """Returns True if the string appears in the list.""" return any([str.find(x) >= 0 for x in substr_list])
b6e8ce2f918fec0b9a671f1c557f6f1d005c734e
701,906
import copy def build_kfold_config(params_dict, train_path, dev_path): """按k-fold拆分好的数据,构造新的json配置,用来启动训练任务 :param params_dict: 原始json配置构造出来的param_dict :param train_path: k-fold拆分之后的训练集路径,list类型 :param dev_path: k-fold拆分之后的评估集路径,list类型 :return: task_param_list: 生成新的json配置,用来启动run_with_json """ assert isinstance(train_path, list), "train_path must be list" assert isinstance(dev_path, list), "dev_path must be list" assert len(train_path) == len(dev_path), "len(train_path) must == len(dev_path)" if not params_dict.__contains__("dataset_reader"): raise ValueError("dataset_reader in json config can't be null") if not params_dict["dataset_reader"]["train_reader"]: raise ValueError("train_reader in json config can't be null") if not params_dict["dataset_reader"]["dev_reader"]: raise ValueError("dev_reader json config can't be null") task_param_list = [] for index in range(len(train_path)): one_task_param = copy.deepcopy(params_dict) one_task_param["dataset_reader"]["train_reader"]["config"]["data_path"] = train_path[index] one_task_param["dataset_reader"]["dev_reader"]["config"]["data_path"] = dev_path[index] one_task_param["dataset_reader"]["dev_reader"]["config"]["shuffle"] = False one_task_param["dataset_reader"]["dev_reader"]["config"]["epoch"] = 1 one_task_param["dataset_reader"]["dev_reader"]["config"]["sampling_rate"] = 1.0 # 1.7版本去掉这两行设置,以用户的json配置为准;http://wiki.baidu.com/pages/viewpage.action?pageId=1292167804 # one_task_param["trainer"]["is_eval_dev"] = 1 # one_task_param["trainer"]["is_eval_test"] = 0 task_param_list.append(one_task_param) return task_param_list
e13a7468a2fa3fd33219abfdf3347579a82de518
701,908
import numpy def makeMostCommonPatternHeuristic(weights): """Return a function that chooses the most common (currently most-used) pattern.""" def weightedPatternHeuristic(wave, total_wave): print(total_wave.shape) # [print(e) for e in wave] wave_sums = numpy.sum(total_wave, (1, 2)) selected_pattern = numpy.random.choice( numpy.where(wave_sums == wave_sums.min())[0] ) return selected_pattern return weightedPatternHeuristic
514bd14e6f04896165d2068a3ddaa77e778e19c5
701,909
def getTagNames(domain): """ Returns a list of tag names used by the domain. :param domain: a domain object :type domain: `escript.Domain` :return: a list of tag names used by the domain :rtype: ``list`` of ``str`` """ return [n.strip() for n in domain.showTagNames().split(",") ]
f24ccdec61eca07cef283ed4e9d981236b530c62
701,910
def matching(fingerAi, finger_i): """ Matching entre dos huellas """ it = 0 ta = 0 tb = 0 for i in range(len(fingerAi)): if fingerAi["f0"].iloc[i]==finger_i["f0"] and \ fingerAi["f1"].iloc[i]==finger_i["f1"] and \ fingerAi["utime"].iloc[i]==finger_i["utime"]: ta = fingerAi["t0"].iloc[i] tb = finger_i["t0"] return True, it, ta, tb it = it+1 return False, it, ta, tb
2ca3c16c5a9ac126314a39598719c8f7f64fa97a
701,911
import socket def is_gce_instance(): """Check if it's GCE instance via DNS lookup to metadata server""" try: socket.getaddrinfo('metadata.google.internal', 80) except socket.gaierror: return False return True
74605bca73a9a46b629212c87f154aa9a4920a1d
701,912
def get_count_value(context, fieldname): """ {% get_count_value fieldname %} """ return {"value":fieldname}
9356b602b2685341f402193c830842e656acc6cb
701,913
def rle_kyc(seq: str) -> str: """ Run-length encoding """ counts = [] count = 0 prev = '' for char in seq: # We are at the start if prev == '': prev = char count = 1 # This letter is the same as before elif char == prev: count += 1 # This is a new char, so record the count # of the previous char and reset the counter else: counts.append((prev, count)) count = 1 prev = char # get the last char after we fell out of the loop counts.append((prev, count)) ret = '' for char, count in counts: # ret += char + str(count) if count > 1 else '' ret += '{}{}'.format(char, count if count > 1 else '') return ret
c617ca2bfe62baed5e141c65ec923297f27ac488
701,914
def is_legal_parameter(name): """ Function that returns true if the given name can be used as a parameter in the c programming language. """ if name == "": return False if " " in name: return False if "." in name: return False if not name[0].isalpha(): return False return True
de4426f5fc14740439c8f278d19e8ec9944e1a2f
701,915
def unity(): """Return a unity function""" return lambda x:x
5e7aa6bfe20f0534244ed0932b3bf87bf7505230
701,916
def num_added_features(include_am, include_lm): """ Determine the number of added word-level features (specifically AM and LM) """ added_feature_count = 0 if include_am: added_feature_count += 1 if include_lm: added_feature_count += 1 return added_feature_count
83f344ad693f846f7a6dda0bcef429565d96870b
701,918
def _get_mudata_autodetect_options_and_encoding_modes( identifier: str, autodetect: dict, encodings: dict[str, dict[str, list[str]]] ) -> tuple[bool, dict | None]: """ Extract the index column (if any) and the columns, for obs only (if any) from the given user input. This function is only called when dealing with datasets consisting of multiple files (for example MIMIC-III). For each file, `index_columns` and `columns_obs_only` can provide three cases: 1.) The filename (thus the identifier) is not present as a key and no default key is provided or one or both dicts are empty: --> No index column will be set and/or no columns are obs only (based on user input) .. code-block:: python # some setup code here ... # filename identifier1 = "MyFile" identifier2 = "MyOtherFile" # no default key and identifier1 is not in the index or columns_obs_only keys # -> no index column will be set and no columns will be obs only (except datetime, if any) index_columns = {"MyOtherFile":["MyOtherColumn1"]} columns_obs_only = {"MyOtherFile":["MyOtherColumn2"]} 2.) The filename (thus the identifier) is not present as a key, but default key is provided --> The index column will be set and/or columns will be obs only according to the default key .. code-block:: python # some setup code here ... # filename identifier1 = "MyFile" identifier2 = "MyOtherFile" # identifier1 is not in the index or columns_obs_only keys, but default key is set for both # -> index column will be set using MyColumn1 and column obs only will include MyColumn2 index_columns = {"MyOtherFile":["MyOtherColumn1"], "default": "MyColumn1"} columns_obs_only = {"MyOtherFile":["MyOtherColumn2"], "default": "MyColumn2"} 3.) The filename is present as a key --> The index column will be set and/or columns are obs only according to its value .. code-block:: python # some setup code here ... # filename identifier1 = "MyFile" identifier2 = "MyOtherFile" # identifier1 is in the index and columns_obs_only keys # -> index column will be MyColumn1 and columns_obs_only will include MyColumn2 and MyColumn3 index_columns = {"MyFile":["MyColumn1"]} columns_obs_only = {"MyFile":["MyColumn2", "MyColumn3"]} Args: identifier: The name of the file autodetect: A Dictionary of files to autodetected categorical columns encodings: A Dictionary from mapping to columns Returns: Index column (if any) and columns obs only (if any) for this specific AnnData object """ _autodetect = False _encodings = None # should use autodetect on this object? if identifier in autodetect: _autodetect = autodetect[identifier] elif "default" in autodetect: _autodetect = autodetect["default"] # get encodings (if autodetection is not used) if not _autodetect: if identifier in encodings: _encodings = encodings[identifier] return _autodetect, _encodings
1b763bba23957e71897bc40acaf020088f75feb3
701,919
def retrieve_cnv_data(store, solution, chromosome=''): """ Retrieve copy number data for a specific solution """ cnv = store['solutions/solution_{0}/cn'.format(solution)] if chromosome != '': cnv = cnv[cnv['chromosome'] == chromosome].copy() cnv['segment_idx'] = cnv.index return cnv
2c77415909ff27a3b3fd00e7abb8d25b67b6ea8f
701,920
def banner(text: str, *, borderChar: str = '='): """Print 'text' as banner, optionally customise 'borderChar'.""" border = borderChar * len(text) return '\n'.join([border, text, border])
76d27b762173e35a15e0e445eccea85cdef3b327
701,922
def parse_turn(turn): """Parse the input from the user for valid player strings and play positions Args: turn (string): Input string from the user that contains the played position (0-8) Returns: (int/None): Returns interger on success or None on failure """ try: # check if position is valid if int(turn) > 8 or int(turn) < 0: print("Position must be 0-8") return None return int(turn) except Exception as e: print("Could not parse position") return None
90abe0050ed6413931f8b50e622e4083c2fa4d87
701,923
def phonenumber(anon, obj, field, val): """ Generates a random US-style phone number """ return anon.faker.phone_number(field=field)
8d19ba96b805fd117e2ceb9a926bb1f8a9966e0b
701,924
def noop(obs): """ Transform that does absolutely nothing! """ return obs
95ad1168d804c1021f328090068c7d6a260b7ca4
701,925
import numpy as np def RectangularGrid(dX, iMax, dY=None, jMax=None): """Return a rectangular uniform rectangular mesh. X and/or Y grid point locations are computed in a cartesian coordinate system using the grid step size and grid points. Call Signature: RectangularGrid(dX, iMax, dY=None, jMax=None) Parameters ---------- dX: float Grid step size along X-axis. iMax : int Number of grid points along X-axis within the domain. dY: float Grid step size along Y-axis. Value required for 2D applications. jMax : int Number of grid points along Y-axis within the domain. Value required for 2D applications. Returns ------- X: 1D or 2D array, float Returns X coordinates at each grid points locations. Y: 2D array, float Returns Y coordinates at each grid points locations. Returns 0 for 1D applications. """ if isinstance(dY, float) and isinstance(jMax, int): X = np.zeros((iMax, jMax), dtype="float") Y = np.zeros((iMax, jMax), dtype="float") for i in range(0, iMax): for j in range(0, jMax): X[i][j] = i*dX Y[i][j] = j*dY else: X = np.zeros((iMax), dtype="float") for i in range(0, iMax): X[i] = i*dX Y = 0.0 print("Uniform rectangular grid generation in cartesian\ coordinate system: Completed.") return X, Y
15445a2e700d3e0989a47e198732582a51c30d5f
701,926
def add(a,b): """ This function returns the sum of the given numbers """ return a + b
9998c4a350973839aeb8f64fe0ba555297f35ccc
701,927
import random def _is_prime(number, attempts=10): """ Miller-Rabin primality test. A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. """ if number != int(number): return False number = int(number) if attempts != int(attempts): attempts = 10 if number in [0, 1, 4, 6, 8, 9]: return False if number in [2, 3, 5, 7]: return True s = 0 d = number - 1 while d % 2 == 0: d >>= 1 s += 1 assert (2 ** s * d == number - 1) def _trial_composite(test_number): if pow(test_number, d, number) == 1: return False for j in range(s): if pow(test_number, 2 ** j * d, number) == number - 1: return False return True for i in range(attempts): if _trial_composite(random.randrange(2, number)): return False return True
05fa3b4a8c9266b491449cc908392c535f5b2196
701,928
import os def touch(filename, mtime): """ doc me """ with open(filename, 'a+'): pass os.utime(filename, (mtime, mtime)) return 0
aaa272ba33ff25b2e83cfa7aa308cc115bd8fb6a
701,929
def flags_to_release(is_minor=False, is_major=False): """Convert flags to release type.""" if is_minor and is_major: raise ValueError("Both `is_minor` and `is_major` are set to 'True'.") if is_minor: return "minor" if is_major: return "major" return "normal"
e4f80774b72da544f20fe6ead5816dbed2a3755c
701,930
from typing import Union import yaml def read_yaml(path: str) -> Union[dict, list]: """Loads yaml at given path Args: path (str): path to yaml file Returns: Union[dict, list]: dictionary or list loaded from yaml depending on the yaml """ with open(path, encoding="UTF-8") as yaml_file: return yaml.safe_load(yaml_file)
66138b8968865d8951ae366ab3adb0c342bbfabe
701,931
def is_legal(x, y, img): """ Check if (x, y) is a valid coordinate in img Args: x (int): x-coordinate y (int): y-coordinate img (numpy.array): Image Returns: bool -> True if valid, False otherwise """ if 0 <= x < img.shape[1] and 0 <= y < img.shape[0]: return True else: return False
bc86f6b032932e4fb33b3d1983fc2a8586176e5f
701,932
def prepare_playlists(user,labelled_data): """ prepares the user's playlists for upload and display Args: user (SpotifyUser) labelled_data (DataFrame or array-like) Returns: Dictionary: uploadable playlists in JSON format """ return user.generate_uploadable_playlists(labelled_data)
85a7843997cb759b866e30d6d70f8fdecfc95dc5
701,933
def add(i): """得到114个add函数对应的的字符串""" return ".add(user_id_list[" + str(i) + "][0], \n" \ "\tpeople[" + str(i) + "], \n" \ "\txaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_='dataMax'), \n" \ "\tyaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_='dataMax'), \n" \ "\tzaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_='dataMax'), \n" \ "\tgrid3d_opts=opts.Grid3DOpts(width=100, height=100, depth=100)," \ "\n)"
5ba345b2e6ed224f06fffab47aef44c01328fe80
701,934
import configparser import os import sys def read_config(config_file): """Read configuration file infomation :config_file: Configuration file :type config_file: string """ cfg = configparser.ConfigParser() try: cur_dir = os.path.dirname(os.path.abspath(__file__)) if os.sep not in config_file: config_file = cur_dir + os.sep + config_file config_ini_info = {"ip": "", "user": "", "passwd": "", "auth": "", "cafile": ""} # Check whether the config file exists if os.path.exists(config_file): cfg.read(config_file) # Get the ConnectCfg info config_ini_info["ip"] = cfg.get('ConnectCfg', 'BmcIP') config_ini_info["user"] = cfg.get('ConnectCfg', 'BmcUsername') config_ini_info["passwd"] = cfg.get('ConnectCfg', 'BmcUserpassword') config_ini_info['sysid'] = cfg.get('ConnectCfg', 'SystemId') try: config_ini_info['auth'] = cfg.get('ConnectCfg', 'Auth') except: config_ini_info['auth'] = 'session' try: config_ini_info['cafile'] = cfg.get('ConnectCfg', 'Cafile') except: config_ini_info['cafile'] = '' except: sys.stderr.write("Please check the file path is correct") sys.exit(1) return config_ini_info
3c8fffbad9eb95e59b4cceda01824f726440b1c4
701,935
def rates_for_yr(rates_all_years, sim_year): """ Filter specific rates for a given year Parameters ---------- rates_all_years : pandas DataFrame rates, to be filtered by year sim_year : int year being simulated Returns ------- pop_w_rates : pandas DataFrame rates for a given year """ rates_yr = rates_all_years[rates_all_years['yr'] == sim_year] return rates_yr
616cec13b0a686c2c7504c187c31dafaa7f88b6f
701,936
def parse_output(output_file): """Parse output file for void fraction data. Args: output_file (str): path to simulation output file. Returns: results (dict): total unit cell, gravimetric, and volumetric surface areas. """ results = {} with open(output_file) as origin: count = 0 for line in origin: if "Surface area" in line: if count == 0: results['sa_unit_cell_surface_area'] = float(line.split()[2]) count = count + 1 elif count == 1: results['sa_gravimetric_surface_area'] = float(line.split()[2]) count = count + 1 elif count == 2: results['sa_volumetric_surface_area'] = float(line.split()[2]) print( "\nSURFACE AREA\n" + "%s\tA^2\n" % (results['sa_unit_cell_surface_area']) + "%s\tm^2/g\n" % (results['sa_gravimetric_surface_area']) + "%s\tm^2/cm^3" % (results['sa_volumetric_surface_area'])) return results
4659c2014861f8467d9c2e1b1dc69c0bbef34cda
701,937
import os import sys def generate_passphrase(passphrase_length, word_list): """Generate the passphrase string. For each word, read 2 bytes from the kernel-space CSPRNG via ``os.urandom`` and convert them to an integer which serves as a list index. A list of 65,536 words is probably enough so we don't need more than 2 bytes (“2 bytes should be enough for everyone.”). Return a space delimited string of words, for the same reason Diceware recommends spaces to be included in the passphrase. Additionally, spaces make it much more legible. Arguments: passphrase_length -- number of words in the resulting passphrase word_list -- list of words from which the passphrase is generated """ passphrase = [] while True: n = int.from_bytes(os.urandom(2), sys.byteorder) try: passphrase.append(word_list[n].rstrip('\n')) except IndexError: continue if len(passphrase) == passphrase_length: break return ' '.join(passphrase)
dc6aa86392f1c49f47c6f169ec98ef5e555f9451
701,938
import os def processed_file_path(source_path, asset_roots, target_directory, target_extension): """Take the path to an asset and convert it to target path. Args: source_path: Path to the source file. asset_roots: List of potential root directories each input file. target_directory: Path to the target assets directory. target_extension: Extension of the target file. Returns: Tuple (target_file, relative_path) where target_file is a path to the target file derived from the source path and relative_path is a relative path to the target file from the matching asset root. """ relative_path = source_path for asset_root in asset_roots: if source_path.startswith(asset_root): relative_path = os.path.relpath(source_path, asset_root) break return (os.path.join(target_directory, os.path.splitext(relative_path)[0] + os.path.extsep + target_extension), os.path.dirname(relative_path))
749bda062d90dae1763d802f2a557d50682e8a4d
701,940
def zoom(scale, center, group): """zoom(scale, center, group) -> float Change the zoom and pan of a group's display. The scale argument is the new zoom factor. If the scale is given, but not the center, the zoom is set to that factor and the view is positioned so the cursor is pointing at the same place it was before zooming. A zero or negative scale value will cause a zoom-to-fit. If both scale and center arguments are given, the view is zoomed and then centered on the specified point. The new scale factor will be returned, or None if the function is run in a non-GUI context. @param scale: New zoom factor. @param center: Optional 2-item tuple specifying the center coordinates. @param group: Optional Group. This is ignored at present. @return: Current zoom factor or None if not in a GUI context. """ return 0.0
fe6c5cafed738d5e53a043fa86e66b22cab0a6af
701,941
import numpy def get_topic_terms(model, topicid, topn, id2token): """ Return a list of `(word_id, probability)` 2-tuples for the most probable words in topic `topicid`. Only return 2-tuples for the topn most probable words (ignore the rest). """ topic = model.state.get_lambda()[topicid] topic = topic / topic.sum() # normalize to probability distribution bestn = numpy.argsort(topic)[::-1][:topn] return [id2token[id] for id in bestn]
b0ca1fd35fb7e8ce89a497c37bfd82b9dd884027
701,944
import json def load_label(label_path): """ Loads a label from a JSON file """ with open(label_path, 'r') as label_file: label = json.load(label_file) return label
f6a2873abee024d64ede78f18a96f0a1b95abd0b
701,945
def resize(anns, size, output_size): """ Parameters ---------- anns : List[Dict] Sequences of annotation of objects, containing `bbox` of [l, t, w, h]. size : Sequence[int] Size of the original image. output_size : Union[Number, Sequence[int]] Desired output size. If size is a sequence like (w, h), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaing the aspect ratio. i.e, if width > height, then image will be rescaled to (output_size * width / height, output_size) """ w, h = size if isinstance(output_size, int): if (w <= h and w == output_size) or (h <= w and h == output_size): return anns if w < h: ow = output_size sw = sh = ow / w else: oh = output_size sw = sh = oh / h else: ow, oh = output_size sw = ow / w sh = oh / h new_anns = [] for ann in anns: bbox = list(ann['bbox']) bbox[0] *= sw bbox[1] *= sh bbox[2] *= sw bbox[3] *= sh new_anns.append({**ann, "bbox": bbox}) return new_anns
800135ac9d65f55ae96d04fc645ac0d2b913b76c
701,947
def has_overlap(x0, xd, y0, yd): """Return True if the ranges overlap. Parameters ---------- x0, y0 : float The min values of the ranges xd, yd : float The widths of the ranges """ return x0 + xd >= y0 and y0 + yd >= x0
6b2a6eff892e28376ed08bf8f60c67f49cdeff44
701,948
def gen_col_list(num_signals): """ Given the number of signals returns a list of columns for the data. E.g. 3 signals returns the list: ['Time','Signal1','Signal2','Signal3'] """ col_list = ['Time'] for i in range(1, num_signals + 1): col = 'Signal' + str(i) col_list.append(col) return col_list
35fe1457c9e256f90f7695e066dcc3202f212d98
701,949
import numpy def cropobjects_merge_bbox(cropobjects): """Computes the bounding box of a CropObject that would result from merging the given list of CropObjects.""" # Find extremes. This will define the output cropobject. t, l, b, r = numpy.inf, numpy.inf, -1, -1 for c in cropobjects: t = min(t, c.top) l = min(l, c.left) b = max(b, c.bottom) r = max(r, c.right) return t, l, b, r
559e96dda48cb5e733c59a3168032037e0eb06e4
701,950
def generate_nested_list(root,nodes): """ Generates a nested list representation of the tree with specified node as root. Useful for checking equality of trees or subtrees. To do: make the nested list form a property that is computed when needed. """ nl = [] if root.children is None: return nl for child in root.children: nl.append(generate_nested_list(child,nodes)) return nl
fa75493c8ccc4b720ee404baa9eb3996ce78f3eb
701,951
def abstract(func): """ An abstract decorator. Raises a NotImplementedError if called. :param func: The function. :return: The wrapper function. """ # noinspection PyUnusedLocal # pylint: disable=unused-argument def wrapper(*args, **kwargs): raise NotImplementedError('{} has not been implemented'.format(func.__name__)) func.__isabstractmethod__ = True return wrapper
3497ae41c4987499cddc610e518a8a9251cadb31
701,953
def non_related_filter(questions_df, non_related_ids): """ Splits a questions dataframe between related and non-related discussions, based on an Ids list of non-related discussions. :param questions_df: > A pandas dataframe of stackoverflow questions containing posts Ids; :param non_related_ids: > List like object containing Ids of manually filtered non-related stack overflow discussions; :return (tuple): > Two dataframes, one with related discussions and another with non-related discussions """ non_related = questions_df.loc[questions_df.Id.isin(non_related_ids)] non_related = non_related.fillna(0.0) related = questions_df.loc[~questions_df.Id.isin(non_related_ids)] related = related.fillna(0.0) return related, non_related
b7e64287b2bdb6a8999bcd8e7efd8e2787b991dd
701,954
import math def sin(x): """Return sin of x (x is in radians)""" return math.sin(x)
c5b091892e54df064b61a109812b3ea1206b1713
701,955
def format_pin(pnum, relatedpnum): """Formats a Parcel ID Number (PIN) from a BS&A PNUM.""" try: if relatedpnum is None or relatedpnum.startswith('70-15-17-6'): p = pnum else: p = relatedpnum p = p.split('-') del p[0] p = ''.join(p) except IndexError: p = None return p
8338fd5b329cf37d3fa59cd1b7d1f71e6694d706
701,956
from datetime import datetime def condense_log_events(log_stream, log_events): """Condense log events into single strings. expects list of dicts.""" condensed_events = [] for event in log_events: event_datetime = datetime.fromtimestamp(event['timestamp'] / 1000) message = "{} | {} | {}".format(log_stream, event_datetime, event['message']) condensed_events.append(message) return condensed_events
94bfdc73d9fad7151162ca3e1bf114cc11950067
701,957
import os def trickle(session_config): """Return a dict with "trickled down" / inherited config values. This will only work if config has been expanded to full form with :meth:`config.expand`. tmuxp allows certain commands to be default at the session, window level. shell_command_before trickles down and prepends the ``shell_command`` for the pane. Parameters ---------- session_config : dict the session configuration. Returns ------- dict """ # prepends a pane's ``shell_command`` list with the window and sessions' # ``shell_command_before``. if "start_directory" in session_config: session_start_directory = session_config["start_directory"] else: session_start_directory = None if "suppress_history" in session_config: suppress_history = session_config["suppress_history"] else: suppress_history = None for window_config in session_config["windows"]: # Prepend start_directory to relative window commands if session_start_directory: if "start_directory" not in window_config: window_config["start_directory"] = session_start_directory else: if not any( window_config["start_directory"].startswith(a) for a in ["~", "/"] ): window_start_path = os.path.join( session_start_directory, window_config["start_directory"] ) window_config["start_directory"] = window_start_path # We only need to trickle to the window, workspace builder checks wconf if suppress_history is not None: if "suppress_history" not in window_config: window_config["suppress_history"] = suppress_history # If panes were NOT specified for a window, assume that a single pane # with no shell commands is desired if "panes" not in window_config: window_config["panes"] = [{"shell_command": []}] for pane_idx, pane_config in enumerate(window_config["panes"]): commands_before = [] # Prepend shell_command_before to commands if "shell_command_before" in session_config: commands_before.extend( session_config["shell_command_before"]["shell_command"] ) if "shell_command_before" in window_config: commands_before.extend( window_config["shell_command_before"]["shell_command"] ) if "shell_command_before" in pane_config: commands_before.extend( pane_config["shell_command_before"]["shell_command"] ) if "shell_command" in pane_config: commands_before.extend(pane_config["shell_command"]) window_config["panes"][pane_idx]["shell_command"] = commands_before # pane_config['shell_command'] = commands_before return session_config
a429f4102f40ced0ee47ad3ed39d1f678e35c3ab
701,958
import datetime as dt def current_year(): """ Returns the current year. """ now = dt.datetime.now() return now.year
34fe2695dfb224d0db39af7dffc084058b93518a
701,959
def get_router_port(endpoint): """ get the network device and port of where the endpoint is connected to. Args: endpoint (endpoint): endpoint A routerport is a dict with the following keys: router (string): name of the netork device port (string): port on the router. vlan (string): VLAN Returns: dict: router, port and vlan """ router = endpoint['router'] port = endpoint['port'] vlan = endpoint['vlan'] return {'router':router, 'port':port, 'vlan':vlan}
30c331169a0c5e1a6b0bf91b8ad43c1db64dc532
701,960
import networkx def createGraph(input_edge_list): """ From list of edges create and return a graph. :param input_edge_list: list of edges :returns G: the graph """ # first thing, how are the nodes separated in an edge with open(input_edge_list, 'r') as f: l = f.readline() delimiter = l[1] print(f"Graph creation started: ") G = networkx.read_edgelist(input_edge_list, delimiter=delimiter) print(f"----- Original graph has {G.number_of_nodes()} nodes and {G.number_of_edges()} edges.") # only consider the largest connected component G = G.subgraph(max(networkx.connected_components(G), key=len)).copy() print(f"----- The largest component subgraph has {G.number_of_nodes()} nodes and {G.number_of_edges()} edges.\n") return G
5a92864aa78cc99218c45031c80a6b89a836f134
701,961
def dummy_callable(obj): """A callable that you probably shouldn't be using :)""" return []
2a0c71bd1a558d3df1c40c5a384fa98bf3cc15ad
701,962
import math def cie76(c1, c2): """ Color comparision using CIE76 algorithm. Returns a float value where 0 is a perfect match and 100 is opposing colors. Note that the range can be larger than 100. http://zschuessler.github.io/DeltaE/learn/ LAB Delta E - version CIE76 https://en.wikipedia.org/wiki/Color_difference E* = 2.3 corresponds to a JND (just noticeable difference) """ l = c2[0] - c1[0] a = c2[1] - c1[1] b = c2[2] - c1[2] return math.sqrt((l * l) + (a * a) + (b * b))
9470b66231252decd8be7f07af2591ddf1278edc
701,963
from pathlib import Path def parse_lst(lst_path): """Extract audio names of nnenglish.""" audio_names = [] with open(lst_path) as fd: for line in fd: audio_path, lang = tuple(line.strip().split()) if lang != "nnenglish": continue audio_name = Path(audio_path).with_suffix("").name audio_names.append(audio_name) return audio_names
82ed0e7a0c13269416e4530157f2a67a68712676
701,964
import random def add_angle(r): """ Add angle for each r value to make up a coordinate of a polar coordinate. """ coords = [] for ri in r: theta = random.random() * 360 coords.append((ri, theta)) if len(coords) == 1: return coords[0] else: return coords
0e91e9c7999627885218dde42bc2849e89071eff
701,965
from typing import OrderedDict def load_status_info(sfile, fudge=None): """ Parse the output of pb_run_status.py, either from a file or more likely from a BASH <() construct - we don't care. It's quasi-YAML format but I'll not use the YAML parser. Also I want to preserve the order. """ res = OrderedDict() if sfile: with open(sfile) as fh: for line in fh: k, v = line.split(':', 1) res[k.strip()] = v.strip() if fudge: # Note this keeps the order or else adds the status on the end. res['PipelineStatus'] = fudge return res
13e6b546d93847b0321da2cb659150345b6a8b20
701,966
def get_tags_from_message(message): """ Given a message string, extracts hashtags and returns a comma-separated list :param message: a Hipchat message body """ tags = {word.strip('#') for word in message.split() if word.startswith('#')} return ','.join(tags)
528f7702f43f8f81adf942c79b292f508773d205
701,967
def tf_read_img(tf, filename): """Loads a image file as float32 HxWx3 array; tested to work on png and jpg images.""" string = tf.read_file(filename) image = tf.image.decode_image(string, channels=3) image = tf.cast(image, tf.float32) image /= 255 return image
662fc1c9840e67fb0ff3fae4b12da5179e286e25
701,968