content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def char_word_tokenize(text): """分词器、中文单独成词,英文单词、连续数字作为一个词""" # 大写转小写,繁体转简体 text = zhconv.convert(text.lower(), 'zh-cn') # 全角转半角 text = full_to_half(text) tokenized_chs = [] text_len = len(text) i = 0 while i < text_len: ch = text[i] # 中文字符 if ch in all: ...
9c788bc185f80dd9304534e30a756918389a2375
3,615,196
import json import traceback def anomalyService(dimValObj, dfDict, anomalyDefProps, detectionRuleType, detectionParams): """ Method to conduct the anomaly detection process """ df = pd.DataFrame(dfDict) anomalyId = dimValObj["anomalyId"] dimVal = dimValObj["dimVal"] contriPercent = dimValO...
bc97fd19c804121cd6694fe907153bb1ea975121
3,615,197
def binarySearch(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return -1 left, right = 0, len(nums) - 1 while left + 1 < right: mid = (left + right) // 2 if nums[mid] == target: return mid elif n...
71d2077f69002ba6e554576f569f8a85a596a0ec
3,615,198
def tokenize(text): """ Function that tokenizes an input text string Parameters: text (str): Input text Returns: list (str): List of tokens extracted from the input text """ tokens = word_tokenize(text) lemmatizer = WordNetLemmatizer() clean_tokens = [] for t...
36ab3cc6c679f5a5a45e3559fbcd405b5c04c387
3,615,199
import _asyncio def threaded_async(func: _typing.Callable): """ Helper decorator used to resolve future in a thread-safe manner. """ future: _typing.Coroutine = func() def _call(): """ Inner function used to resolve the future correctly. """ return _asyncio.run_cor...
3da1397cb382066124fd121d7ab93a45471356a9
3,615,200
def barycenter(P, K, reference="debiased", **kwargs): """Compute OT barycenter.""" ndim = P.ndimension() if ndim > 3 or ndim <= 1: raise ValueError("Data dimension must be 2 for 1d distributions" " or 3 for 2d distributions.") if reference == "debiased": if ndim ...
14ac0b7764bebacdfa6afeede31a544d4c0fca41
3,615,201
def map_serial_number(facilities) -> str: """Map serial number.""" facility = facilities.get("body", {}).get("facilitiesList", [])[0] return str(facility.get("serialNumber", None))
81491de02a2583d30ee31833a427b4ffdebe6a88
3,615,202
def get_shape_xyz(self): """Return the mode shape in cartesian coordinates. Parameters ---------- self : Mode a Mode object Returns ------- shape : ndarray ndarray of the shape (Nnodes*Ndof) """ if self.shape_xyz is not None and self.shape_xyz.size != 0: re...
dea33ea0dccc2196f2ee5676136f88436a22c603
3,615,203
def product_check(product_name): """ Check if product name already exists in the database """ if mongo.db.products.find_one({"name": product_name}): # Display flash message flash("Product " + product_name + " already exists in the database", "warning") product_check...
af7ac0716d92cd1f71bcba2e574c4ca0e0c37078
3,615,204
import hashlib def get_atoms_id(atoms: Atoms) -> str: """ Returns a unique ID for the Atoms object. Note: The .info dict and calculator is excluded from the hash generation. Parameters ---------- atoms .Atoms object Returns ------- md5hash MD5 hash of the .Atoms o...
a37bc45d0638908cc782c75b0d87b233b7be58e7
3,615,207
def get_payees(): """Loads the payees override file""" return load_config_file("payees")
daead676fbb137528fbd55104096660e317a174c
3,615,208
def _get_maxmem(profile_df): """ Get current peak memory :param pandas.core.frame.DataFrame profile_df: a data frame representing the current profile.tsv for a sample :return str: max memory """ return "{} GB".format(str(max(profile_df['mem']) if not profile_df['mem'].empty else 0))
2e628d48f7b4e0e3c1465f09da7aa795d2954a06
3,615,209
def read(file_ref, **kwargs): """Read a LAS file. Note that only versions 1.2 and 2.0 of the LAS file specification are currently supported. Arguments: file_ref (file-like object, str): either a filename, an open file object, or a string containing the contents of a file. Retu...
8582381412814a42b73f3ca3551ea5c4843e47e0
3,615,210
def mk_sentence(_id, topic, category, title): """ e.g. [테슬라-모빌리티] 👀 테슬라가 승차공유 서비스 Tesla Network를 출시합니다. https://snak.news/newsList/news/208?channel=slack&corp=pozalabs""" link = SNAK_URL.format(_id=_id, corp=CORP) return f"[{topic}-{category}] {title} {link}"
665f97aa47f9a8d13a6b33de34524f8efb5177a8
3,615,211
from loopy.kernel.instruction import BarrierInstruction def get_global_barrier_order(kernel): """Return a :class:`tuple` of the listing the ids of global barrier instructions as they appear in order in the kernel. See also :class:`loopy.instruction.BarrierInstruction`. """ barriers = [] visit...
34faf08b5a1382928b5a9efce5a3242c71ac8488
3,615,212
import torch def MaskedNLL(target, probs, balance_weights=None): # adapted from https://gist.github.com/jihunchoi/f1434a77df9db1bb337417854b398df1 """ Args: target: A Variable containing a LongTensor of size (batch, ) which contains the index of the true class for each corr...
17132ad088b00ae096f16946f5026ed2133c8eeb
3,615,214
def count_triangle(tbl_name, conn): """ input is a matrix """ tol = 0.1 b = 'b' lim = 10 cur = conn.cursor() tn = tbl_name print "create matrix..." create_vector_or_matrix(b, conn) print "Counting dimension..." calc_dim_query = "select max(row), max(col) from %s" % (tn) cur.e...
3de7085dffebf052cb033207097c5f472f9a5979
3,615,215
async def process_headers(headers): """Filter out unwanted headers and return as a dictionary.""" headers = dict(headers) header_keys = ( "user-agent", "referer", "accept-encoding", "accept-language", "x-real-ip", "x-forwarded-for", ) return {k: header...
32feeb40c12c4b69d65da1c178e396e85fc9e557
3,615,216
def Bound_EXT(S, Ex, boundaries): """ This function computes the extension of a signal for filtering purposes :param S: The Input signal :param Nf: The Size of the Kernel (must be an odd number!) :param boundaries: The type of extension: ‘reflect’ (d c b a | a b c d | d c b a) The inpu...
273d2e5d9999fc2b4ee452c8a8d6d064f567f403
3,615,217
from typing import Tuple def infer_dtype_from_array( arr, pandas_dtype: bool = False ) -> Tuple[DtypeObj, ArrayLike]: """ Infer the dtype from an array. Parameters ---------- arr : array pandas_dtype : bool, default False whether to infer dtype including pandas extension types. ...
0af3cebe46d10328faa3a9b6f469c0e1956f0cec
3,615,218
def np(url): """ Transforms a reddit link into a no participation URL (which in some subreddits hides voting arrows, to help prevent administrator shadowbans. :param url: URL to transform :return: A no participation (NP) link """ url = urlparse(url) return "https://np.reddit.com{}".forma...
b4b3006b423f0b1f1a6abc7cb8e98c8564658c4d
3,615,219
import torch def sample(method, clf, x0, start, sampling_method, n_samples=[50_000, 100_000], prior=None, inn_prods=None, theta_kern=None): """ Uses a density ratio estimator clf to sample from the posterior for x0 and prior. Inputs: - method: str, either "signature" or "gru-resnet" depending on which ...
dada3aa971f3c02b76520301d7a8813b64c9ed3a
3,615,220
from typing import Tuple def get_current_and_head_revision( database_url: str, alembic_config_filename: str, alembic_base_dir: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]: """ Returns a tuple of ``(current_revision, head_revision)``; see ...
ca9040343be556e831ff6c4220ca5d9451c2c556
3,615,222
def extract_root(pitch): """ Try to extract an integer root from a non-integral pitch """ if isinstance(pitch[0], Fraction): pitch = pitch + 0 root = 1 while True: d = 1 for coord in pitch: if coord.denominator > 1: d = ...
8cda1bf8daef0b948512a720130a5cf28670e5f0
3,615,223
def mean_abs_mismatch(slice0, slice1): """ Mean absoute difference between images """ return np.mean(np.abs(slice0 - slice1))
d8e66d3b4eea3bc921f8f5f47e75d9fcb7d34dc4
3,615,228
def loads(payload, **kwargs): """ Deserialize an object from a bytestring. :param bytes payload: the bytestring to serialize :param kwargs: keyword arguments passed to :class:`~.CBORDecoder` :return: the deserialized object """ fp = uio.BytesIO(payload) return CBORDecoder(fp, **kwargs).d...
9a320636a6eccc43a5b0c7782300e24dde74bad7
3,615,229
def calc_acc(fn: float, fp: float, tp: float, tn: float) -> float: """ :param fn: false negative miss :param fp: false positive or false alarm :param tp: true positive or hit :param tn: true negative or correct rejection :return: accuracy """ return (tp + tn) / (tp + tn + fn + fp)
cd790df66fe1f1537ed700e2a453b383390fee3f
3,615,230
import ray def errors(all_jobs=False): """Get error messages from the cluster. Args: all_jobs: False if we should only include error messages for this specific job, or True if we should include error messages for all jobs. Returns: Error messages pushed from the c...
1f79618dde4ad0f61d814f48c5b3f3388594df77
3,615,231
def _gen_test_tree_4(): """ Not BST 5 3 9 2 10 6 8 """ tree = BinaryNode(5) tree.left = BinaryNode(3) tree.left.left = BinaryNode(2) tree.left.right = BinaryNode(10) tree.right = BinaryNode(9) tree.right.left = BinaryNode(6) tree.right.right = BinaryNode(8) r...
0e9f67bbc85c71f67918fb47099ecbb635688d10
3,615,233
def by_circ(x, y): """ Sort circRNAs by the start and end position """ return x.end - y.end if x.start == y.start else x.start - y.start
5d8205389960b92f10c450fdb6385678a279406b
3,615,234
import yaml def get_rest_of_manifest_values(): """ If an existing manifest is present then we do not want to overwrite any fields the user may have filled out. So we want to read in everything but the resources: section and use that when generating the file. """ stream = open('hardening_manifest/harde...
03cc8afbcdf26a91596d189bafecce08c9cf2895
3,615,235
def ConvertJsonIntoDict(string): """Read a JSON string and convert its contents into a Python datatype.""" if len(string) == 0: print >> sys.stderr, ('Error could not parse empty string') raise Exception('JSON data missing') try: json = simplejson.loads(string) except ValueError, e: print >> sy...
899e7613928848b334da014bcbb870787068d590
3,615,236
def process_html(body): """Transform a screen-optimized HTML body to a mail-optimized one. Relies on :class:`premailer.Premailer` to include styles in HTML body and optimize content. Args: body (str): The HTML string to process. Returns: :class:`str`: The processed HTML mail body....
d281eed35ebd6e8f46a2f97ed2ab58c411492a7d
3,615,237
def img_crop(img, length, cx=None, cy=None): """ Crop the image to square (length^2). If cx and cy are not specified, it will set to where the max pixel count is. I: plt.imread() length: pixel sizes cx, cy: center pixel of the image """ if not (cx and cy): cy, cx = unravel_index(...
7f94b7adc90b53d4bceee8ee880f54aad2bf86a4
3,615,238
import requests import json def post_special(url, param: dict = None): """ 发送 post 请求,主要是参数中的ddjm等参数,可能用于防火墙拦截 :param url: url :param param: param dict :return: 返回json中的data域 """ param_json = COMMON_PARAMS.copy() param_json.update(param if param is not None else {}) response = requ...
8afa3fb936fff574a2f43a81044857f40f0ac7c9
3,615,239
def evaluate_f1_update_confusion_matrix(df, new_rule, class_col_name, counts, min_max, classes): """ Computes the F1 score of the dataset for a given set of rules using leave-one-out cross-evaluation. Assumes that the initial confusion matrix already exists, hence evaluate_f1_initialize_confusion_matrix() s...
17c91fdd00ab6ed3af6419092f85a7f57452ecb3
3,615,241
import time import torch def forward(model, generator, return_input=False, return_target=False): """Forward data to a model. Args: model: object generator: object return_input: bool return_target: bool Returns: audio_name: (audios_num,) clipwise_output: (aud...
f43724008956b7f0695ccd28ab41bab380ebaf4e
3,615,242
def corrfun_mat(image_dict): """ A useful fixture containing the correction function evaluated over the range of the sky plane test image. """ ra = image_dict["ra"] dec = image_dict["dec"] # pre-multiply the image by the correction function return spheroidal_gridding.corrfun_mat(np.fft.ffts...
33a487037f1f7edb7eb5d924f5b1a40569dcf76e
3,615,243
from typing import List def get_nft_info_from_puzzle(nft_coin_info: NFTCoinInfo) -> NFTInfo: """ Extract NFT info from a full puzzle :param nft_coin_info NFTCoinInfo in local database :return: NFTInfo """ uncurried_nft: UncurriedNFT = UncurriedNFT.uncurry(nft_coin_info.full_puzzle) data_ur...
5f88a25b38308db1cc04beb5f84a0d960cc241cc
3,615,244
def fix_masks(masks, indices): """Remove from every mask any common pixels with another mask""" new_masks = [] for ind in indices: mask = masks[ind] for ind1 in indices: if ind != ind1: mask = np.logical_and(mask, np.logical_and(masks[ind], np.logical_not(masks[in...
ca8b043274ace6376d9af03cb912e9195d36ca73
3,615,246
from typing import Sequence def barnsley_fern(range_x: Sequence[float], range_y: Sequence[float], steps: int = 20, samples: int = 20000 ) -> tuple[np.ndarray, np.ndarray]: """Generates a Barnsley Fern Args: init_x: x coordinates of the starting points init_...
e717d34f4b8f737325b53d62f1aac6c8cb6cfe03
3,615,247
def handle_choice(uid): """ This function handles the choice of the user. """ print("Type 'Back' to go back.") choice = input("Enter Code > ") if choice.lower() == "back": show_menu(uid) else: return search_for_choice(uid, choice)
8f1c40d036c8322e33e93ded7f67515dc7004e7e
3,615,250
from typing import Union import torch from typing import Optional from typing import Tuple def get_window(window_type: str, window_size: int, device: Union[str, torch.device], periodic: Optional[bool] = True, padding: Optional[Tuple[int, int]] = (0, 0) ...
f5c0a0ffb509da788fb75f9bd152997abcc2814a
3,615,251
import base64 def process_log_token(logtoken): """ processLogToken retrieve username and password from a given login token (!)Override this method to manage more complex and secure algorithms; tester code uses the following encrypted string to store user credentials: username=<userna...
e4566b4242e172f2699010851760668a6ac18a6e
3,615,252
def _normalize_longitude(lon: float) -> float: """Normalize longitudes between [-180, 180]""" return ((lon + 180.0) % 360.0) - 180.0
e50dc8fee9a0499a2e32f3ccf8b2e9a634581bba
3,615,253
def get_objection_text(): """ Client sends a list of objection ids, we respond with a dictionary of id:text elements. """ objection_labels = request.form.getlist('objections[]') result = [] for label in objection_labels: objection_text = DATABASE.get_objection_text(label) res...
7d02712641162b5e596649a2cbf7e4a93cfca4b2
3,615,254
def test_fallback_max(): """ Feature: JIT Fallback Description: Test max() in graph mode. Expectation: No exception. """ @ms_function def foo(): x = max([1, 2, 3]) return x assert foo() == 3
ae79e6f910c63280cfaacc3f4795a22402cf679f
3,615,255
def get_tf_tensor_shape(tensor): """Get tensor shape, if there is unkown tensor, set it as None""" shape = [] try: shape = tensor.get_shape().as_list() if any(s is None for s in shape): return None return shape except Exception: # pylint: disable=broad-except shape = None return shape
33c7e17102ad2f7d407c1f86b13c7cdfa61ca677
3,615,256
def _update_selected_experiment_table_rows( last_select_click, last_clear_click, experiment_table_indices ): """The callback to select or deselect all rows in the experiment table. Triggered when the select all or clear all button is clicked. """ last_select_click = last_select_click if last_select...
7a527272c780750ea9cbc076f0d947fe9b68a460
3,615,257
from typing import List from typing import Counter def get_answer_slow(input_data: List[str], steps: int) -> int: """ The iteration in process(template, rules) causes the program to run out of memory on large steps Use get_answer instead """ template, rules = parse_input(input_data) for i in ...
a1b0b9abbcf7c351388171598efbdfe8c80d13e7
3,615,258
from typing import List def get_strategies() -> List[MaskingStrategy]: """Returns all supported masking strategies""" return [e.value for e in SupportedMaskingStrategies]
7223f8433fb22fea4a772838875b9aba29af608a
3,615,259
def rc4Decrypt(data, key): """RC4 algorithm""" x = 0 box = list(range(256)) for i in range(256): x = (x + int(box[i]) + int(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 ...
91c959cf03410626378647ab6d85391e5b0970d2
3,615,261
def _move_tutor_version_groups(table): """Tutored moves are never the same between version groups, so the column collapsing ignores tutors entirely. This means that we might end up wanting to show several versions as having a tutor within a single column. So that "E, FRLG" lines up with "FRLG", there h...
5b9d43a11d5e5d92351ac5b93a7ada5b8d5daa36
3,615,262
def load_from_module(path=None, workspace=None): """Load opener interface from path or from python environment. Opener can be defined as an Opener subclass or directly has a module. Return an OpenerWrapper instance. """ interface = utils.load_interface_from_module( 'opener', interf...
ad780aeeb518ef3d7b5a1d30eafb4b8c4c1ef802
3,615,263
import textwrap def make_code_format(light_theme: bool = False) -> str: """Create code format template for rich.""" theme = "light" if light_theme else "dark" code_format = textwrap.dedent( f"""\ <div class="terminal-container"> <div class="terminal {theme}-terminal"> ...
deb5d97f3bce85c1ef91d4c9e88b68474d70c173
3,615,266
import anyio def mqtt_connected(func): """ MQTTClient coroutines decorator which will wait until connection before calling the decorated method. :param func: coroutine to be called once connected :return: coroutine result """ @wraps(func) async def wrapper(self, *args, **kwargs...
54af1ef8b33aa336fb5703d9d2d2b668fbbec8fe
3,615,267
def to_canonical(fn, self, arg, orig_t): """Check and convert an argument to the canonical representation. Arguments: arg: The argument to convert. orig_t: The type of the argument as returned by to_abstract. Returns: A version of the argument where classes/dicts become tuples ...
d87d9ef2e4f1f6be8d356a8ef22959d5fba690ae
3,615,268
def copy_dsa(data: dsa.PolyData) -> dsa.PolyData: """Deep copy a PolyData""" res = dsa.WrapDataObject(vtk.vtkPolyData()) res.VTKObject.DeepCopy(data.VTKObject) return res
0bb0e6fb5160f730c59db7a5692f7de560f408f7
3,615,269
def modify_network_interfaces( self, if_info: list, ) -> bool: """Modify interface information on appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - networkInterfaces - POST - /networkInterfaces :pa...
dcf22de0d88927d1c217f08d744ea18a426c7633
3,615,271
def _wrapped_value_and_num(value): """Returns a list containing value plus the list's length.""" if isinstance(value, (list, tuple)): return value, len(value) else: return [value], 1
811521a18dffd9ee046751c74d4d8a097662c8cd
3,615,272
def perform_fit(cfmclient, fabric_uuid, name, description): """ Request a full fit across managed Composable Fabrics. :param cfmclient: CFM Client object :param fabric_uuid: Valid Fabric UUID of an existing fabric :param name: Simple name of the fit :param description: Longer Description of the ...
66d6462c97b1354ef11b6378b82912030ed40a94
3,615,273
def __get_host_vol_dict(k8s_conf): """ Returns a dict of configured host volumes where the key is the name and the value is the size :param k8s_conf: the k8s configuration used to deploy the cluster :return: dict :raises Exception """ out = dict() host_vols = config_utils.get_host_vo...
2ecef222fa183821e8d4092bd3d648e7b0a363de
3,615,274
def normalize(value, *normalizers, **options): """ normalizes the given value. :param str value: value to be normalized. :param str normalizers: normalizer names to be used. they will be used in the order of their appearance. if not provided, all...
04ce63808264784fee26263fb903468d7d39c3a5
3,615,275
def rescale(image): """ If the input video is other than network size, it will resize the input video :param image: a frame form input video :return: scaled down frame """ scale_side = max(image.shape) # image width and height are equal to 192 scale_value = config["input_width"] / scale_...
0033043752e0d1d5cd58b07734655f61954a44b4
3,615,276
def remove_noise(frame): """ Remove noise using morphological operation: erode, then diate.""" ### Morphology: Opening ### kernel = np.ones((3,3),np.uint8) frame = cv2.morphologyEx(frame, cv2.MORPH_OPEN, kernel, iterations=1) return frame
8dc4af1fd93e8b652f665c98f968b16b92f3922b
3,615,277
def get_instrument_names() -> np.ndarray: """Return the names of each instrument in the metadata cache.""" image_metadata = preprocessing.image_meta.read_metadata() return np.unique(image_metadata["Instrument"])
af187f618d2300cacc1b7ef80937ee32edc65c76
3,615,280
import tempfile def get_reads_with_subseq(subseq: str, run: Fast5run, outfile=None, revcompl=False): """ Get all reads containing specific subsequence :param subseq: sequence to be looked for :param run: Fast5run object, where to search :param outfile: file, where the selected reads should be wri...
458ed02ac0bc76a85c8b629f5feb85f39451222b
3,615,281
def qnt_jogadores(): """ -> Irá ler o arquivo de configurações e analisar o parâmetro "qnt_jogadores" :return: retornará o valor do parâmetro """ try: linha = ler_linha(linha=2, inicio_linha_index=15) return int(linha) except: raise FileNotFoundError("Arquivo não encontra...
ac51b1c5cce84d0bf20faac8c989ab6864553ada
3,615,282
def connected_amp_protocol(): """ :return: ``AMP`` hooked up to transport. """ p = AMP() p.makeConnection(StringTransport()) return p
2128d7bdfea66f8bef70ec34ef5236bb90be12dd
3,615,283
def check_converge(pf, abs_tol=1e-4): """ Return Y/N, converged pf/ raw pf, relative changes """ is_converge = isConverge(pf, abs_tol) if len(pf) >= 2: abs_err = abs(pf[-2]-pf[-1]) else: abs_err = None if is_converge: res = (True, pf[-1], abs_err) else: ...
9f29034d682ba280c4da576e02680b7c5b1a313f
3,615,284
def extract_trajectories(n_true, n_tot, idxs, threshold): """Extract frequency trajectories for different positions on the genome. See the documentation of `extract_trajectory`""" times = sorted(list(n_tot.keys())) trajs = {} for idx in idxs: trajs[idx] = extract_trajectory(n_true, n_tot, id...
58d4e9f493cda9f27bf3f5ae77255c1987071406
3,615,285
import logging import pickle def load_file(file_adress: str): """ load data from file of type pickle, intended to be used with the method save_file, check if the file exist before open. args: file_adress: full adress to the file to be open returns: if the file exist returns the content, ...
91c4cbe19a8c39cf17d7cce20cce06c973ca0d1e
3,615,286
import torch def straight_through_estimator(input: torch.Tensor) -> torch.Tensor: """ straight through estimator >>> straight_through_estimator(torch.randn(3, 3)) tensor([[0., 1., 0.], [0., 1., 1.], [0., 0., 1.]]) """ return _STE.apply(input)
f07588cb723819e7003780552b06ab04e4ab0e76
3,615,287
def bbox_transform_inv(boxes, deltas, mean=None, std=None): """Adjust boxes based on deltas Args boxes : collection of box in the format (x1, y1, x2, y2) deltas : amount of shifting needed to be done to each box mean : fixed distance to shift in each direction std : degree...
f240cf7832aac3522c2c20a996acff26af3e1576
3,615,288
import shutil def os_zipfolder( dir_tozip="/zdisks3/output", zipname="/zdisk3/output.zip", dir_prefix=True, iscompress=True ): """ shutil.make_archive('/zdisks3/results/output', 'zip', root_dir=/zdisks3/results/', base_dir='output') os_zipfolder('zdisk/test/aapackag...
a8baabf165c957a2d23a40842259432724b40b91
3,615,289
def make_task_hashable(task): """ Makes a task dict hashable. Parameters ---------- task : dict task that shall be made hashable. Returns ------- TYPE hashable task. """ if isinstance(task, (tuple, list)): return tuple((make_task_hashable(e) for e in task)...
4e27fe4c27c4ae220ed8b15ce701f2d87796b715
3,615,290
def select_roi(image, title): """ Select a region of interest with PyQtGraph """ global app # created when loading the module X = image.shape[0] Y = image.shape[1] disp_shape = (max(800, X + 100), max(800, Y + 100)) w = pg.GraphicsWindow(size=disp_shape, border=True) w.setWindowTitle('Selec...
2a6100134619990cc62705825deb8bb2264f8025
3,615,291
def read_collections_config(request): """Load settings for a minor repo with shared tree collections""" conf = get_conf_object(request) collections_repo_parent = conf.get("apis","collections_repo_parent") collections_repo_remote = conf.get("apis", "collections_repo_remote") try: git_ssh ...
0fcd22362040de8d46bfb168d7aa512228ad466c
3,615,292
from pathlib import Path def parent(path: str): """Returns the parent `Path` of the given path.""" return Path(path).parent.resolve()
d86b37bc8310b024eb0a78c1b1de404cf6c2c85a
3,615,293
def train_step( env: gym.Env, env_step: TFStep, initial_state: tf.Tensor, actor: tf.keras.Model, critic: tf.keras.Model, actor_optimizer: tf.keras.optimizers.Optimizer, critic_optimizer: tf.keras.optimizers.Optimizer, gamma: float, max_steps_per_ep...
5a552021682067c3e969623ecc2eb0fda92698d7
3,615,294
def get_class_means_between_and_within_covs(samples, classids, bias=True): """ Return class means and the between and shread within class covariance matrix. Args: samples (np.array): input data classids (np.array): identification of classes bias (bool): type of normalization, see np.cov...
3466a93fc0f91357c1a22a7f7e358c7b5a0b6d04
3,615,295
def get_phone_number(phone_number): """ Following suggested RFC 3966 protocol by open id expect: +111-1111-111111 format """ if '-' in phone_number: phone_split = phone_number.split('-') if len(phone_split) > 2: #if had country code return phone_split[2] ...
287d3dde0cabc3c7730ac48bf94b2c4fc809f123
3,615,296
def isGroup(obj): """Returns true if the object is a group, false if not @return: If the object is a group @rtype: bool""" # isinstance is needed here due to NestedGroup's inheritance # pylint: disable=unidiomatic-typecheck return ( type(obj) == opencue.wrappers.group.Group or (...
9072bc3e2d585bb28403c5f4fc5f1ccd92a70cf8
3,615,297
def AppTypeInsert(json_data): """ Insert AppType objects into DB """ result = [] for r in json_data: apptype = AppType(id=int(r['id']), desc=r['desc']) print("[-] apptype: Insert %s ..." % r) db.merge(apptype) result.append(apptype) db.commit() return result
5c00241fa96f3951301fdba99873ed3855deaa5f
3,615,298
from typing import Optional from typing import Dict def get_selections( selection: Selection, *, typename: Optional[str] = None, ) -> Dict[str, SelectedField]: """Resolve subselections considering fragments. Args: selection: The selection to retrieve subselections from ...
5bca9c6f6647713a425d13acba3c7d1f0451341d
3,615,299
def show_topics(A, vocabulary, topn=5): """ find the top N words for each of the latent dimensions (=rows) in a """ topic_words = ([[vocabulary[i] for i in np.argsort(t)[:-topn-1:-1]] for t in A]) return [', '.join(t) for t in topic_words]
886e4afcfa3594f352474ca54ce79d430f09e508
3,615,300
def parse( handle, sequences=None, query_file=None, query_ids=None, max_evalue=0.01, min_identity=30, min_coverage=50, ): """Parse Tabular results from remote BLAST search performed via API. Since the API provides no option for returning query coverage, which is a metric we want...
55ade045fa1f2828059036e55a474f80f129fd37
3,615,301
def read_graph(in_graph, in_graph_is_binary=True): """Reads input graph file as GraphDef. :param in_graph: input graph file. :param in_graph_is_binary: whether input graph is binary, default True. :return: input graphDef. """ assert gfile.Exists(in_graph), 'Input graph pb file %s does not exist...
ba235b503737f35284f85234ca82297775317e4f
3,615,302
import skimage # Defer slow imports import skimage.transform # Defer slow imports import scipy def _find_anomalies(cy_ims, iqr_bounds): """ Given a cy stack of images for a field, find the anomalies. Arguments: cy_ims: array (n_cycles, height, width) iqr_bounds: The inter-quartile-range...
4f38605fe8b80f8c37c4c0b80c9956aeb6908aed
3,615,303
from typing import Mapping from typing import Any import uuid from datetime import datetime def new_contract_from_user(data: Mapping[str, Any]) -> "SmartContractModel": """ Used in creating new contracts Input: SmartContract::L1::Create DTO Returns: SmartContractModel object """ if data.get("v...
e87485b7ebccaf4d6b4b2f4e869a674a047e2673
3,615,304
def mes_com_acentos(mes_a_mudar): """Retorna Mês com Maiúsculas e Acentos.""" meses_a_exibir = { 'janeiro': 'Janeiro', 'fevereiro': 'Fevereiro', 'marco': 'Março', 'abril': 'Abril', 'maio': 'Maio', 'junho': 'Junho', 'julho': 'Julho', 'agosto': 'Agos...
8361d7e747d524242eeb572b839305d58021b35d
3,615,305
def _load_glove(path): """ Loads GloVe pre-trained embedding model via gensim """ tmp_file = get_tmpfile('temp_glove_w2v_format.txt') glove2word2vec(path, tmp_file) return gensim.models.KeyedVectors.load_word2vec_format(tmp_file)
d3eb03153b65739dc5d991c4ca9984207dd81d6e
3,615,306
def flip_chars(items): """Flip all chars in an input str of items.""" return ''.join([flip_char(x) for x in items])
f2e53101b66d625a8bb327699aa7216e48987bdd
3,615,308
def run_prog(code): """Meh """ mem = {} mask = None for line in code: op, args = parse_line(line) if op == "MASK": mask = args elif op == "MEMSET": for addr in apply_mask(mask, args["addr"]): mem[addr] = args["value"] return sum(m...
04d83fa510a0344bbaf354ef05792a62545ce39a
3,615,309
def get_best_k(use_saved_k, labvitals_time_series_list_val, labels_val, k_list): """gets the best_k either from the database or from finding it with the help of the method find_best_k Args: use_saved_k (Bool): should the value be taken from the databse? labvitals_time_series_list_val (Li...
88e13b52b34ac0c3ec22f786399bdc21fcad0392
3,615,310
def interp_operator_2d( dims_in, dims_out, pack_index_in=None, pack_index_out=None ): """Make one interpolation operator to work on a "flattened" 2D array Do this by tiling and repeat the separate interpolation operators Parameters ---------- di...
d316b47558643e03d436c6831253b8f205ab662f
3,615,311
def x2p(X = Math.array([]), tol = 1e-5, perplexity = 30.0): """Performs a binary search to get P-values in such a way that each conditional Gaussian has the same perplexity.""" # Initialize some variables print("Computing pairwise distances...") (n, d) = X.shape; sum_X = Math.sum(Math.square(X), 1); D = Math.add...
7e85e26a7dfd446abfe1546860c7676b4d44287d
3,615,312
import base64 def b64encode(value): """ Encode a value in base64 """ return base64.b64encode(value)
988abf5a9d2c0c1f38f16fbf8f80fd43aa115223
3,615,313
def update(profile_id): """ Update A Profile --- /api/profiles/edit/{profile_id}: put: summary: Update A Profile. security: - APIKeyHeader: [] tags: - Profile parameters: - in: path name: profile_id required: true schema: ...
1314df4f9b452423e995e35513d607fd13043160
3,615,317
def kornia_list(magn: int = 4): """ Returns standard list of kornia transforms, each with magnitude `magn`. Args: magn (int): Magnitude of each transform in the returned list. """ transform_list = [ # spatial K.RandomHorizontalFlip(p=1), K.RandomRotation(degrees=90.0...
fd6fa7a1214484bc0f7c1f6511fe4b525f7d15c5
3,615,318