content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
def GitPush(git_repo, refspec, push_to, force=False, dry_run=False,
capture_output=True, skip=False, **kwargs):
"""Wrapper for pushing to a branch.
Args:
git_repo: Git repository to act on.
refspec: The local ref to push to the remote.
push_to: A RemoteRef object representi... | 3af43d0a819c297735995a9d8c7e39b49937b7a3 | 27,900 |
def boxes_to_array(bound_boxes):
"""
# Args
boxes : list of BoundBox instances
# Returns
centroid_boxes : (N, 4)
probs : (N, nb_classes)
"""
temp_list = []
for box in bound_boxes:
temp_list.append([np.argmax(box.classes), np.asarray([box.x, box.y, box.w, box.... | e01b908e675b84928d1134d8eec4627f36b8af4a | 27,901 |
import os
def bam_to_junction_reads_table(bam_filename, ignore_multimapping=False):
"""Create a table of reads for this bam file"""
uniquely, multi = _get_junction_reads(bam_filename)
reads = _combine_uniquely_multi(uniquely, multi, ignore_multimapping)
# Remove "junctions" with same start and stop
... | d5a832f2834a8635ce04889d3b0ec7a0c082f95d | 27,902 |
from typing import Tuple
def _scope_prepare(scope: str) -> Tuple[object, str]:
"""
Parse a scope string a return a tuple consisting of context manager for the assignation of the tf's scope
and a string representing the summary name. The scope is of the form "<ident1>.<ident2>. ... .<ident3>", the
righ... | 01bcd08d87e23621f3476055379d9c7403fd4b75 | 27,903 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
aftv = hass.data[DOMAIN][entry.entry_id][ANDROID_DEV]
await aftv.adb_close()
hass.data[DOMAIN].p... | 77376bcdf98c9b4c2ac6020e44d704fbe59d9143 | 27,904 |
from typing import Tuple
def render_wrapped_text(text: str, font: pygame.freetype.Font,
color: Color, centered: bool, offset_y: int,
max_width: int) -> Tuple[pygame.Surface, pygame.Rect]:
"""Return a surface & rectangle with text rendered over several lines.
Pa... | 73be30318fd3afe5bf5138b8c21c46caf05022bc | 27,905 |
def comp4(a1,a2,b1,b2):
"""两个区间交集,a1<a2; b1<b2"""
if a2<b1 or b2<a1:#'空集'
gtii = []
else:
lst1 = sorted([a1,a2,b1,b2])
gtii = [lst1[1], lst1[2]]
return gtii | ba4357b16ee09f78b6c09f422d27a42cd91e298e | 27,906 |
from typing import Callable
from typing import Optional
from typing import Union
from typing import Tuple
from typing import List
def fixed_step_solver_template(
take_step: Callable,
rhs_func: Callable,
t_span: Array,
y0: Array,
max_dt: float,
t_eval: Optional[Union[Tuple, List, Array]] = None... | 6e989b1f6d92ddeb4d5f18e9eb110667f28b6a33 | 27,907 |
def set_reference_ene(rxn_lst, spc_dct,
pes_model_dct_i, spc_model_dct_i,
run_prefix, save_prefix, ref_idx=0):
""" Sets the reference species for the PES for which all energies
are scaled relative to.
"""
# Set the index for the reference species, right n... | 52c915060a869f41ee5262190dd7ffac79b1684b | 27,908 |
import torch
def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
"""Returns a center (keypoint) of the LAFs.
Args:
LAF: tensor [BxNx2x3].
Returns:
tensor BxNx2.
Shape:
- Input: :math: `(B, N, 2, 3)`
- Output: :math: `(B, N, 2)`
Example:
>>> input = t... | c172defe938c35e7f41616b48d9d6d3da21eb9d1 | 27,909 |
def get_all_vlan_bindings_by_logical_switch(context, record_dict):
"""Get Vlan bindings that match the supplied logical switch."""
query = context.session.query(models.VlanBindings)
return query.filter_by(
logical_switch_uuid=record_dict['logical_switch_id'],
ovsdb_identifier=record_dict['ov... | df88a52325e1bee59fae3b489a29ce8ee343d1fb | 27,910 |
def conv_input_length(output_length, filter_size, padding, stride):
"""Determines input length of a convolution given output length.
Args:
output_length: integer.
filter_size: integer.
padding: one of "same", "valid", "full".
stride: integer.
Returns:
The input length (integer).
... | 88c80a77d3aee4050625aa080db5d9b246f9e920 | 27,911 |
def convert_data_to_int(x, y):
"""
Convert the provided data to integers, given a set of data with fully
populated values.
"""
# Create the new version of X
x_classes = []
for i in xrange(x.shape[1]):
x_classes.append({item:j for j, item in enumerate(set(x[:,i]))})
new_x = np.zeros(x.shape, dtype='i')
for ... | c8b3f017a34b68edf4f1740f8a3dd2130664ddae | 27,912 |
def send_report(report_text, svc_info, now_str):
"""
Publish report to AWS SNS endpoint
Note: publish takes a max of 256KB.
"""
overage = len(report_text) - MAX_SNS_MESSAGE
if overage > 0:
report_text = report_text[:-overage - 20] + '\n<message truncated/>'
resp = SNS_C.publish(Topic... | 9c48c3d7ba12e11cf3df944942803f36f6c23f52 | 27,913 |
def credential():
"""Return credential."""
return Credential('test@example.com', 'test_password') | 1da4e56abb87c9c5a0d0996d3a2911a23349321b | 27,914 |
def get_ez_from_contacts(xlsx_file, contacts_file, label_volume_file):
"""Return list of indices of EZ regions given by the EZ contacts in the patient spreadsheet"""
CONTACTS_IND = 6
EZ_IND = 7
df = pd.read_excel(xlsx_file, sheet_name="EZ hypothesis and EI", header=1)
ez_contacts = []
contact... | b3e4bfda0d0e9830b34012b7995082e90c9932a8 | 27,915 |
def mapfmt_str(fmt: str, size: int) -> str:
"""Same as mapfmt, but works on strings instead of bytes."""
if size == 4:
return fmt
return fmt.replace('i', 'q').replace('f', 'd') | af51b6ac65c80eef1721b64dcd8ee6a8bb5cbc97 | 27,916 |
import os
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Camera."""
# check for missing required configuration variable
if config.get("file_path") is None:
_LOGGER.error("Missing required variable: file_path")
return False
setup_config = (
{
... | c1adac9e3ebb80993e0d8525d2aaa21e2ff78e7e | 27,917 |
def RandomImageDetection(rows=None, cols=None):
"""Return a uniform random color `vipy.image.ImageDetection` of size (rows, cols) with a random bounding box"""
rows = np.random.randint(128, 1024) if rows is None else rows
cols = np.random.randint(128, 1024) if cols is None else cols
return ImageDetectio... | e7f06b32b771f3eb3c10d09e39bc4be4577d4233 | 27,918 |
def upsample(x, stride, target_len, separate_cls=True, truncate_seq=False):
"""
Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
"""
if stride == 1:
return x
if separate_cls:
cls = x[:, :1]
x = x[:, 1:]
outp... | 716c94cb365144e65a6182e58c39284375c8f700 | 27,919 |
import numpy
def torsional_scan_linspaces(zma, tors_names, increment=0.5,
frm_bnd_key=None, brk_bnd_key=None):
""" scan grids for torsional dihedrals
"""
sym_nums = torsional_symmetry_numbers(
zma, tors_names, frm_bnd_key=frm_bnd_key, brk_bnd_key=brk_bnd_key)
inter... | a2dcd4ec57ae598a42c25102db89af331e6f8a40 | 27,920 |
import ctypes
def get_output_to_console(p_state):
"""Returns a bool indicating whether the Log is output to the console."""
return bool(_Get_Output_To_Console(ctypes.c_void_p(p_state))) | 71599b5a2e4b2708d6e8d5fa003acc89cd0d030c | 27,921 |
def check_valid_column(observation):
"""
Validates that our observation only has valid columns
Returns:
- assertion value: True if all provided columns are valid, False otherwise
- error message: empty if all provided columns are valid, False otherwise
"""
valid... | 104fc6646a5e4d978b2a0cec4322c6f275b82f42 | 27,922 |
import os
def _params_to_filename(job_id, run_id, extra_run_id):
"""
Prepare file name based on params.
Args:
job_id (str): Job Uid
run_id (str): Job Run Uid
extra_run_id (str): Extra Job Uid
Returns:
str: filenames
"""
with current_app.app_context():
... | fde7906dda0fb0146b0e06171098ce0f862b4162 | 27,923 |
def w_getopt(args, options):
"""A getopt for Windows.
Options may start with either '-' or '/', the option names may
have more than one letter (/tlb or -RegServer), and option names
are case insensitive.
Returns two elements, just as getopt.getopt. The first is a list
of (option, value) pairs... | 34095675fa95cbc1c8474a7253b4d49a2e947dc0 | 27,924 |
def get_alt_for_density(density: float, density_units: str='slug/ft^3',
alt_units: str='ft', nmax: int=20, tol: float=5.) -> float:
"""
Gets the altitude associated with a given air density.
Parameters
----------
density : float
the air density in slug/ft^3
densi... | 68243ec75bbe8989e7a9fd63fe6a1635da222cae | 27,925 |
from datetime import datetime
def parse_date_string(date: str) -> datetime:
"""Converts date as string (e.g. "2004-05-25T02:19:28Z") to UNIX timestamp (uses UTC, always)
"""
# https://docs.python.org/3.6/library/datetime.html#strftime-strptime-behavior
# http://strftime.org/
parsed = datetime.strp... | 624e92ceab996d7cfded7c7989e716fbba7abd5e | 27,926 |
def levenshtein_distance(s, t, ratio_calc = False):
""" levenshtein_distance:
Calculates levenshtein distance between two strings.
If ratio_calc = True, the function computes the
levenshtein distance ratio of similarity between two strings
For all i and j, distance[i,j] will contain ... | 670196344e33bd4c474c0b24b306c9fe3d7e093b | 27,927 |
def no_warnings(func):
""" Decorator to run R functions without warning. """
def run_withoutwarnings(*args, **kwargs):
warn_i = _options().do_slot('names').index('warn')
oldwarn = _options()[warn_i][0]
_options(warn=-1)
try:
res = func(*args, **kwargs)
except ... | 52831940551c324b6e9624af0df28cc2442bac2b | 27,928 |
def ParseKindsAndSizes(kinds):
"""Parses kind|size list and returns template parameters.
Args:
kinds: list of kinds to process.
Returns:
sizes_known: whether or not all kind objects have known sizes.
size_total: total size of objects with known sizes.
len(kinds) - 2: for template rendering of gr... | 7f94fd099ea2f28070fe499288f62d1c0b57cce9 | 27,929 |
def load_3D(path,
n_sampling=10000,
voxelize=True,
voxel_mode="binary",
target_size=(30, 30, 30)):
"""Load 3D data into numpy array, optionally voxelizing it.
Parameters
----------
path : srt
Path to 3D file.
n_sampling : int
Number o... | eec6614b2675faa61d9a09b8ff3a491580302a91 | 27,930 |
import array
def create_vector2d(vec):
"""Returns a vector as a numpy array."""
return array([vec[0],vec[1]]) | 0b3cdc81f3744c54dea8aab0ee28743134ff1d42 | 27,931 |
def get_chrom_start_end_from_string(s):
"""Get chrom name, int(start), int(end) from a string '{chrom}__substr__{start}_{end}'
...doctest:
>>> get_chrom_start_end_from_string('chr01__substr__11838_13838')
('chr01', 11838, 13838)
"""
try:
chrom, s_e = s.split('__substr__')
start, ... | 5dbce8eb33188c7f06665cf92de455e1c705f38b | 27,932 |
def Remove_Invalid_Tokens(tokenized_sentence, invalidating_symbols):
"""
Returns a tokenized sentence without tokens that include
invalidating_symbols
"""
valid_tokens_sentence = [] + tokenized_sentence # forcing a copy, avoid pass by reference
for token in tokenized_sentence:
for invalid_symbol in invalidat... | 931858685c6c405de5e0b4755ec0a26a672be3b0 | 27,933 |
def _get_protocol(url):
"""
Get the port of a url.
Default port is 80. A specified port
will come after the first ':' and before the next '/'
"""
if url.find('http://') == 0:
return 'http'
elif url.find('https://') == 0:
return 'https'
else:
return 'h... | 42b2750148829154f17e34a2cebccf4387f07f25 | 27,934 |
import warnings
def convert_spectral_axis(mywcs, outunit, out_ctype, rest_value=None):
"""
Convert a spectral axis from its unit to a specified out unit with a given output
ctype
Only VACUUM units are supported (not air)
Process:
1. Convert the input unit to its equivalent linear unit
... | 3a2b041a128aeeee3b163f66b07cd6f2241702f5 | 27,935 |
def row_to_str(row):
"""Convert a df row to a string for insert into SQL database."""
return str(list(row)).replace("[", "(").replace("]", ")") | fb2b0d598604a124b948f884a6839a40af1203fc | 27,936 |
def interpolate_affines(affines):
"""
"""
# get block grid
block_grid = affines.shape[:3]
# construct an all identities matrix for comparison
all_identities = np.empty_like(affines)
for i in range(np.prod(block_grid)):
idx = np.unravel_index(i, block_grid)
all_identities[id... | 880ea993634a6c4725d02365d75e79705175c2e5 | 27,937 |
import tqdm
def getLineMeasures(file_list, orders, names, err_cut=0):
"""
Find line center (in pixels) to match order/mode lines
"""
# Load in x values to match order/mode lines
x_values = np.empty((len(file_list),len(orders)))
x_values[:] = np.nan # want default empty to be nan
x_errors =... | b13fe9f46457f7d289d09ffba3b769fe4e1c700e | 27,938 |
import os
def is_slackware():
"""
Checks if we are running on a Slackware system.
:returns: **bool** to indicate if we're on a Slackware system
"""
return os.path.exists('/etc/slackware-version') | 69f8acb73317345e19b81b5deec8370784cc11aa | 27,939 |
def signature_exempt(view_func):
"""Mark a view function as being exempt from signature and apikey check."""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.signature_exempt = True
return wraps(view_func)(wrapped_view) | f564ad0ce20e6e2b7ae760c5f50a297f587006d4 | 27,940 |
def setup(args):
"""
Create configs and perform basic setups.
"""
cfg = get_cfg()
add_tridentnet_config(cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
# if args.eval_only:
# cfg.MODEL.WEIGHTS = "/root/detectron2/projects/TridentNet/log_80_20/model_0... | 13d30557537c7e7d18811e016c0eaf43602f1ef2 | 27,941 |
def get_intersections(line, potential_lines, nodes, precision):
"""
Get the intersection points between the lines defined by two planes
and the lines defined by the cost area (x=0, y=0, y=-x+1)
and the lines defined by the possible combinations of predictors
"""
slope, intercept = line
# In... | 3e9811bee159f6c550dea5784754e08bc65624d7 | 27,942 |
def subtract_loss_from_gain(gain_load, loss_load):
"""Create a single DataCollection from gains and losses."""
total_loads = []
for gain, loss in zip(gain_load, loss_load):
total_load = gain - loss
total_load.header.metadata['type'] = \
total_load.header.metadata['type'].replace(... | b53044b802a8ea13befdde850a478c435b0370ef | 27,943 |
def zero_out_noisy_epochs(psg, sample_rate, period_length_sec,
max_times_global_iqr=20):
"""
Sets all values in a epoch of 'period_length_sec' seconds of signal to zero
(channel-wise) if any (absolute) value within that period exceeds
'max_times_global_iqr' times the IQR of all... | 427e2652a2e595bd0b25c3a30d35e088a9b0562b | 27,944 |
import subprocess
def reduce_language_model(language_model_path, out_language_model_path):
"""
TODO DOCUMENTATION
:param language_model_path:
:param out_language_model_path:
:return:
"""
command = 'sphinx_lm_convert'
script = [command,
'-i', language_model_path,
... | 6c4e9ffd4b7221c65834e90573ac0a85d0bb47a4 | 27,945 |
from typing import Tuple
from typing import List
def start_training(channel: Channel) -> Tuple[List[ndarray], int, int]:
"""Start a training initiation exchange with a coordinator.
The decoded contents of the response from the coordinator are returned.
Args:
channel (~grpc.Channel): A gRPC chann... | 70ac5b32b58df84cd386cc820f18a8fe2667d620 | 27,946 |
import re
def has_forbidden(mylist) -> bool:
""" Does the string contain one of the forbidden substrings "ab" "cd" "pq"
"xy"? """
return bool(re.search(FORBIDDEN, mylist)) | 848fb1270ba99f40ef1ff0e23296f76895a5484d | 27,947 |
from main import PAGLuxembourg
def classFactory(iface): # pylint: disable=invalid-name
"""Load PagLuxembourg class from file PagLuxembourg.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
return PAGLuxembourg(iface) | 9ff71fbc9f915435da660861ee9023026dfb2e48 | 27,948 |
def is_official_target(target_name, version):
""" Returns True, None if a target is part of the official release for the
given version. Return False, 'reason' if a target is not part of the
official release for the given version.
target_name: Name if the target (ex. 'K64F')
version: The release ver... | 4cd8a2e3735aa91cd66204568c70e645e6f2f8ed | 27,949 |
from typing import Dict
from typing import Union
from typing import Any
def _convert_to_dict_or_str(elements_map: Dict[str, Element]) -> Dict[str, Union[str, Dict[Any, Any]]]:
"""Combines a dictionary of xml elements into a dictionary of dicts or str"""
return {
key: XmlDictElement(value) if value or ... | a68d1043abb995a632209528a52416a8a4661b58 | 27,950 |
def vsi_tecaji():
"""
Funkcija vrne vse tečaje PGD Hrušica.
"""
poizvedba = """
SELECT id, naziv
FROM tecaji
"""
tecaji = conn.execute(poizvedba).fetchall()
return tecaji | c4e9e9a9422920b38d4dce51a27d4db142c50f90 | 27,951 |
def cosine(u, v, dim=-1):
"""cosine similarity"""
return (u * v).sum(dim=dim) / (u.norm(dim=dim, p=2) * v.norm(dim=dim, p=2)) | 2d2a5a02ce20f6ae37dbefa3c8f9399aef2da8ad | 27,952 |
from datetime import datetime
def retrive_cache_data(format: str, query: str) -> dict[int, Book]:
"""
Retrive the cached data for the query.
"""
date_now = datetime.now()
# save the search results in the cache if not already there or if the cache is expired
if format not in book_cache:
... | 885532f94f1e4b28350d3854ada867f42d386d5f | 27,953 |
def get_orders_loadings_palette_number(client_orders, value):
"""
Searches OrdersLoadingPlaces objects linked with client orders and that contain value
:param client_orders: orders of profile
:param value: value of palettes number for which OrdersLoadingPlaces objects are searching
:return: List wit... | c145997418722e84da5d7420fbba6a8167737f96 | 27,954 |
import math
def rotmat(x=0,y=0,z=0):
"""Rotation Matrix function
This function creates and returns a rotation matrix.
Parameters
----------
x,y,z : float, optional
Angle, which will be converted to radians, in
each respective axis to describe the rotations.
The defau... | f1b31916abb78f3f47c324c3341d06338f6e4787 | 27,955 |
def add_model_components(m, d, scenario_directory, subproblem, stage):
"""
:param m:
:param d:
:return:
"""
m.Horizon_Energy_Target_Shortage_MWh = Var(
m.ENERGY_TARGET_ZONE_BLN_TYPE_HRZS_WITH_ENERGY_TARGET,
within=NonNegativeReals
)
def violation_expression_rule(mod, z... | e6fe56e72fb7cd5906f0f30da2e7166a09eeb3f1 | 27,956 |
def grow_rate(n, k, nu_c, nu_d, sigma, g, dp, rho_c, rho_d, K):
"""
Compute the instability growth rate on a gas bubble
Write instability growth rate equation in Grace et al. as a root
problem for n = f(k)
Returns
-------
res : float
The residual of the growth-rate equation... | 79e277ca7941b80fd52667b4157ffbfd97f9a87e | 27,957 |
def cg_semirelaxed_fused_gromov_wasserstein(C1:th.Tensor,
A1:th.Tensor,
p:th.Tensor,
C2:th.Tensor,
A2:th.Tensor,
... | 5a21edf35423b46826a9b88af62ddd27678538c2 | 27,958 |
def Vinv_terminal_time_series(m_t,Vdc_t):
"""Function to generate time series inverter terminal voltage."""
try:
assert len(m_t) == len(Vdc_t) != None
return m_t*(Vdc_t/2)
except:
LogUtil.exception_handler() | cbbcc7475c30694f3960e1b78b4be64bde283a2b | 27,959 |
def render(ob, ns):
"""Calls the object, possibly a document template, or just returns
it if not callable. (From DT_Util.py)
"""
if hasattr(ob, '__render_with_namespace__'):
ob = ZRPythonExpr.call_with_ns(ob.__render_with_namespace__, ns)
else:
# items might be acquisition wrapped
... | fba552131df5fe760c124e90e58f845f06fbbf44 | 27,960 |
def GetFlakeInformation(flake, max_occurrence_count, with_occurrences=True):
"""Gets information for a detected flakes.
Gets occurrences of the flake and the attached monorail issue.
Args:
flake(Flake): Flake object for a flaky test.
max_occurrence_count(int): Maximum number of occurrences to fetch.
... | 596573749599e7a1b49e8047b68d67a09e4e00e9 | 27,961 |
def get_prop_cycle():
"""Get the prop cycle."""
prop_cycler = rcParams['axes.prop_cycle']
if prop_cycler is None and 'axes.color_cycle' in rcParams:
clist = rcParams['axes.color_cycle']
prop_cycler = cycler('color', clist)
return prop_cycler | 9b571b16cddf187e9bbfdacd598f280910de130a | 27,962 |
def binary_crossentropy(target, output, from_logits=False):
"""Binary crossentropy between an output tensor and a target tensor.
Arguments:
target: A tensor with the same shape as `output`.
output: A tensor.
from_logits: Whether `output` is expected to be a logits tensor.
By default, we... | eb388c3bb3454eec6e26797313534cf089d06a6d | 27,963 |
def create_all_snapshots(volume_ids):
"""
Creates the snapshots of all volumes in the provided list.
Params:
volume_ids (list): List of volumes attached to the instance
Returns:
None
"""
for i in volume_ids:
snapshot(i)
return True | c985bdce6b11e85cedb3d8951447fdf234e3aeb4 | 27,964 |
def stack_subsample_frames(x, stacking=1, subsampling=1):
""" Stacks frames together across feature dim, and then subsamples
x.shape: FEAT, TIME
output FEAT * stacking, TIME / subsampling
"""
# x.shape: FEAT, TIME
seq = []
x_len = tf.shape(x)[1]
for n in range(0, stacking):
tm... | 6cab964588d01cdecec1862cd3c1db681923d20d | 27,965 |
def compute_TVL1(prev, curr, TVL1, bound=20):
"""
Args:
prev (numpy.ndarray): a previous video frame, dimension is
`height` x `width`.
curr (numpy.ndarray): a current video frame, dimension is
`height` x `width`.
bound (int): specify the maximum and minimux of op... | 94d83e0cbfc8e20ed78ba0ab3763d5ddd4e2859a | 27,966 |
def _fetch_all_namespace_permissions(cursor):
"""
Fetches all user-namespace-permissions mapping registered with Herd
:param: cursor to run hive queries
:return: list of all users that have READ on each respective namespace
"""
namespaces = _fetch_all_namespaces()
user_namespace_permissions... | 0802b81a8d731cabbd51b1d3699c0ce64ac6c64a | 27,967 |
def for_in_right(obj, callback=None):
"""This function is like :func:`for_in` except it iterates over the
properties in reverse order.
Args:
obj (list|dict): Object to process.
callback (mixed): Callback applied per iteration.
Returns:
list|dict: `obj`.
Example:
>... | 6d85f7245cd454be61015ca69e1844d1dc830c86 | 27,968 |
def metadata_fake(batch_size):
"""Make a xr dataset"""
# get random OSGB center in the UK
lat = np.random.uniform(51, 55, batch_size)
lon = np.random.uniform(-2.5, 1, batch_size)
x_centers_osgb, y_centers_osgb = lat_lon_to_osgb(lat=lat, lon=lon)
# get random times
t0_datetimes_utc = make_t... | fa55cb231e013f3b5c4193af9c5cfff6f79fce82 | 27,969 |
def delete_document(ix: str, docid: str):
"""
delete a document
PUT request body should be a json {field: value} mapping of fields to update
"""
check_role(Role.WRITER, _index(ix))
try:
elastic.delete_document(ix, docid)
except elasticsearch.exceptions.NotFoundError:
abort(4... | a87c7c23b31ce24da83b81e8d241d4173542a930 | 27,970 |
def sentence_segment(doc, candidate_pos):
"""Store those words only in cadidate_pos"""
sentences = []
for sent in doc.sents:
selected_words = []
for token in sent:
# Store words only with cadidate POS tag
if token.pos_ in candidate_pos and token.is_stop is False and l... | 6c56d47470e60edddfedfeb476aa7833be765218 | 27,971 |
def get_speckle_spatial_freq(image, pos, cx, cy, lambdaoverd, angle=None):
""" returns the spatial frequency of the speckle defined in the area of aperture mask """
""" lambdaoverd = nb of pixels per lambda/D """
nx, ny =image.shape[0], image.shape[1]
k_xy = (np.roll(pos,1,axis=0)-[cx,cy])/lambdaoverd ... | beace113642545f74ba3a49a4a15b0308d0f4535 | 27,972 |
def verify_ping(
device,
address,
loss_rate=0,
count=None,
max_time=30,
check_interval=10):
""" Verify ping loss rate on ip address provided
Args:
device ('obj'): Device object
address ('str'): Address value
loss_rate ('int... | df19e0815a49388189bf480623c156b9992a2fe2 | 27,973 |
from pathlib import Path
import argparse
def add_server_arguments(parser):
"""Add the --bind option to an argparse parser"""
def hostportsplit_helper(arg):
"""Wrapper around hostportsplit that gives better error messages than
'invalid hostportsplit value'"""
try:
return h... | 91aed985ffa395557fb557befc74c2d06853059c | 27,974 |
def get_default(key):
""" get the default value for the specified key """
func = registry.defaults.get(key)
return func() | 081588445955da66d9988e962d2a360ed1193240 | 27,975 |
from typing import List
def antisymmetric(r: Relation) -> (bool, List):
"""Kiểm tra tính phản xứng của r"""
antisymmetric_tuple = []
for x, y in r:
if x == y:
continue
if (y, x) in r:
return False, [((x, y), (y, x))]
antisymmetric_tuple.append(((x, y), (y, x... | d7a7900192850a9b86a56263fec5daea551a034f | 27,976 |
def calc_negative_predictive_value(cause, actual, predicted):
"""Calculate negative predictive value (NPV) for a single cause
Negative predictive value is the number of prediction correctly determined
to not belong to the given cause over the total number of predicted to
not be the cause:
.. math:... | f89976fc5ec9c03e5d8d42a8265ba92e87d91ec8 | 27,977 |
def print_atom_swap(swap):
"""Return atom swap string for DL CONTROL"""
return "{} {}".format(swap["id1"], swap["id2"]) | 4c2fa18434e7a66b98b9716b89a26b622b588cd6 | 27,978 |
import torch
import io
def export_onnx_model(model, inputs):
"""
Trace and export a model to onnx format.
Args:
model (nn.Module):
inputs (torch.Tensor): the model will be called by `model(*inputs)`
Returns:
an onnx model
"""
assert isinstance(model, torch.nn.Module)
... | 006e44dcd019f8a87d6fcee6de0db34ec6ce59b0 | 27,979 |
def dot_product_area_attention(q,
k,
v,
bias,
dropout_rate=0.0,
image_shapes=None,
name=None,
attention... | 947864002406597931c663340e1a258ac2ae5bed | 27,980 |
import glob
import json
import requests
def update_docs(cfid, docs) -> bool:
"""Updates the documentation of an already existing model
The update_docs function can be used to upload the documentation of an already existing model
by simply providing the cfid and the new docs object.
Args:
cfi... | 4aba692996d251536cde7a41cb0e5cdc663caa97 | 27,981 |
def visit_children_first(graph_head, visitor):
"""
:type graph_head: DecisionGraphNode
:param visitor: Visitor
:return:
"""
todo = deque()
todo.append(graph_head)
todo_set = {graph_head}
results = {}
while len(todo) != 0:
node = todo.pop()
todo_set.remove(node)... | 45e2525d83b63e4b3660b4cef9ca36f8be0c16ef | 27,982 |
def random_transform(x, seed=None):
"""Randomly augment a single image tensor.
# Arguments
x: 3D tensor, single image.
seed: random seed.
# Returns
A randomly transformed version of the input (same shape).
"""
np.random.seed(seed)
img_row_axis = 0
img_col_axis = 1
... | 9f0b09dd4c5b0a0f9f00ae15682a27645894b064 | 27,983 |
import sys
import argparse
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object, replace the description
parser = a... | ac80365e1b9227bc4f23021cd04cce777fd08b6d | 27,984 |
def global_avg_pooling_forward(z):
"""
全局平均池化前向过程
:param z: 卷积层矩阵,形状(N,C,H,W),N为batch_size,C为通道数
:return:
"""
return np.mean(np.mean(z, axis=-1), axis=-1) | f12efc7bd368af81164246fcb39a27f9de7e122d | 27,985 |
from typing import Optional
from functools import reduce
import operator
def find_local_term(match_text: SearchText, service: OntologyService) -> Optional[ConditionMatchingSuggestion]:
"""
Note that local search is pretty dumb, uses SearchText which already simplifies a bunch of words
Code looks through l... | 034803bf94d8a8befa7a1ca9099759c022a0da36 | 27,986 |
def label_encoder(adata):
"""
Encode labels of Annotated `adata` matrix using sklearn.preprocessing.LabelEncoder class.
Parameters
----------
adata: `~anndata.AnnData`
Annotated data matrix.
Returns
-------
labels: numpy nd-array
Array of encoded labels
"""
le = ... | 421aa578a965b2e8e66204a368e1c42348148ef6 | 27,987 |
def is_plus_or_minus(token_type: TokenType) -> bool:
"""Check if token is a plus or minus."""
return is_plus(token_type) or is_minus(token_type) | 1f0210505e8e882f07380ffd0d412a62f1d4d44f | 27,988 |
def gen_data(test_size=TEST_SIZE, channels=CHANNELS,
width=WIDTH, height=HEIGHT,
mmean=0, vmean=1, channel_last=False, fc_output=False):
"""
Generate random data to pass through the layer
NOTE:
- The generated data should not be normal, so that the layer can try to
... | 0030330bf93d6abb34f41575aaf1f45a52199393 | 27,989 |
from typing import Union
from typing import List
def plot_r2_pvalues(
model: mofa_model,
factors: Union[int, List[int], str, List[str]] = None,
n_iter: int = 100,
groups_df: pd.DataFrame = None,
group_label: str = None,
view=0,
fdr: bool = True,
cmap="binary_r",
**kwargs,
):
""... | 784a5333514a270bdf69960fa1a857668b414e5a | 27,990 |
import itertools
def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
... | f2f690a410d933ecdffee1898b9d991482a5eb67 | 27,991 |
def _check_lfs_hook(client, paths):
"""Pull the specified paths from external storage."""
return client.check_requires_tracking(*paths) | 403b3db59f6eeec72c8f4a3b18808997b0f34724 | 27,992 |
import argparse
def parse_args():
"""Parse the input argument of the program"""
parser = argparse.ArgumentParser(
description='Process FAQ template files to create the FAQ.')
parser.add_argument('-i', '--input', required=True, metavar='I', nargs='+',
help='FAQ files parsed... | c457a6fa0aed998720d5521890ac3ea263749363 | 27,993 |
def name_to_zamid(name):
"""Converts a nuclide's name into the nuclide's z-a-m id.
Parameters
----------
name: str
Name of a nuclide
"""
dic = d.nuc_name_dic
elt_name = name.split('-')[0]
na = int(name.split('-')[1].replace('*',''))
if '*' in name:
state = 1
... | 89129a288a93c96f3e24003b6dee2adba81dc935 | 27,994 |
def sample_category(name):
"""Create and return a sample category"""
return models.Category.objects.create(name=name) | b9b38954520611ca7808592200ebf871da90bab6 | 27,995 |
from datetime import datetime
import os
def GetAllRunningAUProcess():
"""Get all the ongoing AU processes' pids from tracking logs.
This func only checks the tracking logs generated in latest several hours,
which is for avoiding the case that 'there's a running process whose id is
as the same as a previous A... | aaa57448e4b795ea14e613fd457234f554bbe627 | 27,996 |
import importlib
import os
def get_installed_app_locale_path(appname):
"""
Load the app given by appname and return its locale folder path, if it exists.
Note that the module is imported to determine its location.
"""
try:
m = importlib.import_module(appname)
module_path = os.path... | 68bed5ec8dbb048823f203bd12512393e6238efb | 27,997 |
def file_share_exists(ctx, filesvc, share_name):
"""
Checks if a File Share already exists
:rtype: `azure.storage.file.models.Share` or `None`
:returns: Azure File Share object if the File Share
exists or None if it does not
"""
ctx.logger.debug('Checking if File Share "{0}" exists'... | 504b53119a7e0e881a4486eb009a8663767e84a8 | 27,998 |
def plan_add(request):
"""
测试计划添加
:param request:
:return:
"""
user_id = request.session.get('user_id', '')
if not get_user(user_id):
request.session['login_from'] = '/base/plan/'
return HttpResponseRedirect('/login/')
else:
if request.method == 'POST':
... | 4da776fd83e30019fbd6cdb1b659d8626e0620cc | 27,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.