content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def say(number): """ Speak a number in English """ if number < 0 or number > 999999999999: raise ValueError("input out of range") if not number: return "zero" dct = { 0: "", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight"...
16cd6db8bcc6835042a28823dd92737b574eb9a4
635,139
def strip_block_whitespace(string_list): """Treats a list of strings as a code block and strips whitespace so that the min whitespace line sits at char 0 of line.""" min_ws = min([(len(x) - len(x.lstrip())) for x in string_list if x != '\n']) return [x[min_ws:] if x != '\n' else x for x in string_li...
b77ff928358ff095cd3bb7e5473d13f832f2157a
635,140
import copy def strip_revision_in_copy(doc_map): """ Strip the _rev field in a deep copy of doc_map and return it. :param dict doc_map: A dict representation of a JSON document. :return: doc_map itself without _rev """ new_doc = copy.deepcopy(doc_map) new_doc.pop("_rev", None) return new_doc
b0c5f7c2d674064effb270050aea654610eb90f4
635,141
def checkpoint2epoch(_checkpoint_name: str) -> int: """ Args: _checkpoint_name: e.g. 'epoch=2.ckpt' or 'epoch=2_v0.ckpt' Returns: _epoch: e.g. 2 """ return int(_checkpoint_name.split("epoch=")[-1].split("_")[0].replace(".ckpt", ""))
fb42c47aa29eba167e6469a8025b18bc00854de7
635,142
import re def is_ssh_destination(string) -> bool: """Check if string is a (more or less) valid SSH address (user@host:...).""" return bool(re.match(r'([^\s]+)@([^\s]+):(.*)', string))
06a85c7a25c9c9f40cbd7498402a92d0b89e0d78
635,144
def manual(path, value): # pylint: disable=W0613 """ Dummy function that returns it's input For tools that cannot be read automatically use a value from the toolkit file Parameters ---------- path : str Ignored value : str The value to return Returns ------- ...
86f03be0fb9af76a6a441db146e3f3ce8e6bb048
635,145
def serialize(errors): """Serialize errors.""" error_message = [] if errors: for error in errors: error_message.append('Schema validation: ' + error.message + '.') return error_message
e23a0a402c8cab1d9edb6e38630dc0dcf029f4d2
635,146
def uppercase(s: str) -> str: """ Convert a string to uppercase. Args: s (str): The string to be converted. Returns: str: The converted uppercase string. Example: >>> uppercase('completely different') == 'COMPLETELY DIFFERENT' True """ return s.upper()
f1ecb6e412ea3ce6e46531174881ad230bed3802
635,148
import os def symlink(srcPath, destPath): """create a symbolic link from srcPath to destPath""" return os.symlink(srcPath, destPath)
81e7bef5cbb0619a3c0d8eaa83ead563da73514c
635,149
def get_hcpmmp_mapping(): """Get the Glasser number : name mapping. Returns ------- mapping : dict The Glasser number : name mapping. In principle this could be a list that can be used with `enumerate` and +1, but people usually give regions via numbers so this should be most co...
cbea6a6b3c0a04e8ed8c034746b5ce502b7a99a5
635,150
def get_text_hv(angle): """Returns (ha, va) text horizontal and vertical alignment for line label. This makes the line label text inside its area, assuming areas closed CW. Args: angle (float): line normal vector in degrees, between 180 and -180 """ horiz, vert = ('', '') if abs(angle)...
f52819fb02b1248279de58e312a8fe9b77b16ab6
635,152
def order_of_execution(count: int, k: int): """ This one is linear time. :param count: :param k: :return: """ actions = 0 r = [*range(1, 1 + count, 1)] removed = [] pos = 0 while len(r) != 0: pos = (pos + (k - 1)) % len(r) removed.append(r.pop(pos)) ac...
7390e8a8bc28814acac4ce2f198685f23d823b91
635,153
def deepdiff(d1, d2): """ Calculates the minimal dict that need to be the input as u to deepupdate to get d2 from d1 :param d1: dict 1 :param d2: dict 2 :return: dict """ diff_dict = dict() k1_set = set() for k1 in d1: if k1 in d2: if d1[k1] != d2[k1]: ...
5337cab7f3864f5cce3808ca91a0d78ee8ee4209
635,154
def _incrementResourceVersion(version): """ Pyrsistent transformation function which can increment a ``v1.ObjectMeta.resourceVersion`` value (even if it was missing). :param version: The old version as a ``unicode`` string or ``None`` if there wasn't one. :return unicode: The new version, ...
d1d3675c0761b6818f05b2fd5174c367f76264f6
635,156
def load_words(file_name): """ file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters Depending on the size of the word list, this function may take a while """ print("Loading word list from file.....
54dd92f86b843d01bc2e7fb29002c9adf70c809e
635,157
import os def Daemonize(): """ Create a detached background process (daemon). Returns True for the daemon, False for the parent process. See: http://www.faqs.org/faqs/unix-faq/programmer/faq/ "1.7 How do I get my program to act like a daemon?" """ if os.fork() > 0: return False os.setsid() if os...
510aa34775f5e6f64371f19a7d608a1bd852178f
635,158
import torch def KL_divergence(mu, sigma, beta=1): """ Parameters ---------- mu : Tensor the autoencoder mean tensor sigma : Tensor the autoencoder standard deviation tensor beta : float (optional) the disentanglement coefficient (default is 1) Returns ------- ...
6e038f1dbf672ca66d6e6d39a7d99dff41849b10
635,159
import re def pattern_ylabel(y): """ pattern ylabel """ pattern_num=str(y) if y/10000 >= 1: pattern=r'(\d+)(\d{4})((,\d{4})*)' else: pattern=r'(\d+)(\d{3})((,\d{3})*)' while True: pattern_num,count=re.subn(pattern,r'\1,\2\3',pattern_num) if count==0: ...
8e60b62b50b104ba26ed0fa4213941d8b688a247
635,160
import yaml def load_yaml(file_path): """ Load a yaml file. Handles doc separation by loading all and combining into common dict. """ docs = yaml.load_all(open(file_path,'r',encoding='utf-8'),Loader=yaml.SafeLoader) data = {} for doc in docs: for key in doc: if key not in data: data[key] = doc[key] e...
a8ccd378e2b6e497e03d7111dffe58161b3c14c9
635,162
import torch def eccentricity(a, b): """ a : Semi-major axis b : Semi-minor axis """ # Handle tensor vs not tensor inputs a_not_tensor = False if not torch.is_tensor(a): a_not_tensor = True a = torch.tensor([a]) b_not_tensor = False if not torch.is_tensor(b): ...
80d963771da664390a276ce03a7c63c7ec3cebab
635,163
def make(quantity, units): """Entry point for creating quantities consistently :param quantity: The value to tag with specific units. :type quantity: ``_T`` :param units: The units of this quantity. :type units: :class:`~siquant.units.SIUnit` :rtype: ``_Q`` = :class:`~Quantity` """ retu...
d4feecbd467addd1cd3c2dcd043041e44b9a1141
635,164
import torch def masked_softmax(x, mask, temperature): """Compute softmax values for each sets of scores in x.""" x = x / temperature mask_min_x = x - ((1.0 - mask) * 1e20) mask_min_x -= torch.max(mask_min_x, dim=1, keepdim=True)[0] e_x = torch.exp(mask_min_x) e_x *= mask out = e_x / e_x.s...
0fcbbefba84ed3d8449e6e53e8a2eab1f97bcc9f
635,165
import ctypes def readFromFile(readable, c_struct): """Read ctypes structures from input.""" result = c_struct() chunk = readable.read(ctypes.sizeof(result)) ctypes.memmove(ctypes.byref(result), chunk, ctypes.sizeof(result)) return result
46ae487fa526650cd69dc737f981bafdd93abcde
635,166
def calc_frip(bamfile, ftfile, frip_func, pipeline_manager, aligned_reads_key="Aligned_reads"): """ Calculate the fraction of reads in feature file. Use the given function and data from an aligned reads file and a features file, along with a PipelineManager, to calculate. :param str...
b8f80799ed5fffb9eae886aa5651af7c53316c25
635,167
import sys def load_module(module): """Load a named python module.""" try: module = sys.modules[module] except KeyError: __import__(module) module = sys.modules[module] return module
38bf8b2a9e1e7ef2f06c52096a203f6fb6b6aaf0
635,168
import os import torch def load_pth(path, filename=None, obj_name=None): """ load an obj on the disk as .pth Args: path: supposed to be a string containing the path and filename if specifying just the path without filename, it is also ok so long as the filename is correctly set. ...
e2691971cc8e778913c86f60e4bdd9c2842f7b7e
635,169
def binconv(fp, fp_len): """ Converts 0 to -1 in the tokens' hashes to facilitate merging of the tokens' hashes later on. input : 1001...1 output : [1,-1,-1, 1, ... , 1] """ vec = [1] * fp_len for indx, b in enumerate(fp): if b == '0': vec[indx] = -1 return vec
6f856cad0fe1441d34d295b607fbda550aae1c8c
635,170
import re def remove_stop_words(stop_words, text): """ Description Parameters: ---------------- stop_words: list List of strings to remove text: string String to process Returns: ---------------- filtered: string String with stop words removed """ ...
6e76afea3a001d56ba552280fd20c50ff31dc9aa
635,171
def get_summary_stats(df,product): """ For certain products we want National Summary level information on the reports Return a list of the average quantity and price """ results = [] results.append(df[df["Product"]==product]["Quantity"].mean()) results.append(df[df["Product"]==product]["Pric...
11b7ac4bcef35b723213441777df433d4acaf1af
635,172
from typing import List from typing import Set def separate_and_add_alternative_lang_names( languages: List, sep: str = "/" ) -> Set: """ Takes a language list then separate language name that contains two alternatives by searching elements have two names (in default names is separated by '/') ...
098f8f3a784732b5e77718b02e02409119a68de6
635,173
def get_modified_fields(old_values, new_values): """ Return all fields that have been modified from original fields """ field_changes = {} for key, value in new_values.items(): try: original_value = old_values[key] except KeyError: """If there are addtional ...
deab00eb56ad13c02d7233e924f5cd1377872cba
635,174
def extensionmethod(func): """ Decorator that indicates that the method is a method that is intended to be extended by derived classes to override functionality (aka an "extension point"). Note that the class associated with the method must be based on an `Interface` for this construct to work prope...
39b606bc36a80785a424490bb9f1356efa9ee62d
635,175
def tokenize(text, nlp): """Word tokenize a single string. Parameters ---------- x: str A piece of text to tokenize. nlp: spacy tokenizer, e.g. spacy.lang.en.English By default, a spacy tokenizer with a small English vocabulary is used. NER, parsing, and tagging are disabled...
bb1106ea8f445329bd6e93bd91174948595d4ec8
635,177
def load_dfa(path_to_dfa_file): """ This function reads the DFA in the specified file and returns a data structure representing it. It is up to you to choose an appropriate data structure. The returned DFA will be used by your accepts_word function. Consider using a tuple to hold the parts o...
cfe38e804bda028a142006d2f49ae8152f88ca1b
635,178
def create_fraction_list(): """ Create a list of numerators and denominators. x/y < 0. No zeros. No 11, 22, 33, etc. In ref to PE 33 """ fractions = [] for numerator in range(10, 101): for denominator in range(10, 101): temp = set(str(numerator) + str(denominator)) if...
a259c0094404667f8b2d2dd3037bac8b5a15edaf
635,180
def _mapping_has_any(mapping, **key_values): """Test if a `Mapping` has any key/value pairs in `key_values` (by equality). Or: does `key_values` intersect `mapping` (as sets of key/value pairs)? >>> dct = {'A': 1, 'B': 2, 'C': 3} >>> _mapping_has_all(dct, A=1, B=2) True >>> _mapping_has_al...
8cbbeb363c8801957789832010283afcb0455a06
635,181
def blend(c1, c2): """Alpha blends two colors, using the alpha given by c2""" return [c1[i] * (0xFF - c2[3]) + c2[i] * c2[3] >> 8 for i in range(3)]
b5791e600d94304cea0f5cd69f908454709a4c4c
635,182
def parallel_helper(obj, methodname, *args, **kwargs): """Workaround for Python 2 limitations of pickling instance methods Parameters ---------- obj methodname *args **kwargs """ return getattr(obj, methodname)(*args, **kwargs)
41cea434b4d70a03ffa326f9663ccc55616e4191
635,183
def test_mask_none(dqarr, bitmask): """ Probes 'dqarr' to see whether NONE OF the bits in the specified mask are raised. :Parameters: dqarr: numpy array which represents a dq plane (or part of it). bitmask: integer A bit mask specifying any of the bits...
ebbe5996bafefebee5eaf89c5d7b4c1aa35ee55c
635,184
def get_layer_set(layer: str) -> str: """Layers in the same layer set share a config. Args: layer: Full name of the layer. This will be the PyTorch or Opacus name of the layer in lower case (e.g. linear, rnn, dprnn), prefixed with gsm_ (e.g. gsm_linear, gsm_dprnn) if DP is enabled. Mult...
3cef6d812bbc1951174f4e0da15308e239949eab
635,187
def _short_name(name): # type: (str)->str """ from my_package.sub_package -> m.s """ return ".".join(n[0] if n else n for n in name.split("."))
8ebfd2ceb27cb0ea832445f36d861b35b75cf12d
635,189
import torch def distribute(depth, _x, _y, size_x, size_y, image_height, image_width): """ Distributes the depth associated with each point to the discrete coordinates (image_height, image_width) in a region of size (size_x, size_y). :param depth: :param _x: :param _y: :param size_x: :...
cdf10f3c7532be10d593c63cbdab08fe2190166b
635,191
def selector(df, valtoextract=[], logfoldtohighlight=0.15, pvaltohighlight=0.1, minlogfold=0.15, minpval=0.1): """Part of Volcano plot: A function to separate tfs from everything else""" toshow = (df.pvalue < minpval) & (abs(df.log2FoldChange) > minlogfold) df = df[toshow] sig = (df.pvalue < pvaltohighlight) & ...
120b3baf7cb871e7c75a56d0edc97d13e9e6684e
635,192
def get_context(token_ids, target_position, sequence_length=128): """ Given a text containing a target word, return the sentence snippet which surrounds the target word (and the target word's position in the snippet). :param token_ids: list of token ids (for an entire line of text) :param target_po...
dca93971d2376efabf79b54263edfdca67236cfd
635,193
def get_optional_option(config, section, option): """Return an option from a ConfigParser, or None if it doesn't exist.""" if config.has_option(section, option): return config.get(section, option) return None
e4a7567a66075f19c71dd9175694c8e1ea758bc7
635,195
import time import os import random def message_id(domain): """ Return a string suitable for RFC 2822 compliant Message-ID. :param str domain: A fully qualified domain. :returns: An RFC 2822 compliant Message-ID. :rtype: :py:obj:`str` """ timeval = int(time.monotonic() * 100) pid = os...
eb53c3f9747a8821983f1e646350306745db918f
635,196
import requests def lineNotifyMessage(token, msg): """This function use line notify for sending message""" url = "https://notify-api.line.me/api/notify" headers = { "Authorization": "Bearer " + token, "Content-Type" : "application/x-www-form-urlencoded" } post = {'message': ...
36bc0eb266c45e14c77f2f82f6d55b5271e388d2
635,197
def pbb_to_dict(pbb_all): """ Function that takes the pbb_all array and turns it into a dictionary to be used and added to the pyart radar object. """ pbb_dict = {} pbb_dict['coordinates'] = 'elevation, azimuth, range' pbb_dict['units'] = 'unitless' pbb_dict['data'] = pbb_all pbb_dict['s...
05a1b4643d65f7928e1511ec626e1b84e663f34e
635,198
import os import pickle def load_variables(filename): """ Create or read from disk a file with all the variables for an image or a dataset. :param filename: Variables filename for an image in the dataset. :return: A dictionary containing the variables. """ if not os.path.exists(filename): ...
ce055d172430104018c4a056c477bf56d4381551
635,200
def collect_subset_scores(scorer_list, metric_name, tag_list, reset=False): """ Get the scorer measures of each tag. This function is only used by tasks that need evalute results on tags, and should be called in get_metrics. Parameters: scorer_list: a list of N_tag scorer object met...
4b7cf901b651b1e8e86c3708765b63418c4cbcbe
635,201
def _blocks_changed(block1, block2): """ Compare two Block objects Args: block1: The first block to compare block2: The second block to compare Returns: True if the provided blocks are different, False otherwise """ if block1.name != block2.name: return True ...
62366f781024f719bd4e7370eb59fb8acb206754
635,202
def _find_setup(hs, cabal, srcs): """Check that a Setup script exists. If not, create a default one.""" setup = None for f in srcs: if f.basename in ["Setup.hs", "Setup.lhs"]: if not setup or f.dirname < setup.dirname: setup = f if not setup: setup = hs.action...
48e3a781b3f33958a99f01d95c729b463fc11e46
635,203
def model_phylsowingdatecorrection(sowingDay = 1, latitude = 0.0, sDsa_sh = 1.0, rp = 0.0, sDws = 1, sDsa_nh = 1.0, p = 120.0): """ - Name: PhylSowingDateCorrection -Version: 1.0, -Time step: 1 - Description: * Title: PhylSowingDateCor...
79d41c4e41b2ac18ffae1f08027c3224c6ccfa6a
635,204
import paramiko import json def connect_to_sftp(): """ Uses paramiko to create a connection to Brendan's instance. Relies on authetication information from a JSON file. :return: SFTP_Client """ key = paramiko.RSAKey.from_private_key_file(r'/home/brendan/keys/lightsail.pem') client = paramiko.SSHClient() client...
e467469c811100d92b2c74c1f50bf0f43f5e2ee1
635,206
import copy import collections def stringify_keys(dictionary: dict): """ This helper function will stringify all keys in the given dictionary. For example: > from apps.authentication.models.user import Jobs > data = { Jobs.PTA: True } > stringify_keys(data) { "PTA": Tr...
db5a08fc106ce01ef90d37e896a24db2d143ce13
635,207
def fiber_packages(packages): """ Retrieve all packages of type 'Fibra' :param: list of packages """ lista = [] for pacote in packages: if pacote['tipo'] == 'Pacotes Fibra': lista.append(pacote) return lista
40669cfe3c134dbb82c8237bf8c18f62f8ad77df
635,209
def shift(coord, offset): """ (tuple, tuple) -> tuple Function shifts coord on defined offset and check correctness of shifted coordinates """ res = (chr(ord(coord[0]) + offset[0]), coord[1] + offset[1]) if "@" not in res and "K" not in res and 1 not in res and 11 not in res: return...
5c5ccba89203952829329afc19cc0c9244cb9b6e
635,210
def no_prefs_media(no_desc_media): """ For use when building GuestMedia records """ return no_desc_media
7135b6630ba4829fa5c8baea9a9d29550f8ad9ac
635,211
def test_group_division(): """ Find out if we can divide a group into bipartite? """ def bipart(G): # create adjacency list M = {} for a,b in G: if a not in M: M[a] = [b] else: M[a].append(b) if b not in M: M[b] = [a] else: M[b].append(a) ...
323d29d1934c7c7df099c4c8755d4e033395f236
635,212
import torch def gaussian_discrete_erf(window_size, sigma): """ Discrete Gaussian by interpolating the error function. Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py """ device = sigma.device if isinstance(sigma, torch.Tensor) else None...
0bbfd1c3fee5d5eeca6c83d2ee281301a57ce35a
635,213
def format_params(params, *args): """ Given a dictionary of parameters and a list of keys, return a list of values in the same order as the keys :param params: a dictionary of parameters that we're going to pass into our function :return: A list of the values of the parameters in the same order as ...
341db04bc6be9ae01f2516ae8ab0171feb313a4c
635,214
def get_id(vmfObject, idPropName='id'): """ Returns the ID of the given VMF object. """ return int(vmfObject[idPropName])
ffed36fe64194c5d9aeb5f154639b9f321b33a7d
635,215
import collections def build_toc_item(title, path=None, sub_items=None): """Create an item in the TOC. Args: title (str) - Title for this item. path (str) - Path to the page for this item. sub_items (list) - Items to place in a collapsible subsection. """ item = collections.OrderedD...
47f05ff4b7f63ff1dbcf52f0e87e19ddffab7d7c
635,217
def is_number(number: str) -> float: """Проверка на число.""" while True: try: return float(number) except ValueError: number = input('Неправильный ввод. Введите заново: ')
0844ddc497f8bec29845dfcf991ec779af54d8cf
635,218
def events(): """Returns the events to which you have access""" return [2717]
5649694c3f6819bfd4c7517cd27d6f15c703ca29
635,219
def __ExtractBasePath(target): """Extracts the path components of the specified gyp target path.""" last_index = target.rfind('/') if last_index == -1: return '' return target[0:(last_index + 1)]
de9b4ef1215d976cf10ec5120ea3c338949a4b24
635,220
import importlib def load_class(str_full_type): """ Load a python class given full qualified name. """ type_s = str_full_type.split('.') mod = importlib.import_module('.'.join(type_s[:-1])) cls = getattr(mod, type_s[-1]) return cls
b443517e67462c78129adc509f1c0e0282228a79
635,221
import numpy def find_nearest(doe, nominal_doe, choice_nb, proper_spacing, log_space=True): """Function that returns for each point in nominal DOE point, the indices and max relative error for choice_nb nearest points in feasible DOE. As a distance has to be computed to select nearest in further functions...
865f956ea22fac695697979e2387fd47c053c095
635,222
import os def large_object_file_path(): """ Resolve the file path to the large_object.json file. This is needed by `test_utils.py` as the `timeit` module is not able to resolve the path to the file correctly. """ file_path = os.path.abspath(__file__) directory = os.path.dirname(file_path) ...
7a9b2c3bd7afd9bff5491b473c61be23ea4b962b
635,223
def convert_hex_to_rgb_255(hex_str): """Convert hex color to rgb in range 0-255.""" hex_color = hex_str.lstrip("#") n = len(hex_color) rgb = list(int(hex_color[i : i + int(n / 3)], 16) for i in range(0, int(n), int(n / 3))) return rgb
f9034e0ad00f678226ed40afaa560ee27b416220
635,224
def get_user_email_opt(request): """ Perform email validation for the presqt-email-opt-in header. Parameters ---------- request : HTTP request object Returns ------- Returns the email address if the validation is successful. Raises a custom AuthorizationException error if the valid...
938c2678b03390b01c7636e6e555a36a6875ad3a
635,226
def setStimRate(stimTime_ms,framerate): """rewrite the stim-times to a new frequency Args: stimTime_ms ([type]): [description] framerate ([type]): [description] Returns: [type]: [description] """ for i in range(len(stimTime_ms)): stimTime_ms[i] = i*1000/framera...
7081c343172d9f731c657998a708a039bdde278d
635,227
from typing import List def nd_slice(d: int, dim: int = 0, start: int = 0, end: int = 1) -> List[slice]: """Create a multi-dimensional slice. Args: d (int): number of dimensions dim (int, optional): target dimension that will be sliced. Defaults to 0. start (int, optional): start inde...
c80d27ac36f714504435746fd6c71ed4387fb9d5
635,228
def filter_interface_conf(c): """Determine if an interface configuration string is relevant.""" c = c.strip() if c.startswith("!"): return False if c.startswith("version "): return False if c.startswith("interface"): return False if not c: return False return ...
997f2dc0729185d533e7069c1379c8fa9a4be646
635,229
def _find_or_add_model(model, umap, keys): """Return integer node for given valuation. If absent, then a fresh node is created. @type model: `dict` @type umap: `dict` """ u = tuple(model[k] for k in keys) u = umap.setdefault(u, len(umap)) return u
12f1eac8512cdd448fa75eed2708d57f625558f9
635,230
import torch def assemble_recon_data(heldin, heldin_forward, heldout, heldout_forward): """Combines heldin/heldout and observed/forward data into a single tensor. Parameters ---------- heldin : torch.Tensor A BxTxN tensor. heldin_forward : torch.Tensor A BxT_FWDxN tensor. ...
98708f51f624c4c8c7f11363aa20afd63836f86e
635,231
import socket def getfqdn(): """Get fully qualified hostname.""" hostname = socket.gethostname() if '.' in hostname: return hostname return socket.getfqdn(hostname)
b61b1fb940e708cc113582d9d729ab698eaf1553
635,232
from typing import Dict from typing import List def sort_ranking(dictreplica: "Dict", client_location: "Dict") -> "List": """ Return a list of replicas sorted by ranking metric. NOT IMPLEMENTED :param dictreplica: A dict with replicas as keys (URIs). :param client_location: Location dictionary contain...
20bd08a381909c38888407f20936f0ef340acc3b
635,233
def predict_next_element_recursive(lis, base_case, reduce_function, inference_function): """ :param lis: the list to predict the next element of :param base_case: each iteration would be given the current list. if it returns None we continue the recursion, otherwise we assume that the returned value is...
aefa33316b6628f918969ac93718b33d1eafef54
635,234
import glob import os def retrieve_listof_files_from_dir(directory, file_type='*'): """"Returns a list of files of a directory""" return glob.glob(os.path.join(directory, file_type))
0e749d889ca7834c6f0f3509284b81d1316a3f76
635,235
def prepare_query(site_id: str, condition: str) -> str: """ Creates GraphQL query :type site_id: ``str`` :param site_id: Site ID entered by user :type condition: ``str`` :param condition: filter conditions :rtype: ``str`` :return: GraphQL query """ query = """query getAssetRes...
d086064c472306c0039ae8e92d3cb37aea3d6d67
635,236
import os def genmask(): """Generates a random masking key for a WebSocket frame.""" return os.urandom(4)
0042fb6300cc73b966ff8ae9ff3b139f0ef90fd6
635,237
import re def quick_regexp(input_line,regex,**kwargs): """ Simplified implementation for matching regular expressions. Utility for python's built_in module re . *Previously named QuickRegexp* Tip: Design your patterns easily at [Regex101](https://regex101.com/) Args: input_line (...
7906de25d674165f42e1a559976eb0c7710267b3
635,238
import json def load_categories(annotation_file): """Load categories to be global categories.""" with open(annotation_file) as fobj: ann = json.load(fobj) return {c["id"]: c for c in ann["categories"]}
ef826145026cecb7b9ab1f078b5a37ffbe4bdd15
635,239
def _quote(filename, protect = "="): """Quote the filename, by escaping = by \\= and \\ by \\\\""" return filename.replace("\\", "\\\\").replace(protect, "\\" + protect)
8b1605f7ff7a0948bf99f47dbcff5c4587ab03b5
635,240
import os def get_img_path(target_path: str) -> str: """Returns path to a full image in TCAV results folder structure base in concept path""" base_dir = "/".join(target_path.split('/')[:-2]) img_ind = str(int(target_path.split('/')[-1].split('_')[1][:-4]) + 1) file_name = (4 - len(img_ind)) * '0' + im...
41d57ad46567153811d2d2d7bc5f4f87a8014f91
635,241
def gcd(x: int, y: int) -> int: """정숫값 x와 y의 최대 공약수를 반환""" print(x, y) if y == 0: return x else: return gcd(y, x % y)
7c836a10d15d7d8f0485707e2af26cad801bb563
635,242
def get_bool_from_text_value(value): """ to be deprecated It has issues, as accepting into the registry whatever=value, as False, without complaining """ return (value == "1" or value.lower() == "yes" or value.lower() == "y" or value.lower() == "true") if value else True
1995c1afa00a6ecc52ef1fab67762ab962c84d5a
635,243
def fully_qualified_name(type_: type) -> str: """Construct the fully qualified name of a type.""" return getattr(type_, '__module__', '') + '.' + getattr(type_, '__qualname__', '')
d7a8f2313ca6db3fd9baaf1f275c8f404f7ac091
635,244
def is_passed_counting_roi(current_point, first_point, roi_polygon, roi_outside, is_enter): """ will check if the point passed the counting roi. if the current location in the roi and the first location not in the roi - it passed if the current location not in the roi and the first location in the roi - it ...
d48a158db0251a4ef64ec472d024029cf5f8ef8d
635,245
def _capped_double_heads(num_heads, cap=16): """Calculate the number of heads for the attention layers with more heads. The number of heads will be twice the normal amount (num_heads), until it reaches |cap| heads. Args: num_heads: the num_heads hparam for the model. cap: the maximum number of heads |...
b61bcb1a4fba933c1b17e7320cc73eeabb35dc59
635,246
def convertToFixedSize(aidx, labels, boxes_deltas, bboxes): """Convert a 2d arrays of inconsistent size (varies based on n of objests) into a list of tuples or triples to keep the consistent dimensionality across all images (invariant to the number of objects) :returns label_indices, bbox_indic...
20dfd472b8fc23fede5cc11b8dc80d770d0c840b
635,247
def is_only_preceded_by(string: str, to_find: str, preceded: str) -> bool: """ check if an element in a string is only preceded by the indicated character, even multiple times. Raise an ValueError if to_find is not found :param string: the string to search in :param to_find: the string to searc...
0e2d576c7250a58b139802c8058669112e514a69
635,248
def get_leaps(): """ Gets a list of GPS times for when leap seconds occurred """ leaps = [46828800, 78364801, 109900802, 173059203, 252028804, 315187205, 346723206, 393984007, 425520008, 457056009, 504489610, 551750411, 599184012, 820108813, 914803214, 1025136015, 1119744016, 1167264017]...
7ec7d403655715e48e3850dcfe9b30c2d268d84a
635,249
def request_queries(resource_model, object_ids): """Collect queries corresponding to given object_ids :param ResourceModel resource_model: :param object_ids: :return ResourceModel, List[int|byte], queries: """ object_ids = [ i for i in object_ids if ( i in resour...
198087b1fb1fda20293e7aebd0be3bbf6e138d29
635,250
def db_connection_string(request): """ :type request: _pytest.fixtures.FixtureRequest :rtype: str """ cmd = request.config.getoption("--db-connection") return cmd if cmd else "postgresql://postgres:postgres@localhost/gold-digger-test"
01aedc7a32a347d69ecae998bf9a8bd2e91c2d3a
635,251
def get_comment(uid): """ return comment for variable """ return uid.description
d9db3ba0408e067236d267741b707e3ed428ad6f
635,253
def _extract_args(frame): """ Extract the arguments given to the function called in the given frame. :param frame: the frame from a traceback object :return: None if there were no arguments, otherwise a tuple of the function's arguments. """ # Number of arguments given to the function. ...
fd2ff2a53e3dd606be865296d7e2658b28717740
635,254
def _2str(unit): """ Convert unit list to str """ if not isinstance(unit,list): raise TypeError('Input required as <list>!') return ' '.join([str(u) for u in unit])
a90f2ae6be0566645ede63dc28046ec6598c8705
635,256
def sub_block_values(config, key): """Extract set of values associated with a sub block key Parameters ---------- config : str Path of the config file. key : str Sub block key (e.g. "SubCategory") Returns ------- set(str) Unique values of the given key """ ...
3e52aeeae05ef8f57dac1a2a85de055cec10afac
635,257