content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def spawn_shell(shell_cmd): """Spawn a shell process with the provided command line. Returns the Pexpect object.""" return pexpect.spawn(shell_cmd[0], shell_cmd[1:], env=build_shell_env())
07de3ae221b427baddb0b47f1d52e3eae91035e7
3,646,200
from collections import OrderedDict import sep from grizli import utils import tqdm def analyze_image(data, err, seg, tab, athresh=3., robust=False, allow_recenter=False, prefix='', suffix='', grow=1, subtract_background=False, include_empty=False, ...
b90920ac00a995fde90c43b07cae45a752786c15
3,646,201
import re import random import time import requests import os def qr(tag): """ called by an AJAX request for cipherwallet QR code this action is typically invoked by your web page containing the form, thru the code in cipherwallet.js, to obtain the image with the QR code to display it will re...
ed70f32df3a06fd6dc890a1ba324783f273c8e38
3,646,202
def get_experiment_table(faultgroup, faultname, tablename): """ Get anny table from a faultgroup """ node = faultgroup._f_get_child(faultname) table = node._f_get_child(tablename) return pd.DataFrame(table.read())
16c78e6925d3da227402e2e17e00bac38ff72ab7
3,646,203
def kjunSeedList(baseSeed, n): """ generates n seeds Due to the way it generates the seed, do not use i that is too large.. """ assert n <= 100000 rs = ra.RandomState(baseSeed); randVals = rs.randint(np.iinfo(np.uint32).max+1, size=n); return randVals;
6d98adfba2917ede64d0572c21d6fe1041327241
3,646,204
import PIL def filter_sharpen(image): """Apply a sharpening filter kernel to the image. This is the same as using PIL's ``PIL.ImageFilter.SHARPEN`` kernel. Added in 0.4.0. **Supported dtypes**: * ``uint8``: yes; fully tested * ``uint16``: no * ``uint32``: no * ``uin...
28b83153dc8931430e22f63f889cf195f01f80da
3,646,205
async def zha_client(hass, config_entry, zha_gateway, hass_ws_client): """Test zha switch platform.""" # load the ZHA API async_load_api(hass) # create zigpy device await async_init_zigpy_device( hass, [general.OnOff.cluster_id, general.Basic.cluster_id], [], None, ...
ba659195dc2e3d8d3510c25edcf4850a740483c1
3,646,206
import random def summary_selector(summary_models=None): """ Will create a function that take as input a dict of summaries : {'T5': [str] summary_generated_by_T5, ..., 'KW': [str] summary_generted_by_KW} and randomly return a summary that has been generated by one of the summary_model in summary_model if summar...
b8a2336546324d39ff87ff5b59f4f1174e5dd54c
3,646,207
import collections from datetime import datetime def handle_collectd(root_dir): """Generate figure for each plugin for each hoster.""" result = collections.defaultdict(lambda: collections.defaultdict(dict)) for host in natsorted(root_dir.iterdir()): for plugin in natsorted(host.iterdir()): ...
48eb4f2ad5976d51fbe1904219e90620aea1a82c
3,646,208
def create_policy_case_enforcement(repository_id, blocking, enabled, organization=None, project=None, detect=None): """Create case enforcement policy. """ organization, project = resolve_instance_and_project( detect=detect, organization=organization, project=projec...
60864cd51472029991a4bb783a39007ea42e4b58
3,646,209
def svn_fs_new(*args): """svn_fs_new(apr_hash_t fs_config, apr_pool_t pool) -> svn_fs_t""" return apply(_fs.svn_fs_new, args)
6ade0887b16e522d47d70c974ccecf8f8bec1403
3,646,210
import os def cam_pred(prefix, data_dir): """ """ groundtruth_dict = read(os.path.join('../data/contrast_dataset', 'groundtruth.txt')) cam = CAM(model=load_pretrained_model(prefix, 'resnet')) if data_dir == '../data/split_contrast_dataset': normalize = transforms.Normalize(mean=[0.7432, 0...
262cd00733047d2f61fff2fe440b6e81548ed533
3,646,211
def least_similar(sen, voting_dict): """ Find senator with voting record least similar, excluding the senator passed :param sen: senator last name :param voting_dict: dictionary of voting record by last name :return: senator last name with least similar record, in case of a tie chooses first alphabe...
8bcc8cde75e9ce060f852c0e7e03756d279491f0
3,646,212
import logging def _send_req(wait_sec, url, req_gen, retry_result_code=None): """ Helper function to send requests and retry when the endpoint is not ready. Args: wait_sec: int, max time to wait and retry in seconds. url: str, url to send the request, used only for logging. req_gen: lambda, no parameter fu...
d6856bf241f857f3acd8768fd71d058d4c94baaa
3,646,213
def load_file(path, types = None): """ load file in path if file format in types list ---- :param path: file path :param code: file type list, if None, load all files, or not load the files in the list, such as ['txt', 'xlsx'] :return: a list is [path, data] """ ext = path.split(".")[-1]...
dab404cf2399e3b87d23babb1a09be2b94c3d924
3,646,214
import numpy def get_dense_labels_map(values, idx_dtype='uint32'): """ convert unique values into dense int labels [0..n_uniques] :param array values: (n,) dtype array :param dtype? idx_dtype: (default: 'uint32') :returns: tuple( labels2values: (n_uniques,) dtype array, values2labe...
cd9f2884e26fa22785e24598f0f485d2931427d8
3,646,215
def delete_debug_file_from_orchestrator( self, filename: str, ) -> bool: """Delete debug file from Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - debugFiles - POST - /debugFiles/delete :param...
3357fc26e48771a716445b38c1fcc5c592c39cf9
3,646,216
from typing import Match def _replace_fun_unescape(m: Match[str]) -> str: """ Decode single hex/unicode escapes found in regex matches. Supports single hex/unicode escapes of the form ``'\\xYY'``, ``'\\uYYYY'``, and ``'\\UYYYYYYYY'`` where Y is a hex digit. Only decodes if there is an odd number of b...
3fdb275e3c15697e5302a6576b4d7149016299c0
3,646,217
def predict_next_location(game_data, ship_name): """ Predict the next location of a space ship. Parameters ---------- game_data: data of the game (dic). ship_name: name of the spaceship to predicte the next location (str). facing: facing of the ship (tuple) Return ------ predic...
996b58e0ac8d8754a49020e0e5df830fa472be99
3,646,218
from pathlib import Path import os def get_absolute_filename(user_inputted_filename: str) -> Path: """Clean up user inputted filename path, wraps os.path.abspath, returns Path object""" filename_location = Path(os.path.abspath(user_inputted_filename)) return filename_location
d8d704f4adcaa443658789c6d178b3ddb05552d0
3,646,219
def check_answer(guess, a_follower, b_follower): """Chcek if the user guessed the correct option""" if a_follower > b_follower: return guess == "a" else: return guess == "b"
acd1e78026f89dd1482f4471916472d35edf68a7
3,646,220
import argparse def command_line_arg_parser(): """ Command line argument parser. Encrypts by default. Decrypts when --decrypt flag is passed in. """ parser = argparse.ArgumentParser(description='Parses input args') parser.add_argument('input_file', type=str, help='Path to i...
c1e9305e2967368fb36ad8fcdbb654ef04f8d3bf
3,646,221
def respond(variables, Body=None, Html=None, **kwd): """ Does the grunt work of cooking up a MailResponse that's based on a template. The only difference from the lamson.mail.MailResponse class and this (apart from variables passed to a template) are that instead of giving actual Body or Html param...
214513edf420dc629603cc98d1728dec8c81aee9
3,646,222
from typing import Dict def canonical_for_code_system(jcs: Dict) -> str: """get the canonical URL for a code system entry from the art decor json. Prefer FHIR URIs over the generic OID URI. Args: jcs (Dict): the dictionary describing the code system Returns: str: the canonical URL ""...
f111a4cb65fa75799e799f0b088180ef94b71cc8
3,646,223
def correspdesc_source(data): """ extract @source from TEI elements <correspDesc> """ correspdesc_data = correspdesc(data) try: return [cd.attrib["source"].replace("#", "") for cd in correspdesc_data] except KeyError: pass try: return [cd.attrib[ns_cs("source")].repla...
18a2fe1d0daf0f383c8b8295105ad0027b626f31
3,646,224
def leaders(Z, T): """ (L, M) = leaders(Z, T): For each flat cluster j of the k flat clusters represented in the n-sized flat cluster assignment vector T, this function finds the lowest cluster node i in the linkage tree Z such that: * leaf descendents belong only to flat cluster j (i.e. T[p...
7b72b33b87e454138c144a791612d7af8422b0a6
3,646,225
from typing import List def create_unique_views(rows: list, fields: List[str]): """Create views for each class objects, default id should be a whole row""" views = {} for r in rows: values = [r[cname] for cname in fields] if any(isinstance(x, list) for x in values): if all(isin...
24b311c8b013f742e69e7067c1f1bafe0044c940
3,646,226
from typing import List import torch def check_shape_function(invocations: List[Invocation]): """Decorator that automatically tests a shape function. The shape function, which is expected to be named systematically with `〇` instead of `.`, is tested against the corresponding op in `torch.ops.*` f...
be237f2209f1e2007b53a1ecbe0c277bf2b37fe7
3,646,227
def _prepare_images(ghi, clearsky, daytime, interval): """Prepare data as images. Performs pre-processing steps on `ghi` and `clearsky` before returning images for use in the shadow detection algorithm. Parameters ---------- ghi : Series Measured GHI. [W/m^2] clearsky : Series ...
9433cce0ccb9dae5e5b364fce42f8ed391adf239
3,646,228
import numpy def interleaved_code(modes: int) -> BinaryCode: """ Linear code that reorders orbitals from even-odd to up-then-down. In up-then-down convention, one can append two instances of the same code 'c' in order to have two symmetric subcodes that are symmetric for spin-up and -down modes: ' c +...
e9b178165c8fe1e33d880dee056a3e397fa90bce
3,646,229
from sklearn.neighbors import NearestNeighbors def nearest_neighbors(data, args): """ 最近邻 """ nbrs = NearestNeighbors(**args) nbrs.fit(data) # 计算测试数据对应的最近邻下标和距离 # distances, indices = nbrs.kneighbors(test_data) return nbrs
d91014d082f7a15a26e453d32272381b7578c9de
3,646,230
def gradient(v, surf): """ :param v: vector of x, y, z coordinates :param phase: which implicit surface is being used to approximate the structure of this phase :return: The gradient vector (which is normal to the surface at x) """ x = v[0] y = v[1] z = v[2] if surf == 'Ia3d' or su...
2105c491f122508531816d15146801b0dd1c9b75
3,646,231
def authenticated_client(client, user): """ """ client.post( '/login', data={'username': user.username, 'password': 'secret'}, follow_redirects=True, ) return client
5f96ef56179848f7d348ffda67fc08cfccb080ed
3,646,232
def viterbi(obs, states, start_p, trans_p, emit_p): """ 請參考李航書中的算法10.5(維特比算法) HMM共有五個參數,分別是觀察值集合(句子本身, obs), 狀態值集合(all_states, 即trans_p.keys()), 初始機率(start_p),狀態轉移機率矩陣(trans_p),發射機率矩陣(emit_p) 此處的states是為char_state_tab_P, 這是一個用來查詢漢字可能狀態的字典 此處沿用李航書中的符號,令T=len(obs),令N=len(trans_p.key...
42f3037042114c0b4e56053ac6dfc6bd77423d39
3,646,233
def add_merge_variants_arguments(parser): """ Add arguments to a parser for sub-command "stitch" :param parser: argeparse object :return: """ parser.add_argument( "-vp", "--vcf_pepper", type=str, required=True, help="Path to VCF file from PEPPER SNP." ...
5fd6bc936ba1d17ea86a49499e1f6b816fb0a389
3,646,234
import graph_scheduler import types def set_time_scale_alias(name: str, target: TimeScale): """Sets an alias named **name** of TimeScale **target** Args: name (str): name of the alias target (TimeScale): TimeScale that **name** will refer to """ name_aliased_time_scales = list(filter...
889f2b70735a11ce8330e58b7294d3d115334d5f
3,646,235
def find_bounding_boxes(img): """ Find bounding boxes for blobs in the picture :param img - numpy array 1xWxH, values 0 to 1 :return: bounding boxes of blobs [x0, y0, x1, y1] """ img = util.torch_to_cv(img) img = np.round(img) img = img.astype(np.uint8) contours, hierarchy = cv2.fin...
7b7de4d163b18b099721c39b69721e477c473c16
3,646,236
from typing import Optional from datetime import datetime def resolve_day(day: str, next_week: Optional[bool] = False) -> int: """Resolves day to index value.""" week = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', ...
d09aba564f0293ac8b92699427199998bf7e869f
3,646,237
def write_image(image, path, bit_depth='float32', method='OpenImageIO', **kwargs): """ Writes given image at given path using given method. Parameters ---------- image : array_like Image data. path : unicode Image p...
754bfa4ffbc14fd7f8123c2cab754d0f3814ed05
3,646,238
import logging def get_gsheet_data(): """ Get's all of the data in the specified Google Sheet. """ # Get Credentials from JSON logging.info('Attempting to read values to Google Sheet.') creds = ServiceAccountCredentials.from_json_keyfile_name('TrackCompounds-1306f02bc0b1.json', SCOPES) lo...
872671a1bc9b17fec5e6db3fb4a7172567da4eff
3,646,239
def name_tensor(keras_tensor, name): """ Add a layer with this ``name`` that does nothing. Usefull to mark a tensor. """ return Activation('linear', name=name)(keras_tensor)
9ac83e8974efa2e48ab14d150a5da47ac7c23fb5
3,646,240
import operator def pluck(ind, seqs, default=no_default): """ plucks an element or several elements from each item in a sequence. ``pluck`` maps ``itertoolz.get`` over a sequence and returns one or more elements of each item in the sequence. This is equivalent to running `map(curried.get(ind), seqs)...
9bb31f94115eec0ba231c3c2bf9c067a52efca52
3,646,241
def shape_metrics(model): """"" Calculates three different shape metrics of the current graph of the model. Shape metrics: 1. Density 2. Variance of nodal degree 3. Centrality The calculations are mainly based on the degree statistics of the current graph For more information one is referred to...
003e72145ade222a7ec995eae77f6028527e8ba9
3,646,242
def calculate_actual_sensitivity_to_removal(jac, weights, moments_cov, params_cov): """calculate the actual sensitivity to removal. The sensitivity measure is calculated for each parameter wrt each moment. It answers the following question: How much precision would be lost if the kth moment was ex...
30f51ecc2c53126b6e46f5301bef857d104381cf
3,646,243
def escape_html(text: str) -> str: """Replaces all angle brackets with HTML entities.""" return text.replace('<', '&lt;').replace('>', '&gt;')
f853bcb3a69b8c87eb3d4bcea5bbca66376c7db4
3,646,244
import random def pptest(n): """ Simple implementation of Miller-Rabin test for determining probable primehood. """ bases = [random.randrange(2,50000) for _ in range(90)] # if any of the primes is a factor, we're done if n<=1: return 0 for b in bases: if n%b==0: return 0...
3a74cfebb6b14659a34ab0b6c761efd16d2736fa
3,646,245
def schedule_conv2d_NCHWc(outs): """Schedule for conv2d_NCHW[x]c Parameters ---------- outs : Array of Tensor The computation graph description of conv2d_NCHWc in the format of an array of tensors. The number of filter, i.e., the output channel. Returns ------- sch ...
a24cb4f6e1dd3d8891bc82df75f53c8afe709727
3,646,246
def calc_E_E_hs_d_t(W_dash_k_d_t, W_dash_s_d_t, W_dash_w_d_t, W_dash_b1_d_t, W_dash_ba1_d_t, W_dash_b2_d_t, theta_ex_d_Ave_d, L_dashdash_ba2_d_t): """1時間当たりの給湯機の消費電力量 (1) Args: W_dash_k_d_t(ndarray): 1時間当たりの台所水栓における節湯補正給湯量 (L/h) W_dash_s_d_t(ndarray): 1時間当たりの浴室シャワー水栓における節湯補正給湯量 ...
00cf40b221d2a24081d9c362fb5e8474057ddb93
3,646,247
import functools def keras_quantile_loss(q): """Return keras loss for quantile `q`.""" func = functools.partial(_tilted_loss_scalar, q) func.__name__ = f'qunatile loss, q={q}' return func
173a9410c2994bd02e5845a85cc2050489ce2d12
3,646,248
from typing import Dict import os import json def _load_template_file() -> Dict: """ Read and validate the registration definition template file, located in the same directory as this source file Returns ------- Dict Contents of the registration definition template file JSON, conv...
db3d3d8af9d78e8949dfb7428e45cf926346b7d0
3,646,249
from typing import Mapping from typing import Union def _reactions_table(reaction: reaction_pb2.Reaction, dataset_id: str) -> Mapping[str, Union[str, bytes, None]]: """Adds a Reaction to the 'reactions' table. Args: reaction: Reaction proto. dataset_id: Dataset ID. Returns: Dict ...
b09df06a13d1f1d42ab22da1c6bcc00c48c2e81d
3,646,250
from typing import List from typing import Dict from typing import Any import time import json def get_incidents_for_alert(**kwargs) -> list: """ Return List of incidents for alert. :param kwargs: Contains all required arguments. :return: Incident List for alert. """ incidents: List[Dict[str,...
48d2519d5e5aa25d6b0fc6a6e2c959489e861e1c
3,646,251
def pbar(*args, **kwargs): """ Progress bar. This function is an alias of :func:`dh.thirdparty.tqdm.tqdm()`. """ return dh.thirdparty.tqdm.tqdm(*args, **kwargs)
3de7101becc015e402aa067c676104f34679e549
3,646,252
import torch def calc_driver_mask(n_nodes, driver_nodes: set, device='cpu', dtype=torch.float): """ Calculates a binary vector mask over graph nodes with unit value on the drive indeces. :param n_nodes: numeber of driver nodes in graph :param driver_nodes: driver node indeces. :param device: the d...
2d2a08a86629ece190062f68dd25fc450d0fd84e
3,646,253
from typing import List def all_fermions(fields: List[Field]) -> bool: """Checks if all fields are fermions.""" boolean = True for f in fields: boolean = boolean and f.is_fermion return boolean
eb54d5ad5b3667e67634b06d2943e2d14c8a0c61
3,646,254
def open_file(name): """ Return an open file object. """ return open(name, 'r')
8921ee51e31ac6c64d9d9094cedf57502a2aa436
3,646,255
import math def _bit_length(n): """Return the number of bits necessary to store the number in binary.""" try: return n.bit_length() except AttributeError: # pragma: no cover (Python 2.6 only) return int(math.log(n, 2)) + 1
bea6cb359c7b5454bdbb1a6c29396689035592d7
3,646,256
def read_dwd_percentile_old(filename): """ Read data from .txt file into Iris cube :param str filename: file to process :returns: cube """ # use header to hard code the final array shapes longitudes = np.arange(-179.5, 180.5, 1.) latitudes = np.arange(89.5, -90.5, -1.) data ...
4d8366606c4e00eb43aa2c6a50a735617c7ca242
3,646,257
import base64 def media_post(): """API call to store new media on the BiBli""" data = request.get_json() fname = "%s/%s" % (MUSIC_DIR, data["name"]) with open(fname, "wb") as file: file.write(base64.decodestring(data["b64"])) audiofile = MP3(fname) track = {"file": data["name"], "title...
ff2aa7df2cdc6ea9bf3d657c7bb675e824639107
3,646,258
from pathlib import Path def obtain_stores_path(options, ensure_existence=True) -> Path: """ Gets the store path if present in options or asks the user to input it if not present between parsed_args. :param options: the parsed arguments :param ensure_existence: whether abort if the path does not e...
8bb3ff96cdc57f85058ad7cd3c96552462b8de9f
3,646,259
import os import fnmatch import pickle def extract_res_from_files(exp_dir_base): """Takes a directory (or directories) and searches recursively for subdirs that have a test train and settings file (meaning a complete experiment was conducted). Returns: A list of dictionaries where each element...
167124abb8d4ab22abe4237cc6ccbf691b6eab90
3,646,260
def compute_roc(distrib_noise, distrib_signal): """compute ROC given the two distribributions assuming the distributions are the output of np.histogram example: dist_l, _ = np.histogram(acts_l, bins=n_bins, range=histrange) dist_r, _ = np.histogram(acts_r, bins=n_bins, range=histrange) tprs, fp...
d9a970435fd7b0dc79cfb4eca24a6e6779ce9300
3,646,261
def zoom(clip, screensize, show_full_height=False): """Zooms preferably image clip for clip duration a little To make slideshow more movable Parameters --------- clip ImageClip on which to work with duration screensize Wanted (width, height) tuple show_full_height S...
668ef2b598432fc18510a5a69b73e400eec42b17
3,646,262
import typing def create( host_address: str, topics: typing.Sequence[str]) -> Subscriber: """ Create a subscriber. :param host_address: The server notify_server address :param topics: The topics to subscribe to. :return: A Subscriber instance. """ return Subscriber(create_...
40221a3be496528115afdc2eda063a006e08aadd
3,646,263
def solution(n): """ Return the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution(1000) 31875000 """ product = -1 d = 0 for a in range(1, n // 3): """Solving t...
a0bf0f0bde50f536f6c91f2b52571be38e494cea
3,646,264
import sys def python2_binary(): """Tries to find a python 2 executable.""" # Using [0] instead of .major here to support Python 2.6. if sys.version_info[0] == 2: return sys.executable or "python" else: return "python2"
054870972e68aa5b9e8609d93b8a82ad5e95d634
3,646,265
def with_metaclass(meta, *bases): """A Python 2/3 compatible way of declaring a metaclass. Taken from `Jinja 2 <https://github.com/mitsuhiko/jinja2/blob/master/jinja2 /_compat.py>`_ via `python-future <http://python-future.org>`_. License: BSD. Use it like this:: class MyClass(with_metacla...
0fe8e95fe29821e4cda8b66ff54ddd1b73e51243
3,646,266
def energy(particles): """total kinetic energy up to a constant multiplier""" return np.sum([particle.size ** 2 * np.linalg.norm(particle.speed) ** 2 for particle in particles])
29cae5c46d053f6fa558ba7a839d8b647c86d236
3,646,267
def post_adaptation_non_linear_response_compression_matrix(P_2, a, b): """ Returns the post adaptation non linear response compression matrix. Parameters ---------- P_2 : numeric or array_like Point :math:`P_2`. a : numeric or array_like Opponent colour dimension :math:`a`. ...
6b7f8bcc62142e99c63c0e7a9b073e25f3c36e8c
3,646,268
def forward(network, x): """ 入力信号を出力に変換する関数 Args: network: ネットワークのDict x: Inputの配列 Returns: 出力信号 """ w1, w2, w3 = network['W1'], network['W2'], network['W3'] b1, b2, b3 = network['B1'], network['B2'], network['B3'] # 1層目 a1 = np.dot(x, w1) + b1 z1 = si...
93c79a049e4c45f31a502aa81f840e48ff41d229
3,646,269
from typing import List def join_with_and(words: List[str]) -> str: """Joins list of strings with "and" between the last two.""" if len(words) > 2: return ", ".join(words[:-1]) + ", and " + words[-1] elif len(words) == 2: return " and ".join(words) elif len(words) == 1: return ...
ecb2c1fa060657f2ea4173c4382a81c9b42beeb9
3,646,270
from nipype.interfaces.base import Bunch def condition_generator(single_sub_data, params_name, duration = 2): """Build a bunch to show the relationship between each onset and parameter Build a bunch for make a design matrix for next analysis. This bunch is for describing the relationship between each ons...
6a4743043a49b6a1703c3b42840256a58e07f3bd
3,646,271
from typing import Dict from typing import Iterable from pathlib import Path def create_pkg( meta: Dict, fpaths: Iterable[_res_t], basepath: _path_t = "", infer=True ): """Create a datapackage from metadata and resources. If ``resources`` point to files that exist, their schema are inferred and added...
a668e4f1eacbf14d39165f9dbd4af1b283078ef1
3,646,272
from typing import Callable from typing import Any def one_hot( encoding_size: int, mapping_fn: Callable[[Any], int] = None, dtype="bool" ) -> DatasetTransformFn: """Transform data into a one-hot encoded label. Arguments: encoding_size {int} -- The size of the encoding mapping_fn {Callabl...
48758666885969c10b5e6ef46f2d392cd06800a2
3,646,273
def is_url_relative(url): """ True if a URL is relative, False otherwise. """ return url[0] == "/" and url[1] != "/"
91e1cb756a4554973e53fd1f607515577bc63294
3,646,274
def distance_matrix(lats, lons): """Compute distance matrix using great-circle distance formula https://en.wikipedia.org/wiki/Great-circle_distance#Formulae Parameters ---------- lats : array Latitudes lons : array Longitudes Returns ------- dists : matrix ...
a322306d13f2e15b60a61eb1fcff95c71f005d07
3,646,275
def _split_link_ends(link_ends): """ Examples -------- >>> from landlab.grid.unstructured.links import _split_link_ends >>> _split_link_ends(((0, 1, 2), (3, 4, 5))) (array([0, 1, 2]), array([3, 4, 5])) >>> _split_link_ends([(0, 3), (1, 4), (2, 5)]) (array([0, 1, 2]), array([3, 4, 5])) ...
3aee58b5e4e928d45a33026c0b9e554c859d0d6f
3,646,276
from heapq import heappop, heappush def dijkstra(vertex_count: int, source: int, edges): """Uses Dijkstra's algorithm to find the shortest path in a graph. Args: vertex_count: The number of vertices. source : Vertex number (0-indexed). edges : List of (cost, edge) (0-indexed...
d33f8dc28bf07154ffd7582a5bdd7161e195f331
3,646,277
import os import secrets def save_picture(form_picture): """ function for saving the path to the profile picture """ app = create_app(config_name=os.getenv('APP_SETTINGS')) # random hex to be usedin storing the file name to avoid clashes random_hex = secrets.token_hex(8) # split method for...
5c725a06508d4d4316b85305ae37f30d80a90d28
3,646,278
def plot_labels(labels, lattice=None, coords_are_cartesian=False, ax=None, **kwargs): """ Adds labels to a matplotlib Axes Args: labels: dict containing the label as a key and the coordinates as value. lattice: Lattice object used to convert from reciprocal to Cartesian coordinates ...
b0172061e043fcaef38d2503be67333862da3acf
3,646,279
def contains(poly0, poly1): """ Does poly0 contain poly1? As an initial implementation, returns True if any vertex of poly1 is within poly0. """ # check for bounding box overlap bb0 = (min(p[0] for p in poly0), min(p[1] for p in poly0), max(p[0] for p in poly0), max(p[1] for p in poly...
26ea4bd17a55ed05afa049a9aaab5237f0965674
3,646,280
import os import json def get_ids_in_annotations(scene, frame, quality): """ Returns a set of all ids found in annotations. """ annotations_path = os.path.join(scene, '%sPose3d_stage1' % quality, 'body3DScene_%s.json' % frame) if not os.path.exists(annotations_...
9e754af7ec397e9a36151b7f49f69d2de6ca0128
3,646,281
def new_halberd(game_state): """ A composite component representing a Sword item. """ c = Composite() set_item_components(c, game_state) set_melee_weapon_component(c) c.set_child(Description("Halberd", "A long stick with a with an axe-head at one end." ...
1e6ccdce08a5e4e26c6dc8d09db38ef4b6d7b2f0
3,646,282
from typing import List def get_regional_services(service_list: List[AWSService] = None) -> List[AWSService]: """List all services which are tied to specific regions.""" services = service_list or get_services() return [s for s in services if s.is_regional]
d856acfc24430102ccb72a76eedbc47ace842894
3,646,283
import os import errno def _ReapUntilProcessExits(monitored_pid): """Reap processes until |monitored_pid| exits, then return its exit status. This will also reap any other processes ready to be reaped immediately after |monitored_pid| is reaped. """ pid_status = None options = 0 while True: try: ...
ef540cc60634fe13ddc58b434f7fabe01109ddda
3,646,284
def f_setup_config(v_config_filename): """This function read the configuration file""" df_conf_file = pd.read_csv(v_config_filename, delimiter="|", header=0) api_key = df_conf_file[df_conf_file.CONFIG_VAR == 'API_KEY']['VALUE'].values[0] data_dir = df_conf_file[df_conf_file.CONFIG_VAR == 'DATA_DIR']['V...
b2e9a8e822a2c582549055184cc8096f174fdb3b
3,646,285
def choose_username(email): """ Chooses a unique username for the provided user. Sets the username to the email parameter umodified if possible, otherwise adds a numerical suffix to the email. """ def get_suffix(number): return "" if number == 1 else "_"+str(number).zfill(3) user_mo...
594c060df6df5c89c7c08a2e3979960866cc5688
3,646,286
def lms2rgb(image): """ Convert an array of pixels from the LMS colorspace to the RGB colorspace. This function assumes that each pixel in an array of LMS values. :param image: An np.ndarray containing the image data :return: An np.ndarray containing the transformed image data """ return np...
736d7101a4c4256725fd4f09c6a453c418c1ae81
3,646,287
def __apply_to_property_set (f, property_set): """ Transform property_set by applying f to each component property. """ properties = feature.split (property_set) return '/'.join (f (properties))
5091065f90b602a775c24eca9e2ab3bc6861e0c8
3,646,288
from typing import Dict import tarfile import os def _zip_index(job_context: Dict) -> Dict: """Zips the index directory into a single .tar.gz file. This makes uploading and retrieving the index easier since it will only be a single file along with compressing the size of the file during storage. ...
675061fe65c97ddabb159cd4d960c8cdafca27a3
3,646,289
def _return_feature_statistics(feature_number: int, feature_value: float, names: list): """ Arguments: feature_number (int) -- number of the feature feature_value (float) -- value of the feature (used to compute color) names (list) -- list of feature names Returns: """ per...
9cc678c1180e6533bd803b00388db84d085030b3
3,646,290
def calc_eta_FC(Q_load_W, Q_design_W, phi_threshold, approach_call): """ Efficiency for operation of a SOFC (based on LHV of NG) including all auxiliary losses Valid for Q_load in range of 1-10 [kW_el] Modeled after: - **Approach A (NREL Approach)**: http://energy.gov/eere/fuelcells/d...
0cd14d976d773dc34d7ea96e80db4267e33aac1f
3,646,291
from typing import Tuple def erdos_renyi( num_genes: int, prob_conn: float, spec_rad: float = 0.8 ) -> Tuple[np.ndarray, float]: """Initialize an Erdos Renyi network as in Sun–Taylor–Bollt 2015. If the spectral radius is positive, the matrix is normalized to a spectral radius of spec_rad and the scal...
87e29376ec79ea9198bb3c668fdc31fc61216a26
3,646,292
import _ctypes def IMG_LoadTextureTyped_RW(renderer, src, freesrc, type): """Loads an image file from a file object to a texture as a specific format. This function allows you to explicitly specify the format type of the image to load. The different possible format strings are listed in the documenta...
ef9f963e71b7419ec790bd3fdb06eb470d30972b
3,646,293
def soft_l1(z: np.ndarray, f_scale): """ rho(z) = 2 * ((1 + z)**0.5 - 1) The smooth approximation of l1 (absolute value) loss. Usually a good choice for robust least squares. :param z: z = f(x)**2 :param f_scale: rho_(f**2) = C**2 * rho(f**2 / C**2), where C is f_scale :return: """ loss...
95813cd59c99ab94e6b4693237dc85f5b7d31b14
3,646,294
def calculate_hit_box_points_detailed(image: Image, hit_box_detail: float = 4.5): """ Given an image, this returns points that make up a hit box around it. Attempts to trim out transparent pixels. :param Image image: Image get hit box from. :param int hit_box_detail: How detailed to make the hit bo...
dd74e18fac1fe96728837ce8af62c38461592baa
3,646,295
async def open_local_endpoint( host="0.0.0.0", port=0, *, queue_size=None, **kwargs ): """Open and return a local datagram endpoint. An optional queue size argument can be provided. Extra keyword arguments are forwarded to `loop.create_datagram_endpoint`. """ return await open_datagram_endpoint(...
a3b03408bbe35972b0588912a0628df2be9cddc5
3,646,296
from typing import Union def parse_bool(value: Union[str, bool]) -> bool: """Parse a string value into a boolean. Uses the sets ``CONSIDERED_TRUE`` and ``CONSIDERED_FALSE`` to determine the boolean value of the string. Args: value (Union[str, bool]): the string to parse (is converted to lowercas...
86bb61b82eb71627f3563584779f3a17ea1bc8b7
3,646,297
from datetime import datetime import traceback import requests def send_rocketchat_notification(text: str, exc_info: Exception) -> dict: """ Sends message with specified text to configured Rocketchat channel. We don't want this method to raise any exceptions, as we don't want to unintentionally break any...
c466621cfd8ead8f6773bc1c461fb779c0374937
3,646,298
def get_number_of_forms_all_domains_in_couch(): """ Return number of non-error, non-log forms total across all domains specifically as stored in couch. (Can't rewrite to pull from ES or SQL; this function is used as a point of comparison between row counts in other stores.) """ all_forms =...
a30f5e6410dc3b91c3a962169fad20e2a8d4a8fb
3,646,299