content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_bounded_progress():
"""
returns progress as a tensor between 0 and 1
"""
assert get_default_counter().expected_count is not None
return get_default_counter()._bounded_progress | 77,400 |
def get_bucket_website(Bucket=None):
"""
Returns the website configuration for a bucket. To host website on Amazon S3, you can configure a bucket as website by adding a website configuration. For more information about hosting websites, see Hosting Websites on Amazon S3 .
This GET operation requires the S3:... | 77,401 |
def polygon_clip(rp, cp, r0, c0, r1, c1):
"""Clip a polygon to the given bounding box.
Parameters
----------
rp, cp : (N,) ndarray of double
Row and column coordinates of the polygon.
(r0, c0), (r1, c1) : double
Top-left and bottom-right coordinates of the bounding box.
Returns... | 77,402 |
def _is_start_piece_sp(piece):
"""Check if the current word piece is the starting piece (sentence piece)."""
special_pieces = set(list('!"#$%&\"()*+,-./:;?@[\\]^_`{|}~'))
special_pieces.add(u"€".encode("utf-8"))
special_pieces.add(u"£".encode("utf-8"))
# Note(mingdachen):
# For foreign characters, we always... | 77,403 |
def atrpips(data, length):
"""Average True Range indicator in pips
Arguments:
data {list} -- List of ohlc data [open, high, low, close]
length {int} -- Lookback period for atr indicator
Returns:
list -- ATR (in pips) of given ohlc data
"""
atr_pips = []
avtr = atr(data,... | 77,404 |
def start_day(start):
"""Return TMIN, TAVG, TMAX."""
start_day = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start).group_by(Measurement.date).all()
start_day_list = list(start_day)
return jsonify(start_da... | 77,405 |
def ensure_folder(path):
"""Makes sure folder exists.
Args:
path (str): Full path.
"""
Path(path).mkdir(parents=True, exist_ok=True) | 77,406 |
def test_add_vertex_data_bad_args():
"""
add_vertex_data() with various bad args, checks that proper exceptions are
raised.
"""
from cugraph.experimental import PropertyGraph
merchants = dataset1["merchants"]
merchants_df = cudf.DataFrame(columns=merchants[0],
... | 77,407 |
def x86_jns(ctx, i):
"""jump if not sign"""
conditional_jump(ctx, i, conditional.NS) | 77,408 |
def ungroup(items):
"""Inverse of group."""
for g in items:
for v in g:
yield v | 77,409 |
def R123(a,b,c, degrees=False):
"""Returns a rotation matrix based on: Z*Y*X"""
if degrees:
a *= deg2rad
b *= deg2rad
c *= deg2rad
s3 = np.sin(c); c3 = np.cos(c)
s2 = np.sin(b); c2 = np.cos(b)
s1 = np.sin(a); c1 = np.cos(a)
return np.array(
[
[c1*c2,... | 77,410 |
def get_next(
base: datetime,
interval: Interval,
frequency: int,
at_time: Optional[time] = None,
days: Optional[list[int]] = None,
) -> Union[datetime, date]:
"""Get the next due date, starting from the given base."""
logger.info(
f"Getting next due date with base {base}, interval {... | 77,411 |
def guess_font_size(
size: tuple[int, int], font_name: str
) -> tuple[Union[ImageFont, FreeTypeFont], int]:
"""Try and figure out the correct font size for a given height and font.
Args:
``size``: The dimensions of the image in pixels.
``font_name``: The name of the font we're using.
R... | 77,412 |
def create_model(
time_set=None,
time_units=pyo.units.s,
nfe=5,
tee=False,
calc_integ=True,
):
"""Create a test model and solver
Args:
time_set (list): The beginning and end point of the time domain
time_units (Pyomo Unit object): Units of time domain
nfe (int): Numb... | 77,413 |
def read_table(h5file, path, start=None, stop=None, step=None, condition=None) -> Table:
"""Read a table from an HDF5 file
This reads a table written in the ctapipe format table as an `astropy.table.Table`
object, inversing the column transformations units.
This uses the same conventions as the `~ctap... | 77,414 |
def get_valid_ref(ref: Any) -> str:
"""Checks flow reference input for validity
:param ref: Flow reference to be checked
:return: Valid flow reference, either 't' or 's'
"""
if ref is None:
ref = 't'
else:
if not isinstance(ref, str):
raise TypeError("Error setting ... | 77,415 |
def k_argmin(l, k, func):
"""
Gets the indices and values of the k-smallest function results
from func.
"""
l_map = map(func, l)
return k_min(l_map, k) | 77,416 |
def create_zip_task(
result: dict = None,
task_uid: str = None,
data_provider_task_record_uid: List[str] = None,
data_provider_task_record_uids: List[str] = None,
run_zip_file_uid=None,
*args,
**kwargs,
):
"""
:param result: The celery task result value, it should be a dict with the ... | 77,417 |
def add_ports_from_markers_square(
component: Component,
pin_layer: LayerSpec = "DEVREC",
port_layer: Optional[LayerSpec] = None,
orientation: Optional[int] = 90,
min_pin_area_um2: float = 0,
max_pin_area_um2: float = 150 * 150,
pin_extra_width: float = 0.0,
port_names: Optional[Tuple[st... | 77,418 |
def register_with_elbs(instance_id, elb_names):
"""
Registers instance_id with each load balancer (classic type) listed in
collection elb_names.
"""
print(yellow("Registering {} with classic ELBs {}.".format(
instance_id, elb_names)))
for elb in elb_names:
client('elb').register_... | 77,419 |
def calc_periodicity(peak_info, period_min=5, period_max=15):
"""
calculate the period
:param peak_info:
:param period_min:
:param period_max:
:return:
"""
num_peaks = peak_info.shape[0]
# calculate periodicity
peak_info[:num_peaks-1, 2] = np.diff(peak_info[:, 0])
peak_info =... | 77,420 |
def calculate_tetra():
""" Calculate tetranucleotide frequencies for each input sequence, and
their Pearson correlation, as described in Teeling et al. (2004a)
Env. Micro. 6 938-947 doi:10.1111/j.1462-2920.2004.00624.x;
Teeling et al. (2004b) BMC Bioinf. 5 163 doi:10.1186/1471-2105-5-163;
... | 77,421 |
def create_global_resource(group: str, version: str, kind: str, plural: str, verbs=None) \
-> Type[GenericGlobalResource]:
"""Create a new class representing a global resource with the provided specifications.
**Parameters**
* **group** `str` - API group of the resource. Example `stable.example.co... | 77,422 |
def logtransform_feature(metadata, column):
"""Apply a logarithm transformation to the column within
metadata with; to avoid NaN, the applied operation is f:x->log(1+x)
Parameters
----------
metadata: pd.DataFrame
Metadata
column: object
string designing the name of the column t... | 77,423 |
def outline_to_implementation(
name: str,
design: str,
outline: fiat.Outline) -> Dict[Hashable, Any]:
"""[summary]
Args:
name (str): [description]
design (str): [description]
outline (fiat.Outline): [description]
Returns:
Dict[Hashable, Any]: [description]
... | 77,424 |
def contextualize(argv):
""" Generate context features
Generate two context features SentenceBefore[XYZ] and SentenceAfter[XYZ] for
each feature XYZ in the given set.
"""
parser = AutoHelpArgumentParser(prog='contextualize')
parser.add_argument('-f', dest='fields', metavar='LIST',
... | 77,425 |
def match(pattern, name):
"""Test whether a name matches a wildcard pattern.
Arguments:
pattern (str): A wildcard pattern, e.g. ``"*.py"``.
name (bool): A filename.
Returns:
bool: `True` if the filename matches the pattern.
"""
try:
re_pat = _PATTERN_CACHE[(pattern... | 77,426 |
def _OldEnough(try_bot_cache, bot_id):
"""Checks if the build in the given bot's cache is older than threshold."""
built_cp = try_bot_cache.full_build_commit_positions[bot_id]
tot_cp = git.GetCommitPositionFromRevision('HEAD')
return built_cp < tot_cp - STALE_CACHE_AGE | 77,427 |
def the_joke():
"""
Combining both joke and emojis into one function.
"""
return yomama() + laugh() | 77,428 |
def return_dict():
"""
"interfaces": {
"Tunnel0": {
"state": "UP"
},
"Tunnel1": {
"state": "DOWN"
}
}
}
"""
return {"interfaces": {"Tunnel0": {"state": "UP"}, "Tunnel1": {"state": "DOWN"}}} | 77,429 |
def allocation_with_lowest_gain(agents: List[Agent], allocations: List[CakeAllocation]) -> CakeAllocation:
"""
Finds an allocation such that for all agents, gain(agent) (as defined by `get_agent_gain`) in that
allocation scope is less than the sum of gain(agent) for all other allocation scopes.
:param a... | 77,430 |
def train_model(network, train_set, val_set, output_dir, tb_dir,
model_name="default",
max_iters=100000):
""" Entry of training model
Params
------
`network`: network for training, it should inherit DenseNet class
`train_set`: a string, specify the tr... | 77,431 |
def replace_magnitude(x, mag):
"""
Extract the phase from x and apply it on mag
x [B,2,F,T] : A tensor, where [:,0,:,:] is real and [:,1,:,:] is imaginary
mag [B,1,F,T] : A tensor containing the absolute magnitude.
"""
phase = torch.atan2(x[:, 1:], x[:, :1]) # imag, real
return torch.cat([... | 77,432 |
def is_ip_address(host: str) -> bool:
"""Determine if host is an IP Address."""
try:
ip_address(host)
except ValueError:
return False
return True | 77,433 |
def cut_rod2(p, n, r={}):
"""Cut rod.
Same functionality as the original but implemented
as a top-down with memoization.
"""
q = r.get(n, None)
if q:
return q
else:
if n == 0:
return 0
else:
q = 0
for i in range(n):
... | 77,434 |
def RunLoad(redis_vm, load_vm, threads, port, test_id):
"""Spawn a memteir_benchmark on the load_vm against the redis_vm:port.
Args:
redis_vm: The target of the memtier_benchmark
load_vm: The vm that will run the memtier_benchmark.
threads: The number of threads to run in this memtier_benchmark process... | 77,435 |
def choose_vnc_display():
"""Try to choose a free vnc display.
"""
def netstat_local_ports():
"""Run netstat to get a list of the local ports in use.
"""
l = os.popen("netstat -nat").readlines()
r = []
# Skip 2 lines of header.
for x in l[2:]:
# Lo... | 77,436 |
def change_last_activation_to_linear(model: Model, dependencies=None) -> Model:
"""
Changes last activation function to linear, if it already is linear - returns same model
:param dependencies: necessary objects for custom functions in keras
:param model: Keras model
:return: Keras model with linear... | 77,437 |
def test_tensorboard_tsne_with_output_directory(tmp_path: pathlib.Path) -> None:
"""Tests writing TensorBoard files using the t-SNE projection method, varying case deliberately."""
_call_wth_features_and_output_path(tmp_path, ["-m", "tensorBoard", "-p", "t-SNe"])
_assert_tensorboard_files_exist(tmp_path) | 77,438 |
def add_afsc_links(full_afsc_dict, reddit):
"""
Add links to /r/AirForce wiki from given filename into the dictionary.
:param dict: either enlisted_dict or officer_dict
:param reddit: PRAW reddit object
"""
# gets dict of AFSC to link on /r/AirForce wiki
wiki_page = reddit.subreddit("AirForc... | 77,439 |
def import_data():
"""
Export data via CRUD controller.
Old - being replaced by Sync.
"""
title = T("Import Data")
return dict(title=title) | 77,440 |
def generate_code_point_set(cpp, public_name, set):
"""Generates a sparse set of code points. Every entry in the array encodes a range
of code points that are included in that set. Both ends are inclusive."""
private_name = public_name + "_"
ranges = []
current = None
expected = None
for c... | 77,441 |
def _set_karma(bot, trigger, change, reset=False):
"""Helper function for increasing/decreasing/resetting user karma."""
channel = trigger.sender
user = trigger.group(2).split()[0]
if reset:
bot.db.set_nick_value(user, 'karma', 0)
return
karma = bot.db.get_nick_value(user, ... | 77,442 |
def read_kazr(filename, field_names=None, additional_metadata=None,
file_field_names=False, exclude_fields=None):
"""
Read K-band ARM Zenith Radar (KAZR) NetCDF ingest data.
Parameters
----------
filename : str
Name of NetCDF file to read data from.
field_names : dict, opt... | 77,443 |
def addScriptOptions(parser, pos_args, kw_args):
""" add script-specific script options """
script_options_group = parser.add_argument_group('Options')
hlpstr = "Prefix string for output filenames. Can optionally include a " \
"full path. Defaults to the input filename."
... | 77,444 |
def get_dag(node):
"""
:param str node:
:return: Maya dag path node
:rtype: OpenMaya.MDagPath
"""
sel = OpenMaya.MSelectionList()
sel.add(node)
return sel.getDagPath(0) | 77,445 |
def aistats2022():
"""Font size for AISTATS 2022."""
return _from_base(base=10) | 77,446 |
def format_filt( something ):
"""
Example of a filter that can be used within
the Jinja2 code
"""
return "Not what you asked for" | 77,447 |
def download_latest(dest_folder):
"""
Download the latest Meta-Review dump into a folder.
:param dest_folder: Path to destination folder on local disk.
"""
logging.info("Connecting to Amazon S3")
# Connect to S3
s3 = boto3.resource("s3")
# Select the bucket containing dumps of the Tru... | 77,448 |
async def test_401_refresh_token_success(
aresponses, v2_server, v2_subscriptions_response
):
"""Test that a successful refresh token carries out the original request."""
async with v2_server:
v2_server.add(
"api.simplisafe.com",
f"/v1/users/{TEST_USER_ID}/subscriptions",
... | 77,449 |
def scatter_2D(ax, x, y, color, clf=None, x_label="X", y_label="Y", title="2D Scatter"):
"""
:param x:
:param y:
:param color:
:param clf: If given, a mesh will be plotted showing the decision boundaries.
:return:
"""
if clf is not None:
x_range = x.max() - x.min()
y_ran... | 77,450 |
def conv_upample(conv, x, occupy, real_num, out_coords, out_occupy, out_stride=1, mul_occupy_after=True):
"""
Add occupancy value for sparse convolution that decreases the stride for input data
"""
if occupy.ndim < 2:
occupy = occupy.unsqueeze(1)
if conv.kernel.ndim < 3:
conv.kerne... | 77,451 |
def get_field_node(field_config: dict, config: dict, source=None) -> object:
"""
get field node.
"""
required = field_config.get(FIELD_REQUIRED, False)
field_type, field_attrs = tuple(field_config[FIELD_TYPE].items())[0][0], tuple(
field_config[FIELD_TYPE].items())[0][1]
if field_type ==... | 77,452 |
def subcycles() -> Parser:
"""Return a parser to parse the <subcycles> tag.
:return:
A parser that consumes the <subcycles> tag and produces an
:class:`rads.config.ast.Assignment` AST node which assigns to
"subcycles" a :class:`rads.config.tree.SubCycles` dataclass.
:raises rads.co... | 77,453 |
def container_for_context(username: str, labbook: Optional[LabBook] = None, path: Optional[str] = None,
override_image_name: Optional[str] = None) -> ContainerOperations:
"""Instantiate an instance that can build images and run containers via Docker.
Context is obtained via the standa... | 77,454 |
def suggest(term):
"""
Find most appropriate EFO term for arbitrary string
Arg:
* string
Returntype: string (EFO ID)
"""
server = 'http://www.ebi.ac.uk/spot/zooma/v2/api'
url_term = re.sub(" ", "%20", re.sub("[%&]", "", term))
ext = "/services/annotate?propertyValue=%s&filter=required:[none],ontologies:[... | 77,455 |
def test_update_uncombined_name():
"""Unit testing for heudiconv.convert.update_uncombined_name(), which updates
filenames with the ch field if appropriate.
"""
# Standard name update
base_fn = 'sub-X_ses-Y_task-Z_run-01_bold'
metadata = {'CoilString': 'H1'}
channel_names = ['H1', 'H2', 'H3'... | 77,456 |
def plot_matplotlib_dgt(func, **kwargs):
"""
Plot scalar discontinuous Galerkin Trace functions in 2D
"""
# Get information about the underlying function space
function_space = func.function_space()
family = func.ufl_element().family()
mesh = function_space.mesh()
ndim = mesh.geometry().... | 77,457 |
def mapi_async(mapper: Callable[[TSource, int], Awaitable[TResult]]) -> Projection[TSource, TResult]:
"""Map with index async.
Returns an observable sequence whose elements are the result of
invoking the async mapper function by incorporating the element's
index on each element of the source.
"""
... | 77,458 |
def descriptors_to_file(config_filepath: str, descriptors: kapture.Descriptors) -> None:
"""
Writes descriptors to CSV file.
:param config_filepath:
:param descriptors:
"""
return image_feature_to_file(config_filepath, descriptors) | 77,459 |
def printarr(arr):
"""
print the array
:param arr:
:return:
"""
print("\n".join(arr)) | 77,460 |
def parseEdmSize(lines):
"""
Returns a list of dictionaries
Example of data:
>>> parseEdmSize(lines = ( 'File MINBIAS__RAW2DIGI,RECO.root Events 8000', 'TrackingRecHitsOwned_generalTracks__RECO. 407639 18448.4', 'recoPreshowerClusterShapes_multi5x5PreshowerClusterShape_multi5x5PreshowerXClustersShape_RECO. 289.787... | 77,461 |
def get_activation_function(label: str) -> ActivationFunction:
"""Get activation function by label
:param label: string denoting function
:return: callable function
"""
if label == 'lin':
return Linear()
if label == 'sigmoid':
return Sigmoid()
if label == 'tanh':
ret... | 77,462 |
def Detector_List(scanIOC):
"""
Define the detector used for:
keithley_live_strseq()
Detector_Triggers_StrSeq()
BeforeScan_StrSeq() => puts everybody in passive
CA_Average()
WARNING: can't have more than 5 otherwise keithley_live_strseq gets angry.
"""
BL_mode=BL_Mod... | 77,463 |
def _instance_accuracy(label, raw_pred, compare_func, return_float=True, feed_dict=None, args=None):
"""get instance-wise accuracy for structured prediction task instead of pointwise task"""
# disctretize output predictions
if not args.task_is_sudoku:
pred = as_tensor(raw_pred)
pred = (pred ... | 77,464 |
def get_stressors(lat,lon):
"""
Example for looking up stressors at a particular location.
"""
# Note df is a flattened list of lat/lon values that only includes those over land
df = pvcz.get_pvcz_data()
# Point of interest specified by lat/lon coordinates.
lat_poi = float(lat)
lon_po... | 77,465 |
def load_and_prepare_image(filename, img_shape=224, rescale=True):
"""
Preparing an image for image prediction task.
Reads and reshapes the tensor into needed shape (img_shape, img_shape, 3).
Image tensor is rescaled.
:param filename (str): full-path filename of the image
:param img_shape (int):... | 77,466 |
def reset_deployments(AmznClientToken=None, Force=None, GroupId=None):
"""
Resets a group\'s deployments.
See also: AWS API Documentation
Exceptions
:example: response = client.reset_deployments(
AmznClientToken='string',
Force=True|False,
GroupId='string'
)
... | 77,467 |
async def stop_pull(ctx, tutor):
"""removes the reaction message sent by a tutor.
display 'message not found' error message:
if tutor does not have a reaction message circulating the queue.
Parameters
----------
:param Context ctx: the current Context.
:param 'Worker' tutor: the object... | 77,468 |
def jacobi_recr_coeffs(n, alpha, beta):
"""calculate the coefficients used in recursion relationship
Args:
n: the targeting order
alpha: the alpha coefficient of Jacobi polynomial
beta: the veta coefficient of Jacobi polynomial
Returns:
a1, a2, a3, a4: the coefficients used... | 77,469 |
def get_key(window, key):
"""
Returns the last reported state of a keyboard key for the specified
window.
Wrapper for:
int glfwGetKey(GLFWwindow* window, int key);
"""
return _glfw.glfwGetKey(window, key) | 77,470 |
def setup_database() -> tp.Generator[tp.Any,tp.Any,tp.Any]:
""" Fixture to set up PydupeDB in tmporary Directory"""
with tempfile.TemporaryDirectory() as newpath:
old_cwd = os.getcwd()
os.chdir(newpath)
cwd = pl.Path.cwd()
dbname = pl.Path(newpath) / ".pydupe.sqlite"
file... | 77,471 |
def gaussian_mlp_policy_tf_ppo_benchmarks():
"""Run benchmarking experiments for Gaussian MLP Policy on TF-PPO."""
iterate_experiments(gaussian_mlp_policy, MuJoCo1M_ENV_SET, seeds=_seeds) | 77,472 |
def service_unavailable(request,template_name='503.html'):
"""
Default service unavailable view
"""
return TemplateResponse(request,template_name,status=503) | 77,473 |
def utcnow_str():
""" Return a new datetime string representing UTC day and time. """
return time2str(datetime.datetime.utcnow()) | 77,474 |
def set_backend_session():
"""
Configure Keras TensorFlow backend to allocate GPU memory efficiently in shared environments.
"""
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.compat.v1.Session(config=config)
tf.compat.v1.keras.backend.set_session(sess) | 77,475 |
def test_partial_write_lsts_non_reg(ds_from_uvfits, test_outfile):
"""Test partial writing along lst axis with non regular spacing."""
np.random.seed(0)
ds = ds_from_uvfits
ds.delay_transform()
ds.initialize_save_file(test_outfile)
lsts = ds.lst_array.flatten()
np.random.shuffle(lsts)
as... | 77,476 |
def client_test_invoke_action(servient, protocol_client_cls, timeout=None):
"""Helper function to test Action invocations on bindings clients."""
exposed_thing = next(servient.exposed_things)
action_name = uuid.uuid4().hex
@tornado.gen.coroutine
def action_handler(parameters):
input_value... | 77,477 |
def accuracy(output, target, topk=(1,)):
"""
Computes the precision@k for the specified values of k
Parameters
----------
output : pytorch tensor
output, e.g., predicted value
target : pytorch tensor
label
topk : tuple
specify top1 and top5
Returns
-------
... | 77,478 |
def compute_divide(z, w):
"""
Compute `z` divided by `w`.
:param z: MathsComplexNumber object to be divided.
:param w: MathsComplexNumber object to divide by.
:return: MathsComplexNumber object of `z` divided by `w`.
"""
# z = a + bj
# w = c + dj
a, b = z.re, z.im
c, d = w.re,... | 77,479 |
def _build_deeplab(inputs_queue, outputs_to_num_classes, ignore_label):
"""Builds a clone of DeepLab.
Args:
inputs_queue: A prefetch queue for images and labels.
outputs_to_num_classes: A map from output type to the number of classes.
For example, for the task of semantic segmentation with 21 semanti... | 77,480 |
def clean_up():
"""Clean up the cache.
Finish introspection for timed out nodes.
:return: list of timed out node UUID's
"""
timeout = CONF.timeout
if timeout <= 0:
return []
threshold = timeutils.utcnow() - datetime.timedelta(seconds=timeout)
uuids = [row.uuid for row in
... | 77,481 |
def create_triggers_sql(*, audit_logged_model: Type[Model]) -> Sequence[str]:
"""
Create the SQL requried to set up triggers for audit logging to the given
audit log entry model.
"""
# Get the model that we are audit logging
audit_logged_table = audit_logged_model._meta.db_table # noqa
tri... | 77,482 |
def _get_neighbors(loc, image, voxels, thresh, dist_params):
"""Find all the neighbors above a threshold near a voxel."""
neighbors = set()
for axis in range(len(loc)):
for i in (-1, 1):
next_loc = np.array(loc)
next_loc[axis] += i
if thresh is not None:
... | 77,483 |
def is_partition(set_of_sets, alphabet):
"""
Determine whether `set_of_sets` partitions `alphabet`; that is,
is every element of `alphabet` represented exactly once in `set_of_sets`?
Parameters
----------
set_of_sets : a (frozen)set of (frozen)sets
The potential partition.
alphabet ... | 77,484 |
def OMO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2020-06-08", **kwargs
) -> Graph:
"""Ret... | 77,485 |
def AddIgnoreFileFlag(parser, hidden=False):
"""Add --ignore-file flag."""
parser.add_argument(
'--ignore-file',
hidden=hidden,
help='Override the `.gcloudignore` file and use the specified file '
'instead. See `gcloud topic gcloudignore` for more information.') | 77,486 |
def _render_dimensional_metric_cell(row_data: pd.Series, metric: Metric):
"""
Renders a table cell in a metric column for pivoted tables where there are two or more dimensions. This function
is recursive to traverse multi-dimensional indices.
:param row_data:
A series containing the value for t... | 77,487 |
def pca_init_dense(model, mu_dense_layer_name, undense_layer_name, generator,
input_len=None,
do_vae=True,
logvar_dense_layer_name=None,
nb_samples=None,
tqdm=tqdm,
vis=False):
"""
initialize the (V... | 77,488 |
def allocationsCount(memory):
"""Return the total number of allocations.
"""
return np.count_nonzero(memory['allocations'] > 0) | 77,489 |
def _histoprint_csv(infile, **kwargs):
"""Interpret file as as CSV file."""
import pandas as pd
# Read the data
data = pd.read_csv(infile)
cut = kwargs.pop("cut", "")
if cut is not None and len(cut) > 0:
try:
data = data[data.eval(cut)]
except Exception as e:
... | 77,490 |
def test_export_mt_report(mock_app, case_obj):
"""Test the CLI command that exports the MT variants"""
runner = mock_app.test_cli_runner()
assert runner
# Thy the CLI without parameters
result = runner.invoke(cli, ['export', 'mt_report'])
# it should return error
assert 'Missing option "-... | 77,491 |
def file_docker_pull_latest():
"""#! /usr/bin/env bash
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source ${SCRIPT_DIR}/docker-environment-vars.sh
echo "${SENZING_HORIZONTAL_RULE}"
echo "${SENZING_HORIZONTAL_RULE:0:2} Pull ${SENZING_PROJECT_NAME} docker containers for DockerHub.... | 77,492 |
def load_data(path=None):
"""Downloads the Mendeley dataset to local storage, if not already downloaded. This will generate 2 csv files (train and test), which contain all the path
information.
Args:
path (str, optional): The path to store the Mendeley data. Defaults to None, will save at `temp... | 77,493 |
def _get_annotation_type(annotation) -> AnnotationType:
"""
Returns the type of a given annotation.
Annotation can be a BinaryBuffer, TypedBuffer or something else
"""
if isinstance(annotation, list):
if len(annotation) == 2:
return AnnotationType.BINARY_BUFFER
elif len... | 77,494 |
def is_obvious_builtin(node, value):
# type: (ast.expr, Any) -> bool
"""
Return True if this node looks like a builtin and it really is
(i.e. hasn't been shadowed).
"""
return ((isinstance(node, ast.Name) and
node.id in builtins_dict and
builtins_dict[node.id] is value)... | 77,495 |
def extract_problems(cfg, login_reply, filename='kattis'):
""" Stores solved prolbems and stats in .json file """
data = {}
solved = []
header_url = get_url(cfg, '', 'problems')
try:
result = submissions(header_url, login_reply.cookies)
except requests.exceptions.RequestException as err:... | 77,496 |
def write_book(xl_json, wb_name):
""" """
wb_path = Path(wb_name)
if wb_path.exists():
wb = load_workbook(wb_name)
else:
wb = Workbook()
wb.remove(wb.active)
ws = wb.create_sheet(xl_json['worksheet name'])
print(f"Writing {xl_json['worksheet name']}...")
# Write... | 77,497 |
def insert_records(conta, data):
"""
Recebe o objeto e inseri a data no banco de dados. A data são os logs de exibições recebidos do manager.
param: conta : Account:
data: list of dicts:
return: records: int: Quantidade de registros inseridos
"""
records = 0
i = len(data) - 1
... | 77,498 |
def sample_2d_no_compete(alternatives, choosers, sample_size, capacities=None):
"""
Samples alternatives in a manner that guarantees that capacities will
be respected: the maximum # of times a given alternative can appear
in the sample (across choosers) is equal to its capacity.
Use this for the la... | 77,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.