content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import decimal def is_numeric(value): """ Check whether *value* is a numeric value (i.e. capable of being represented as a floating point value without loss of information). :param value: The value to check. This value is a native Python type. :return: Whether or not the value is numeric. :rtype: bool """ if...
4224e3a1af56e75256d5c6d7f7d990ea3ae9343a
33,400
def _position_to_features(sam_reader, allele_counter, region, position, exclude_contig): """Extracts the AlleleCount data from a given position.""" # We build the AlleleCount at the position. reads = sam_reader.query(region) for read in reads: allele_counter.add(read) counts = al...
7b430c6488a7f21661505a8ac9212f2fe2289744
33,401
def p_name(username): """ 根据用户名获取昵称 :param username: 用户名 :return: """ friend = itchat.search_friends(userName=username) if not friend: return '' return friend.get('RemarkName') or friend.get('NickName')
4a07df0a973f533bd740b6d8d11ca2eb981617d5
33,402
def user_profile(self): """Return this user's UserProfile, or None if one doesn't exist.""" try: return self.userprofile except UserProfile.DoesNotExist: return None
7ca38535ed779c591d7dc76b52861e6a9a126c8f
33,403
def get_policy_list(cluster_name): """ 获取存储策略列表 :param cluster_name: :return: """ data = [] status = '' message = '' resp = {"status": status, "data": data, "message": message} pm = PolicyManager(cluster_name) try: sfo_policys = pm.policys() for policy in sfo_...
5b53acebbd7eaf52975bf393a4b4f87c7fe7e550
33,404
def package_air_ticket(request): """ view air ticket package for customer """ air_tickets = AirTicket.objects.all()[::-1] package_air_tickets = PackageAirTicket.objects.all()[::-1] context = { 'air_tickets': air_tickets, 'package_air_tickets': package_air_tickets, 'user_inf...
0e7f70d3f49d6a5ef25f669d3f58768e933050b2
33,405
def CheckNodeJSPackage(package): """ Check whether a node.js package is installed """ cmd = "node -e \"var d3=require('%s');\"" % package x = RunCommand(cmd) return x == 0
ba6709f641548bab52aafdc589f4730268b3b778
33,406
import re def compilable(tex): """Return tex-math content wrapped so that it can be compiled using tex.""" # remove "\usepackage{pmc}". It's not clear what the contents # of this package are (I have not been able to find it), but # compilation more often succeeds without it than with it. tex = te...
8381999e503194d7d9f2a1fbe751775a6bf48dd2
33,407
def filter_matches(matches, threshold=0.75): """Returns filterd copy of matches grater than given threshold Arguments: matches {list(tuple(cv2.DMatch))} -- List of tupe of cv2.DMatch objects Keyword Arguments: threshold {float} -- Filter Threshold (default: {0.75}) Returns: li...
c2cbec1da42d96575eb422bfdda6a1351e24508b
33,408
def V_PT(P, T, substance, eos = IDEAL_GAS): """Returns specific volume.""" mw = get_parameter(substance, 'molecular-weight') Vmol = eos.Vmol_PT(P, T, substance) return Vmol / mw
776164131c2e59295bcdf1100697c5ca84931074
33,409
def checks(poly_fit_left, poly_fit_right, poly_fitx_left, poly_fitx_right, poly_fity): """Check if found lanes make sense.""" # check curvature y_eval = np.max(poly_fity) curvature_left = (((1 + (2*poly_fit_left[0]*y_eval + poly_fit_left[1])**2)**1.5) /...
a5d2a807a29dfacc4b184aa591577161c3c5933c
33,410
from pathlib import Path def run( dataset_file: str = Path.joinpath(DATA_DIR, "processed", "winequality_clean.csv"), params_file: str = Path.joinpath(MODELS_DIR, "params.json").read_text(), ): """ Run the training process """ dataset = load_dataset(dataset_file) train_test = split_dataset(...
f2f82baebe910a8ada8dbfe77791e33d2a72e168
33,411
import string import random def createRandomStrings(l,n,chars=None,upper=False): """create list of l random strings, each of length n""" names = [] if chars == None: chars = string.ascii_lowercase #for x in random.sample(alphabet,random.randint(min,max)): if upper == True: ...
678b5aeb3cc98ae2b47822500fcbaff05081058a
33,412
def create_model(reader_input, base_model=None, is_training=True, args=None): """ given the base model, reader_input return the output tensors """ labels = reader_input[-1] cls_feats = base_model.final_sentence_representation cls_feats = fluid.layers.dropout( x=cls_feats, ...
9afcb97036c959ddf476e9844ab18cdf792ddbbd
33,413
def shot_mix(df1): """ Calculates the average of the poisson models for shots and shots on target """ df1["H_att_Poi_mix"] = (3*df1["H_att_PoiS"] + 3*df1["H_att_PoiST"] + 2*df1["H_att_PoiG"]) / 8 df1["A_att_Poi_mix"] = (3*df1["A_att_PoiS"] + 3*df1["A_att_PoiST"] + 2*df1["A_att_PoiG"]) / 8 df1["H...
6d7fe94ce4e90de26d0c5154ad2d0ae54d7409ca
33,414
import sys def find_devices(name=None, serial_number=None, vid_pid=None, device_id=None, hid_enumeration=None, chip_name=None): """ Returns a list of keyplus keyboards that are currently connected to the computer. The arguments can be used to filter result. Args: name: filter...
9c1952f599a81b59a098f85feac942564ef21df7
33,415
def jobs(): """ lista de jobs """ rows = db(db.job).select(orderby=db.job.created_on) return locals()
067d7f9840cdd0ee52c7c2fefe3d5942170203c3
33,416
import base64 async def reserve_subdomain(request: Request, req: t.Optional[ReservationRequest] = None): """ Reserve a subdomain for use with an application. If no subdomain is given, a random subdomain is reserved and returned. If a set of SSH public keys is given, they are associated with the subd...
11d56868f6a0f4439ada5ad0755333c1b0ad9f74
33,417
def get_previous_quarter(today): """There are four quarters, 01-03, 04-06, 07-09, 10-12. If today is in the last month of a quarter, assume it's the current quarter that is requested. """ end_year = today.year end_month = today.month - (today.month % 3) + 1 if end_month <= 0: end_year -= 1 end_mo...
4175c80d2aa75c0e3e02cdffe8a766c4a63686d0
33,418
from typing import Dict from typing import Union import logging import os def example_log_file(temporary_log_directory) -> Dict[str, Union[logging.Logger, logging.RootLogger, str]]: """Create a temporary log file for testing purposes.""" # Create a temporary directory to store the log file, and define a file...
8767d87232a987d8380b92d64b3a496bb5ce4c32
33,419
def extract_metadata(document): """Return the dict containing document metadata. :param document: :type document: :class:`docutils.nodes.document` :returns: docinfo data from document :rtype: dict From: https://github.com/adieu/mezzanine-cli @ mezzanine_cli/parser.py License: BSD (https://...
8c097569d240cc32ffc4496eda0e1e14e5269052
33,420
import os def get_bottleneck_features(model=None, source='path', container_path=None, tensor=None, classes=None, save=False, filename=None, ...
0dae2d4c4c35752492e7d27ed89aab9ae61a9b01
33,421
import scipy def ibp_loglik(Z, alpha): """Probability of an assignment matrix drawn from an IBP prior, where each customer chooses new dishes consecutively from the end, but otherwise the columns are unordered.""" N, K = Z.shape total = K * np.log(alpha) new_dish_counts = np.bincount(first_custome...
89178a93d32aefc7e1557363e27db4c6f2e9ee43
33,422
def neighbours(geohash): """ Returns all 8 adjacent cells to specified geohash:: | nw | n | ne | | w | * | e | | sw | s | se | :param geohash: string, geohash neighbours are required of :returns: neighbours as namedtuple of geohashes with properties n,ne,e,se,s,sw,w,nw ...
1fd5a515e9e72cc62b98d7cda57592ae1faa1595
33,423
def get_payload(address): """ According to an Address object, return a valid payload required by create/update address api routes. """ return { "address": address.address, "city": address.city, "country": str(address.country), "first_name": address.first_name, ...
34fde5090aae774a24a254ea7dd7f03cc0f784be
33,424
def new_alphabet(shift): """ :param shift: int, The magic number that user input to produce shifted. :return: str, a new_alphabet will be returned. """ first_half = ALPHABET[shift:] second_half = ALPHABET[:shift] # first_half = ALPHABET[(26 - shift):] # second_half = ALPHABET[0:(26 - shi...
71f3bf1c48647d8bc7641cb3070acebdb1d0170f
33,425
def _tensor_equal_tensor(x, y): """ Determine if two tensors are equal. Args: x (Tensor): first input tensor. y (Tensor): second input tensor. Returns: bool, if x == y return true, x != y return false. """ return F.equal(x, y)
a1149d02b520a79584a28c57424a4c1dfbdd4021
33,426
def CleanUnicodeString(s, separator=None): """Return list of words after lowering case and may be removing punctuations. Args: s: a unicode string. separator: default is None which implies separator of whitespaces and punctuation is removed. Returns: Lowered case string after removing runs of ...
c017cfd99d2153e3f10716f3664f665f315ecd89
33,427
def compute_cumulants(G, mus, R=None, return_R=False): """ Compute the cumulants of a Hawkes process given the integrated kernel matrix `G` and the baseline rate vector `mus` Arguments --------- G : np.ndarray The integrated kernel matrix of shape shape dim x dim mus : np.ndarray ...
1c1b48147af0b2d46f87d1f6050137d778db3e97
33,428
def interp_2d_to_3d(gs, grid, gt): """Interpolate 2D vector to a 3D grid using a georeferenced grid. Parameters ---------- gs : geopandas.GeoSeries Input geopandas GeoSeries grid : array_like 2D array of values, e.g. DEM gt : tuple GDAL-style geotransform coefficients fo...
fe0ae9ee3bb65a2b7ab255bb228a5d4411790d2d
33,429
import traceback def norecurse(f): """Decorator that keeps a function from recursively calling itself. Parameters ---------- f: function """ def func(*args, **kwargs): # If a function's name is on the stack twice (once for the current call # and a second time for the previous...
e7c7bebbbebcf53dad6772862f9ed4287c19a13d
33,430
def compare_model(models_list=None, x_train=None, y_train=None, calculate_accuracy=False, scoring_metrics=None, scoring_cv=3, silenced=False): """ Trains multiple user-defined model and pass out report Parameters ---------------- models_list: list a list of models to be trained ...
23f35fe1db665fe9b71262392a964d5562d09c69
33,431
def Material (colorVector): """ Material color. """ if colorVector == None: return None else: assert isinstance (colorVector, (list, tuple)) assert len (colorVector), 3 for cid in range (0, 3): assert colorVector[cid] >= 0 assert colorVector[ci...
89cee73c485669786f1a7cc4855ad8460c9db023
33,432
from typing import Callable def linear_objective( weights: np.ndarray, samples: np.ndarray, labels: np.ndarray, loss_fn: Callable ) -> float: """Calculates the final loss objective for a linear model""" # Compute scores for loss z = (samples @ weights) * labels # Mean loss over batch loss = np...
feac29c0d516897ac3c30c70c50364ff32407669
33,433
import os import shutil from datetime import datetime def generate_html_jump(htmlfilename, projectname, css_filename, jumpinfos): """Generates an html file at filename that contains links to all items in paths. :param htmlfilename: Filename of the resultant file. :param projectname: The name of the p...
27b8ee8b5ea29fb5d0b274a3a7ac7bfb43aa3a4f
33,434
import itertools import pathlib def jpg_walk(path: str, filter_types: list) -> list: """ 获取指导目录全部的图片路径 """ with checkTimes("image walker"): pools = list( itertools.chain( *[ list(pathlib.Path(path).glob(f"**/*.{types}")) f...
53524f3758601fbdc5f7664c234d30b995dd48ab
33,435
import math def auto_border_start(min_corner_point, border_size): """Determine upper-right corner coords for auto border crop :param min_corner_point: extreme corner component either 'min_x' or 'min_y' :param border_size: min border_size determined by extreme_frame_corners in vidstab process :return:...
e09d48a8c8c59053516357cbfd320cf92a080cc4
33,436
def val(model): """ 计算模型在验证集上的分数 """ top_k = 3 # 状态置为验证 model.eval() # 数据准备 dataset = ZhiHuData(conf.dev_data) data_loader = DataLoader(dataset, batch_size=conf.batch_size) # 预测 predict_label_and_marked_label_list = [] for i, batch in enumerate(data_loader): title, conte...
402bbcc829ec7e51e6ff70ab0c2b0a1b24b08c46
33,437
import array def regress_origin(x, y): """Returns coefficients to regression "y=ax+b" passing through origin. Requires vectors x and y of same length. See p. 351 of Zar (1999) Biostatistical Analysis. returns slope, intercept as a tuple. """ x, y = array(x, "float64"), array(y, "float64") ...
6466f5cb38e3be1070d25051161809018601f689
33,438
import configparser def bootPropsConfig(artifact, resources, targetDir, scalaVersion = "2.13.1"): """Create the configuration to install an artifact and its dependencies""" scala = {} scala["version"] = scalaVersion app = {} app["org"] = artifact.org app["name"] = artifact.name app["vers...
66b8a4d641b3b1728e1d99c3f7bd7104806cdc50
33,439
import requests def broadcast_transaction(hex_tx, blockchain_client=BlockchainInfoClient()): """ Dispatch a raw transaction to the network. """ url = BLOCKCHAIN_API_BASE_URL + '/pushtx' payload = {'tx': hex_tx} r = requests.post(url, data=payload, auth=blockchain_client.auth) if 'submitte...
34953d3cbdcd83b4fd9f7971214653f32466db63
33,440
import sys def check_energies(input_file): """ check energies """ print("Checking for intermidiate energies in input file %s" % input_file) f = None try: f = open(input_file, 'r') except IOError: print("Couldn't read from energy file %s" % input_file, file=sys.stderr) ...
fcb0dd7e4c2120ff525a61077dedf5997ad2baaf
33,441
import tempfile import subprocess def convert_BigWig2Wig(fname, path_to_binary=None): """ uses the UCSC bigwigToWig to do the conversion, ready for reading """ tmp_path = tempfile.mkdtemp() success=subprocess.check_call(["BigWig2Wig", fname, "%s/out.wig" % ...
97286ac5b36257f5522e94ae15ffd5772d54d726
33,442
def concat(inputs_list, axis=-1): """ Concatenate input tensors list Parameters ---------- inputs_list: Input tensors list axis: Axis along which to concatenate the tensors """ return tf.concat(inputs_list, axis=axis)
42bbe9ca6873ad9e66e13dd4fb29780a01c5e941
33,443
import torch def string_to_tensor(string, char_list): """A helper function to create a target-tensor from a target-string params: string - the target-string char_list - the ordered list of characters output: a torch.tensor of shape (len(string)). The entries are the 1-shifted ind...
eb6c7fcccc9802462aedb80f3da49abec9edc465
33,444
from typing import Iterable def do_lock( project: Project, strategy: str = "all", tracked_names: Iterable[str] | None = None, requirements: list[Requirement] | None = None, dry_run: bool = False, ) -> dict[str, Candidate]: """Performs the locking process and update lockfile.""" check_proje...
bb2d42774efff8df02778f219f09a1cf56c2e78d
33,445
def unique_nrpzs_active_subquery(): """Returns unique NRPZS within active centers.""" return db.session.query(OckovaciMisto.nrpzs_kod) \ .filter(OckovaciMisto.status == True) \ .group_by(OckovaciMisto.nrpzs_kod) \ .having(func.count(OckovaciMisto.nrpzs_kod) == 1) \ .subquery()
f46f3424b460e12d7096f165055ec7cf291eef91
33,446
def retrieve_context_service_interface_point_total_potential_capacity_total_size_total_size(uuid): # noqa: E501 """Retrieve total-size Retrieve operation of resource: total-size # noqa: E501 :param uuid: ID of uuid :type uuid: str :rtype: CapacityValue """ return 'do some magic!'
5a018beed4c7352235b8f29425ac28f47717091b
33,447
def index(): """ Index page. """ return render_template('dashboard/index.html')
e12209bc31f0a7f118359e847a3c39bd1a79f557
33,448
def is_tax_id_obligatory(country): """ Returns True if country is in EU or is Poland. Returns False for others. """ if country.name in all_eu_countries: return True return False
f9ae6f1baff4f77b2c6255f85e57833a1b7cc830
33,449
def indexTupleToStr(idx): """ Generate a string contains all the lowercase letters corresponding to given index list. Parameters ---------- idx : list of int A list of indices, each should be in [0, 26). Returns ------- str A string that corresponding to the indices...
5f234cff34b530316b6a957de7604321a82a309b
33,450
def _LookupPermset(role, status, access): """Lookup the appropriate PermissionSet in _PERMISSIONS_TABLE. Args: role: a string indicating the user's role in the project. status: a Project PB status value, or UNDEFINED_STATUS. access: a Project PB access value, or UNDEFINED_ACCESS. Returns: A Perm...
f9188ca34476e29e743ea92f689097a41c8dcb35
33,451
def _add_sld_boilerplate(symbolizer): """ Wrap an XML snippet representing a single symbolizer in the appropriate elements to make it a valid SLD which applies that symbolizer to all features, including format strings to allow interpolating a "name" variable in. """ return """ <StyledLayerDescri...
971199333570d5bc7baefec88f35b92922ef6176
33,452
def calculate_distance(location1, location2): """Calculate geodesic distance between two coordinates with ellipsoidal earth model. Args: location1: tuple of (latitude, longitude) as floats in Decimal Degrees location2: tuple of (latitude, longitude) as floats in Decimal Degrees Returns: A float in me...
569ae6af353d772234359ed70ac65e732ef2732a
33,453
def user(): """ form传值变量名: email,call,signature,mail,pre_school,address,detail_address,nickname 返回值: user_info: 用户个人信息的字典 """ if 'USR_ID' in session: if request.method == 'GET': user_info = query_db("SELECT * FROM student WHERE user_id = %s", ...
40a960150cab9b88d848f742109c5120f4a846a4
33,454
def sequence_names_match(r1, r2): """ Check whether the sequences r1 and r2 have identical names, ignoring a suffix of '1' or '2'. Some old paired-end reads have names that end in '/1' and '/2'. Also, the fastq-dump tool (used for converting SRA files to FASTQ) appends a .1 and .2 to paired-end reads if option -I ...
645ac09011cc4b94c5b6d60bf691b6b1734d5b6b
33,455
import torch def generate_mobile_module_lints(script_module: torch.jit.ScriptModule): """ Args: script_module: An instance of torch script module with type of ScriptModule Returns: lint_map: A list of dictionary that contains modules lints """ if not isinstance(script_module, torc...
4a6b25388fb549a273345f2f16f8e471c468a691
33,456
from typing import Set def manipulation(macid: MACID, decision: str, effective_set: Set[str]) -> bool: """Check whether a decision is motivated by an incentive for manipulation. Graphical Criterion: 1) There is a directed decision-free path from D_A to an effective decision node D_B. 2) There is a di...
d84df003733c7f18c668ef08a7804773b6e501c8
33,457
def _get_client_ids_meeting_condition(train_tff_data, bad_accuracy_cutoff, good_accuracy_cutoff, invert_imagery_likelihood, classifier_model): """Get clients that classify <bad_accuracy_cutoff or >good_ac...
c7d5878ee045eead44f50416aceac3005b0d4e2c
33,458
def get_wccp_service_group_settings( self, ne_id: str, cached: bool, ) -> dict: """Get per-group WCCP configuration settings from appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - wccp - GET - /wccp...
75e07296893eabafbbf0285134cf33cb3eb46480
33,459
def container_storage_opt() -> int: """Return the size for the 'storage_opt' options of the container. Return -1 if no option (or the default 'host') was given.""" if "storage_opt" in settings.DOCKER_PARAMETERS: storage = settings.DOCKER_PARAMETERS["storage_opt"].get("size", -1) if stor...
5d345bffd37dc0599d7ef137c08798a226322368
33,460
import random import sys def sscreen_chrome(url: str, path: str, website_name: str, index: int, width=1920, height=1080): """Настройка браузера и создание скриншота в формате png/base64 Args: url (str): URL сайта для перехода методом get path (str): Путь сохранения скриншота в формате png ...
8da5e78909bf45e4b94d825cdf684c8b8db645f1
33,461
import copy def construct_insert_conversatie_query(graph_uri, conversatie, bericht, delivery_timestamp): """ Construct a SPARQL query for inserting a new conversatie with a first bericht attached. :param graph_uri: string :param conversatie: dict containing escaped properties for conversatie :par...
61710bc10985cbf91bba354cd06916b77da587d7
33,462
def _minimum_chunk_size_accuracy( data: pd.DataFrame, partition_column_name: str = NML_METADATA_PARTITION_COLUMN_NAME, prediction_column_name: str = NML_METADATA_PREDICTION_COLUMN_NAME, target_column_name: str = NML_METADATA_TARGET_COLUMN_NAME, required_std: float = 0.02, ): """Estimation of min...
3401ccb564cd69e82effc8d7c949feffe725a7fa
33,463
def estimate_directions(correlations, pairs): """Estimate directions from a correlation matrix for specific pairs. Parameters ---------- correlations : numpy.ndarray, shape=(n_samples, n_samples) A correlation matrix. Can contain nan values. pairs : numpy.ndarray, shape=(< n_samples, 2) ...
be4282922bd8b052a60211ab61c4c678ef154e05
33,464
import os def render_template2(template, template_vars): """convenience function to render template in a non-Flask context""" loader_dir = os.path.join(os.path.dirname(__file__), 'templates') loader = FileSystemLoader(loader_dir) env = Environment(loader=loader, extensions=['jinja2.ext.i18n']) t...
043dc0c5717120685eb505f75220a8d773a807da
33,465
import argparse def build_parser(): """Build the argument parser.""" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug...
173c5e6d5276e79e234742f46576213db4ddf0a4
33,466
def get_est_input_size(out, height, p2pkh_pksize, p2sh_scriptsize, nonstd_scriptsize, p2wsh_scriptsize): """ Computes the estimated size an input created by a given output type (parsed from the chainstate) will have. The size is computed in two parts, a fixed size that is non type dependant, and a variable ...
621cea04217ac7b1396d89ecdfa4e8a3812bd636
33,467
import win32com.client def VisumInit(path=None,COMAddress='Visum.Visum.125'): """ ### Automatic Plate Number Recognition Support (c) 2012 Rafal Kucharski info@intelligent-infrastructure.eu #### VISUM INIT """ Visum = win32com.client.Dispatch(COMAddress) if path != None: Visum.Load...
dc9ebcb271ba86f3ab1180bed6b3da553e416f7d
33,468
def get(section, option, default=None): """ Simple accessor to hide/protect the multiple depth dict access: conf["SECTION"]["OPTION"] """ if section in conf.keys(): if option in conf[section].keys(): return conf[section][option] return default
9ece13a6cf0df1f50f5d9db70c035aef88fe2412
33,469
def inceptionresnetv1(**kwargs): """ InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for mod...
d424c883e03899cd37bc4f5421bd779ff85be991
33,470
import os import re def commonpath(paths): """py2 compatible version of py3's os.path.commonpath >>> commonpath([""]) '' >>> commonpath(["/"]) '/' >>> commonpath(["/a"]) '/a' >>> commonpath(["/a//"]) '/a' >>> commonpath(["/a", "/a"]) '/a' >>> commonpath(["/a/b", "/a"])...
94b92bd6802cc7483db2e3e05b8fb6a8a9630372
33,471
from typing import Dict def series_length(x: np.array, freq: int = 1) -> Dict[str, float]: """Series length. Parameters ---------- x: numpy array The time series. freq: int Frequency of the time series Returns ------- dict 'series_length': Wrapper of len(x). ...
a84f8e9f66bc862237ddff5ac651e961147aeee2
33,472
import requests import sys def request_put_multipart(uri, headers, multipart_title, multipart_file): """ Requests PUT uri as multipart. """ try: if multipart_file != '': f = open(multipart_file, "rb") else: f = None multipart_body = { multipart_title : (...
033492c044bcc5ab8f0218e8875a432fc2963863
33,473
import pygrib def _load_uvtp(date, time, latitude=-30, longitude=289.5): """Load U, V, T componenents of wind for GFS file given date and time.""" # do not want pygrib to be a dependency for the whole psfws package. # load in dataset (specific date/time given by args) try: grbs = pygrib.open(...
7cb414b26df805b946154f78782373955f3e6422
33,474
from typing import OrderedDict import six def ds2_variables(input, output_vars=False, names=None): """Generate a collection of `DS2Variable` instances corresponding to the input Parameters ---------- input : function or OrderedDict<string, tuple> or Pandas DataFrame or Numpy or OrderedDict<string, ty...
50bed5939530679dd36edd5a911b212687a085aa
33,475
import os import json def get_default_dal(_db_type, _db_name=""): """Returns a default database connection for the given db typ. Read from environment variable first, then assume files are in /config/subdirectory. # TODO: Fix so it uses \ on the windows platform. """ cfg_path = os.path.expanduser( ...
e6452f7687848251a3c3b61805db22306d2c60de
33,476
import hashlib def register(): """Register User""" # forget any user_id session.clear() # If the user has been redirected through an event url event = request.args.get('event') # if user reached route via POST (as by submitting a form via POST) if request.method == 'POST': # ch...
b6eb1c717a1c52dd206d6bb4f17e768a5a33bbc1
33,477
from typing import Sequence def topological_sort(edges: Sequence[Sequence]) -> list: """Produce a topological sorting (if one exists) using a BFS approach. Args: edges (Sequence[Sequence]): A list of edges pairs, ex: [('A', 'B'), ('A', 'C')]. Returns: list: An array with a non-unique top...
48a48449e7cd9390abbe2b589994cd7476684f69
33,478
def map_currency(currency, currency_map): """ Returns the currency symbol as specified by the exchange API docs. NOTE: Some exchanges (kraken) use different naming conventions. (e.g. BTC->XBT) """ if currency not in currency_map.keys(): return currency return currency_map[currency]
98b235952b042109a4e2083ce6c8fd85690c22e3
33,479
def FastResultRow(cols): """Create a ResultRow-like class that has all fields already preparsed. Non-UTF-8-String columns must be suffixed with !.""" getters = {} _keys = [] for i, col in enumerate(cols.split()): if col[-1] == '!': col = col[:-1] getter = itemgetter(i...
61483f6b3e6627eb5b2125c3a458e3baf6d263eb
33,480
def new_answer(notification): """ Obtains a new answer body for notifs where **source is the post** """ answer = Answer.query.filter_by(id=notification.target_id).first() post = Post.query.filter_by(id=notification.source_id).first() if not isinstance(answer, Answer): return "A new ...
41755acbaa870f0fabb9295a75a47c7e652bbbc0
33,481
def gather_indexes(sequence_tensor, positions): """Gathers the vectors at the specific positions. Args: sequence_tensor: Sequence output of `BertModel` layer of shape (`batch_size`, `seq_length`, num_hidden) where num_hidden is number of hidden units of `BertModel` layer. positions: Pos...
82e1b4520cbac66d45d56fc1f66286578acab0dd
33,482
def _check_type(value, expected_type): """Perform type checking on the provided value This is a helper that will raise ``TypeError`` if the provided value is not an instance of the provided type. This method should be used sparingly but can be good for preventing problems earlier when you want to rest...
a18ecfe9d63e6a88c56fc083da227a5c12ee18db
33,483
def find_rbm_procrustes(frompts, topts): """ Finds a rigid body transformation M that moves points in frompts to the points in topts that is, it finds a rigid body motion [ R | t ] with R \in SO(3) This algorithm first approximates the rotation by solving the orthogonal procrustes problem. """ ...
ae478e3c2139fe5bef1beb5c12ce75b07dee98e7
33,484
from typing import Callable import functools def adapt_type_to_browse_processor() -> Callable[[MediaProcessorType], BrowseGeneratorType]: """ Create generator for media objects from provided ID's :return: Decorator """ def _decorate(func: MediaProcessorType): """ Decorate ...
bbed3ec54ca966cc1886d02abbf5ccae8daca25c
33,485
from sys import path async def file( location, status=200, mime_type=None, headers=None, filename=None, _range=None, ): """Return a response object with file data. :param location: Location of file on system. :param mime_type: Specific mime_type. :param headers: Custom Headers...
10aa98edd4bc54b42d4540ea0b0837c70aa582d8
33,486
import healpy as hp def get_skyarea(output_mock, Nside): """ """ # compute sky area from ra and dec ranges of galaxies nominal_skyarea = np.rad2deg(np.rad2deg(4.0*np.pi/hp.nside2npix(Nside))) if Nside > 8: skyarea = nominal_skyarea else: pixels = set() for k in output_...
243e6d7a4b10673ed1d7fd03db48e7ac12c6ec0e
33,487
import os def _fetch_checksum(checksum, image_info): """Fetch checksum from remote location, if needed.""" if not (checksum.startswith('http://') or checksum.startswith('https://')): # Not a remote checksum, return as it is. return checksum LOG.debug('Downloading checksums file from %s', ...
a2d28bc2e0b0a6b019e78e49bd2799952dc21498
33,488
def get_patch_info(shape, p_size): """ shape: origin image size, (x, y) p_size: patch size (square) return: n_x, n_y, step_x, step_y """ x = shape[0] y = shape[1] n = m = 1 while x > n * p_size: n += 1 while p_size - 1.0 * (x - p_size) / (n - 1) < 50: n += 1 w...
b681f355ffbf3c7f5653996cd021950e2c9689d4
33,489
def validate_token(token=None): """Helps in confirming the Email Address with the help of the token, sent on the registered email address.\n Keyword Arguments: token -- Token passed in the user's email """ try: res = URLSafeTimedSerializer(SECRET).loads( # noqa token, salt=VERIF...
36ae68623cb04c0d3964c23b3ebc36a82376bec8
33,490
def rate2amount( rate: xr.DataArray, dim: str = "time", out_units: str = None ) -> xr.DataArray: """Convert a rate variable to an amount by multiplying by the sampling period length. If the sampling period length cannot be inferred, the rate values are multiplied by the duration between their time coor...
1a660711d6e5d7bffc14608e65aeb6d0ae5d7740
33,491
def makechis(d, N, maxchi): """Create the vector of chis for the chain. This is a length-N+1 list of exponents of d. The exponents are of the form [0, 1, 2, 1, 0] (if N+1 is odd) [0, 1, 2, 2, 1, 0] (if N+1 is even) Any numbers in the above exceeding ln(maxchi) / ln(d) are replace...
45dea0c399b1a8d8a055c28015d17f12d3ce5112
33,492
import requests def generate_input_f(reagent, MW, density): """ A helper function to properly formate input for concentration-to-amount calculations. Returns a dictionary where each key is a reagent component and each value is a sub-dictionary containing concentration, phase, molecular weight, and density...
2c8225509ba1512270a5ebfce130f79f2fba172c
33,493
def addCol(adjMatrix): """Adds a column to the end of adjMatrix and returns the index of the comlumn that was added""" for j in range(len(adjMatrix)): adjMatrix[j].append(0) return len(adjMatrix[0])-1
29ee11953cbdb757e8ea80e897751059e42f1d90
33,494
def get_table_m_1_a_5(): """表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小)) Args: Returns: list: 表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小)) """ # 表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小)) table_m_1_a_5 = np.array([ (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, ...
0ec4fbf123b503a31bf199f6a392147d07e8e714
33,495
import subprocess def get_shell_python_version(command='python -V'): """ Get version of Python running in shell | None --> tuple Use command keyword to test python3 instead of python if python version is Python 2. Minor version is not used at present but is included in case it is needed in futur...
27e441adb062c236881e4fc85d9e55db0962e4bc
33,496
import os def get_all_pattern_files(): """Return all data files in the data folder""" d = raw_data_dir() return sorted([x for x in os.listdir(d) if is_pattern_file(os.path.join(d, x))])
71766562529f392b21ac0efe943ef7e979e09590
33,497
import re def _get_first_sentence(s): """ Get the first sentence from a string and remove any carriage returns. """ x = re.match(r".*?\S\.\s", s) if x is not None: s = x.group(0) return s.replace('\n', ' ')
9e78fdba3a47c0f9faae6a938ab58498455555b2
33,498
def open_tsg_from_legos(filename): """ Open thermosalinograph (TSG) transect from the LEGOS dataset, and homogenize the coordinates Parameters ---------- filename : str Name of the file to open Returns ------- ds : xarray.Dataset The TSG transect under the ...
69c999c53fb8faff622b5f274e79ed6ef9415ddd
33,499