content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def use_scratch_dir(original_wf, scratch_dir): """ For all RunVaspCustodian tasks, add the desired scratch dir. Args: original_wf (Workflow) scratch_dir (path): Path to the scratch dir to use. Supports env_chk Returns: Workflow """ for idx_fw, idx_t in get_fws_and_tasks(...
0e45b317d477b84fe92359f10a6294d86b5ff670
3,627,400
from typing import cast import tqdm def infer_tests_wrapper( weight_path: str, model_name: str, dataset: COCO_Dataset, test_name: str, handler_constructor: type, data_dump_dir: str=None, video_dump_dir: str=None, img_dump_dir: str=None, skip_if_data_dump_exists: bool=False, show_preview: bool=Fals...
8df325dc6ae58f520d479c6b1046ace0e186449b
3,627,401
def auto_peak_finder(prominence, x_data, y_data): """ automatic peak finding routine which finds peaks given a user supplied prominence, and presents the peaks until user is happy :param prominence: height from noise to tip of peaks :param x_data: x_data as np array :param y_data: y_data as np a...
1e23d23c0edc679a3429b3ef0f91b905c34e91d7
3,627,402
from typing import OrderedDict def dataframe_reg_as_panel(df,against='index',regfunc='OLS'): """ Perform regression for each of the columns of the dataframe, and return the regression result as panel. Parameters: ----------- against: the variable used as the independent variable in the re...
fac0d6c768b4c8bd9fbafad4ba5e3216e539f28d
3,627,403
import threading def serve_pyr(name, url, root_path, config='config.ini'): """Serve the Pyramid app locally in a separate thread that forks a subprocess that invokes the pserve executable. Return a function that stops serving the Pyramid app. """ process = _fork_server_process(url, root_path, conf...
a21e182b27b424bb7bf0e669209391a429d81541
3,627,404
def order_line_needs_automatic_fulfillment(line_data: OrderLineInfo) -> bool: """Check if given line is digital and should be automatically fulfilled.""" digital_content_settings = get_default_digital_content_settings() default_automatic_fulfillment = digital_content_settings["automatic_fulfillment"] co...
baa85396d3da44670ce634353db55a589ca27387
3,627,405
def docker_setup(project_path: str) -> bool: """ Tries to find evidence of a docker setup in the project. """ _file_names = ['[Dd]ockerfile', '[Dd]ocker-compose.yml'] for name in _file_names: _findings = search_filename( base_folder=project_path, file_name=name, ...
6f1e18d83cbcfdac21105b89a6dedb8c17e1d026
3,627,406
def prac_q_count(year, month, day, hour, qtemplate): """ Fetch the practice count for the given time/qtemplate or return False if not found. Can be used when deciding if to INSERT or UPDATE. Note: may return 0 if count is zero, is not same as not exist (False) """ sql = """SELECT "qtemplate"...
adc90d18d8f55ab76a4f3939b622f6ba30a86c66
3,627,407
import getpass import base64 def get_headers(gargs): """Get the required headers. """ headers = { 'Content-type': 'application/json' } if gargs.no_passwd: return headers if gargs.passwdfile is not None: passwd = open(gargs.passwdfile, "r").read().strip() auth_str ...
04d7a9da9e30fbfdf86b0a09d23dc178a0615d27
3,627,408
import torch def highest_prob_class(y_predicted: torch.Tensor, y_true: torch.Tensor, **kwargs) -> _TensorOrTensors: """ Get the index of class with highest probability. """ y_predicted = y_predicted.max(dim=-1)[1] assert y_true.shape == y_predicted.shape return y_predicted, y_true
8107c2f960e22d7da9c042242365ebb1f2e96722
3,627,409
def vectorized_local_axes(three_atoms_coords): """ Takes as an argument a Nx3x3 block of reference atom coordinates to construct N local axes systems (Nx3x3) """ u12 = vectorized_unit_vector(three_atoms_coords[:, [0,1], :]) u23 = vectorized_unit_vector(three_atoms_coords[:, [1,2], :]) if np.any(...
2f19924b516ce76fc4f769e675c78f0e5ddfd3c1
3,627,410
def set_option(option, value): """Set a single option using the flat format, i.e ``section.option`` Parameters ---------- option: str Option name in the ``section.option`` format value: Value to set Example ------- .. ipython:: python @suppress from xoa...
a5cb71e60da6d80bf0409c91945dd31a9e44be74
3,627,411
def dict_to_capabilities(caps_dict): """Convert a dictionary into a string with the capabilities syntax.""" return ','.join("%s:%s" % tpl for tpl in caps_dict.items())
12a321ba5f337f8da116ec7adec68d717fbc776f
3,627,412
import numpy def delta(flag, F, K, t, r, sigma): """Returns the Black delta of an option. :param flag: 'c' or 'p' for call or put. :type flag: str :param F: underlying futures price :type F: float :param K: strike price :type K: float :param t: time to expiration in years ...
b3439872aa41e697d42d1e2ef503996e82651db8
3,627,413
def main(X, Y, X0, Y0, depth, omegaX, omegaY, omegaZ, ax, ay, az, opening, nu, verbose=False): """ Test CDM with test input parameters X0, Y0, depth: define the position of the dislocation omegaX, omegaY, omegaZ: define the orientation (clockwise rotations) of the dislocation ax, ay, az: define the ...
40a887b8282cd29c7b63c15882eaf4191a0658f4
3,627,414
def extend_view(response, fetch_page_data, fetch_multimedia, raise_errors): """ Extends view query results with pronunciation URLs, multimedia URLs, and extended hanja information by scraping the dictionary website. This function modifies the response in-place, and returns the modified object. See ...
0c35341fb146144f8bc3efa4a98d89419d625e1a
3,627,415
def mean(vector): """ Calculates the arithmetic mean of the given vector. Args: ----- vector : list A non-empty list/array of numbers to be averaged. Returns: -------- mean : float The arithmetic mean of the given vector. """ return sum(vector) /...
71bd9a37cb0bfb166632866d0a29be9b14236364
3,627,416
import os import subprocess def main(): """ Composes a BLAST command from a (DataTable) AJAX request, forwarded from molmod endpoint /blast_run, and executes the command using subprocess. """ # # Format the BLAST command - return an error if the input form is missing # required values. ...
71542a32a5a4dd8ee12bb588e18a0c815ef0fcec
3,627,417
import math def get_hamming_window(w, h, rot, sx, sy, out_size_w, out_size_h): """ A hamming window map :param w: init ellipse w :param h: init ellipse h :param rot: rotation angle(rad) :param sx: center x coordinate of the window :param sy: center y-coordinate of the window :param out...
4611eb52ba8abd00c1c78a78fb60b62ae13a5755
3,627,418
def reconstructimage(lpyramid, f): """ Reconstruct image from Laplacian pyramid Args: lpyramid: Laplacian pyramid f: 2d filter kernel Returns: Reconstructed image as (H, W) np.array clipped to [0, 1] """ # # You code here # lpyramid_flip = np.flip(lpyramid) g...
2cc70a899ab5694846010fcd6980e245d25671f1
3,627,419
def convert_to_pressure_levels(mv, plevs, dataset, var, season): """ Given either test or reference data with a z-axis, convert to the desired pressure levels. """ mv_plv = mv.getLevel() # var(time,lev,lon,lat) convert from hybrid level to pressure if mv_plv.long_name.lower().find('hybrid') ...
b4f14f9a62356f3e3718fce7a71f8c3efc2d347e
3,627,420
def matrix2xzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rz(k2) @ Rx(k1) = [[c2c3, -c1s2c3+s1s3, s1s2c3+c1s3], [s2, c1c2, -s1c2], [-c2s3, c1s2s3+s1c3, -s1s2s3+c1c3]] """ rotation_matrices = rotation_matrices.resha...
9371a5b459f9c92354752e94a9fb292add1dca96
3,627,421
from datetime import datetime def do_auth(): """ perform authentication using API_KEY, stores token and stored timestamp in integration context, retrieves new token when expired """ auth = demisto.getIntegrationContext() now_epoch = int(datetime.today().strftime('%s')) if ("token" in ...
875c4dd44c2e253b62382a1ffb37ab0fbc5c3333
3,627,422
async def write_credential_def(controller, schema_id): """ Writes Credential Definition to the ledger Parameters: ---------- controller: AriesController The aries_cloudcontroller object Schema id Returns: ------- write_cred_response :dict """ write_cred_response =...
4825dc30aa0ecf4097b654d7119fb2a9be41818a
3,627,423
def guess_cloudwatch_log_group(alarm_name): """ Guess the name of the CloudWatch log group most likely to contain logs about the error. """ if alarm_name.startswith("loris-"): return "platform/loris" if alarm_name.startswith("catalogue-api-romulus"): return "ecs/catalogue_api_gw...
94822c16ce6c84b154be40581eb74e25e2cbe898
3,627,424
def update_attrs(orig, keys, override): """Utility function for altering and adding the specified attributes to a particular repository rule invocation. This is used to make a rule reproducible. Args: orig: dict of actually set attributes (either explicitly or implicitly) by a particu...
82498f78604924c281da1fab372a871d5f224010
3,627,425
def GetCreateLabelsFlag(extra_message='', labels_name='labels', validate_values=True): """Makes the base.Argument for --labels flag.""" value_type = VALUE_FORMAT_VALIDATOR if validate_values else None format_help = [KEY_FORMAT_HELP] if validate_values: format_help.append(VALUE_FORMAT...
aa8e5e6f40d2a9ab53668ff16b5c9227bca42541
3,627,426
import six def unflatten(d, splitter='tuple', inverse=False): """Unflatten dict-like object. Parameters ---------- d : dict-like object The dict that will be unflattened. splitter : {'tuple', 'path', Callable} The key splitting method. If a Callable is given, the Callable will be ...
44100cfcc8d3cc399f94bd6d3f6e7e780d7a1012
3,627,427
def get_mapped_to_elements(mapper): """ The mapper list contains all the element names that have been mapped to by other elements """ mapper_list = [] for element in mapper: for list_element in mapper[element]: if list_element not in mapper_list: mapper_list.a...
6f8d940997f4b871b6934db0592663448343e031
3,627,428
def psd(time, rate, norm='leahy'): """ Returns power spectral density from a (real) time series with Leahy normalization. Args: time: array of times (evenly binned). rate: array of rate in counts/s. Kwargs: norm: Normalization (only Leahy for ...
878dda8fc3821560335d7b14fc0d8863b2f0f84e
3,627,429
async def session_fetch( handle: SessionHandle, category: str, name: str, for_update: bool = False ) -> EntrySetHandle: """Fetch a row from the Store.""" category = encode_str(category) name = encode_str(name) return await do_call_async( "askar_session_fetch", handle, categor...
ab3c0a9ec2006e4b83b8c2018c3dcf529f9f532d
3,627,430
def login(hostname, username, password): """Login to the switch and return the console with the prompt at `#`""" try_again = True alternatives = [r'[\r\n]+.+#', "Permission denied", "[Pp]assword: *", ">", "(ibmnos-cli/iscli):*",...
b705470108c07ca88497e883e1c55325596ad36c
3,627,431
def _ComputeImageDiff(failure_image, golden_image): """Compute mask showing which pixels are different between two images.""" return (ImageChops.difference(failure_image, golden_image) .convert('L') .point(lambda i: 255 if i else 0))
e830aff6434928d1b32b76bfc61b7fc366c24a36
3,627,432
def load_pytest_conf(path, parser): """loads a ``pytestconf.py`` file and update default parser and / or tester. """ namespace = {} exec(open(path, 'rb').read(), namespace) if 'update_parser' in namespace: namespace['update_parser'](parser) return namespace.get('CustomPyTester', PyTe...
435584078584538adadd0feb7455f2010e1cdc4c
3,627,433
def svn_client_import3(*args): """ svn_client_import3(svn_commit_info_t commit_info_p, char path, char url, svn_depth_t depth, svn_boolean_t no_ignore, svn_boolean_t ignore_unknown_node_types, apr_hash_t revprop_table, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t "...
a10005cfcafa90fab40efaa84b8c69f461a7e772
3,627,434
def labs(**kwargs): """ Change plot title, axis labels and legend titles. Parameters ---------- kwargs: A list of new names in the form aesthetic='new name', e.g. title='Plot title' or aes-name='Scale label' Returns -------- Axis label specification. Note -...
84820d0a626e623919957ff48b5a95f4a28d3756
3,627,435
def _filter(paths, cgroups, rgroups): """ Keep only paths with the appropriate cgroups and/or rgroups """ kept = [] for path in paths: valid_cgroup = (cgroups is None or _cname(path) in cgroups) valid_rgroup = (rgroups is None or _rname(path) in rgroups) if valid_cgroup and valid...
a90b89be831bcad3da9ed4e692c0d78d232537b3
3,627,436
def patch(target, new): """Simplified module monkey patching via context manager. Args: target: Target class or object. new: Object or value to replace the target with. """ def _import_module(target): components = target.split('.') import_path = components.pop(0) ...
c5d9fbf37d35991938838bc813ebc443c9934304
3,627,437
def _load_with_pydub(filename, audio_format): """Open compressed audio file using pydub. If a video file is passed, its audio track(s) are extracted and loaded. This function should not be called directely, use :func:`from_file` instead. :Parameters: `filename`: path to audio file. ...
b16fa9897afd63650c2de66765aec6710ae131cc
3,627,438
from typing import Optional def get_storage(store: Optional[StorageEngine] = None) -> StorageEngine: """Get current storage method.""" if store is not None: return store else: if _storage_stack.top is not None: out: StorageEngine = _storage_stack.top return out ...
eeeaa059feacd22aa8c3b79e10b9826d49108af5
3,627,439
def UniformDot(d=100, p=100, tol=1e-2): """ Let U be a random `d` x `p` matrix with i.i.d. uniform entries. Then Sigma = ``cov2corr``(U^T U) """ U = np.random.uniform(size=(d, p)) V = np.dot(U.T, U) V = cov2corr(V) return cov2corr(shift_until_PSD(V, tol=tol))
a8c491c01f9f47dc1442f476c363bff1ae588f3a
3,627,440
def get_supported_eline_list(*, lines=None): """ Returns the list of the emission lines supported by ``scikit-beam`` Parameters ---------- lines : list(str) tuple or list of strings, that defines, which emission lines are going to be included in the output list (e.g. ``("K",)`` or ...
c711a66b2d8b8c1017d75024e93d18668d0b8106
3,627,441
def visualize_test(test_data_full, test_data, thetas): """ Visualize Test for Testing Results :param test_data_full: the test data set (full) with labels and data :param thetas: model parameters :return: fig """ fig, ax = plt.subplots() ax.scatter(test_data_full...
2d84204578b7cb26ebda381c5f2a25319d0fee93
3,627,442
def normalization(data, dmin=0, dmax=1, save_centering=False): """ Normalization in [a, b] interval or with saving centering x` = (b - a) * (xi - min(x)) / (max(x) - min(x)) + a Args: data (np.ndarray): data for normalization dmin (float): left interval dmax (float): right interval save_centering (bool): if...
acfa7aaae1bb7eb5752751f5c929ddb7868ccf49
3,627,443
import os def relpath(path: str, start: str = os.curdir) -> str: """Return a relative version of a path""" try: return os.path.relpath(path, start) except ValueError: return path
cd9daffa197a0443eb49ca515c805902eb404554
3,627,444
def normalize_adjacency_matrix(adjacency_matrix): """ Helper function for denoise_predictions. Arguments: adjacency_matrix: A matrix of size h * w, https://en.wikipedia.org/wiki/Adjacency_matrix For this type of normalization, should be symmetric - i.e. from an...
60043f8ee4ee8cf19c33dec683b0c8fc28d3d1fb
3,627,445
import six import struct def dl_parse_bsd_lo(link_packet): """parse bsd loopback packet""" if len(link_packet) < 4: return None, None # first 4 bytes are packet size which always less then 256, may be LE or BE if six.byte2int(link_packet) == 0 and six.indexbytes(link_packet, 1) == 0: p...
2d1a7eb62742ce8f43b11b836e9ad8fe78d3a097
3,627,446
def energycalc(spcode0, climatezone, dbh_orig, height, azimuth, distance, vintage, shade_reduction, lu_conversion_shade, lu_conversion_climate, eqpt_cooling_potential, eqpt_heating_potential): """Calculates avoided emissions values given tree and building relationship data. Args: spcode0 - species cod...
3164bf258aef232093541f6f421becd034461cbe
3,627,447
def _create_scene_object(token: str, object_type: TrackedObjectType) -> Agent: """ :param token: a unique instance token :param object_type: agent type. :return: a random Agent """ scene = SceneObject.make_random(token, object_type) return Agent( tracked_object_type=object_type, ...
1d71b8a25980f40768900aaf22874b11b5b3fc99
3,627,448
def conv3x3_group(in_planes, out_planes, groups=1, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, groups=groups, stride=stride, padding=1, bias=False)
f594509979bffc438fb459b15ddc3a64c9a1220d
3,627,449
def named(name): """Change the name of something (via a decorator).""" def decorator(obj): obj.__name__ = name return obj return decorator
5b4873e7e6475e23ab13cd1fc203d6c79622d96d
3,627,450
def split_repo_and_dir(repo): """ Split the input string org-name/repo-name/subdir-name/more/sub/dirs (where '/subdir-name/more/sub/dirs' is optional) into org-name/repo-name and subdir-name/more/sub/dirs The second part might be the empty string if no subdir-name was given. """ parts = repo.s...
c5cfb58fa0780af0391fc07fa78279af4f5c2790
3,627,451
from pathlib import Path import os import shutil def save_upload_file_tmp(upload_file: UploadFile): """Saves recieved dat and returns directory""" try: suffix = Path(upload_file.filename).suffix direc = mkdtemp(dir="dat") with NamedTemporaryFile( delete=False, suffix=suffix...
6b5a7a659ccbc0697a96429f6a7f92491371c308
3,627,452
import requests def hits_recorded(pitcher_id=None): """Get the number of hits recorded by each historical pitcher. If pitcherId is specified, only that pitcher is returned. `pitcher_id` is a single string UUID or list of string UUIDs. Returns dictionary {pitcher_id: count}""" params = {} if pitch...
3b0b2e81ce35ad0437c1721a18518ab3b6ed53ff
3,627,453
def calculateOnlineVariance(data): """ Returns the variance of the given list. :param data: A list of numbers to be measured (ie. the window) :returns: The variance of the data. """ n, mean, M2 = 0, 0, 0 for x in data: n = n + 1 delta = x - mean mean = mean + delta/n M2 = M2 + delta*(x-mean) varian...
bf8d70cd736471e4723db07fb609aff6a7ccec50
3,627,454
def clamp(x, xmin, xmax): """Constrain a value to lie between two further values, element-wise. The returned value is computed as `min(max(x, xmin), xmax)`. The arguments can be scalars or :class:`~taichi.Matrix`, as long as they can be broadcasted to a common shape. Args: x (:mod:`~taichi...
80b4ef6224031502cf444b86141398ba60c77bda
3,627,455
def anim_curve_exists(attr_curve_name): """ """ anim_curve = get_anim_curve(attr_curve_name) if not anim_curve: return True else: return False
03f84bf231fa6100574c4ff3c6cc516e48a5a95b
3,627,456
from datetime import datetime def create_string(item): """Create strings for tests.""" return WEBEX_TEAMS_TEST_STRING_TEMPLATE.substitute( prefix=WEBEX_TEAMS_TEST_STRING_PREFIX, item=item, datetime=str(datetime.datetime.now()) )
b6c9ebfc38a7a3b875b2bfec531a5fc64e94eb59
3,627,457
from typing import List def save_image_with_legends_and_labels(save_path: str, image: np.ndarray, legends: List[Rectangle], labels: List[str]) -> (plt.Figure, plt.Axes): """ Saves the given image with the given legends rects and labels Args: save_path: the p...
6c485c8fb367fcc7301ad68d08c674f615574bf9
3,627,458
from datetime import datetime import time def nod_uploadkey(private, own=False, date=None): """Generate the key for the next News of the Day entry. >>> nod_uploadkey("USK@foo,moo,goo/WebOfTrust/0", own=False, date=datetime.datetime(2010,1,1)) 'SSK@foo,moo,goo/nod-shared-2010-01-01' >>> nod_uploadkey(...
ec51a0b56e3922c0c5d9f74d2885086e582d729d
3,627,459
def is_struct(struct): """ Checks if the message is a data structure or an rpc request/response""" return (not struct.name.endswith("Request") and not struct.name.endswith("Response"))
0dbce36cad826988cc18d86a31b91f2090d5e338
3,627,460
def relative_round(value, relative_digits): """Rounds to a given relative precision""" if isinstance(value, tuple): return tuple((relative_round(x, relative_digits) for x in value)) if value == 0 or isinstance(value, str) or np.isnan(value) or np.isinf(value): return value value_preci...
932665f95969c603b053e6ce18415f78abd43891
3,627,461
import xmlrpc def get_pypi_proxy(): """Returns a RPC ServerProxy object pointing to the PyPI RPC URL. :rtype: xmlrpclib.ServerProxy :return: the RPC ServerProxy to PyPI repository. """ return xmlrpc.client.ServerProxy(PYPI_XMLRPC)
26439fb81911aeb3ca864f1883be9b84d176752c
3,627,462
def replace_labels(code): """ Replaces free labels in `code` with integers, and accordingly any label call / branch. For example, code: ('BRANCH', 'L0') ('LABEL', '2+') ('1+',) ('EXIT',) ('LABEL', 'L0') returns: ('BRANCH', 1) ('LABEL', 0) ...
92384d83020021543d2e2f85a79d4df9f6e9017e
3,627,463
import pandas as pd from typing import Union from pathlib import Path import tarfile def read_tarfile_csv(path: Union[str, Path], inner_path: str, sep: str = "\t", **kwargs): """Read an inner CSV file from a tar archive. :param path: The path to the tar archive :param inner_path: The path inside the tar ...
24b3183da5787c095e78fc1bc7a1ed4e4012d6d2
3,627,464
def hasReturnType(matcher): """Match a function/method with a specified return type >>> from glud import * >>> config = ''' ... class X {}; ... X u(); ... int v(); ... ''' >>> m = functionDecl(hasReturnType(builtinType())) >>> for c in walk(m, parse_string(config).cursor): ... ...
dbc9ab35f5bd3184080252c5feb9858df573217f
3,627,465
from pathlib import Path def calc_path(filename): """Calculate a filepath based off of current file""" logger.info("calc_path filename: %s", filename) if filename is None: return None filepath = Path(filename) if not filepath.is_absolute(): filepath = Path(__file__, "..", filepath)...
ee5ef9a645194a4c6ea334d57a3499dbbc7a50f0
3,627,466
def get_enum_map(mri, name): """ Returns enum value to name and name to enum value map. @param mri mri instance @param name name of enum """ ret = {} tdm = mri.engine.tdm n = len(name) + 1 roles = tdm.getByHierarchicalName(name) constants = roles.getConstants() for c...
e781790c7e7f5a24e12fb986e2e45d735157a7b6
3,627,467
import time def CreateWebsList(AssetInfo, TimePause, TimesFetch): """ Get web pages """ AssetTickers = list(AssetInfo.keys()) # Create a linked list for every asset WebsLists = dict() for s in AssetTickers: WebsLists[s] = WebLinkedList.WebList() # Start crawling for t in range(Tim...
f1bb57d56360d596d33769100f101d9f7ba74ef7
3,627,468
def spatial_filter(x, y, z, dx, dy, sigma=3.0): """ des: outlier filtering within the defined spatial region (dx * dy). arg: x, y: coord_x and coord_y (m) z: value dx, dy: resolution in x (m) and y (m) n_sigma: cut-off value thres: max absolute value of data retu...
ff1f5f8af17b2cce453ec1c75e4df5eafbaf5957
3,627,469
def _log_add(x, y): """ Add x and y in log space. """ if x == -np.inf: return y if y == -np.inf: return x return np.max([x, y]) + np.log1p(np.exp(-abs(x - y)))
ff4ab48c9ddb446f17456049d6f5317306cdc7a2
3,627,470
import asyncio def query_by_name(first, last, jurisdictions=None, timeout=None): """Query jurisdictions with an inmate name. :param first_name: Inmate first name to search. :type first_name: str :param last_name: Inmate last name to search. :type last_name: str :param jurisdictions: List of...
effff7fd1b75baea0a65b4a21e87894a39d1f783
3,627,471
import ray import psutil import time def test_basic(ray_start_with_dashboard): """Dashboard test that starts a Ray cluster with a dashboard server running, then hits the dashboard API and asserts that it receives sensible data.""" assert (wait_until_server_available(ray_start_with_dashboard["webui_url"]) ...
c31926cd6ce1976fec2adcdebebfe8c8b8a0bf99
3,627,472
def arc_length_3point(A, B, C): """ Returns length of arc defined by 3 points, A, B and C; B is the point in between """ ### Meticulously transcribed from # https://develop.openfoam.com/Development/openfoam/-/blob/master/src/mesh/blockMesh/blockEdges/arcEdge/arcEdge.C p1 = np.asarray(A) p2 = np.asa...
aa51863f08d6b4d22e8321252506bf575861e191
3,627,473
def connect_bucket(cfg): """ TODO: do we really need this? """ return ( cfg.bucket, boto3.client('s3') )
cb60266d59f3692e061276c9cdabfa6879aad116
3,627,474
def dsymv(alpha, A, X, beta, Y, Uplo=CblasLower): """ returns y' This function computes the matrix-vector product and sum \M{y' = S{alpha} A x + S{beta} y} for the symmetric matrix A. Since the matrix A is symmetric only its upper half or lower half need to be stored. When Uplo is CblasUpper th...
d4bb0aed936dbf3e0d94b8e76f9b1ef24f5536a7
3,627,475
def view_categories(request): """View category posts view""" categories = Category.objects.all() ret_dict = { 'categories': categories, 'view_rss': 'rss/categories.xml', 'current_nav': 'categories', } ret_dict = __append_common_vars(request, ret_dict) return render(requ...
22cf5ef4e8c7a9aed13f5b528c44f2ecb9c93979
3,627,476
def zfill_to_collection_size(index: int, collection_size: int) -> str: """ Prepends amount of zeroes required for indexes to be string-sortable in terms of given collection size. Examples: for 10 items prepends up to 1 zero: 1 -> "01", 10 -> "10" for 100 items prepends up to 2 zeroes: 7 -> "...
df086ba9c4485dd0073c9a9b4485cb0c0d423859
3,627,477
import os.path def parse_fname_meta(file): """ Takes a file name and separates out any/all metadata of interest (Serial ID, Source, NN Tags) Decisions to be made: How strict to be on naming? This should be in the config file... FOR NOW: Only Impose 3 Rules: * UNTIL FIRST "_" is Serial ...
892a46c54e842033fb610131264455b6de0272a1
3,627,478
def _make_grid_spec(storage) -> GridSpec: """Make a grid spec based on a storage spec.""" assert 'tile_size' in storage crs = CRS(storage['crs']) return GridSpec(crs=crs, tile_size=[storage['tile_size'][dim] for dim in crs.dimensions], resolution=[storage['resolu...
37d3b7cd005e4bf8e0d813bdefb0ef367b80dd6c
3,627,479
def gaussian_2d_cylind(shape, center, resolution, scale, sigma=1, min_range_rho=0): """Generate gaussian map. Args: shape (list[int]): Shape of the map. [y, x] sigma (float): Sigma to generate gaussian map. Defaults to 1. Returns: np.ndarray: Generated gaussian map. [rh...
6490bdb3edd7930ac6d0c899338d3487263c8daf
3,627,480
from datetime import datetime async def create_specific_guid(guid: str, data: GuidIn): """ Create a record w/ a guid specified in the path. Also cleans up expired records & caches the new record. Raises an exception if you try to overwrite an existing record. """ try: guid = validate...
67d1a3615e54cd330bf22e8846987b71360fde0a
3,627,481
def partition(predicate, values): """ Splits the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4] """ results = ([], []) for item in values: results[predicate(item)].append(item...
27184fd908ab2d214db86b612e2e5cbec9393a07
3,627,482
def get_colors(color='ALL'): """ get color palette as a dictionary """ if color == 'ALL': return color_dict['palette'] return color_dict['palette'][color]
719fb6ce8a335c80694eb0418eace8ca4b7bc397
3,627,483
def avoid_line_too_long(pretty_html_text): """ detect any line with more than 998 characters """ lines = pretty_html_text.split('\n') new_lines = [] for line in lines: line_length = len(line) if line_length >= 998: # Cut the line in several parts of 900 characters ...
610021c6ee52e0b8cc0f20951383b9f559ce0f59
3,627,484
def stringify_tags(tags, human_readable=False): """ 格式化 Beancount 标签列表 """ if human_readable: if len(tags) == 0: return _('无') return ', '.join(f'#{t}' for t in tags) return ' '.join(f'#{t}' for t in tags)
c4b7fce339754fbd437972c8de4e3cc38ad9d6f5
3,627,485
from datetime import datetime def is_friday(): """判断是否是周五""" return datetime.date.today().weekday() == 4
b8536933c973677366e3b19c19cb57cbc33980c6
3,627,486
def _parse_exclude_images_commands(commands, experiments, reflections): """Parse a list of list of command line options. e.g. commands = [['1:101:200'], ['0:201:300']] or commands = [[101:200]] allowable for a single experiment. builds and returns a list of tuples (exp_id, (start, stop)) """ ...
e1decbcce826d1fe32a9b5c98b745f43e754a3b4
3,627,487
def thomson_spec_series(eleckineng, photeng, T, as_pairs=False): """ Thomson ICS spectrum of secondary photons by series method. Parameters ---------- eleckineng : ndarray Incoming electron kinetic energy. photeng : ndarray Outgoing photon energy. T : float CMB tempera...
a261aa1c344404f71c8a17712865276e28fc5831
3,627,488
def voxel_grid_sampling(coords: np.ndarray, voxel_size: float) -> np.ndarray: """Voxel grid sampling Args: coords: coords (N, C) voxel_size: voxel grid size Returns: samples: sample coords (M, C) """ N, C = coords.shape # get voxel indices. indices_float = coor...
145af0fc17887536ee3ebe466a3920d1abd717e9
3,627,489
def compute_skewness(data): """ Skewness of the data (per channel). Parameters ---------- data : ndarray, shape (n_channels, n_times) Returns ------- output : ndarray, shape (n_channels,) """ ndim = data.ndim return stats.skew(data, axis=ndim - 1)
563f7a10d882b23e9cbb717cae4b9f251de0fd11
3,627,490
def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): """Compute the one-dimensional FFT for real input. The returned array contains the positive frequency components of the corresponding :func:`fft`, up to and including the Nyquist frequency. Args: x (cupy.ndarray): Array ...
4ba7bf16788f7587e3a7076612d6a27d75749c7a
3,627,491
from pathlib import Path def copy_from_table_row(row, clobber=False): """Perform a single copy operation using information from a single row of a copy_table. Args: param1 (type): The first parameter. param2 (type): The second parameter. Returns: Path: destination path returned by...
49ca233700b33bb2d2a643acc65363651caebce9
3,627,492
def mustache(template, partials=None, **kwargs): """Usage: {{ mustache('path/to/whatever.mustache', key=value, key1=value1.. keyn=valuen) }} or, with partials {{ mustache('path/to/whatever.mustache', partials={'partial_name': 'path/to/partial.mustache'}, \ key1=value1...
22af5bc7ff4dbeb6459761c827bba7bd1317edb0
3,627,493
from typing import List from typing import Dict from typing import Any def from_protos( proto_list: List[american_option_pb2.AmericanEquityOption], american_option_config: "AmericanOptionConfig" = None ) -> Dict[str, Any]: """Creates a dictionary of preprocessed swap data.""" prepare_fras = {} for a...
20f7bb76873068744b6652966884c62650e1c8a6
3,627,494
def proxy_capture(self, link_guid, user_agent=''): """ start warcprox process. Warcprox is a MITM proxy server and needs to be running before, during and after phantomjs gets a screenshot. Create an image from the supplied URL, write it to disk and update our asset model with the path. The heavy l...
6174b416ee001b35075d9d89f374dddadd839475
3,627,495
def create_operator(key, value, context): """ Create operator instance along with its arguments Args: key: operator name value: operator arguments context (Dict): Python dictionary holding all imported modules Returns: Tasrif pipeline...
89a1a8603818faae1704d6e74ff2bc5b026a1fef
3,627,496
import logging def get_combined_segmentation_points(ts, loc_df, time_query, filters_in_df, filter_methods): """ We can have mixed filters in a particular time range for multiple reasons. a) user switches phones from one platform to another b) user signs in simultaneously to phones on both platforms ...
00caa605fc9945efa6e852c9da4fcbdaaba606e9
3,627,497
import os import re def is_experiment(names): """[Check names follows experiment rules] Args: names ([str]): [names founds in the path] Returns: [type]: [True or false ] """ regexps = get_regular_expressions(os.path.join(dir_rules, 'experiment_rules.json')) conditions = [] ...
7e88f317425332ab9b4efa0e14a6ec69153ede50
3,627,498
def est_positif_non_nul(valeur: any): """Indique si la valeur fournie est un entier positif non nul.""" if valeur is not None: if isinstance(valeur, int): return valeur > 0 if isinstance(valeur, float) and valeur.is_integer(): return valeur > 0 return False
03e799f73cfc3e112d61d638d6c120ede049991d
3,627,499