content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time import shutil import os def local_run( inputs, build_results, timeout=10, number=3, repeat=1, min_repeat_ms=0, cooldown_interval=0, enable_cpu_cache_flush=False, verbose=1, ): """ Run function of LocalRunner to test the performance of the input BuildResults. ...
abe40ae0a18612fc3080d9516efbeca7e92ee0f5
69,800
from typing import Tuple from typing import Optional import os def log_model_summary(model: nn.Module, input_size: Tuple[int], full_summary: bool=True, working_dir: str=".", model_name: Optional[str]=None, verbose: bool=1): """ produce a text file with the model summary TODO: A...
0ca293db7e761dd401ee805e8b9431cae623f455
69,801
def load_pretrain_embed(embedding_path, max_scan_num=1000000, add_seg_vocab=False): """ 从pretrained word embedding中读取前max_scan_num的词向量 Args: embedding_path: 词向量路径 max_scan_num: 最多读多少 """ ## 如果是使用add_seg_vocab, 则全局遍历 if add_seg_vocab: max_scan_num = -1 embed_dict = di...
dadf109469c70baf922791c3b20f4a5339e1a46b
69,802
def get_object_name(object): """ Retrieves the name of object. Parameters: object (obj): Object to get name. Returns: str: Object name. """ if object.name[-5:-3] == '}.': return object.name[:-4] return object.name
fc695c8bf19817c3217bf6000358695c88de07aa
69,803
def list_functor(annotation): """Convert to List of type values""" to_type = next(iter(annotation), None) if _is_subtype(to_type, entities.AttributeV2): return partial(map, attr_v2_functor(to_type.__args__)), list return partial(map, entities.converter(to_type)), list
3e8eeec884756964a8c2287a56ed421986b6fff9
69,804
def create_nine_digit_product(num): """ Create a nine digit string resulting from the concatenation of the product from num and multipliers (1, 2, 3,).... Return 0 if string cannot be length 9. """ result = '' counter = 1 while len(result) < 9: result += str(num * counter) ...
9c6765349edfa7e03dc8d2ffe7bf6a45155f3ad0
69,805
import os import logging import re def main(unused_argv): """Moves swig generated classes to a common container class. The .csproj filename is used to find the .cs file (with the same name) which will contain all of the other SWIG generated classes. Args: unused_argv: Extra arguments not consumed by the...
063e3d2eaa77c4bd3e920e005bdbae6c76016661
69,806
def ReplaceValues(df, lY, iQ1, iQ2): """ Purpose: Replace all values in dataframe below i1 by i1, and all values above i2 by i2. Inputs: lY list of names of relevant columns from df df dataframe i1 first value (lower boarder) i2 second value ...
30c1199f645e2b10ffb885d543783d513818f254
69,807
def peak_indices_to_times(time, picked_peaks): """ Converts peak indices to times. Parameters ---------- time: ndarray array of time, should match the indices. picked_peaks: dict dictionary containing list of indices of peak start, center, and end. Returns ----------- ...
99aa76fbc399b2b99d4dc9c8d3e4b67e4ee2d3af
69,808
from typing import Optional from typing import List from typing import Any from typing import Tuple def _create_on_round_end_fn( file_checkpoint_manager: Optional[FileCheckpointManager] = None, metrics_managers: Optional[List[MetricsManager]] = None, validation_fn: Optional[ValidationFnType] = None): ""...
6f48db732bfb24e63cc49ce8935f3f44a7aca498
69,809
import pandas as pd import os def nsw74psid_a(path): """A Subset of the nsw74psid1 Data Set The `nsw74psidA` data frame has 252 rows and 10 columns. See `nsw74psid1` for more information. This data frame contains the following columns: trt a numeric vector age a numeric vector educ ...
8c69590cf0b75eac5fc8f8faca4388df97c8e186
69,810
from typing import Tuple import asyncio async def read_govee() -> Tuple[float, float]: """Connects to the H5179 device and gets the lab temperature and humidity.""" h5179 = config["sensors"]["H5179"] reader, writer = await asyncio.wait_for( asyncio.open_connection(h5179["host"], h5179["port"]), ...
3489957c1a68f00731c6924606c6d15faa15a613
69,811
def init_baseline_artm( dataset, modalities_to_use, main_modality, num_topics, bcg_topics, model_params: dict = None, ): """ Creates simple artm model with standard scores. Parameters ---------- dataset : Dataset modalities_to_use : list of str ...
9aa0339316a75417e4afc756810a43d9a50a936b
69,812
def es_annotation_doc(): """ Minimal JSON document for an annotation as returned from Elasticsearch. This contains only fields which can be assumed to exist on all annotations. """ return { "_id": "annotation_id", "_source": { "authority": "hypothes.is", "tar...
085f8077d5f5cbf278a3b1be1734de081a55b769
69,813
def incmean(prevmean, n, x): """Calculate incremental mean""" newmean = prevmean + int(round((x - prevmean) / n)) return newmean
4176a07d0ad8eb96d3dd5d8b2cb46b8aecd1da20
69,814
def ccode(expr, dtype=np.float32, **settings): """Generate C++ code from an expression calling CodePrinter class :param expr: The expression :param settings: A dictionary of settings for code printing :returns: The resulting code as a string. If it fails, then it returns the expr """ return Cod...
1fdceb916a1e1c5536bf8794852d58b393f47aef
69,815
import torch def uses_placeholder_y(ds): """If ``ds`` is a ``skorch.dataset.Dataset`` or a ``skorch.dataset.Dataset`` nested inside a ``torch.utils.data.Subset`` and uses y as a placeholder, return ``True``.""" if isinstance(ds, torch.utils.data.Subset): return uses_placeholder_y(ds.datas...
1bbdfdfa644db3298a6148380155980a57183d62
69,816
def evenFibSum(limit): """Sum even Fib numbers below 'limit'""" sum = 0 a,b = 1,2 while b < limit: if b % 2 == 0: sum += b a,b = b,a+b return sum
cdf9cdb1cfb419713e794afff4d806945994692e
69,817
def copy_arrays(mapper, reverse=False): """ Build an Iteration/Expression tree performing the copy ``k = v``, or ``v = k`` if reverse=True, for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`. The loop bounds are inferred from the dimensions used in ``k``. """ i...
44d346a751d8f92edb34729c9093d174ec55f499
69,818
def OneHotFromList(elements, dtype='float32', strict=True, name=None): # pylint: disable=invalid-name """A block that converts PyObject input to a one-hot encoding. Differs from `OneHot` in that the user specifies the elements covered by the one-hot encoding rather than assuming they are consecutive integers. ...
cde6231cc9701d450e6d7f5b44d630f08a657899
69,819
def _get_tfbt(output_dir, feature_cols): """Configures TF Boosted Trees estimator based on flags.""" learner_config = learner_pb2.LearnerConfig() learner_config.learning_rate_tuner.fixed.learning_rate = FLAGS.learning_rate learner_config.regularization.l1 = 0.0 # Set the regularization per instance in such a...
e5a548858850745087add9fb65bc233c880b3aa3
69,820
from datetime import datetime def dateandtime_now() -> str: """ Returns the datetime in following format as string YYYYMMDD_HHMMSS """ jetzt = datetime.datetime.now() dt = '' for time in ['year', 'month', 'day', 'hour', 'minute', 'second']: _time = str(getattr(jetzt, time)) ...
700032adc66298f98fc6687c5dbf48fe4b0706c5
69,821
def get_n_first(file_names, checksums, N_first): """ Given a list of file_names and a list of checksums, returns the 'N_first' items from both lists as a zip object. :param file_names: list of file names :param checksums: list of sha256 checksums :param N_first: int or None. If None, all items ...
13a8157dcd55fa43b0cd71eb877abddc832ff143
69,822
from typing import Tuple def singular_value_decomposition( m: np.ndarray ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Perform singular value decomposition. :param m: an input matrix M. :returns: a tuple (d, U, V), where d is a 1d matrix containing the diagonal elements of a non-ne...
b9e469f3d42b1140fc4d3303d763954d8541c69a
69,823
def get_library(gi, lib_name, lib_desc="", lib_synopsis="", create=True): """ Get the id corresponding to given library, and create it if it doesn't exist yet """ print("Looking for lib '" + lib_name + "'") libs = gi.libraries.get_libraries() found_lib = None for lib in libs: if not...
b8f9c6fff4c0162185fc71c08de9ff7b03272d4b
69,824
def state_to_index(valuation, base): """ Maps states to an decimal integers. """ factor = 1 integer = 0 for i in range(len(valuation)): integer += factor * valuation[i] factor *= base return integer
c05deefd07d0faf2749489fbc6f37576e1433c8d
69,825
def check_index_values_are_unique(data, index=None, duplicates_as_error=True): """Checks index for duplicate rows. Args: data: DataFrame to check index: optional index to use. If not specified, uses index from `data`. duplicates_as_error: If True, raises an error if duplicates are found...
cf29309022e0303c0c49b716388b2cf73909f547
69,826
def extract_conversions(conversions_path, index_path, alignments=None, quality=27, n_threads=8): """Wrapper around `extract_conversions_part` that works in parallel. :param conversions_path: path to conversions CSV :type conversions_path: str :param index_path: path to conversions index :type index...
503268fe61d6ae3bc4c2bb607b12781d00f09233
69,827
def bgr2luma(im): """Converts BGR image to grayscale Luma :param im: np.ndarray BGR uint8 :returns nd.array GRAY uint8 """ im_y, _, _ = cv.split(cv.cvtColor(im, cv.COLOR_BGR2YUV)) return im_y
39f97822dea6170be74d60c357fc51f4160e1acd
69,828
def get_lock_path_from_repo(git_repo): """ >>> app_module = {'git_repo': 'git@github.com:claranet/ghost.git'} >>> get_lock_path_from_repo(app_module['git_repo']) '/ghost/.mirrors/.locks/git@github.com:claranet/ghost.git' >>> app_module = {'git_repo': ' git@github.com:claranet/spaces.git '} >>> g...
b722e69dcaa5fd6a6299ee42ddaa7f14097a25a4
69,829
def cross_entropy_with_selfnorm(input, label, name=None, coeff=1.0, softmax_selfnorm_alpha=0.1, layer_attr=None): """ A loss layer for multi class entro...
b8bda752dc9eaf1b69014481bd27be992fc4870b
69,830
def random_contrast(img, low=0.5, high=1.5): """ Randomly scales the contrast of a given RGB image. """ mean = img.mean(axis=(0,1), keepdims=True) cf = np.random.uniform(low, high, mean.shape) img -= mean img *= cf img += mean img[img > 1] = 1 img[img < 0] = 0 return img
7a3ae56c2bbf79dac312bfc176d021dc5bccc1cb
69,831
import os import json import collections from datetime import datetime def load_file(filename): """raise EOFError als file niet gelezen kan worden geeft geen resultaat als bestand niet bestaat """ if not os.path.exists(filename): return {} with open(filename, "r") as f_in: nt_data ...
9145ee9062ecc6bd1711e1ccc95548b17bc215fb
69,832
def get_movie_or_create(movie: str): """ Находит фильм в бд или создает его, возвращает id фильма. """ try: result = Movies.select().where(Movies.name==movie).get() except DoesNotExist: result = Movies.create(name=movie) return result.id
c7581ec1421d7a487fc253f3a65c544f8a3f60c6
69,833
def generalized_box_iou(boxes1, boxes2): """Compute GIoU of each pais in boxes1 and boxes2 GIoU = IoU - |A_c - U| / |A_c| where A_c is the smallest convex hull that encloses both boxes, U is the union of boxes Details illustrations can be found in https://giou.stanford.edu/ Args: boxes1: ...
671520a3967b6120d23c8944456e13e3118ef8a7
69,834
def getConstValue(stateStruct, obj): """ Evaluates the obj, in case it is a expression which can be evaluated at compile time. """ if hasattr(obj, "getConstValue"): return obj.getConstValue(stateStruct) if isinstance(obj, (CNumber,CStr,CChar)): return obj.content if isinstance(obj, CFunc...
91c1ae469ef23b91ef4f76bf35481560243cdfc7
69,835
def prepare_vcf_table(varfile, sample, variants): """Prepare vcf table.""" header = [ "CHROM", "POS", "REF", "ALT", "AF", "DP", "DP4", "GEN[0].AD", "SB", "FS", "EFF[*].GENE", "ID", "EFF[*].AA", ] head...
396eb3966196352dbbbe0ff6c9386aba7fcc032b
69,836
def counts_from_confusion(confusion): """ Obtain TP, FN FP, and TN for each class in the confusion matrix """ counts_list = [] # Iterate through classes and store the counts for i in range(confusion.shape[0]): tp = confusion[i, i] fn_mask = np.zeros(confusion.shape) fn...
7c9b1f8309ef7a0304aa218e75f90d0c6a09bd66
69,837
def vaccination_view(): """ App route to display India level vaccination data :return: """ dates, cumulative_data, daily_data, fully_vaccinated, daily_fully_vaccinated, sources = service.vaccination_data() context = { 'dates': dates.tolist(), 'cumulative_data': cumulative_data.to...
0f4fb72c72abf31d65c2b541fc891d6c574c6252
69,838
def im_to_torch(img): """Transform ndarray image to torch tensor. Parameters ---------- img: numpy.ndarray An ndarray with shape: `(H, W, 3)`. Returns ------- torch.Tensor A tensor with shape: `(3, H, W)`. """ img = np.transpose(img, (2, 0, 1)) # C*H*W img = to_t...
fcda6a9e65d87b09ff5d1340dcf958fb1f14089e
69,839
from typing import Sequence from typing import Optional def animate_atom_phonon( position: Sequence[float], qpt_cart: np.ndarray, d_vector: np.ndarray, n_frames: int = 30, s_frame: int = 0, e_frame: Optional[int] = None, magnitude: float = 1.0, ): """Return atom position series determi...
72cdb958f540bd16525ccb1a885f75e38b1482e7
69,840
def get_f1sc(y_true, y_pred, threshold = 0.5): """ - Description y_true: should be one-hot encoded tensor y_pred: should be logit tensor threshold: thres to claim it is 1 - Reutrn f1-score under threshold """ y_true = tf.argmax(y_true, axis = 1) y_pred = y_pred[:,1] >= threshold ...
c21436263fcfa938ee70c2c90bf2ed4375edceec
69,841
import os import json import requests def init_api_client(): """ Initialize Flask API Client This is necessary for the grant code method """ log = Logger() config = get_config() app_name = config.get('application', 'name') app = Flask('{0}_api_client'.format(app_name), template_folder...
6cfd5d8604d2b40c8578b682994da3aea4658b15
69,842
def rules(supvisors): """ Return the instance to test. """ return ProcessRules(supvisors)
68fd580498e590a320cfb8ba25e177fdfbe7f512
69,843
def _parse_build(encoded_data, pointer=0, spec=None, spec_params=None, strict=False): """ Parses a byte string generically, or using a spec with optional params :param encoded_data: A byte string that contains BER-encoded data :param pointer: The index in the byte string to parse from ...
3824e87b120b63cbbc18a140b8b2c0cca95d5405
69,844
def cache_basic_crud_update_row_view(request, id): """ Renders the Django edit form page and execute the update statement. But, with invalidating the cache to clear the previous cached results. """ if request.method == "GET": # Check if the row id existed or not. if is_contact_us_id...
83d90a5fe70715dd6e8e0aff8b342a193c77ac19
69,845
def interpolate_at_times(df_or_series, new_times) -> ndarray: """ Parameters ----------- df_or_series: Pandas DataFrame or Series new_times: iterable, numpy array can be a n-d array, list. """ assert df_or_series.index.is_monotonic_increasing, "df_or_series must be a increasing ...
f9dd3dbb780331f40d38d505bceac609ed88df86
69,846
def PFullInstantiate (inOTF, access, err): """ Fully instantiate an OTF by opening and closing return 0 on success, else failure inOTF = Python OTF object access = access code 1=READONLY, 2=WRITEONLY, 3=READWRITE err = Python Obit Error/message stack """ #######################...
fa5691292e27153afeebe6ef42fe91b974c2b933
69,847
from typing import Any async def get_user_info_by_id_async(client: Any, user_id: str): """Gets profile information about a user by id.""" return (await make_call_async(client, "users.info", user=user_id))["user"]
262dc6afa0f17a3f2debd0d05738b20441f4f2d9
69,848
def getStep(raw, config): """ Detect the type of the build step and generate a model from it """ if exists(raw, "partitiontable"): ptable = partitiontable() ptable.reference = raw["partitiontable"] return ptable if exists(raw, "format"): form = format() form.r...
54518f813709b5b578cf87504343024a9306450c
69,849
def _compute_background_amplitude(image_spot): """Compute amplitude of a spot and background minimum value. Parameters ---------- image_spot : np.ndarray, np.uint A 3-d image with detected spot and shape (z, y, x). Returns ------- psf_amplitude : float or int Amplitude of t...
84a5138d2757459f8e0a61c12222cb32fa24662d
69,850
def strip_comments(string, comment_symbols=frozenset(('#', '//'))): """ :param string: A string containing json with comments started by comment_symbols. :param comment_symbols: Iterable of symbols that start a line comment (default # or //). :return: The string with the comments removed. """ lines = string.split...
4dfc1b0e627d8559db61f00b10fa5cb807ba2d01
69,851
def return_user_best_video(username): """ In GET request - Returns video ID of the video uploaded by the user with the highest view count. """ if request.method == 'GET': return str(db.get_best_video_ID(username))
9751f36a0cd45c54ca38f4e2f19a6be43df8fed3
69,852
def get_unique_tasks(*task_groups): """ Compare input JSON objects containing tasks and return a unique set :param json_objects: lists of task objects :type json_objects: list :rtype: list """ # Combine all sub-json objects into a single group unique_tasks = [] # Get a list of ta...
c9eb32ea0a953e797ea28021c3a434941f7b05ff
69,853
def get_srl16_init(site, srl): """ Decodes SRL16 INIT parameter. Returns two initialization strings, each one for one of two SRL16s. """ lut_init = get_lut_init(site, srl) bits = lut_init.replace("64'b", "") assert bits[1::2] == bits[::2] srl_init = bits[::2] return "16'b{}".forma...
651cef9d266fe2edd896f17018cda1455d2d54a8
69,854
def problema(n): """ Input n - maxim number of digits that can produce this result """ suma = 0 b = {} for i in product(range(10), repeat=n): aux = reduce(lambda x, y: 10*x + y, i) b[aux] = sum(map(lambda x: x**5, i)) if aux == b[aux]: suma += aux ...
f6c5d0436b8d41f82c56c996f9e26fb53887abd8
69,855
import sys def mergeRectify(input_frames, cameras, grid): """ This function performs image rectifications at one timestamp given the associated extrinsics, intrinsics, and distorted images corresponding to each camera contained within the CameraData object. The function utilizes matchHist to match...
14bb579fb81fb652a06deec20736b7c07a13f02f
69,856
def news_detail(news_id): """ 新闻详情 :param news_id: :return: """ # 显示用户是否登录的逻辑 print('test') user = g.user print(user) # 右侧新闻排行的逻辑 news_list = [] try: news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS) except Exception as e...
abf8f3d3542ca80eb0fbd907dfcc4cb7a668c4dd
69,857
def directorio_imagen(instance, filename): """Obtiene el directorio para guardar las imagenes de los platillos""" # Obtenemos la extension del archivo para guardar la imagen solo con el id y nombre del platillo extension = filename.rsplit('.', 1)[1] return f"platillo/imagen/{instance.id}_{instance.nomb...
90db760562327a16858e1bf6419fb1ed6e9eeefa
69,858
import json def output_fn(prediction, accept): """Format prediction output The default accept/content-type between containers for serial inference is JSON. We also want to set the ContentType or mimetype as the same value as accept so the next container can read the response payload correctly. ""...
47ad5dcb528c8fbaca9b0de22f6745dd1c058da2
69,859
def stack_error_improvement_matrix(result_list, model_names, error='mae'): """Computes the stacked error improvement matrix, which for each element (i,j) contains the pairwise stacked error improvement of model_list i and j. Returns as pd.DataFrame. Arguments: result_list: a list of SPSbBandwidthOptimi...
540d01a8764643ccec3db68fb8bd5a95ddb423ae
69,860
from typing import Union def gen_batch_vectors( n_batches: int, n_features: int, batch_scale: float, bio_batch_angle: Union[float, None] = None, projection_to_bio: Union[np.ndarray, None] = None, ) -> np.ndarray: """Generates a batch-effect vector for each batch, optionally with some relat...
744ffced9013686b14a6c4100a24f8df81b70093
69,861
def main(): """ Main procedure; accept the file name as a command-line parameter and run the solver. """ if len(sys.argv) < 2: print 'Specify the file name corresponding to the Brick Pop screenshot as the first ' \ 'positional argument.' return sys.exit(1) return solve...
9db3fc1fd77a07e1a58c2eafe513edf357a08167
69,862
def is_multiple_folder(schema_map): """ Return True if the schema map identifies a multiple folder. :param schema_map: the schema map to be examined :return: True if the map identifies a multiple folder """ property_type = get_type(schema_map) if property_type == "array": return get_...
c18d6a7557e458998a4d2c008f7b1f3b74fff2c7
69,863
def cicle_move(A): """ move first to last and move elements between first and last 1 element back :param A: list to execute cicle move :return: """ tmp = A[0] for i in range(len(A) - 1): A[i] = A[i + 1] A[len(A) - 1] = tmp return A
4948b863829d77a879ad0ec9745bb3a35e580026
69,864
import torch def test_is_index_valid() -> None: """ Test if checks for valid sequence positions work. """ def _create(pos: int) -> ScalarDataSource: z = torch.empty(0) return ScalarDataSource(metadata=GeneralSampleMetadata(id="", sequence_position=pos), ...
cb3210c2fd59ceb013b8bc909fa9f08cf03e1af1
69,865
def load_keras_model(dataset, model_name): """ Loads pretrained model from disk for a given dataset type. """ folder_path = '../Models/' model_path = folder_path + dataset + '/' + model_name + '_model.json' try: json_file = open(model_path, 'r') except IOError: print('\nE...
70f2670d414466a675646e6689dff7ac4f609c08
69,866
def _is_float_or_nan(val): """Check whether a given item is a float or np.nan""" try: float(val) except ValueError: if val is np.nan: return True return False else: if not isinstance(val, bool): return True else: return False
9eadced4492fd052173b4a6d953df7862df2c370
69,867
import collections def resize(img, size, interpolation=Image.BILINEAR): """Resize the input PIL.Image to the given size. Args: img (PIL.Image): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to th...
829bbdeea7cb99dbc2f935330b5180319e17da9e
69,868
from operator import concat def scriptGen(step, config): """ Generate a script command from a parser.executor.script """ if not step.model.command == None: return concat(["\n# Executing custom script"], script.script(shell="", payload=step.model.command).exec()) with open(step.model.file, ...
bc1bd50e05c8514d32483d3c5aaf9951494d15f6
69,869
def read_binary_file(bf: str): """ to read binary file :param bf: :type bf: :return: :rtype: """ # example: f'./local_data/MSG+0415.3km.lon' data = np.fromfile(bf, '<f4') # little-endian float32 # data = np.fromfile(bf, '>f4') # big-endian float32 return data
4ecf7fb3098339b5ea0e77e738bb59f863cf641c
69,870
def get_bounding_boxes(start_path = '.'): """ Extracts a bounding box file and returns a dictionary """ return GetBoundingBoxes(start_path).unpack_all()
a0d80d6d6a77555e4bdbecaf7bd52e8403270965
69,871
def get_VAE_os(X): """ takes in only data 'X', in samples as rows format returns only list of outlier scores for each sample higher score = more outlier gives reconstruciton error from AE, should be largest for outliers """ losses = get_vae_losses(X) return losses
1c1a078409b29d2e7306b72ddbe670f56cf9f538
69,872
def get_activation_gradients(label): """Gets the sample gradient w.r.t activation according to the model_fn.""" # The sample loss is (label - logits)**2, where # logits = \sum_j^HIDDEN_LAYER_SIZE ( # \sum_i^EMBEDDING_DIM w_i * kernel + bias) # # Note kernel and bias are both constant initializer...
6714795be6893106ecbfacecd368854b377ae75c
69,873
import os def get_scene_path(scene_id): """ Gibson scene path :param scene_id: scene id :return: scene path for this scene_id """ data_path = gibson2.g_dataset_path assert scene_id in os.listdir( data_path) or scene_id == 'stadium', "Scene {} does not exist".format(scene_id) r...
3bdb59e61441930f75c266d8d5c60c44c75fe47b
69,874
import gzip import tqdm import json def read_examples(input_file): """Read a SQuAD-like json file into a list of Examples.""" def is_whitespace(c): if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F: return True return False reader = tf.gfile.Open(input_file, "rb") if input...
f0ea238c4313ec6a0779452014c7875feeefbb4e
69,875
def make_options( testcase_id='1', current=False, build='chromium', disable_goma=False, goma_threads=10, goma_load=8, iterations=11, disable_xvfb=False, target_args=None, edit_mode=False, skip_deps=False, enable_debug=False, extra_log_params=None, force=False): ...
79ca25f9ea7fc4266ecc4dc76f73e7f620408096
69,876
async def record(request): """Renders the video recording and upload view.""" return templates.TemplateResponse("record.html", {"request": request})
fa3d6633a68f9cf1f01aab8d45b3198024a4d219
69,877
import ctypes import readline def rl_get_point() -> int: # pragma: no cover """ Returns the offset of the current cursor position in rl_line_buffer """ if rl_type == RlType.GNU: return ctypes.c_int.in_dll(readline_lib, "rl_point").value elif rl_type == RlType.PYREADLINE: return i...
257dd29b23869b6e6245773f86e64ef58f9e763b
69,878
def plot_averages( fig: go.Figure, data: pd.DataFrame, value_col: str, aggregate: dict, color: str, line_shape: str = "spline", color_discrete_sequence: list = px.colors.qualitative.G10, category_orders: dict = default_category_orders(), mode: str = "polar", ): """Add traces for ...
b3f99ee216fc8375ea071ca7483c9c003fe38bff
69,879
import typing def rating(apikey: str, symbol: str) -> typing.List[typing.Dict]: """ Query FMP /rating/ API. :param apikey: Your API key. :param symbol: Company ticker. :return: A list of dictionaries. """ path = f"rating/{symbol}" query_vars = {"apikey": apikey} return __return_js...
fddc609276e0f63e2f6523337c47a95c9f651a94
69,880
import tokenize def tokenize_code(text): """Tokenize code strings. This simply considers whitespaces as token delimiters. Args: text: A code string to be tokenized. Returns: A list of strings representing the tokens in the code. """ return tokenize.RegexpTokenizer(r'\w+').tokenize(text)
692eec16363f4d6816482025942aac7e149f3910
69,881
def getScriptClass(scriptVersion, script): """ getScriptClass returns the class of the script from the known standard types. NonStandardTy will be returned when the script does not parse. NOTE: All scripts that are not version 0 are currently considered non standard. """ if scriptVersion !...
ead86ca55a820bf0f93aa31f70c74c733a61f253
69,882
import sys import subprocess import string import MySQLdb import reportlab import xlwt import os from re import T def about(): """ The About page provides details on the software depedencies and versions available to this instance of Sahana Eden. """ python_version = sys.version web2py_ver...
592243b25ec429d5247d44e0cf8487fbcaa180a5
69,883
def print_compare(x, y): """ Helper method used in :meth:`Sets.ParentMethods._test_elements_eq_symmetric`, :meth:`Sets.ParentMethods._test_elements_eq_tranisitive`. INPUT: - ``x`` -- an element - ``y`` -- an element EXAMPLES:: sage: from sage.categories.sets_cat import print...
7a591b52fb20bc2bf0ec8ea029e4f10b3e1fee26
69,884
def Words_Before_and_after(words, item, nbr): """ :param words: list of words :param item: word of interest :param nbr: number of words wanted before and after the word of interest :return: list of words before and after the word of interest """ liste = [[words[item], item]] for n in ran...
6dc874565a308cc642bf0510a3be56264c6d89e9
69,885
async def get_mocked_redis_client(*args, **kwargs) -> RedisCluster: """ Return a stable RedisCluster object that have deterministic nodes and slots setup to remove the problem of different IP addresses on different installations and machines. """ cluster_slots = kwargs.pop("cluster_slots", defau...
5fb6e3b70971a27ceaef2676741b2a36f4168039
69,886
import yaml def df_to_yaml(df): """ conert DataFrame to yaml string """ d = df.to_dict(orient='records') return yaml.dump(d)
285b4cad92e73fbaec19e631664bb474ecaf309f
69,887
import sys import os import importlib def get_detector(net, prefix, epoch, data_shape, mean_pixels, ctx, nms_thresh=0.5, force_nms=True): """ wrapper for initialize a detector Parameters: ---------- net : str test network name prefix : str load model prefix ...
bd5609cb4bb42379702ccfe365da1eaac97fbe83
69,888
from datetime import datetime def naturaltime(text, now=None): """Convert a naturaltime string to a datetime object.""" text = text.lower().strip() if not now: now = datetime.now() if text == 'now': return now if text == 'yesterday': return now - timedelta(days=1) if t...
25f56b5afd11cd5e4b6dd4a94a1de3c47476bd1e
69,889
def get_polar(d, Re=6371.): """ Convert to polar coordinates """ th = d.grange / Re r = d.height + Re dop, sth, dth = d.dop, d.sth, d.dth return th, r, dop, sth, dth
1d4710152b5dbbbfd09cdc5cbf934f3adb94deeb
69,890
def _corr_vectors(A, B, axis=0): """Compute pairwise correlation of multiple pairs of vectors. Fast way to compute correlation of multiple pairs of vectors without computing all pairs as would with corr(A,B). Borrowed from Oli at Stack overflow. Note the resulting coefficients vary slightly from the on...
51df38f9e1703c98718d3f15b481975ce82f47a2
69,891
def getGenomesInHal(halFile): """Get a set of all genomes in the hal file.""" spaceSeparatedGenomes = popenCatch("halStats --genomes %s" % halFile).strip() return set(spaceSeparatedGenomes.split(" "))
fad81779e8a8e8788117099d96526083e8d635b1
69,892
def diagflat(d, k=0): """ Create a two-dimensional array with the flattened input as a diagonal. Parameters ---------- d : array_like Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional Diagonal to set; 0, the default, correspon...
6dbf5f72eda5771bd0a7080a353de69a65ebeca3
69,893
import re def hasNoProcessExtension(file_name: str): """ Determine if the file should not be processed, just copied directly """ m = re.search(r'(?<=\.)[^.]+', file_name) return m.group() in CONFIG['ignoredExtensions'] if m else False
cc67d7e8633454a852f87a7a41aa7d85624cbf21
69,894
def get_patchy_N0s(qekey_in, npatches, pixivmap_t, pixivmap_p, cls_unl, cls_cmb_dat, cls_cmb_filt, cls_weight, lmin_ivf, lmax_ivf, lmax_qlm, transf, rvmap_uKamin_t_data=None, rvmap_uKamin_p_data=None, joint_TP=False, nlevt_fid=None, nlevp_fid=None, cacher=cachers.cacher_mem(), source...
3e504133ea53409bff3475468843dbf3ae183b87
69,895
def generate_sphere(radius): """Generates a centered boolean mask of a 3D sphere""" rint = np.ceil(radius).astype('int') t = np.arange(-rint, rint+1, 1) x,y,z = np.meshgrid(t, t, t, indexing='ij') r = np.sqrt(x*x + y*y + z*z) sphere = r < radius return sphere
56b3e45397464701ecd472e90ffc863785646200
69,896
def find_percentile_coordinate(cube: Cube) -> Coord: """Find percentile coord in cube. Args: cube: Cube contain one or more percentiles. Returns: Percentile coordinate. Raises: TypeError: If cube is not of type iris.cube.Cube. CoordinateNotFoundError: If no...
718f4ef482a317784c46c397bf68e8630631e857
69,897
def get_user_plants(user_id): """Returns a list of plants a user has added.""" user_plants = User.query.get(user_id).plants unpacked_user_plants = {} for plant in user_plants: unpacked_user_plants[plant.plant_id] = plant.__dict__ if '_sa_instance_state' in unpacked_user_plants[plant.p...
f2fdd16bc535eab5fcfe28d65f2ebe74dfaeceb5
69,898
import six import sh def apply_sh(actions): """Add the shell function to any actions that are strings""" return [ a if six.callable(a) else sh(a, log_command=False) for a in actions ]
dd2d24fccb0e8d02752a3f5bd86bc0b41161b87d
69,899