content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def decode_base58(s: str) -> bytes:
"""
Decode base58.
:param s: base58 encoded string
:return: decoded data
"""
num = 0
for c in s:
if c not in BASE58_ALPHABET:
raise ValueError(
"character {} is not valid base58 character".format(c)
)
... | 5,341,900 |
def test_sequence_transform():
"""Test the sequence transformation."""
record = NavigableDict({'a': {'one': {'_text': '1'}}, 'b': {'two': {'_text': '2'}}})
transform = Transform([('sequence', ('combine', 'a', 'a.one._text', 'b.two._text'), ('join', 'a', ', ', 'a'))])
result = transform(record)
asser... | 5,341,901 |
def ports_info(ptfadapter, duthost, setup, tx_dut_ports):
"""
Return:
dut_iface - DUT interface name expected to receive packtes from PTF
ptf_tx_port_id - Port ID used by PTF for sending packets from expected PTF interface
dst_mac - DUT interface destination MAC address
src_mac -... | 5,341,902 |
def test_text_single_line_of_text(region, projection):
"""
Place a single line text of text at some x, y location.
"""
fig = Figure()
fig.text(
region=region,
projection=projection,
x=1.2,
y=2.4,
text="This is a line of text",
)
return fig | 5,341,903 |
def safely_get_form(request, domain, instance_id):
"""Fetches a form and verifies that the user can access it."""
form = get_form_or_404(domain, instance_id)
if not can_edit_form_location(domain, request.couch_user, form):
raise location_restricted_exception(request)
return form | 5,341,904 |
def generate_hazard_rates(n, d, timelines, constant=False, independent=0, n_binary=0, model="aalen"):
"""
n: the number of instances
d: the number of covariates
lifelines: the observational times
constant: make the coeffients constant (not time dependent)
n_binary: the number of binary... | 5,341,905 |
def magma_dsyevd_gpu(jobz, uplo, n, dA, ldda, w, wA, ldwa, work, lwork, iwork,
liwork):
"""
Compute eigenvalues of real symmetric matrix.
"""
jobz = _vec_conversion[jobz]
uplo = _uplo_conversion[uplo]
info = ctypes.c_int()
status = _libmagma.magma_dsyevd_gpu(jobz, uplo,... | 5,341,906 |
def load_graph(graph_url):
"""
Function that loads a graph given the URL
for a text representation of the graph
Returns a dictionary that models a graph
"""
graph_file = urllib2.urlopen(graph_url)
graph_text = graph_file.read()
graph_lines = graph_text.split('\n')
graph_lines = ... | 5,341,907 |
def extract_spectra(hdu, dy=7):
"""Extract a spectrum for a source
"""
#first define the good region around the spectra
max_list=[]
x_arr = np.arange(len(hdu[1].data[0]))
max_arr = x_arr*0.0 - 1
for xc in x_arr:
f = 1.0 * hdu[1].data[dy:-dy,xc]
m = (hdu[3].data[dy:-dy,xc]=... | 5,341,908 |
def enable_virtual_terminal_processing():
"""Enables virtual terminal processing on Windows.
This includes ANSI escape sequence interpretation.
See http://stackoverflow.com/a/36760881/2312428
"""
SetConsoleMode(GetStdHandle(-11), 7) | 5,341,909 |
def _prune_ami(ami):
"""Actually deregister AMI and its associated snapshot"""
LOGGER.info('Identified that [%s] is eligible to be pruned..', ami.id)
ami.deregister(delete_snapshot=True)
LOGGER.info('Deregistered [%s] and snapshot [%s]..', ami.id,
ami.block_device_mapping['/dev/sda1'].... | 5,341,910 |
def calculate_regularization_term(means, n_objects, norm):
"""means: bs, n_instances, n_filters"""
bs, n_instances, n_filters = means.size()
reg_term = 0.0
for i in range(bs):
if n_objects[i]:
_mean_sample = means[i, : n_objects[i], :] # n_objects, n_filters
_norm = to... | 5,341,911 |
async def cmd_module(message : discord.Message, args : str, isDM : bool):
"""return statistics about a specified inbuilt module
:param discord.Message message: the discord message calling the command
:param str args: string containing a module name
:param bool isDM: Whether or not the command is being ... | 5,341,912 |
def plot_timeseries_histograms(
axes: Axes,
data: pd.DataFrame,
bins: Union[str, int, np.ndarray, Sequence[Union[int, float]]] = "auto",
colormap: Colormap = cm.Blues,
**plot_kwargs,
) -> Axes: # pragma: no cover
"""Generate a heat-map-like plot for time-series sample data.
The kind of inp... | 5,341,913 |
def mode(x):
""" Find most frequent element in array.
Args:
x (List or Array)
Returns:
Input array element type: Most frequent element
"""
vals, counts = np.unique(x, return_counts=True)
return vals[np.argmax(counts)] | 5,341,914 |
def has_path(matrix, path: str) -> bool:
"""
Given a matrix, make sure there is a path for a given string or not.
Parameters
----------
path: str
A given path, like "abcd"
Returns
-------
out: bool
Whether the given path can be found in the matrix
"""
if not pa... | 5,341,915 |
def _convert_to_classic_address(json: Dict[str, Any], field: str) -> None:
"""
Mutates JSON-like dictionary to convert the given field from an X-address (if
applicable) to a classic address.
"""
if field in json and is_valid_xaddress(json[field]):
json[field] = xaddress_to_classic_address(js... | 5,341,916 |
def nodes_locker(nodes, lock=True, lockName=True, lockUnpublished=True):
"""Lock or unlock nodes and restore lock state on exit
For node publishing, suggest using:
- lock=False
- lockName=True
- lockUnpublished=True
This will lock nodes' all attributes and names, but not locking no... | 5,341,917 |
def gensim_processing(data):
"""
Here we use gensim to define bi-grams and tri-grams which enable us to create a create a dictonary and corpus
We then process the data by calling the process_words function from our utils folder
"""
#build the models first
bigram = gensim.models.Phrases(data, mi... | 5,341,918 |
def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
"""Check compatibility between given library and cudnn/cudart libraries."""
ldd_bin = which('ldd') or '/usr/bin/ldd'
ldd_out = run_shell([ldd_bin, lib], True)
ldd_out = ldd_out.split(os.linesep)
cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
cuda_... | 5,341,919 |
def image_upload_to(instance, filename):
"""Create the path where to store the files.
If the file instance is a Sponsor, the file has to be the logo so it will be uploaded to
MEDIA_ROOT/sponsors/<sponsor_name>/logo<ext>.
"""
logger.debug("Hello!")
path = None
basename, ext = os.path.spl... | 5,341,920 |
def _distances(value_domain, distance_metric, n_v):
"""Distances of the different possible values.
Parameters
----------
value_domain : array_like, with shape (V,)
Possible values V the units can take.
If the level of measurement is not nominal, it must be ordered.
distance_metric : ... | 5,341,921 |
def show_completed_models(completed_models):
"""Show completed models that were printed"""
print("\nThe following models have been printed")
for model in completed_models:
print(model) | 5,341,922 |
def log_mvn_likelihood(mean: torch.FloatTensor, covariance: torch.FloatTensor, observation: torch.FloatTensor) -> torch.FloatTensor:
"""
all torch primitives
all non-diagonal elements of covariance matrix are assumed to be zero
"""
k = mean.shape[0]
variances = covariance.diag()
log_likeliho... | 5,341,923 |
def unique_identity_attribute(form, field):
"""A validator that checks the field data against all configured
SECURITY_USER_IDENTITY_ATTRIBUTES.
This can be used as part of registration.
Be aware that the "mapper" function likely also normalizes the input in addition
to validating it.
:param fo... | 5,341,924 |
def M_Mobs(H0, M_obs):
"""
Given an observed absolute magnitude, returns absolute magnitude
"""
return M_obs + 5.*np.log10(H0/100.) | 5,341,925 |
def generate_proctoring_requirements_email_context(user, course_id):
"""
Constructs a dictionary for use in proctoring requirements email context
Arguments:
user: Currently logged-in user
course_id: ID of the proctoring-enabled course the user is enrolled in
"""
course_module = modu... | 5,341,926 |
def test_no_version_error(get_collection_rules, get_conf_file):
"""
Error is raised if there is no version in the collection rules loaded from URL.
"""
upload_conf = insights_upload_conf()
with raises(ValueError):
upload_conf.get_conf_update()
get_collection_rules.assert_called_once_wit... | 5,341,927 |
def mutate_strings(s):
"""Return s with a random mutation applied"""
mutators = [
delete_random_character,
insert_random_character,
flip_random_character
]
mutator = random.choice(mutators)
# print(mutator)
return mutator(s) | 5,341,928 |
def get_one_hot(inputs, num_classes):
"""Get one hot tensor.
Parameters
----------
inputs: 3d numpy array (a x b x 1)
Input array.
num_classes: integer
Number of classes.
Returns
-------
One hot tensor.
3d numpy array (a x b x n).
"""
... | 5,341,929 |
def one_hot_encoder(batch_inds, num_categories):
"""Applies one-hot encoding from jax.nn."""
one_hots = jax.nn.one_hot(batch_inds, num_classes=num_categories)
return one_hots | 5,341,930 |
def c2_msra_fill(module: nn.Module):
"""
Initialize `module.weight` using the "MSRAFill" implemented in Caffe2.
Also initializes `module.bias` to 0.
Args:
module (torch.nn.Module): module to initialize.
"""
nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
... | 5,341,931 |
def part1(entries: defaultdict) -> int:
"""part1 solver take the entries and return the part1 solution"""
return calculate(entries, 80) | 5,341,932 |
def smartspim_multichannel_stitched_request(test_client,
test_imaged_smartspim_request_twochannels_nonadmin):
""" A fixture that runs the stitching task synchronously.
Submits a test job to spock
and makes an entry into the spockadmin db to testing
of job status checkers. """
print('----------Setup smartspim_mul... | 5,341,933 |
def reset():
"""Reset the draw state, including palette, camera position, clipping and fill pattern."""
global pen_color, off_color
pen_color = 6
off_color = 0
pal()
camera()
clip() | 5,341,934 |
def ceki_filter(data, bound):
""" Check if convergence checks ceki are within bounds"""
ceki = data["ceki"].abs() < bound
return ceki | 5,341,935 |
def chunk_iterator( gffs ):
"""iterate over the contents of a gff file.
return entries as single element lists
"""
for gff in gffs:
yield [gff,] | 5,341,936 |
def get_middleware(folder, request_name, middlewares=None):
""" Gets the middleware for the given folder + request """
middlewares = middlewares or MW
if folder:
middleware = middlewares[folder.META.folder_name + "_" + request_name]
else:
middleware = middlewares[request_name]
if mi... | 5,341,937 |
def convert_dm_compatible_observations(
observes: Dict,
dones: Dict[str, bool],
observation_spec: Dict[str, types.OLT],
env_done: bool,
possible_agents: List,
) -> Dict[str, types.OLT]:
"""Convert Parallel observation so it's dm_env compatible.
Args:
observes : observations per agen... | 5,341,938 |
def test_get_interfaces_no_ifconfig_nor_ip(mock_subprocess):
"""Test get_interfaces()."""
mock_bad = subprocess.CompletedProcess(args='', returncode=127, stdout=b'',
stderr=b'Command not found')
mock_subprocess.side_effect = [mock_bad, mock_bad]
assert mech.uti... | 5,341,939 |
def tf_repeat_2d(a, repeats):
"""Tensorflow version of np.repeat for 2D"""
assert len(a.get_shape()) == 2
a = tf.expand_dims(a, 0)
a = tf.tile(a, [repeats, 1, 1])
return a | 5,341,940 |
def test_cake():
"""Test that the cake example from gemd can be built without modification.
This only tests the fix to a limited problem (not all ingredients being reconstructed) and
is not a full test of equivalence, because the reconstruction creates "dangling paths."
Consider a material/process run/s... | 5,341,941 |
def accuracy(output, target, topk=(1,), output_has_class_ids=False):
"""Computes the accuracy over the k top predictions for the specified values of k"""
if not output_has_class_ids:
output = torch.Tensor(output)
else:
output = torch.LongTensor(output)
target = torch.LongTensor(target)
... | 5,341,942 |
def remove_alias(alias):
"""
Removes an alias from being active
Parameters
----------
alias : string
Alias to be removed
"""
db = get_db()
db.tags.update_many({}, {'$pull': {'alias': alias}}) | 5,341,943 |
def null_zone_tree(domain, clobber_soa):
"""Starting at domain, change any domain's soa that is clobber_soa to None.
"""
if domain.soa is None:
pass # Keep searching (even though you won't find anything)
elif domain.soa == clobber_soa:
pass # Kill it with fire!
elif domain.soa != c... | 5,341,944 |
def masked_residual_block(c, k, nonlinearity, init, scope):
"""
Residual Block for PixelCNN. See https://arxiv.org/abs/1601.06759
"""
with tf.variable_scope(scope):
n_ch = c.get_shape()[3].value
half_ch = n_ch // 2
c1 = nonlinearity(c)
c1 = conv(c1, k=1, out_ch=half_ch, ... | 5,341,945 |
def calculate_lookup(src_cdf: np.ndarray, ref_cdf: np.ndarray) -> np.ndarray:
"""
This method creates the lookup table
:param array src_cdf: The cdf for the source image
:param array ref_cdf: The cdf for the reference image
:return: lookup_table: The lookup table
:rtype: array
"""
lookup... | 5,341,946 |
def measureInTransitAndDiffCentroidForOneImg(prfObj, ccdMod, ccdOut, cube, rin, bbox, rollPhase, flags, hdr=None, plot=False):
"""Measure image centroid of in-transit and difference images
Inputs:
-----------
prfObj
An object of the class prf.KeplerPrf()
ccdMod, ccdOut
(int) CCD m... | 5,341,947 |
def readGlobalFileWithoutCache(fileStore, jobStoreID):
"""Reads a jobStoreID into a file and returns it, without touching
the cache.
Works around toil issue #1532.
"""
f = fileStore.getLocalTempFile()
fileStore.jobStore.readFile(jobStoreID, f)
return f | 5,341,948 |
def get_user_granted_assets_direct(user):
"""Return assets granted of the user directly
:param user: Instance of :class: ``User``
:return: {asset1: {system_user1, system_user2}, asset2: {...}}
"""
assets = {}
asset_permissions_direct = user.asset_permissions.all()
for asset_permission in... | 5,341,949 |
def nullColumns(fileHeaders, allKeys):
"""
Return a set of column names that don't exist in the file.
"""
s1 = set(fileHeaders)
s2 = set(allKeys)
return s2.difference(s1) | 5,341,950 |
def listable_attachment_tags(obj, joiner=" "):
"""
Return an html string containing links for each of the attachments for
input object. Images will be shown as hover images and other attachments will be
shown as paperclip icons.
"""
items = []
attachments = obj.attachment_set.all()
labe... | 5,341,951 |
def test_specified_profile_preferred():
"""
Tests that credentials pointed to by the profile environment variable are prioritized over the default credential file credentials.
"""
save_env()
os.environ[citr_env_vars.CITRINATION_API_KEY] = ""
os.environ[citr_env_vars.CITRINATION_SITE] = ""
os... | 5,341,952 |
def distance_km(lat1, lon1, lat2, lon2):
""" return distance between two points in km using haversine
http://en.wikipedia.org/wiki/Haversine_formula
http://www.platoscave.net/blog/2009/oct/5/calculate-distance-latitude-longitude-python/
Author: Wayne Dyck
"""
ret_val = 0
radius =... | 5,341,953 |
def _flip(r, u):
"""Negate `r` if `u` is negated, else identity."""
return ~ r if u.negated else r | 5,341,954 |
def get_arguments():
"""Defines command-line arguments, and parses them."""
parser = ArgumentParser()
# Execution mode
parser.add_argument(
"--mode",
"-m",
choices=['train', 'test', 'full'],
default='train',
help=(
"train: performs training... | 5,341,955 |
def twoThreeMove(tri, angle, face_num, perform = True, return_edge = False):
"""Apply a 2-3 move to a taut triangulation, if possible.
If perform = False, returns if the move is possible.
If perform = True, modifies tri, returns (tri, angle) for the performed move"""
face = tri.triangle(face_num)
... | 5,341,956 |
def obterUFEstadoPorNome(estado):
"""
Retorna o codigo UF do estado a partir do nome do estado
:param estado: Nome do estado
:return codigoDoEstado: Código UF do estado
"""
try:
with open("./recursos/estados.csv", newline="") as csvfile:
reader = csv.DictReader(csvfile, delim... | 5,341,957 |
def get_random_byte_string(byte_length):
""" Use this function to generate random byte string
"""
byte_list = []
i = 0
while i < byte_length:
byte_list.append(chr(random.getrandbits(8)))
i = i + 1
# Make into a string
byte_string = ''.join(byte_list)
return byte_string | 5,341,958 |
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
Complexity Analysis:
Best case: O(t)
Worst Case: O(t)
In the best case the pattern is the empty string(''). In that scenario
thi... | 5,341,959 |
def is_igb(request):
"""
Checks the headers for IGB headers.
"""
if 'HTTP_EVE_TRUSTED' in request.META:
return True
return False | 5,341,960 |
def compile_ADAM_train_function(model, gparams, learning_rate=0.001, b1=0.9, b2=0.999, e=1e-8,
gamma=1 - 1e-8):
"""
ADAM update rules
Default values are taken from [Kingma2014]
References:
[Kingma2014] Kingma, Diederik, and Jimmy Ba.
"Adam: A Method for Stochasti... | 5,341,961 |
def Runge_Kutta_Fourth_Order(inputs, coordinate_file, temperature, zeta=-1., **keyword_parameters):
"""
This function determines the gradient of thermal expansion of a strucutre between two temperatures using
a forth order Runge-Kutta numerical analysis
:param Method: Gradient Isotropic QHA ('GiQ');
... | 5,341,962 |
def elapsed_timer():
"""https://stackoverflow.com/a/30024601"""
start = default_timer()
elapser = lambda: default_timer() - start
yield lambda: elapser()
end = default_timer()
elapser = lambda: end-start | 5,341,963 |
def wooqi_conf():
"""
Wooqi configuration file read from specific project which is using wooqi
Return a dictionary containing all configuration attributes
"""
config_file_path = '{}/wooqi_conf.cfg'.format(os.getcwd())
if os.path.isfile(config_file_path):
config = read_cfg(config_file_pat... | 5,341,964 |
def linear_svr_pred(X_train, Y_train):
"""
Train a linear model with Support Vector Regression
"""
svr_model = LinearSVR(random_state=RANDOM_STATE)
svr_model.fit(X_train, Y_train)
Y_pred = svr_model.predict(X_train)
return Y_pred | 5,341,965 |
def write_benchmark_records(records, path):
"""Write benchmark records to file at path"""
with open(path, 'wt') as f:
print_benchmark_records(records, f) | 5,341,966 |
def area(rad: float = 1.0) -> float:
"""
return area of a circle
>>> area(2.0)
3.141592653589793
>>> area(3.0)
7.0685834705770345
>>> area(4.0)
12.566370614359172
"""
return rad * rad * math.pi / 4 | 5,341,967 |
def check_coverage_running(url, coverage_name):
"""
Check if Navitia coverage is up and running
:param url: Navitia server coverage url
:param coverage_name: the name of the coverage to check
:return: Whether a Navitia coverage is up and running
"""
_log.info("checking if %s is up", coverage... | 5,341,968 |
def test_data1_important_metadata(dimap):
"""
Test important metadata parameters
"""
# Check extracted data is correct
expected = 'DIMAP'
assert dimap.metadata_format == expected, assert_error(expected, dimap.metadata_format)
expected = '2.12.1'
assert dimap.metadata_version == expected... | 5,341,969 |
def associate_route_table(DryRun=None, SubnetId=None, RouteTableId=None):
"""
Associates a subnet with a route table. The subnet and route table must be in the same VPC. This association causes traffic originating from the subnet to be routed according to the routes in the route table. The action returns an ass... | 5,341,970 |
def plt_comp_by_alt_4ARNA_flights(dpi=320, just_SLR=True, show_plot=False,
RunSet=None, res='4x5', flight_nums=[],
just_plot_GEOS_Chem=False,
inc_GEOSChem=False,
context="paper", font_... | 5,341,971 |
def make_random_board(row_count, col_count, density=0.5):
"""create a random chess board with given size and density"""
import random
board = {}
for row_num in range(row_count):
for col_num in range(col_count):
factor = random.random() / density
if factor >= 1:
... | 5,341,972 |
def create_roots(batch_data):
"""
Create root nodes for use in MCTS simulation. Takes as a parameter a list of tuples,
containing data for each game. This data consist of: gametype, state, type of player 1
and type of player 2
"""
root_nodes = []
for data in batch_data:
game = data[0... | 5,341,973 |
def _parse_crs(crs):
"""Parse a coordinate reference system from a variety of representations.
Parameters
----------
crs : {str, dict, int, CRS}
Must be either a rasterio CRS object, a proj-string, rasterio supported
dictionary, WKT string, or EPSG integer.
Returns
-------
... | 5,341,974 |
def hs_instance_get_all(context):
"""Get a list of hyperstash instances."""
return IMPL.hs_instance_get_all(context) | 5,341,975 |
def import_from_file(module_name: str, filepath: str):
"""
Imports a module from file.
Args:
module_name (str): Assigned to the module's __name__ parameter (does not
influence how the module is named outside of this function)
filepath (str): Path to the .py file
Returns:
... | 5,341,976 |
def test_vectorized2():
"""See that heatindex and windchill can do lists"""
t = datatypes.temperature([80.0, 90.0], "F")
td = datatypes.temperature([70.0, 60.0], "F")
hdx = meteorology.heatindex(t, td)
assert abs(hdx.value("F")[0] - 83.93) < 0.01 | 5,341,977 |
def setresuid(ruid, euid, suid):
"""Set the current process's real, effective, and saved user ids.""" | 5,341,978 |
def plot_chirp(stim_inten, spike_bins, smooth=True, ax=None):
"""
Plot the response to a chirp stimulus (but could be any repeated stimulus, non-shuffled).
The response is plotted with seaborn's lineplot.
params:
- stim_inten: The whole stimulus intensity
- spike_bins: The cell's respon... | 5,341,979 |
def _cigar_convert(cigar, chromosome, vci_file, strand='+', position=0):
"""
PHASE 1
Convert each CIGAR element to new mappings and construct an array on NEW cigar elements
For example, depending on the Intervals in the CHAIN file, let's say we have the following
CIGAR string: 35M49N65M
This ... | 5,341,980 |
def get_parser():
"""Creates an ArgumentParser object."""
parser = argparse.ArgumentParser(
"clinker",
description="clinker: Automatic creation of publication-ready"
" gene cluster comparison figures.\n\n"
"clinker generates gene cluster comparison figures from GenBank files."
... | 5,341,981 |
def test_sample_detail_renders_net_attributes(client, project):
"""should include basic inforamtion about the net set
(sample number. set data and time. lift data and time, effort
duration, orientation and set depth),
"""
# sam 1 has both dates and times for set and lift times
sample = project.... | 5,341,982 |
def init_context_processor(app):
"""定义html模板方法"""
@app.context_processor
def pjax_processor():
"""
pjax处理器
"""
def get_template(base, pjax=None):
pjax = pjax or 'pjax.html'
if 'X-PJAX' in request.headers:
return pjax
else:... | 5,341,983 |
def tiered(backup_tier, R):
"""Returns a tier aware checker.
The returned checker ensures that it's possible to construct a set
(of length R) including given set s that will contain exactly one
node from the backup tier.
`backup_tier` is a list of node ids that count as backups.
A typical inv... | 5,341,984 |
def ls_chebyshev( A, b, s_max, s_min, tol = 1e-8, iter_lim = None ):
"""
Chebyshev iteration for linear least squares problems
"""
A = aslinearoperator(A)
m, n = A.shape
d = (s_max*s_max+s_min*s_min)/2.0
c = (s_max*s_max-s_min*s_min)/2.0
theta = (1.0-s_min/s_max)/(1... | 5,341,985 |
def random_window(image_shape, w_size, n):
"""Yield randomly placed sub-images of the given image.
Parameters
----------
image_shape : tuple (nrows, ncols)
Image shape (img.shape).
w_size : tuple (width, height)
Window size as a pair of width and height values.
n : int
N... | 5,341,986 |
def compute_confusion_matrix(args, df_inference, strata):
"""From a list of prediction summary (as produced by get_cloud_prediction_summary), compute a confusion matrix."""
y_true = df_inference["vt_" + strata].values
y_predicted = df_inference["pred_" + strata].values
y_true = np.vectorize(get_closes... | 5,341,987 |
def get_metadata(**kwargs):
"""Metadata
Get account metadata
Reference: https://iexcloud.io/docs/api/#metadata
Data Weighting: ``Free``
.. warning:: This endpoint is only available using IEX Cloud. See
:ref:`Migrating` for more information.
"""
return Metadata(**kwargs).... | 5,341,988 |
def get_resnet50_moco_state_dict() -> dict:
"""
Get weight of ResNet50 trained with MoCo.
Returns:
(dict): Parameters and persistent buffers of ResNet50.
"""
model_path = get_model_root() / "resnet50_moco.pth"
if not model_path.exists():
# TODO download this from remote
... | 5,341,989 |
def start_blockchains(prefab, node_name):
"""
Start blockchains daemons on a node
"""
# a bit unrelated but make sure that curl is installed
prefab.core.run('apt-get update; apt-get install -y curl', die=False, showout=False)
print("Starting tfchaind daemon on {}".format(node_name))
t... | 5,341,990 |
def write_utf16(file: BinaryIO, val: str):
"""write a utf-16 string to file"""
for c in val:
file.write(c.encode("utf-16LE"))
file.write(b"\x00\x00") | 5,341,991 |
def _validate_client(redis_client, url, tenant, token, env, blacklist_ttl,
max_cache_life):
"""Update the env with the access information for the user
:param redis_client: redis.Redis object connected to the redis cache
:param url: Keystone Identity URL to authenticate against
:par... | 5,341,992 |
def _fetch(data_filename: str) -> str:
"""Fetch a given data file from either the local cache or the repository.
This function provides the path location of the data file given
its name in the histolab repository.
Parameters
----------
data_filename: str
Name of the file in the histolab... | 5,341,993 |
def ADR(cpu_context: ProcessorContext, instruction: Instruction):
"""Compute address of label at a PC-relative offset."""
operands = instruction.operands
pc = cpu_context.registers.pc
opvalue2 = operands[1].value
result = pc + opvalue2
logger.debug("0x%X + 0x%X = 0x%X", pc, opvalue2, result)
... | 5,341,994 |
def subset_and_group_svs(input_dataset, sample_subset, sample_remap, sample_type, ignore_missing_samples, write_subsetted_bed=False):
"""
Parses raw SV calls from the input file into the desired SV output format for samples in the given subset
:param input_dataset: file path for the raw SV calls
:param... | 5,341,995 |
def test_name_equality_check_in_pipfile_not_setup(setup_deps_and_extras,
pipfile_deps_and_extras):
"""
Checks that the proper errors are raised when a dependency name is present
in the Pipfile but not in setup.py
Args:
setup_deps_and_extras (dic... | 5,341,996 |
def load_data():
"""
Carrega os dados do dataset iris
:return: dados carregados em uma matriz
"""
data = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data", header=None)
# utiliza somente as duas primeiras classes
data = data[:100]
# transforma as... | 5,341,997 |
async def activate_clients(
*,
client_id: int,
session: Session = Depends(get_session),
):
"""
Activate a client using its id as a key.
Parameters
----------
client_id : int
ID of the client to be activated.
session : Session
SQL session that is to be used to activat... | 5,341,998 |
def display_error_message(strip_xonsh_error_types=True):
"""
Prints the error message of the current exception on stderr.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
exception_only = traceback.format_exception_only(exc_type, exc_value)
if exc_type is XonshError and strip_xonsh_error_... | 5,341,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.