content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Sequence def _lcs(pred_tokens: Sequence[str], target_tokens: Sequence[str]) -> int: """Common DP algorithm to compute the length of the longest common subsequence. Args: pred_tokens: A tokenized predicted sentence. target_tokens: A tokenized target s...
7189136a6ceeb3079c3d34bdacf2ee4c37b519ad
678,112
import numbers def _ordinal_tier(a): """ Returns the "tier" of a. Bigger ordinals have higher tier. This is used to speed up comparison by seeing when an ordinal is vastly larger than another. As currently implemented, this reflects the height of the leading term of the CNF. """ if isinsta...
7de5068ef092f8cb25731981c32fa32b6f738a5e
678,113
import torch def load_io_dataset(dataset_path: str, device=None): """ Load the saved dataset, map the data location to `device`. Args: dataset_path: Path to the checkpoint (.pt format) device: Device for the data. Returns: The loaded IO dataset """ data = torch.load(dataset_...
181dc0dc3c2cb0615068bc6620af9af4d86d1274
678,114
def dice_similarity_coefficient(inter, union): """Computes the dice similarity coefficient. Args: inter (iterable): iterable of the intersections union (iterable): iterable of the unions """ return 2 * sum(inter) / (sum(union) + sum(inter))
ae58310528b7c24b7289cb3bcf76c72745c8bacc
678,115
def edit_distance(str1, str2, m, n): """Compute the Edit Distance between 2 strings.""" if m == 0: return n if n == 0: return m if str1[m-1] == str2[n-1]: return edit_distance(str1, str2, m-1, n-1) insert = edit_distance(str1, str2, m, n-1) remove = edit_distance(s...
17a295bfbe5b9ce01d40eed956266a08f6fea2bc
678,116
def rint(f: float) -> int: """ Rounds to an int. rint(-0.5) = 0 rint(0.5) = 0 rint(0.6) = 1 :param f: number :return: int """ return int(round(f, 0))
82f89c49135e0081db7ac4615a51d3dd24665309
678,117
import os def files(path): """Names of files in a directory""" return [ filename for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))]
b608d351df532dd5075246239a2207697ee6df9f
678,118
def merge_with(f, *dicts): """Returns a dict that consists of the rest of the dicts merged with the first. If a key occurs in more than one map, the value from the latter (left-to-right) will be the combined with the value in the former by calling f(former_val, latter_val). Calling with no dicts retur...
1ddb503b6a000932d115f8045676c409e05abe5c
678,119
def ok(results): """Return whether or not all results are status 200 OK.""" return all([result['data'].ok for result in results])
42e61dc39110b196837a3ac353c1996d32fa434c
678,120
import os def getegid(space): """ getegid() -> gid Return the current process's effective group id. """ return space.wrap(os.getegid())
830179f3ee9ed458431325e09b45f8b1d3696c63
678,122
from io import StringIO def write_tgf(graph, key_tag=None): """ Export a graph in Trivial Graph Format .. note:: TGF graph export uses the Graph iternodes and iteredges methods to retrieve nodes and edges and 'get' the data labels. The behaviour of this process is determined by the single...
580dd0da85e580e3cb6864aa0bcd28d78f4bbee1
678,124
from typing import Counter def consensus(string): """ Generate a consensus sequence from an input string. If there are mo Parameters: ----------- string :: str String representing all of the basecalls at that position Returns: -------- 'X' - tie at this position Otherwise...
65777e4738dd4fcbc0aaad7d09b21cb6443b201b
678,126
def valid_elements(symbols,reference): """Tests a list for elements that are not in the reference. Args: symbols (list): The list whose elements to check. reference (list): The list containing all allowed elements. Returns: valid (bool): True if symbols only contains elements from ...
a6fb3a6c09e76da865a76e4ae320f9cfef55a91c
678,127
import torch def collate_fn(batch): """Collate batches of images together. """ imgs, targets = list(zip(*batch)) imgs = torch.stack(imgs) targets = torch.LongTensor(targets) return imgs, targets
e2979b3e335c8c3aef3d18612705e7fd1e4331d0
678,128
import torch def any(input_, axis=None, keepdims=False): """Wrapper of `torch.any`. Parameters ---------- input_ : DTensor Input tensor. axis : None or int or tuple of ints, optional Axis or axes to operate on, by default None keepdims : bool, optional If true, the axe...
76d6ca1c662215d068f168989ea36f68fd113b6e
678,129
def sled_down_hill(data, rise, run): """PART ONE Checks how many trees you'd hit on the way down a slope that looks like the following where each tree is a "#": ........#.............#........ ...#....#...#....#............. .#..#...#............#.....#..# ..#......#..##............###.. ...
aeca482032a6a4c2e871c34eeb9489828c7f4e7f
678,130
def _merge_clusters_in_list(cluster_lists): """Return a list of sets, each set has the clusters to merge.""" output_list = [] for input_list in cluster_lists: input_set = set(input_list) added = False for output_set in output_list: if output_set.intersection(input_set): ...
62f1c208fb46d7e90577622a1deb9fdd9834416a
678,131
import hashlib def file_hash_sha256(file): """Return SHA-256 hash of file as hexadecimal string.""" with open(file, 'rb') as hf: hfstuff = hf.read() ho = hashlib.sha256() ho.update(hfstuff) return ho.hexdigest()
46db04556269113a31d3850e5bd44096b52832fc
678,132
def percent_change(d1, d2): """Calculate percent change between two numbers. :param d1: Starting number :type d1: float :param d2: Ending number :type d2: float :return: Percent change :rtype: float """ return (d2 - d1) / d1
45a8de67340432eff3cd3c9fee695b1f1db7d46a
678,133
import re def isvowel(char): """Check whether char is tibetan vowel or not. Args: char (str): char to be checked Returns: boolean: true for vowel and false for otherwise """ flag = False vowels = ["\u0F74", "\u0F72", "\u0F7A", "\u0F7C"] for pattern in vowels: if r...
3476271b9109a2d42d404c20ebebade95549af9a
678,134
import re def check_numbers_or_dots(to_clean): """Cleans the input""" expression = r"([0-9].[0-9]*.[0-9]*)/" result = re.search(expression, to_clean) if result: return result.group(1) return None
3fb4a1cde21cd9bb2d124e803f154ef464f04629
678,135
import os import glob import json def custom_labware_dict(labware_dir_path): # make it so it redirects back to original path """Given the path of a folder of custom labware .json files will create dict of key = name and value = labware definition to be loaded using protocol.load_labware_from_definition v...
55ad03c64c740750c620b581a65e4088172edbc6
678,136
import requests def is_ec2_instance(): """Validate EC2 instance.""" try: response = requests.get( "http://instance-data/latest/meta-data/instance-id") except requests.exceptions.RequestException: return False else: return bool(response.status_code == 200)
42f1e17652d36cdfc7ff3494b72031e2978d6fa6
678,137
def divisors(): """This challenge is to print out all the divisors of a chosen number.""" def divisors(num): divisor_list = [] for check in range(2, num): if num % check == 0: print(check) divisor_list.append(check) return divisor_list ch...
cbd6e0c6404ea970323695fbf2892298096d5136
678,138
import binascii import base64 def read_pem(data): """Read PEM formatted input.""" data = data.replace(b"\n",b"") data = data.replace(b"",b"") data = data.replace(b"-----BEGIN PUBLIC KEY-----",b"") data = data.replace(b"-----END PUBLIC KEY-----",b"") return binascii.hexlify(base64.b64decode(dat...
a05ecf4d3b476b92fede74e844ba8fde8ef53382
678,139
def get_configuration(provider_registry, suite_id): """Get a stored configuration by suite ID. :param provider_registry: The provider registry to get configuration from. :type provider_registry: :obj:`environment_provider.lib.registry.ProviderRegistry` :param suite_id: The ID of the suite to get config...
616606fcf3c0d5f4f78a11dfd4c3acb674d36e82
678,140
def _indent(string, width=0): #pragma: no cover """ Helper function to indent lines in printouts """ return '{0:>{1}}{2}'.format('', width, string)
9a77537d2562834a3acb2f746ef397b17cbc8333
678,141
def set_num_gpu_to_one() -> int: """ set gpu number to one """ return 1
b7249dfeb4214a3bccdd96e127b5cfbd1683fb57
678,142
def pick_sample_file(EEGfile,n=0): """this function is used as a way to get names for dictionary variables""" """It takes an EEG file string and return the string before the dot""" file_to_read=EEGfile[n] fileName=file_to_read.split('.')[0] return file_to_read,fileName
e3e0e5c5581c295b6d4c0bc3204a615ad9a2ad6f
678,143
import os def get_upload_path_news_attachment(instance, filename): """ Function to get upload path for news """ upload_dir = "newsAttachment" return os.path.join(upload_dir, filename)
fc0a61591bd7bea0eb62cf2b61b2f855c9bbd56c
678,144
def is_list(node: dict) -> bool: """Check whether a node is a list node.""" return 'listItem' in node
ad01033afe51391db2e5966247080e7263baa5e4
678,146
def get_cart_data_for_checkout(cart, discounts, taxes): """Data shared between views in checkout process.""" lines = [(line, line.get_total(discounts, taxes)) for line in cart] subtotal = cart.get_subtotal(discounts, taxes) total = cart.get_total(discounts, taxes) delivery_price = cart.get_delivery_...
37c236eb4a183fd22bd1ee714fdfa39ca539dabb
678,147
def _is_using_intel_oneapi(compiler_version): """Check if the Intel compiler to be used belongs to Intel oneAPI Note: Intel oneAPI Toolkit first version is 2021.1 """ return int(compiler_version.split(".")[0]) >= 2021
ceaa0ebe12112e3106071f6af2e4b51809c7a0b1
678,148
def serialize(obj): """Generate a serialized object for display.""" if obj is None: return None if isinstance(obj, (int, float, tuple, str, bool)): return obj if isinstance(obj, dict): return {k: serialize(obj[k]) for k in obj} if isinstance(obj, list): return [serial...
62825b94ae36cc62f7880fe4de18fb0529f222c3
678,149
def build_hass_attribution(source_attribution: dict) -> str | None: """Build a hass frontend ready string out of the sourceAttribution.""" if (suppliers := source_attribution.get("supplier")) is not None: supplier_titles = [] for supplier in suppliers: if (title := supplier.get("titl...
835261d04f1bdfba5dff8671b194f10881b6b22b
678,150
import socket def faasFunctionName(): """ Gets the name of this FaaS function by parsing the k8s pod name Returns: str: The name of the the FaaS function """ return "-".join(socket.gethostname().split("-")[:-2])
98af23686c872a709a1fb3ba1175cb4411a6c680
678,151
def celsius_to_fahrenheit(temperature_in_c): """Convert temperature from celsius to fahrenheit PARAMETERS ---------- temperature_in_c : float A temperature in degrees Celsius RETURNS ------- temperature_in_f : float A temperature in degrees Fahrenheit """ temperatur...
d3589f7e87aae4b03d3184baf6db7c2c2602b54e
678,152
def path_probability(trans_mat, quad_to_matrix_index, path): """ Computes the probability of a given path :param trans_mat: trained transition matrix (numpy matrix) :param quad_to_matrix_index: dictionary to keep track of indicies :param path: input path of neo4j types :return: float representing probability of s...
c0c078e7fc16ff787c805779746ace939e8db0d4
678,153
import os def get_file(file_name, subdirectory=''): """ loads a file as a string from the test resources directory based on the provided file name and subdirectory """ if not file_name: assert False actual_path = os.path.dirname(__file__) response = os.path.join(actual_path, '../resources', su...
e180bafdcbf3248074e2425f405fd7bf2af94da5
678,154
def frameToCell(frame, info): """ Convert a frame and game info to a cell representation """ return str((info['x']//32,info['y']//32,info['act'],info['zone']))
f20c4132001d7a754221c311d866b707f7375b1a
678,156
def usage(wf): """CLI usage instructions.""" return __doc__
4825dc18eb22e83fcf4d14e7a0dea1ce1457a9e7
678,157
from typing import Optional def none_if_blank(param) -> Optional[str]: """returns a stripped string or None if string it empty""" if param: param = param.strip() if param: return param return None
355bc4e624e6a0cf5eac3fa040a876aacec1b1eb
678,158
from typing import List import torch def conv( in_channels: int, out_channels: int, stride: int = 1, groups: int = 1, kernel_size: int = 3, padding: int = 1, ) -> List[torch.nn.Module]: """ 3x3 convolution with padding.""" return [ torch.nn.Conv2d( in_channels, ...
6b69392050747be39b9a4a15da60a08e64647df8
678,159
def join_hostname_index(hostname, index): """Joins a hostname with an index, reversing splti_hostname_index().""" return "{}~{}".format(hostname, index)
7e7dc902c9c47cae5c8a930f6979b97a5e7e3f2c
678,160
def count_number_matrices_2(m, upper_bounds, lower_bounds): """ Calculates the number of possible matrices for n=2 """ upper_bounds = [int(v) for v in upper_bounds] lower_bounds = [int(v) for v in lower_bounds] possValues = [0]*(max(upper_bounds)+1) for i in range(lower_bounds[0], upper_bounds[0]+1): possValues[...
5245ad4239b27966f75f010ce3c96005af25597f
678,161
def beamer_query_args(): """xrandr arguments for querying current status.""" return ("xrandr", "--query")
714eed417173b86c538a314bb17350ceb6853479
678,162
def t03_SharingIsPassByReference(C, pks, crypto, server): """Verifies that updates to a file are sent to all other users who have that file.""" alice = C("alice") bob = C("bob") alice.upload("k", "v") m = alice.share("bob", "k") bob.receive_share("alice", "k", m) score = bob.download("k"...
ffdcde1c6dd9fcb6053715789287efabbe7ed6f1
678,163
def get_char_codes(text): """Change text to list of character codes of the characters.""" return [ord(letter) for letter in text]
7dda64e752b92503e83ab4e4d7fa77749235cc2a
678,164
def kJ_h2W(x): """kJ/h -> W""" return x/3.6
ace136a6f27a1415bf727ad679b491203f8822c4
678,165
import gzip import bz2 def open_file(file_name, flags='r'): """Opens a regular or compressed file (decides on the name) :param file_name a name of the file, it has a '.gz' or '.bz2' extension, we open a compressed stream. :param flags open flags such as 'r' or 'w' """ if fi...
cf20f393cf12bc2a7d446dae2afd72a24272b463
678,166
def _average_gradients_across_replicas(replica_context, gradients): """Computes the average gradient across replicas. This computes the gradient locally on this device, then copies over the gradients computed on the other replicas, and takes the average across replicas. This is faster than copying the gradi...
b9fed78a7efdb3452477b30a485b5147db15de0c
678,167
def all_data(request, data, data_missing): """Parametrized fixture giving 'data' and 'data_missing'""" if request.param == 'data': return data elif request.param == 'data_missing': return data_missing
b915255d6b7a3585a5ccee057b37a80fea6dfcf0
678,168
import torch def make_prediction(neural_net, save_path, images, classes, p = True): """ function to make prediction -------------------------- parameters: neural_net: a torch neural network save_path: path to load neural network from images: images to predict class of classes: the pos...
90ae9ea05bd20d26f75ba571458174f77aea7624
678,170
def _extract_month_from_filename(fname): """Extract month number from precipitation file name""" return str(fname[7:].split('.tif')[0])
b01b5c6e537bc0de431bc854ae878ccfe62e71d8
678,171
def format_pkg_data(master_package_data: list): """ Format and parse the reponse from pypi.org so we can build a dictionary of needed data for each package. Example response string (pkg_data variable below) looks like this: b' <a href="https://files.pythonhosted.org/packages/9f/a5/eec74d8d1016e6c2042ba31...
6b69c03392f5fbb22d26ada635cc303ec64f8626
678,172
def bytes_to_text(byte_array, encoding='UTF-8'): """ Decode a byte array to a string following the given encoding. :param byte_array: Byte array to decode. :param encoding: String encoding (default UTF-8) :return: a decoded string """ return bytes(byte_array).decode(encoding)
e3a65f2f0f3e7833dba6a476b1516db148e51136
678,173
import logging def has_file_handlers(logger): """To check if a log file has a file handler Parameters: * logger (object): Logger file object Returns: * bool: True if logger is a file handler logger """ for handler in logger.handlers: if isinstance( handler, logging.FileHandler ): retu...
c99e141d98fbc210bb4f52e0c9583dee79009370
678,174
import os def get_modified_fname(fname, ext, suffix='.'): """ Change the name of provided filename to different. Suffix should contain dot, since it is last part of the filename and dot should separate it from extension. If not, dot will be added automatically. """ path, _ = os.path.splitext(f...
7dadea9a47bbdeae2d9c8b89ffd0f4d0b5fecc90
678,175
def get_gse_gsm_info(line): """ Extract GSE and GSM info Args: line: the entry to process Returns: the GSE GSM info tuple """ parts = line.strip().split(",") if parts[0] == "gse_id": return None return parts[0], parts[1:]
f03eb86316382fba0d5f55bd09e7fc15f84c0078
678,178
def filter_title_transcriptions(df): """Filter the title transcriptions.""" df = df[df['motivation'] == 'describing'] df = df[df['tag'] == 'title'] return df
bf31ac36d204cd4c8e645e5f878fbf551e3c8b8c
678,179
def cli(ctx, form_id): """Get details of a given form. Output: A description of the given form. For example:: {'desc': 'here it is ', 'fields': [], 'form_definition_current_id': 'f2db41e1fa331b3e', 'id': 'f2db41e1fa331b3e', 'layout': [...
6bb213de18ed9fb617d66ad317379c18b64c76a3
678,180
def _get_speaking_time(main_segment_list): """ calculating the speaking time""" duration = 0 for a_segment in main_segment_list: duration += (a_segment[1] - a_segment[0]) return duration
6d7b6fe36975666aab14f779d75e39b6452ffefe
678,181
from typing import Iterable from typing import Union def smoothen(message: Iterable): """ Recebe um iterável e o formata numa caixinha. - Feito para lidar especialmente com strings ou listas/tuplas/conjuntos/dicionários de strings. - Para dicionários, somente os valores, convertidos para string, são '...
f22f81121d8031e30df816848b2e20798097dca3
678,182
import tempfile import subprocess def _process_svg(image_data): """Process a SVG: save the data, transform to PDF, and then use that.""" _, svg_fname = tempfile.mkstemp(suffix='.svg') _, pdf_fname = tempfile.mkstemp(suffix='.pdf') raw_svg = ''.join(image_data).encode('utf8') with open(svg_fname, '...
f120ee1959ac127a310d50d2e48a6b859894d7eb
678,183
def draw_batches(data, batch_size=128): """ Create a list of batches for the given data. Args: data: the dataframe returned by load_data batch_size: number of samples to include in each batch Returns: a list of batches. Each batch is a part of the data dataframe with batch_...
5eeca78dcac797b62f4498281d306648523ebb57
678,184
import glob def count_traj_files(path, extension): """ path : string Path of directory containing trajectory files. extension : string File extension type for trajectory files. EX) 'dcd', 'xtc', ... """ return len(glob.glob1(path,"*."+extension))
f3609858a68311b8294d7be59ee5c159eb2a53f6
678,185
import argparse import os def get_parameters(): """ Defines the (default) parameters used :return: The parameters in the options argparse class """ parser = argparse.ArgumentParser() parser.add_argument("--data_folder", default="/Users/mbarbier/Documents/data/test_data_camera/2020_03_02_fluor...
ca3b95fcb217822a5e35d25c680e4aa5e01b0bcd
678,186
def constant_term_denominator(opponent): """ Returns the constant part $\bar{a}$ for memory one strategies. """ constant = -opponent[1] + opponent[3] + 1 return constant
20babb3e9c49043f9f155db1bfb94e784d08097c
678,188
def tokenizer_lemmatizer(text, parser, stopwords=[]): """ Take a unicode string of text and return a list containing the lemmatized tokens :param: unicode, parser, list of unicode strings :returns: list of lemmatized tokens :rvalue: unicode """ parsed_data = parser(text) ...
5dc0ec64e28d9740842907038645928380a8a368
678,189
import random import string def create_temporary_cache_directory_name() -> str: """Create a temporary cache directory name.""" temp_directory_name = ''.join([random.choice(string.ascii_letters) for i in range(10)]) return ".tmp-" + temp_directory_name
f88196e367ba4611cf1176fad584fb7edb779a62
678,190
def get_hooks_cmds(cmds_info, pattern_key): """.""" keys = [] cmds = [] msgs = [] pattern_key = 'recipe.hooks.' + pattern_key for key in cmds_info: if key.startswith('recipe.hooks.') and key.endswith('.pattern'): if pattern_key in key: keys.append(key) key...
2847f3df1915b32f22408d4b5d4db879a60c4bc1
678,191
def _filter_cells(dictionary, filter_mask): """Filter 1- and 2-D entries in a dictionary""" for key, value in dictionary.items(): if key != "meta": if len(value.shape) == 1: dictionary[key] = value[filter_mask] else: dictionary[k...
4e80bce60b9bb04e0a31e4883914816057ad3721
678,193
def _get_scatterable_task_id(chunk_operators_d, task_id): """Get the companion scatterable task id from the original meta task id""" ids = [] for operator_id, chunk_operator in chunk_operators_d.iteritems(): if task_id == chunk_operator.scatter.task_id: ids.append(chunk_operator.scatter....
22354fbc0f67be8ef7f588339980ba21b0e3e8c1
678,194
def get_dict_value(dict_var, key, default_value=None, add_if_not_in_map=True): """ This is like dict.get function except it checks that the dict_var is a dict in addition to dict.get. @param dict_var: the variable that is either a dict or something else @param key: key to look up in dict @param ...
f54b8e52d8330b673f506426e0c6d8430a3f97f5
678,195
import os def hide_file(file_path): """隐藏文件夹或者文件""" x = os.system(f'attrib +a +s +h +r {file_path}..') if x == 0: return True else: return False
d2d695203d2851823de899ee43084f37eab3743f
678,196
def cleanly(text: str): """ Splits the text into words at spaces, removing excess spaces. """ segmented = text.split(' ') clean = [s for s in segmented if not s == ''] return clean
4425bb9ee3414e669d5cb0a925f09bc29fadcd49
678,197
import os def is_plugin(path: os.PathLike) -> bool: """Return True if the path has the extension of a plugin.""" plugin_exts = [".esl", ".esp", ".esm"] return os.path.splitext(path)[1] in plugin_exts
6d43b1abf226d0215f57255b27825ecdae4d01c3
678,198
def freestyle_table_params(rows, aging): """Returns parameters for OpenSQL freestyle request""" return {'rowNumber': str(rows), 'dataAging': str(aging).lower()}
f764202958acc29b4d21d481406ee029eedb28f6
678,199
def manhattan(point1, point2): """Computes distance between 2D points using manhattan metric :param point1: 1st point :type point1: list :param point2: 2nd point :type point2: list :returns: Distance between point1 and point2 :rtype: float """ return abs(point1[0] - point2[0]) + ab...
ed1d0b6ba47e107f2540b634d338de91d7048cec
678,201
import six def _sort_params(param_dict): """ Sort a key-value mapping with non-unique keys. """ param_list = [] for name, value_list in six.iteritems(param_dict): if isinstance(value_list, (list, tuple)): param_list.extend((name, value) for value in value_list) else: ...
ce1af3a6aabdddcea73323ce3906d65d8af6b5ba
678,202
def strip_if_scripts(if_outscript, if_inscript): """ Given an OutScriptIf and an InScriptIf satisfying it, return the "active" parts of them. I.e., if if_inscript.condition_value=True, return the "true" branch, else the "false" branch. :return: a 2-tuple of (OutScript, InScript) """ # extra...
5bcb9832761ee7eee4b703923c847e303e4c3547
678,203
def find_largest_digit(n): """ :param n: :return: """ # Base Case if n < 0: n = -n if (n/10) < 1: # 當只剩個位 return n # Self-Similarity else: # 在還有至少兩個位數的情況下 one = n - int(n/10)*10 # 獲得個位數值 tens = int(n/10) # 獲得十位數值以上=捨去個位 ten = tens - int(tens/10)*10 # 獲得十位數值 if one > ten: # 當個位數值大於十位數值 n = ...
95a289cda5fd4dac7673f67c6827baee0485b513
678,205
def get_num(num_lst): """最多只能将“元素”缩小到 2 个""" new_lst = [] n = len(num_lst) # 为了轮回 if n % 3 == 0: pass elif n % 3 == 1: new_lst.append(num_lst[-1]) # 防止看错:前面是 new_lst,后面是 num_lst n -= 1 else: new_lst.append(num_lst[-2]) new_lst.append(num_lst[-1])...
00773f6fd02bb305895ca8f66ecc9212ba7882fb
678,206
def getadminname(s,admindf): """Convert adminname from id_num to actual str name """ extractednamelist=admindf[admindf.id==s].name.values if extractednamelist: adminname=extractednamelist[0] else: adminname=None return adminname
e3a2b1ed96d877fee91ac37438f7cf31087565c2
678,207
import numpy def Define_SearchWindow(_noisyImg, _BlockPoint, _WindowSize, Blk_Size): """ return the coordinate of search window's reference point """ point_x = _BlockPoint[0] # current corrdinate point_y = _BlockPoint[1] # # get 4 coordinates LX = point_x + Blk_Size / 2 - _WindowSize ...
d3c358222a1e4c26160e9210b5c91a368dd3cf26
678,208
def findall_attr(xml, attr, value): """Find all matches, at any depth, in the xml tree.""" return xml.findall('.//*/[@{}="{}"]'.format(attr,value))
2df85d3ad616e503ae922b3e10eb6baefc5fe662
678,209
def should_ensure_cfn_bucket(outline, dump): """Test whether access to the cloudformation template bucket is required. Args: outline (bool): The outline action. dump (bool): The dump action. Returns: bool: If access to CF bucket is needed, return True. """ return not outli...
df675ba6b785f04fd2cd6f33378fa4b13281703a
678,211
def _wayback_timestamp(**kwargs): """Returns a valid waybackpy timestamp. The standard archive URL format is https://web.archive.org/web/20191214041711/https://www.youtube.com If we break it down in three parts: 1 ) The start (https://web.archive.org/web/) 2 ) timestamp (20191214041711) 3 ...
3c31b55f69517086bc18db5b4076a3ba097a6360
678,214
def lap_time_to_seconds(time_str): """Returns the lap time string as a float representing total seconds. E.g. '1:30.202' -> 90.202 """ min, secs = time_str.split(':') total = int(min) * 60 + float(secs) return total
8a0e6332aaf181c702d6608921a986223d5ec1b7
678,215
def _prompt_confirmation(msg): """ Prompt a confirmation message :param msg: The message to show :type msg: str :return: bool """ confirm_resp = input('{} y/n: '.format(msg)) return confirm_resp.lower().strip() == 'y'
1e9a7f0a1f92e87a6b4156f2e4f10c5273f0d13b
678,216
def process_instance(el): """ Process each 'process instance' element from the .mxml file and returns as dict """ resp = [] for entry in el[1:]: r = { "TraceId": el.get("id") } for item in entry: if item.tag == 'Data': r[ite...
502e7072ecdb89beae39d779e68138f4299c9027
678,217
def _tchelper(tc_deps,evals,deps): """ modifies graph in place """ for e in evals: if e in tc_deps: # we've already included it continue else: if e in deps: # has additional dependnecies tc_deps[e]=deps[e] # add to tc_deps the dependencies of the dependencies _tchelper(tc_deps,deps[e],deps) r...
46f47ff447f0179e4fdd2d5ceb4c020b7f4fe7a2
678,218
def Score(low, high, n): """Score whether the actual value falls in the range. Hitting the posts counts as 0.5, -1 is invalid. low: low end of range high: high end of range n: actual value Returns: -1, 0, 0.5 or 1 """ if n is None: return -1 if low < n < high: retu...
31e669223c2573c2fc8c28bf8b91570582de97d3
678,219
def add(x, y): """The usual hello world demo.""" # traceback.print_stack() return x + y
642ba017cbf1c9a79d80cc2ed7c771b0481f3e60
678,220
def _matches_section_title(title, section_title): """Returns whether title is a match for a specific section_title. Example: _matches_section_title('Yields', 'yield') == True Args: title: The title to check for matching. section_title: A specific known section title to check against. """ title =...
babe15b50ffbe46f7cc95469117a4b034e20ec0a
678,222
import os import csv def get_label_info(csv_path): """ Retrieve the class names and label values for the selected dataset. Must be in CSV format! # Arguments csv_path: The file path of the class dictionairy # Returns Two lists: one for the class names and the other for the label ...
a9237c52b33b47b91a4cdce107f3290fba585961
678,223
def _find_private_network(oneandone_conn, private_network): """ Validates the private network exists by ID or name. Return the private network ID. """ for _private_network in oneandone_conn.list_private_networks(): if private_network in (_private_network['name'], ...
f8a2835423a1738e518e7ee4ece1afc60df009ba
678,224
def postprocess(output_val): """ This postprocess simply returns the input ``output_val``. :param output_val: dictionary mapping output_data to output_layers :return: ``output_val`` """ return output_val
5188abd27c2c37ca646a4641d0f19f22558fee70
678,225
def mm2m(millimeters): """millimeters -> meters""" return millimeters/1000
4c31ed9df60b76ab0f7c8f0393c72f804da9aab1
678,226
import torch def _gen_mask(valid_step: torch.Tensor, batch_size: int, seq_len: int): """ Mask for dealing with different lengths of MDPs Example: valid_step = [[1], [2], [3]], batch_size=3, seq_len = 4 mask = [ [0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], ] """ as...
a4ff58133dd576ea833b34180007f466a329dd72
678,228