content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def mkXRDTag(t):
"""basestring -> basestring
Create a tag name in the XRD 2.0 XML namespace suitable for using
with ElementTree
"""
return nsTag(XRD_NS_2_0, t) | c770afdcf21576d761e111afc8556f7c37745099 | 3,614,726 |
def auth(
func=None,
roles=None,
permissions=None,
requires=None,
login_redirect=None,
should_remember_referrer=True):
"""Guards a controller action against unauthorized and unauthenticated access.
Args:
roles (list|string): A list of roles that are able ... | 43916198f76f2e840ba6b4535117a35a54d70294 | 3,614,727 |
def site_stat_stmt(table, site_col, values_col, fun):
"""
Function to produce an SQL statement to make a basic summary grouped by a sites column.
Parameters
----------
table : str
The database table.
site_col : str
The column containing the sites.
values_col : str
T... | c704d5687effd3c12abb3feecde9041eb88aae7a | 3,614,728 |
def to_time_units(obj, freq):
"""Multiply each element with `freq_delta` to get result in time units."""
if not checks.is_array(obj):
obj = np.asarray(obj)
return obj * freq_delta(freq) | 86ca6c833d32e9e03b4afcba8462f69fa42670d4 | 3,614,729 |
import random
def perform_learning_step(epoch):
""" Makes an action according to eps-greedy policy, observes the result
(next state, reward) and learns from the transition"""
def exploration_rate(epoch):
"""# Define exploration rate change over time"""
start_eps = 1.0
end_eps = 0.... | e10ccdaeffeb37800ca52db193dbfd6426ebc9dd | 3,614,730 |
def read_bhrc(filename, **kwargs):
"""Read the Iran BHRC strong motion data format.
Args:
filename (str): path to BHRC data file.
kwargs (ref):
Other arguments will be ignored.
Returns:
list: Sequence of one StationStream object containing 3
StationTrace objects... | 3d86478e22189b3910ca6e509911437fb2bfbb58 | 3,614,731 |
def random_pdf(x, dx, seed_i=False, n_iter=1000, silent=True):
"""
Created on 24/06/2016
Modified on 29/06/2016 to reverse shape
"""
len0 = len(x)
if not silent:
print(len0)
# Mod on 29/06/2016
x_pdf = np.zeros((len0, n_iter), dtype=np.float64)
# x_pdf = np.zeros((n_iter, l... | aa5940ae6913ab40aeb10d319b7e0bdab01a0453 | 3,614,732 |
import itertools
def vertical_split(im):
"""
Split an image vertically. This works for member list as well as (well, most times) scouting screenshots
:param im: screenshot data
:return: the ratio for resizing the screenshot, a list of (start, stop) chunks to use when looping
"""
im_gray = cv2... | 78b2c423f72f0c75ce7712ee8f74a1564caa2990 | 3,614,733 |
def interp2d(image):
"""
Bilinear interpolation method to be used for upscaling
Args:
tensor_nchw (tensor): tensor of shape (N, C, H, W)
Return:
tensor of shape (N, C, Hout, Wout), where Hout and Wout are computed
by applying the scale factor to H and W
"""
# return ... | 14a40dcf0b3a22d9493b99c0cf5c96e41f37fd2e | 3,614,734 |
def get(cls, key):
"""
Get an entity by key
"""
return build_key(cls, key).get() | 58113088582c61dc67bb4d0366a9f4f35256c959 | 3,614,736 |
def page_not_found(__=None):
"""
What to return if a user requests an endpoint that doesn't exist.
"""
print(app.root_path)
return transiter_error_handler(exceptions.PageNotFound(flask.request.path)) | 21dd68dc51607bee937f327c5c8ac864d5309029 | 3,614,737 |
import copy
def rational_diagonal_form(self, return_matrix=False):
"""
Returns a diagonal form equivalent to Q over the fraction field of
its defining ring. If the return_matrix is True, then we return
the transformation matrix performing the diagonalization as the
second argument.
INPUT:
... | 9bee64eabd0a4550455e99542ff7db3c89526892 | 3,614,738 |
def _format_source_error(filename, lineno, block):
""" A helper function which generates an error string.
This function handles the work of reading the lines of the file
which bracket the error, and formatting a string which points to
the offending line. The output is similar to:
File "foo.py", li... | 32d093e53811415338877349ca8e64b0e9261b1d | 3,614,739 |
def calc_exposure(k, src_rate, bgd_rate, read_noise, neff):
"""
Compute the time to get to a given significance (k) given the source rate,
the background rate, the read noise, and the number
of effective background pixels
-----
time = calc_exposure(k, src_rate, bgd_rate, read_noise, neff)
... | 993853d244cfa5c6619300def02294a2497d78df | 3,614,740 |
def decode_image(contents, channels=None, name=None):
"""Convenience function for `decode_gif`, `decode_jpeg`, and `decode_png`.
Detects whether an image is a GIF, JPEG, or PNG, and performs the appropriate
operation to convert the input bytes `string` into a `Tensor` of type `uint8`.
Note: `decode_gif` return... | 2d875772abbd02b716922880c88b63b8c080eed8 | 3,614,741 |
def get_all_round_info_from_cache():
"""Returns a dictionary containing all the round information.
example: {"rounds": {"Round 1": {"start": start_date, "end": end_date,},},
"competition_start": start_date,
"competition_end": end_date}
"""
rounds_info = cache_mgr.get_cache('r... | e996b97290112116c65c66d9db3fe7c19f9b242c | 3,614,743 |
def type_or_null(names):
"""Return the list of types `names` + the name-or-null list for every type in `names`."""
return [[name, 'null'] for name in names] | 72cbefcbba08c98d3c4c11a126e22b6f83f4175b | 3,614,744 |
def scratch(request, slug=None):
"""
Get or create a scratch
"""
if request.method == "GET":
db_scratch = get_object_or_404(Scratch, slug=slug)
return Response(ScratchSerializer(db_scratch).data)
elif request.method == "POST":
data = request.data
if "target_as... | d7c13689f7f7a4bb97c1c4d8e2fb20636f1cbf7a | 3,614,745 |
def variables_pool(variable, question='Variable to analyze'):
"""
:param variable: the variable chosen from variable pool in your dataframe
:param question: default parameter ("Variable to analyze")
don't :return:
"""
def guide(diz):
"""
function that guides user to chose the ri... | fcff9eaa1467d96251ba08eaa433aa05b7b769f2 | 3,614,746 |
import torch
def quadratic_matmul(x: torch.Tensor, A: torch.Tensor) -> torch.Tensor:
"""Matrix quadratic multiplication.
Parameters
----------
x : torch.Tensor, shape=(..., X)
A batch of vectors.
A : torch.Tensor, shape=(..., X, X)
A batch of square matrices.
Returns
----... | 78335f6a57f34701f3f1fe9b8dd74e9b8be686a3 | 3,614,748 |
def get_global_step(estimator):
"""Return estimator's last checkpoint."""
return int(estimator.latest_checkpoint().split("-")[-1]) | 11b4a96f74d029f9d9cc5a0fcc93da7504729eb7 | 3,614,749 |
from src.priorityq import PriorityQ
def test_q():
"""Test fixtures of priority qs."""
q0 = PriorityQ()
q1 = PriorityQ()
q1.insert('sgds', 10)
q1.insert('another', 9)
q1.insert('another', 8)
q1.insert('another', 7)
q1.insert('another', 6)
return q0, q1 | fd5e9cb0a0110b96c34bbc9b85e44596d1180dc5 | 3,614,750 |
def make_mlb_classifier_and_data_with_feature_extraction_pipeline():
"""Create data set and classifier for testing a multi-label
classification scenario with a feature extraction pipeline.
"""
newsgroups_train = fetch_20newsgroups(subset="train")
X, Y = newsgroups_train.data, newsgroups_train.targe... | 478077dbecde141e7d92f00cfe9e8d961d14a1b0 | 3,614,751 |
def read_volume(filepath, dtype=None, return_affine=False):
"""Return numpy array of data from a neuroimaging file.
Args:
filepath: path-like, path to volume file.
dtype: dtype-like or str, data type of the volume data.
return_affine: boolean, if true, return tuple of volume data and
... | d581155c06599b6e987db5a7fdc2f62e4918e25b | 3,614,752 |
import traceback
import json
def Import(context, request):
""" FOSS FIAStar analysis results
"""
infile = request.form['data_file']
fileformat = request.form['format']
artoapply = request.form['artoapply']
override = request.form['override']
sample = request.form.get('sample',
... | 7536c920b36c8158976b02f6c75cbce1ac8e3bf7 | 3,614,753 |
def meantime_blockedby_pp_hat(arr_rate, pp_mean_svctime, pp_cap, pp_cv2_svctime):
"""
Approximate unconditional mean time blocked in ldr or csect waiting for a pp bed.
Modeling pp as an M/G/c queue and using approximation by Kimura.
"""
pp_svcrate = 1.0 / pp_mean_svctime
meantime = qng.mgc_mean... | 5c7e8de26b1f131e7e9a02743f51e2c62ef5023d | 3,614,754 |
def _combine_grad(evoked, picks):
"""Create a new instance of Evoked with combined gradiometers (RMSE)."""
def pair_and_combine(data):
data = data ** 2
data = (data[::2, :] + data[1::2, :]) / 2
return np.sqrt(data)
picks, ch_names = _grad_pair_pick_and_name(evoked.info, picks)
th... | 5469cc60f27be8646f9f20fa28b3e305d6d1bf38 | 3,614,755 |
def each_segment(time_ci, energy_ci, rate_ref, meta_dict,\
start_time, end_time):
"""
Turns the event list into a populated histogram, stacks the reference band,
and makes the cross spectrum, per segment of light curve.
Parameters
----------
time_ci : np.array of floats
1-D array of... | 043fa5e18021f54ddc4eb7da1e1c45c50453ee8c | 3,614,756 |
import torch
def box_iou(boxes1, boxes2):
"""Compute pairwise IoU across two lists of anchor or bounding boxes.
Defined in :numref:`sec_anchor`"""
def box_area(boxes): return ((boxes[:, 2] - boxes[:, 0]) *
(boxes[:, 3] - boxes[:, 1]))
# Shape of `boxes1`, `boxes2`, `a... | c358c15b99d0e742487a92630ff927606ad6d896 | 3,614,757 |
def feature_reconstruction_loss(base, output):
"""
Compute the content loss for style transfer.
Inputs:
- output: features of the generated image, Tensor with shape [height, width, channels]
- base: features of the content image, Tensor with shape [height, width, channels]
Returns:
- scala... | aab47546c68a83e687eeabe77d89fdb7aa51ab8b | 3,614,760 |
import time
def attempt_to_acquire_lock(s3_conn, lock_uri, sync_wait_time, job_name,
mins_to_expiration=None):
"""Returns True if this session successfully took ownership of the lock
specified by ``lock_uri``.
"""
key = _lock_acquire_step_1(s3_conn, lock_uri, job_name, mins... | 714eb9daaaa242aeb6d877a10b1fffaf353a606e | 3,614,761 |
import torch
def multiclass_nms(
multi_bboxes,
multi_scores,
score_thr,
nms_cfg,
max_num=-1,
score_factors=None,
multi_attrs=None,
multi_feats=None,
):
"""NMS for multi-class bboxes.
Args:
multi_bboxes (Tensor): shape (n, #class*4) or (n, 4)
multi_scores (Tenso... | 4f7075c93b0c4c7fc5d4905237a35bb48f445314 | 3,614,762 |
import torch
def get_device():
""" Get the device on which running."""
return torch.device("cuda" if torch.cuda.is_available() else "cpu") | 9ab3e98a98f9f6c1630ee4bd76c170efae029d68 | 3,614,763 |
def make_png_thumbnail():
"""Make a thumbail of the first page of a PDF and return it.
:return: A response containing our file and any errors
:type: HTTPS response
"""
f = request.files["file"]
max_dimension = int(request.args.get("max_dimension"))
with NamedTemporaryFile(suffix=".%s" % "pd... | fefc14618bea13693878983c9630280b32584115 | 3,614,764 |
import uuid
def rand_uuid():
"""Generate a random UUID string
:return: a random UUID (e.g. '1dc12c7d-60eb-4b61-a7a2-17cf210155b6')
:rtype: string
"""
return str(uuid.uuid4()) | fc35e154eeab62988bcd96799ce0f688f4ec427a | 3,614,765 |
import logging
def get_logfile_name():
"""
Return the current logfile name
"""
return logging.getLoggerClass().root.handlers[0].baseFilename | 28b5d6628890a6cccb09a68f24e6257d425c3833 | 3,614,766 |
def sign(x, y):
"""Fortran's sign transfer function"""
return x * tf.math.sign(y) | 05f44a6f8955b50318e65e3ad0a633c2acaf8d8d | 3,614,767 |
def filter_linksearchtotals(queryset, filter_dict):
"""
Adds filter conditions to a LinkSearchTotal queryset based on form results.
queryset -- a LinkSearchTotal queryset
filter_dict -- a dictionary of data from the user filter form
Returns a queryset
"""
if "start_date" in filter_dict:
... | 96a7e816e7e2d6632db6e6fb20dc50a56a273be9 | 3,614,768 |
def mean(samps):
"""
Find the mean point forecasts.
"""
return np.mean(samps, axis=0) | 8821fe547e1b1f12626544ca2d8056b725cf00e1 | 3,614,769 |
def all():
"""
Returns all W2S Scenarios in [GWh/a]
:return:
"""
sc = (read("szenarien_w2s.xlsx")
.pipe(start_pipeline)
.pipe(NaNtoZero)
.pipe(format_df)
.pipe(convert_PJ_to_GWH)
)
return sc | 7cac87baf53c7bfeda5bd2158801628c989178ce | 3,614,771 |
def test_download_cache_hit(mocker):
"""Check that download is not repeated on cache hit."""
data = b"Hello, world"
data_checksum = "4ae7c3b6ac0beff671efa8cf57386151c06e58ca53a78d83f36107316cec125f"
cached_path = cache_path(f"downloads/{data_checksum}")
# Tidy up from a previous test, if applicable... | 244e483ccef50c877e5023d0dd857e2f92ca34b9 | 3,614,772 |
import transformers
import torch
import tqdm
def eval_two_span(
val_data: data.DataLoader,
model: transformers.PreTrainedModel,
loss_func: nn.modules.loss._Loss,
dev: torch.device=None
) -> float:
"""Evaluate a two span edge probing model.
Args:
val_data: valid... | 6873dc6e5dcbd5d19ee7321b42f5bac7aa63d2f8 | 3,614,773 |
import csv
def get_column(path, c=0, r=1, sep='\t'):
""" extracts column specified by column index
assumes that first row as a header
"""
try:
reader = csv.reader(open(path, "r"), delimiter=sep)
return [row[c] for row in reader] [r :]
except IOError:
print('list_rows: f... | 036a1630417224474e8bfe7a9c038a04bd3ea0d5 | 3,614,775 |
def part2(lines):
"""
>>> part2(load_example(__file__, "24"))
19
"""
return run(lines, Part2) | bfd2aaf0aff01365c3825a1b4608670739f56875 | 3,614,776 |
def add_md_padding(data, endian='big'):
"""Merkle-Damgard padding
Args: data(string)
Returns: data+padding(string)
"""
size = len(data) & 0x3f # len_in_bytes % 64
if size < 56:
size = 56 - size
else:
size = 120 - size
p = bytes(b'\x80') + bytes(b'\x00'*63)
p = p[:si... | 6138c66f854b8746db78ba5e8979e88d831d3a84 | 3,614,778 |
def list_fridge():
"""
List all items in the frigde.
:return: dict with all items and amounts
:rtype: dict
"""
return MOCK_FRIDGE | 56988ae3f27e92b2afdfcd404f15ab396c89468b | 3,614,779 |
def evaluate_hessian_val(A, point, direction):
"""
Returns the value of Hessian function in the given direction.
"""
hess_p = (A - np.diag((A.dot(point)).dot(point.T))).dot(direction)
return np.sum(hess_p * direction) | 92c9c62d2e80bf172b2e04c3e533b0cbf021e244 | 3,614,780 |
import numpy
def frustrated_loop(graph, num_cycles, R=float('inf'), cycle_predicates=tuple(),
max_failed_cycles=100, planted_solution=None, seed=None):
"""Generate a frustrated-loop problem.
A generic frustrated-loop (FL) problem is a sum of Hamiltonians, each generated
from a single ... | f1e7bccdb17c9703c9b4fa78bc3da4ce583c88a9 | 3,614,781 |
def _projection_unit_simplex(x: jnp.ndarray) -> jnp.ndarray:
"""Projection onto the unit simplex."""
s = 1.0
n_features = x.shape[0]
u = jnp.sort(x)[::-1]
cssv = jnp.cumsum(u) - s
ind = jnp.arange(n_features) + 1
cond = u - cssv / ind > 0
idx = jnp.count_nonzero(cond)
threshold = cssv[idx - 1] / idx.a... | 9d0cae071d27b2a105da9be945f59c50d5462e60 | 3,614,782 |
def channel_id_str_to_bytes(channel_id_str):
"""
Args:
channel_id_str: string representation of channel id
Returns:
bytes representation of channel id
"""
assert type(channel_id_str) in [str, bytes]
if isinstance(channel_id_str, bytes):
return channel_id_str
qid_byte... | 2267fa7d810ca09a6498c8ab9cfffc0d6c8fcb9e | 3,614,783 |
from typing import Optional
def compiled(
model: tf.keras.Model,
loss=None,
metrics=None,
optimizer=None,
run_eagerly: Optional[bool] = None,
# steps_per_execution: Optional[int] = None,
) -> tf.keras.Model:
"""Mutate model in-place by compiling and return the model for convenience."""
... | 809497352df4ac3ed609e525c3916bf6e506b80a | 3,614,784 |
def vtkVariantExtract(v, t=None):
"""
Extract the specified value type from the vtkVariant, where the type is
in the following format: 'int', 'unsigned int', etc. for numeric types,
and 'string' or 'unicode string' for strings. You can also use an
integer VTK type constant for the type. Set the ty... | 9d34e1b0e989d6b36b78f97eab7bbc9d1e49740e | 3,614,785 |
import collections
import itertools
def _create_region_groups(const_regions, psvs, genome, max_dist=1000):
"""
Groups closeby const regions if they have the same CN even if there is a region with a different CN between them.
"""
psv_ix = 0
n_psvs = len(psvs)
# Key: copy_num, value: list of Pl... | 5f75d088d31ea5b889ab5f77dbd7ee7abbe18dad | 3,614,786 |
import imp
def _LoadConfigModule(name: str, path: str):
"""Loads a script from external file specified by path.
Unprefixed path is looked for in the current working directory using
regular file open operation. This should work with relative config paths.
Args:
name: Name of the new module.
path: Pat... | cd2d15bdd357c5efcfe15648a5fca437f3cdda8b | 3,614,787 |
def _parse_icq(fileobj):
"""Parse a International Comet Quarterly (ICQ) format file."""
df = pd.read_fwf(fileobj, colspecs=list(ICQ_COLUMNS.values()),
names=ICQ_COLUMNS.keys(), header=None)
return df | 40bd2302991e40e014caff6e3b4e4020ff1fa82b | 3,614,788 |
def IperfTCP(target_src, target_dst, dst, length, window=None):
"""Convenience method for starting a TCP IperfSet.
See IperfSet for more details.
Args:
target_src: A single host or list of hosts.
target_dst: A single host or list of hosts (1:1 with target_src).
dst: A single address/hostname or a li... | 98a94718e29d116acfaadd18bf20855fa2dfadb5 | 3,614,789 |
def plot_riemann(states, s, riemann_eval, t, fig=None, color='b', layout='horizontal',conserved_variables=None):
"""
Take an array of states and speeds s and plot the solution at time t.
For rarefaction waves, the corresponding entry in s should be tuple of two values,
which are the wave speeds that bou... | af1a53cd84e4e51ee0934c2fe303465fab338636 | 3,614,790 |
def find_in_list(list_one, list_two):
"""Find and return an element from list_one that is in list_two, or None otherwise."""
for element in list_one:
if element in list_two:
return element
return None | 9376b38a06cadbb3e06c19cc895eff46fd09f5c1 | 3,614,791 |
from typing import List
from typing import Tuple
def getElementById(idName: str, fileName: str) -> List[Tuple[int, str]]:
"""Returns first matching tag from an HTML/XML document"""
nonN: List[str] = []
with open(fileName, "r+") as f:
html: List[str] = f.readlines()
for line in html:
... | e0888a41c7cbdf4a0ef449bbbfb23ed650e2ab12 | 3,614,792 |
def skip_after(timeout: int or float):
"""
Creates an async pool with an associated timeout, but
without raising a TooSlowError exception. The pool
is simply cancelled and code execution moves on
"""
assert timeout > 0, "The timeout must be greater than 0"
mgr = TaskManager(timeout, False)
... | 1015389638164a2d1131c6a634e918e66645b2d2 | 3,614,793 |
from pathlib import Path
def read_peak_correlations(file_name):
"""
Read in the custom peak correlation Excel file provided by JAX.
"""
df = pd.DataFrame(pd.read_excel(file_name))
tab = Table.from_pandas(df) #read(file_name, format="ascii.csv")
# tab.rename_column('\ufeffMm_chr', 'Mm_chr')
... | f1fc20cfec167cf9aaa0284e4cb08e7cf4fdb74e | 3,614,794 |
import torch
def sample(model, block_size, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic compl... | 7d5888a961b9f29c7345fe207f71e26aaf646eef | 3,614,796 |
def explore_result_coverage_detail():
"""Get coverage detail info
Get coverage detail info loading from disk
:return: a list, each element is dict map in list, if coverage file not exist,
will return [],for example:
[{
"fileName": "1.jpg",
"sampleNum": 5,
... | e7a6cf085414743f59d24da790d8115c36a35047 | 3,614,797 |
def gradient_dx(fx: tf.Tensor) -> tf.Tensor:
"""
Function to calculate gradients on x-axis of a 3D tensor using central finite difference.
It moves the tensor along axis 1 to calculate the approximate gradient, the x axis,
dx[i] = (x[i+1] - x[i-1]) / 2
:param fx: shape = (batch, m_dim1, m_dim2, m_d... | 452bb2240db6d155f072288aa32751167f7eb943 | 3,614,798 |
def _real_freq_filter(rfft_signal, filters):
"""Helper function to apply a full filterbank to a rfft signal
"""
nr = rfft_signal.shape[0]
subbands = filters[:, :nr] * rfft_signal
return subbands | 0bee4822ac1d6b5672e4ad89bb59f03d72828244 | 3,614,800 |
def _strip_extension(name, ext):
"""
Remove trailing extension from name.
"""
ext_len = len(ext)
if name[-ext_len:] == ext:
name = name[:-ext_len]
return name | aa1e6f8c68e09597e2566ecd96c70d2c748ac600 | 3,614,801 |
def node_clique_number(G,nodes=None,cliques=None):
""" Returns the size of the largest maximal clique containing
each given node.
Returns a single or list depending on input nodes.
Optional list of cliques can be input if already computed.
"""
if cliques is None:
if nodes is not None:
... | 143fa46b1bd7365bc306489e77d697d5741701a4 | 3,614,802 |
def str_to_list(s):
# type: (str) -> List[str]
"""Convert string to list."""
if isinstance(s, str):
return s.split(',')
return s | bdc59bfcfadf815ecce5adc599fbca98f9924fe6 | 3,614,803 |
import torch
def get_online_seed_from_cam_sal_seg(cam: torch.Tensor, sal: torch.Tensor,
seg_prob: torch.Tensor, cls_in_label: torch.Tensor,
cam_thresh: float, sal_thresh: float, ignore_label: int) -> torch.Tensor:
"""Get online seed from CA... | 96fd29570fef0fb352c8b32a4ac5d3bf49ae4dbe | 3,614,804 |
import inspect
def check_parameter(**kwargs):
"""Check dtype of the function's parameters.
Parameters
----------
kwargs : Type or Tuple[Type]
Map of each parameter with its expected dtype.
Returns
-------
_ : bool
Assert if the array is well formatted.
"""
# get ... | 597c205c091b207f529fd961cd808c5a99285b4f | 3,614,805 |
def part1(data):
"""
>>> part1(read_input())
192
"""
return sum(is_valid(passport) for passport in data) | cd68c276151b540d2bb02aaca0f7eb039addc79d | 3,614,806 |
def minimize(func, x0, args=(), *, method, tol=None, options=None):
"""Minimization of scalar function of one or more variables.
This API for this function matches SciPy with some minor deviations:
- Gradients of ``fun`` are calculated automatically using MindSpore's autodiff
support when required.
... | d0affb1dc4bbe141504528fba55baf8a2fa29ae9 | 3,614,807 |
from mxnet.gluon.model_zoo.vision import get_model
def get_network(name, batch_size):
"""Get the symbol definition and random weight of a network"""
dtype = 'float32'
input_shape = (batch_size, 3, 224, 224)
output_shape = (batch_size, 1000)
if "resnet" in name:
n_layer = int(name.split("-... | 1d874b32c7421f189a4cd47259875d02ba524eb1 | 3,614,808 |
from typing import Callable
from typing import Dict
def web_template() -> Callable[[Request, str], _TemplateResponse]:
"""Create a dependency which may be injected into a FastAPI app."""
def _template(request: Request, page: str, context: Dict = {}) -> _TemplateResponse:
"""Create a template from a r... | 39e5b04dcbc586670b7a165444976e1beac178aa | 3,614,809 |
def core_number(G):
"""Returns the core number for each vertex.
A k-core is a maximal subgraph that contains nodes of degree k or more.
The core number of a node is the largest value k of a k-core containing
that node.
Parameters
----------
G : NetworkX graph
A graph or directed gr... | 74e9852cac0e7ad321090e4959b1b6f88d8a55b7 | 3,614,810 |
def create_meeting(
client,
name: str,
description: str = None,
title: str = None,
duration: int = 60000, # duration in mins ~6 weeks
):
"""Create a Zoom Meeting."""
body = {
"topic": title if title else f"Situation Room for {name}",
"agenda": description if description else... | a5157575a8921a612a09dc6cf9038f0c45513cd4 | 3,614,811 |
def hours(datetime):
"""
Returns the hours component for the given datetime value, in local time.
"""
return datetime.hour() | a88d932b49ded87e472cf902e39a1ca3c3e4ac2b | 3,614,812 |
def compute_checksum(filename):
"""Computes the MD5 checksum of the contents of a file.
filename: string
"""
cmd = 'md5sum ' + filename
return pipe(cmd) | b6fc037ac42c0f86bf196ff6f93fe7cb94bf45ea | 3,614,814 |
def clean_text(
raw_text,
fix_unicode=True,
to_ascii=False,
lower=True,
no_line_breaks=True,
no_urls=True,
no_emails=True,
no_phone_numbers=True,
no_numbers=False,
no_digits=False,
no_currency_symbols=True,
no_punct=False,
... | d63d0c4eff28de4677c12e080a37d6f40309a395 | 3,614,815 |
def _get_s3_provider():
"""
Gets S3 Config Provider
:return: Instance of S3ConfigProvider
:rtype: S3ConfigProvider
"""
return S3ConfigProvider(
bucket=CONFIG_PROVIDERS['s3']['bucket'],
config_base=CONFIG_PROVIDERS['s3']['base']
) | 2192daa02b57a58267d34662294886aeb8f8bc1b | 3,614,816 |
def is_path_fully_cached(path):
"""Returns true if all the bytes of the path are cached, false otherwise"""
rc, stdout, stderr = exec_process("hdfs cacheadmin -listDirectives -stats -path %s" % path)
assert rc == 0
caching_stats = stdout.strip("\n").split("\n")[-1].split()
# Compare BYTES_NEEDED and BYTES_CAC... | 2bcf4258b52d9e8f739ff5523f6b036d42013c4f | 3,614,818 |
def find_camera_tracking_pts_topics():
"""
Returns list of all tracking_pts topics associated with a camera
"""
topic_list = find_topics_w_ending('tracking_pts')
topic_list = [topic for topic in topic_list if 'camera' in topic.split('/')]
return topic_list | afd3de49187bdec69deab0418ea3bcc3c627f8e2 | 3,614,819 |
def get_batch_size(dataset: tf.data.Dataset,
optimization_batch_size: int = BATCH_AUTO_TUNE) -> int:
"""Computes optimization batch size for processing steps in batches.
Args:
dataset: episodes or steps dataset.
optimization_batch_size: user-provided hint for the batch size.
Returns:
... | f437e6403031f879ffe3047bb008732cba4a5497 | 3,614,820 |
def get_uuid_from_url(url: str) -> str:
""" Strip the URL from the string. Returns the UUID. """
return url.split('/')[-1] | d9e0ea9ed186d1ba19c40ead9d08108c45dbf850 | 3,614,821 |
def texFrac(frac):
""" Tex render for Fractions"""
return ["\\frac{" , str(frac._num) , "}{" , str(frac._denom) , "}"] | fd0ed6af8b50f8a4b89e0d83d7cb3e3c3a5f3a90 | 3,614,822 |
def repeated_hindsight_gumbel_estimation(
universe, probabilities, values, num_samples, normalize, repetitions):
"""Uses Hindsight Gumbel Estimation multiple times with different Gumbels."""
# Use the same samples for each repetition!
results = ppswor_samples(universe, probabilities, num_samples)
all_sampl... | 6f6ad6e712d87350e34b397010eb0be86095ec9c | 3,614,824 |
def get_progress_string(tag, epoch, minibatch, nbatches, cost, time,
blockchar=u'\u2588'):
"""
Generate a progress bar string.
Arguments:
tag (string): Label to print before the bar (i.e. Train, Valid, Test )
epoch (int): current epoch to display
minibatch (i... | 23d7b5dfcc2fd11841a87a3c94f3e8f4d9840a36 | 3,614,825 |
def calcRingCentroidNormal(atomCoords):
""" extract aromatic ring geometric info from a numpy array """
a1 = atomCoords[0]
a2 = atomCoords[1]
a3 = atomCoords[2]
centroid = averageCoords(atomCoords)
plane = calcPlane(a1, a2, a3)
v1 = vector(centroid, a1)
v2 = vector(centroid, a2)
nor... | 1c1719ef1bfe1564e6fbbe16c14507b9daf6149e | 3,614,826 |
import copy
def flip_horizontal(original: Image) -> Image:
"""Written by: Cameron Legree
Student No. 101153496
Returns a copy of an image flipped along a horiontal line centered in the
image. orginal_image must be loaded prior to passing it through the
function.
>>>flip_horizontal(miss_sull... | 143a839c789ad26f5d7174bf25902b85936a4e13 | 3,614,827 |
from typing import List
from typing import Optional
def span_to_label(tokens: List[str],
labeled_spans: dict,
scheme: Optional[str] = 'BIO') -> List[str]:
"""
Convert spans to label
:param tokens: a list of tokens
:param labeled_spans: a list of tuples (start_idx, e... | dbd572d4c306f31202c93b5983f5dd4cdd237074 | 3,614,828 |
def expand_markup(abbr: str, config: Config) -> str:
"""
Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that
produces structured output like HTML) and outputs it according to options
provided in config
"""
return stringify_markup(markup_abbreviation(abbr, config), config) | 2af46f12fcecb0bedcc01b94aeb2b92dc51e3a7c | 3,614,829 |
def withinStdDevRange(a, b):
"""Returns the percent of samples within the std deviation range a, b"""
if b < a:
return 0;
if a < 0:
if b < 0:
return (withinStdDev(-a) - withinStdDev(-b)) / 2;
else:
return (withinStdDev(-a) + withinStdDev(b)) / 2;
else:
return (withinStdDev(b) - with... | 27b293805656b7e33af9843bab48b25ecfa98d47 | 3,614,831 |
import logging
import requests
def commit_email():
"""Receive web hook from github and generate email."""
# Only look at push events. Ignore the rest.
event = flask.request.headers['x-github-event']
logging.info('Received "{0}" event from github.'.format(event))
if event != 'push':
loggin... | 36e97fe8a52094c6d9274c58aa9dd69b10106573 | 3,614,832 |
def unimodal_converter(data):
"""
Returns ground truth labels when data is split modally to text and image
data: dataframe object
"""
for column in ["string", "numeric"]:
unimodal_image, unimodal_text = [], []
for i in range(len(data)):
temp_val = data.loc... | 623208e7b8ee9e4f1e494c95d7ec0c16558f85b9 | 3,614,833 |
def convert_ids_to_tokens(inv_vocab, ids):
"""Converts a sequence of ids into tokens using the vocab."""
output = []
for item in ids:
output.append(inv_vocab[item])
return output | da1aa84d271fe46cedf530c2871ee54c57e676e2 | 3,614,834 |
import aiohttp
async def remove_device(
ws_client: aiohttp.ClientWebSocketResponse, device_id: str, config_entry_id: str
) -> bool:
"""Remove config entry from a device."""
await ws_client.send_json(
{
"id": 1,
"type": "config/device_registry/remove_config_entry",
... | 095926990c48a5f61267eb059591a80c48f7e3eb | 3,614,836 |
def build_senator_details(details):
"""Build the test data for a senator."""
data = build_us_details(details)
data['terms'][-1]['state_rank'] = details[5]
data['terms'][-1]['class'] = details[6]
data['terms'][-1]['url'] = details[7]
data['terms'][-1]['phone'] = details[8]
return data | d1a12b12d48d1b05e0be343eaf0c4eb3a1d295bf | 3,614,837 |
import array
def normalize(y: ndarray, max_value: float) -> ndarray:
"""
Performs normalization of given values
:param y: ndarray - numpy array of histogram values derived from TCSPC method
:param max_value: float - maximal value in given data
:return: ndarray - numpy array of normalized histogram... | d70ee12a6aefc49d53da265ab1d0cc120e392cec | 3,614,838 |
import logging
import pickle
import time
def load_obj(path):
"""
return the python object saved in the given path
:param path: the path to be loaded
:return:
"""
logger = logging.getLogger("load_obj")
retry_count = 3
while retry_count > 0:
try:
with open(path, 'rb'... | d486846bdf284366a89a48e7d7ad0f86239b9f83 | 3,614,839 |
def xgboost_data_preparation(validation_list: list, dataframe: pd.DataFrame, target: np.array, key: str):
""" xgboost data preparing for training
The function transforms the data from a Pandas dataframe format to a xgboost-compatible format.
:param list validation_list: The list that contains the data the... | 8e88c4dc146e5a8e97ac8464411004115de3b80c | 3,614,840 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.