content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getRandomChests(numChests):
"""Return a list of (x, y) integer tuples that represent treasure
chest locations."""
chests = []
while len(chests) < numChests:
newChest = [random.randint(0, BOARD_WIDTH - 1),
random.randint(0, BOARD_HEIGHT - 1)]
# Make sure a chest is... | 46,300 |
def random_tolerance(value, tolerance):
"""Generate a value within a small tolerance.
Credit: /u/LightShadow on Reddit.
Example::
>>> time.sleep(random_tolerance(1.0, 0.01))
>>> a = random_tolerance(4.0, 0.25)
>>> assert 3.0 <= a <= 5.0
True
"""
value = float(value)... | 46,301 |
def importExportCookie(session, event, stdin_fd, predetermined_input):
"""
Parameters
----------
session : ikabot.web.session.Session
event : multiprocessing.Event
stdin_fd: int
predetermined_input : multiprocessing.managers.SyncManager.list
"""
sys.stdin = os.fdopen(stdin_fd)
co... | 46,302 |
def routes_stations():
"""The counts of stations of routes."""
return jsonify(
[
(n.removeprefix("_"), int(c))
for n, c in r.zrange(
"Stats:Route.stations", 0, 14, desc=True, withscores=True
)
]
) | 46,303 |
def montage(packed_ims, axis):
"""display as an Image the contents of packed_ims in a square gird along an aribitray axis"""
if packed_ims.ndim == 2:
return packed_ims
# bring axis to the front
packed_ims = np.rollaxis(packed_ims, axis)
N = len(packed_ims)
n_tile = math.ceil(math.sqrt(... | 46,304 |
def blocks2image(Blocks, blocks_image):
""" Function to stitch the blocks back to the original image
input: Blocks --> the list of blocks (2d numpies)
blocks_image --> numpy 2d array with numbers corresponding to block number
output: image --> stitched image """
image = np.zeros(np.shape(blocks_im... | 46,305 |
def box_mesh(x_extent: float, y_extent: float, z_extent: float) -> Mesh:
"""create a box mesh"""
# wrapper around trimesh interface
# TODO: my own implementation of this would be nice
box = trimesh.primitives.Box(extents=(x_extent, y_extent, z_extent)).to_mesh()
return box.vertices, box.faces | 46,306 |
def create_bucket(storage_client, bucket_name, parsed_args):
"""Creates the test bucket.
Also sets up lots of different bucket settings to make sure they can be moved.
Args:
storage_client: The storage client object used to access GCS
bucket_name: The name of the bucket to create
p... | 46,307 |
def learn_parameters(df_path: str, pas: Dict[str, List[str]]) -> \
Tuple[Dict[str, List[str]], nx.DiGraph, Dict[str, List[float]]]:
"""
Gets the parameters.
:param df_path: CSV file.
:param pas: Parent-child relationships (structure).
:return: Tuple; first item is dictionary of domains; sec... | 46,308 |
def extract_urls_n_email(src, all_files, strings):
"""IPA URL and Email Extraction."""
try:
logger.info('Starting IPA URL and Email Extraction')
email_n_file = []
url_n_file = []
url_list = []
domains = {}
all_files.append({'data': strings, 'name': 'IPA Strings Du... | 46,309 |
def find_scan_info(filename, position = '__P', scan = '__S', date = '____'):
"""
Find laser position and scan number by looking at the file name
"""
try:
file = filename.split(position, 2)
file = file[1].split(scan, 2)
laser_position = file[0]
file = file[1].... | 46,310 |
def run_svm():
"""
This function models the SVM classifier and evaluates the performance using the test data.
:return: Nothing. It only prints the accuracy in the end.
:rtype: None
"""
# seed_everything()
clf = svm.SVC(kernel='linear', C=10)
training_data = pd.read_csv(constants.TRAI... | 46,311 |
def arglast(arr, convert=True, check=True):
"""Return the index of the last true element of the given array.
"""
if convert:
arr = np.asarray(arr).astype(bool)
if np.ndim(arr) != 1:
raise ValueError("`arglast` not yet supported for ND != 1 arrays!")
sel = arr.size - 1
sel = sel -... | 46,312 |
def number_formatter(number, pos=None):
"""Convert a number into a human readable format."""
magnitude = 0
while abs(number) >= 100:
magnitude += 1
number /= 100.0
return '%.1f%s' % (number, ['', '', '', '', '', ''][magnitude]) | 46,313 |
def init(module=pygame):
"""Initialize the given module."""
if module != pygame:
module.init()
return
# Main pygame init
if not pygame.display.get_init():
pygame.display.init() # Pygame events require the display module
pygame.joystick.init()
# if not gui_runni... | 46,314 |
def simcore_tree(cookies, tmpdir):
"""
bakes cookie, moves it into a osparc-simcore tree structure with
all the stub in place
"""
result = cookies.bake(
extra_context={"project_slug": PROJECT_SLUG, "github_username": "pcrespov"}
)
workdir = Path(result.project).resolve()
... | 46,315 |
def calc_density(temp, pressure, gas_constant):
"""
Calculate density via gas equation.
Parameters
----------
temp : array_like
temperatur in K
pressure : array_like
(partial) pressure in Pa
gas_constant: array_like
specicif gas constant in m^2/(s^2*K)
Returns
... | 46,316 |
def __parse_ws_data(content, latitude=52.091579, longitude=5.119734):
"""Parse the buienradar xml and rain data."""
log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude)
result = {SUCCESS: False, MESSAGE: None, DATA: None}
# convert the xml data into a dictionary:
try:
... | 46,317 |
def test_ZMQCommSendThreads_4(is_blocking, raise_exception, delay_between_reads, encryption_enabled):
"""
ZMQCommSendThreads: Timeout at the server.
"""
public_key, _, server_kwargs = _gen_server_keys(encryption_enabled=encryption_enabled)
thread = threading.Thread(target=_zmq_server_delay2, kwargs... | 46,318 |
def trackCtx(*args, **kwargs):
"""
This command can be used to create a track context.
Flags:
- alternateContext : ac (bool) [create,query]
Set the ALT+MMB and ALT+SHIFT+MMB to refer to this context.
- exists : ex (bool) [create]
... | 46,319 |
def load_post_data(model, metadata): # NOQA: C901
"""Fully load metadata and contents into objects (including m2m relations)
:param model: Model class, any polymorphic sub-class of
django_docutils.rst_post.models.RSTPost
:type model: :class:`django:django.db.models.Model`
:param metadata:
... | 46,320 |
def address(addr, label=None):
"""Discover the proper class and return instance for a given Oscillate address.
:param addr: the address as a string-like object
:param label: a label for the address (defaults to `None`)
:rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress`
"""... | 46,321 |
def retrieve_molecule_number(pdb, resname):
"""
IDENTIFICATION OF MOLECULE NUMBER BASED
ON THE TER'S
"""
count = 0
with open(pdb, 'r') as x:
lines = x.readlines()
for i in lines:
if i.split()[0] == 'TER': count += 1
if i.split()[3] == resname:
... | 46,322 |
def insert_unjudged_data_for_group(db_conn, job_id, group_id, data):
"""
Insert group data into the DB.
This function goes through an iterable of dicts row-by-row adding each query, domain, and
result set to the DB. It first upserts queries into `arcs_query` table, and from that
operation a unique ... | 46,323 |
def aggregate_division_return(model_0, model_m, num_device):
"""
Return total delta weight to center device
:param the temp model (device 0) which just stored all the clients' weights
:param master model to aggregate all the results from device 0
:param number of devices which is divisor
"""
... | 46,324 |
def _windows_write_string(s, out, skip_errors=True):
""" Returns True if the string was written using special methods,
False if it has yet to be written out."""
# Adapted from http://stackoverflow.com/a/3259271/35070
import ctypes
import ctypes.wintypes
WIN_OUTPUT_IDS = {
1: -11,
... | 46,325 |
def in_relative_frame(
pos_abs: np.ndarray,
rotation_matrix: np.ndarray,
translation: Point3D,
) -> np.ndarray:
"""
Inverse transform of `in_absolute_frame`.
"""
pos_relative = pos_abs + translation
pos_relative = pos_relative @ rotation_matrix
return pos_relative | 46,326 |
def check_url_namespace(app_configs=None, **kwargs):
"""Check NENS_AUTH_URL_NAMESPACE ends with a semicolon"""
namespace = settings.NENS_AUTH_URL_NAMESPACE
if not isinstance(namespace, str):
return [Error("The setting NENS_AUTH_URL_NAMESPACE should be a string")]
if namespace != "" and not names... | 46,327 |
def get_exif_data(fn):
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
exif_data = {}
i = Image.open(fn)
info = i._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for t in value:
... | 46,328 |
def _create_bz2_from_files(archive, files, target_directory):
"""Take a list of file names and add them `archive`.
Example:
_create_bz2_from_files('pictures.tar.bz2',
['pic1.png.gpg', 'pic2.png.gpg'])
Params:
archive - name of the archive to be created
... | 46,329 |
def get_circuitpython_version(device_path):
"""
Returns the version number of CircuitPython running on the board connected
via ``device_path``. This is obtained from the ``boot_out.txt`` file on the
device, whose content will start with something like this::
Adafruit CircuitPython 4.1.0 on 2019... | 46,330 |
def onWriteProtectChanged(protected, doc):
""" Method called when the read only status of a document is changed """
pass | 46,331 |
def _setup_modules(module_cls, variable_reparameterizing_predicate,
module_reparameterizing_predicate, module_init_kwargs):
"""Return `module_cls` instances for reparameterization and for reference."""
# Module to be tested.
module_to_reparameterize = _init_module(module_cls, module_init_kwarg... | 46,332 |
def delete_session_infringement_invoice(session):
""" Infringement Penalty session ID """
if 'wc_infringement_invoice' in session:
del session['wc_infringement_invoice']
session.modified = True | 46,333 |
def external_compatible(request, id):
""" Increment view counter for a compatible view """
increment_hit_counter_task.delay(id, 'compatible_count')
return json_success_response() | 46,334 |
def lowpass_xr(da,cutoff,**kw):
"""
Like lowpass(), but ds is a data array with a time coordinate,
and cutoff is a timedelta64.
"""
data=da.values
time_secs=(da.time.values-da.time.values[0])/np.timedelta64(1,'s')
cutoff_secs=cutoff/np.timedelta64(1,'s')
axis=da.get_axis_num('time')
... | 46,335 |
def _calc_zonal_correlation(dat_tau, dat_pr, dat_tas, dat_lats, fig_config):
"""
Calculate zonal partial correlations for sliding windows.
Argument:
--------
dat_tau - data of global tau
dat_pr - precipitation
dat_tas - air temperature
dat_lats - latitude of the given mo... | 46,336 |
def is_unary(string):
"""
Return true if the string is a defined unary mathematical
operator function.
"""
return string in mathwords.UNARY_FUNCTIONS | 46,337 |
def set_snapshot(key, url):
"""Sets the snapshot for the given instance template revision.
Args:
key: ndb.Key for a models.InstanceTemplateRevision entity.
url: URL for the snapshot to use for instances created from this template.
"""
itr = key.get()
if not itr:
logging.warning('InstanceTemplateR... | 46,338 |
def GetBucketAndRemotePath(revision, builder_type=PERF_BUILDER,
target_arch='ia32', target_platform='chromium',
deps_patch_sha=None):
"""Returns the location where a build archive is expected to be.
Args:
revision: Revision string, e.g. a git commit hash or... | 46,339 |
def cutmix_padding(h, w):
"""Returns image mask for CutMix.
Taken from (https://github.com/google/edward2/blob/master/experimental
/marginalization_mixup/data_utils.py#L367)
Args:
h: image height.
w: image width.
"""
r_x = tf.random.uniform([], 0, w, tf.int32)
r_y = tf.random.uniform([], 0, h, tf... | 46,340 |
def run_cmd(cmd, logger):
"""
using os to run a command line
arg:
cmd: a command line
logger: handler of logging file
"""
try:
os.system(cmd)
except OSError as e:
logger.error("Runing command line '{}' fails: {}".format(cmd, e))
raise | 46,341 |
def compute_star_verts(n_points, out_radius, in_radius):
"""Vertices for a star. `n_points` controls the number of points;
`out_radius` controls distance from points to centre; `in_radius` controls
radius from "depressions" (the things between points) to centre."""
assert n_points >= 3
vertices = []... | 46,342 |
def iterLoad(dataFormat,path,corpusSizeCutoff=500):
"""
Iteratively load sections of a (presumably large) corpus. This will create a generator that provides kindred.Corpus objects that are subsets of the larger corpus. This should be used to lower the memory requirements (so that the entire file doesn't need to be lo... | 46,343 |
def test_session_log_append(device_slog, commands, expected_responses):
"""Verify session_log matches expected content, but when channel writes are also logged."""
session_file = expected_responses['session_log_append']
# Create a starting file
with open(session_file, "wb") as f:
f.write(b"Initi... | 46,344 |
def create_ordering_dict(iterable):
"""Example: converts ['None', 'ResFiles'] to {'None': 0, 'ResFiles': 1}"""
return dict([(a, b) for (b, a) in dict(enumerate(iterable)).iteritems()]) | 46,345 |
def sparse2tuple(mx):
"""Convert sparse matrix to tuple representation.
ref: https://github.com/tkipf/gcn/blob/master/gcn/utils.py
"""
if not sp.isspmatrix_coo(mx):
mx = mx.tocoo()
coords = np.vstack((mx.row, mx.col)).transpose()
values = mx.data
shape = mx.shape
return coords, values, shape | 46,346 |
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error) | 46,347 |
def correct_predicted(y_true, y_pred):
""" Compare the ground truth and predict labels,
Parameters
----------
y_true: an array like for the true labels
y_pred: an array like for the predicted labels
Returns
-------
correct_predicted_idx: a list of index of correct predicted
correct... | 46,348 |
def coord_image_to_trimesh(coord_img, validity_mask=None, batch_shape=None, image_dims=None, dev_str=None):
"""Create trimesh, with vertices and triangle indices, from co-ordinate image.
Parameters
----------
coord_img
Image of co-ordinates *[batch_shape,h,w,3]*
validity_mask
Boolea... | 46,349 |
def lambda_handler(event, context):
"""Lambda function which raises an exception and creates Custom tag &
context.
Args:
event (dict): Parameter to pass in event data to the handler.
context (bootstrap.LambdaContext): Parameter to provide runtime information to the handler.
"""
with... | 46,350 |
def test_trim():
"""Verify trim
"""
errfmt = r'Overflow in format %sQ%d\.%d\.'
for init, args, _, s, m, n, bits in initstr_gen():
x = uut.FixedPoint(init, *args)
xx = uut.FixedPoint(x)
# Fractional bit trimming
x.trim(fracs=True)
nose.tools.assert_equal(x, xx, f'... | 46,351 |
def expand_db_html(html, for_editor=False):
"""
Expand database-representation HTML into proper HTML usable in either
templates or the rich text editor
"""
def replace_a_tag(m):
attrs = extract_attrs(m.group(1))
if 'linktype' not in attrs:
# return unchanged
r... | 46,352 |
def hungarian(matrx):
"""Runs the Hungarian Algorithm on a given matrix and returns the optimal matching with potentials. Produces intermediate images while executing."""
frames = []
# Step 1: Prep matrix, get size
matrx = np.array(matrx)
size = matrx.shape[0]
# Step 2: Generate trivi... | 46,353 |
def open_spreadsheet_from_args(google_client: gspread.Client, args):
"""
Attempt to open the Google Sheets spreadsheet specified by the given
command line arguments.
"""
if args.spreadsheet_id:
logger.info("Opening spreadsheet by ID '{}'".format(args.spreadsheet_id))
return google_cl... | 46,354 |
def train(config_path):
""" Trains a model for a maximum of config.max_epochs epochs
Args:
config_path: string, path to a config.json file
"""
# Load configuration
if not os.path.exists(config_path):
print 'Error: No configuration file present at specified path.'
return
... | 46,355 |
def perturb_BB(image_shape, bb, max_pertub_pixel,
rng=None, max_aspect_ratio_diff=0.3,
max_try=100):
"""
Perturb a bounding box.
:param image_shape: [h, w]
:param bb: a `Rect` instance
:param max_pertub_pixel: pertubation on each coordinate
:param max_aspect_ratio_diff: result ca... | 46,356 |
def simpleCheck(modelConfig, days=100, visuals=True, debug=False, modelName="default", outputDir="outputs", returnTimeseries=False):
"""
runs one simulatons with the given config and showcase the number of infection and the graph
"""
loadDill, saveDill = False, False
pickleName = flr.fullPath("c... | 46,357 |
def neural_network(inputs, weights):
"""
Takes an input vector and runs it through a 1-layer neural network
with a given weight matrix and returns the output.
Arg:
inputs - 2 x 1 NumPy array
weights - 2 x 1 NumPy array
Returns (in this order):
out - a 1 x 1 NumPy array, rep... | 46,358 |
def complex_randn(shape):
"""
Returns a complex-valued numpy array of random values with shape `shape`
Args:
shape: (tuple) tuple of ints that will be the shape of the resultant complex numpy array
Returns: (:obj:`np.ndarray`): a complex-valued numpy array of random values with shape `shape`
... | 46,359 |
def load_pairs(inputdir, regex, npairs=100):
"""Load a previously generated set of pairs."""
pairfiles = glob.glob(path.join(inputdir, regex))
pairs = []
slcnr = 0
tilenr = 0
for pairfile in pairfiles:
p, src, dst, model, w = pickle.load(open(pairfile, 'rb')) # , encoding='latin1'
... | 46,360 |
def sin(x: REAL) -> float:
"""Sine."""
x %= 2 * pi
res = 0
k = 0
while True:
mem_res = res
res += (-1) ** k * x ** (2 * k + 1) / fac(2 * k + 1)
if abs(mem_res - res) < _TAYLOR_DIFFERENCE:
return res
k += 1 | 46,361 |
def _getitem_row_chan(avg, idx, dtype):
""" Extract (row,chan,corr) arrays from dask array of tuples """
name = ("row-chan-average-getitem-%d-" % idx) + tokenize(avg, idx)
dim = ("row", "chan", "corr")
layers = db.blockwise(getitem, name, dim,
avg.name, dim,
... | 46,362 |
def make_gzip(tar_file, destination):
"""
Takes a tar_file and destination. Compressess the tar file and creates
a .tar.gzip
"""
tar_contents = open(tar_file, 'rb')
gzipfile = gzip.open(destination + '.tar.gz', 'wb')
gzipfile.writelines(tar_contents)
gzipfile.close()
tar_contents.clo... | 46,363 |
def symmetrize_confusion_matrix(CM, take='all'):
"""
Sums over population, symmetrizes, then return upper triangular portion
:param CM: numpy.ndarray confusion matrix in standard format
"""
if CM.ndim > 2:
CM = CM.sum(2)
assert len(CM.shape) == 2, 'This function is meant for single subje... | 46,364 |
def get_entry_values():
"""Get entry values"""
entry = {}
for key, question in ENTRY_QUESTIONS.items():
input_type = int if key == "time" else str
while True:
print_title(MAIN_MENU[1].__doc__)
print(question)
user_input = validate(get_input(), input_type)... | 46,365 |
def test_provider_regex_invalid(client: Eve, sample_schema: dict):
"""Test to ensure regex defaults invalid inputs
:param Eve client: Mockerena app instance
:param dict sample_schema: Sample schema data
:raises: AssertionError
"""
sample_schema["file_format"] = "json"
sample_schema["column... | 46,366 |
def _create_snapshot(provider_id, machine_uuid, skip_store, wait_spawning):
"""Create a snapshot.
"""
_retrieve_machine(provider_id, machine_uuid, skip_store)
manager = _retrieve_manager(provider_id)
return manager.create_snapshot(machine_uuid, wait_spawning) | 46,367 |
def get_masked_lm_output(bert_config, input_tensor, positions,
label_ids, label_weights):
"""Get loss and log probs for the masked LM."""
input_tensor = gather_indexes(input_tensor, positions)
with tf.variable_scope("cls/predictions"):
# We apply one more non-linear transformation be... | 46,368 |
def binary_classification_loss(logits, targets, reduction='mean'):
"""
Loss.
:param logits: predicted classes
:type logits: torch.autograd.Variable
:param targets: target classes
:type targets: torch.autograd.Variable
:param reduction: reduction type
:type reduction: str
:return: er... | 46,369 |
def setup_rezconfig_file(local_packages_folder, release_packages_path):
"""
Write a rezconfig.py file for packages folder settings and create an env var to let rez reading it
"""
rez_config_filename = os.path.join((os.path.split(local_packages_folder)[0]), "rezconfig.py")
os.environ["REZ_CONFIG_FIL... | 46,370 |
def transform_with(sample, transformers):
"""Transform a list of values using a list of functions.
:param sample: list of values
:param transformers: list of functions
"""
assert not isinstance(sample, dict)
assert isinstance(sample, (tuple, list))
if transformers is None or len(transforme... | 46,371 |
def test_whichenv_invalid_debug_environ(cd_tmp_path):
"""Test ``runway whichenv`` with invalid debug environ."""
runway_yml = cd_tmp_path / "runway.yml"
runway_yml.write_text(
six.u(yaml.safe_dump({"deployments": [], "ignore_git_branch": True}))
)
runner = CliRunner()
result = runner.inv... | 46,372 |
def concat_eval(x, y):
"""
Helper function to calculate multiple evaluation metrics at once
"""
return {
"recall": recall_score(x, y, average="macro", zero_division=0),
"precision": precision_score(x, y, average="macro", zero_division=0),
"f1_score": f1_score(x, y, average="macro... | 46,373 |
def test_double_renderer():
"""Test two sibling divs."""
vdom = html('<div id="d1">div1</div><div id="d2">div2</div>')
assert ["div1"] == vdom[0].children
assert ["div2"] == vdom[1].children | 46,374 |
def main():
"""
The main function for the command line ``test_abaqus`` script.
"""
encoding = sys.getdefaultencoding()
from docopt import docopt
msg = "Usage:\n"
msg += " test_abaqus ABAQUS_FILENAME [-d]\n"
msg += ' test_abaqus -h | --help\n'
msg += ' test_abaqus -v | --version\n'... | 46,375 |
def split_into_regions(arr: np.ndarray, mode=0) -> List[np.ndarray]:
"""
Splits an array into its coherent regions.
:param mode: 0 for orthogonal connection, 1 for full connection
:param arr: Numpy array with shape [W, H]
:return: A list with length #NumberOfRegions of arrays with shape [W, H]
... | 46,376 |
def register_model(model_uri, name):
"""
Create a new model version in model registry for the model files specified by ``model_uri``.
Note that this method assumes the model registry backend URI is the same as that of the
tracking backend.
:param model_uri: URI referring to the MLmodel directory. Us... | 46,377 |
def noreplace(f):
"""Method decorator to indicate that a method definition shall
silently be ignored if it already exists in the full class."""
f.__noreplace = True
return f | 46,378 |
def reset_weights(model):
"""
re-initialise weight and bias values
"""
session = tf.keras.backend.get_session()
for layer in model.layers:
if hasattr(layer, 'kernel_initializer'):
layer.kernel.initializer.run(session=session) | 46,379 |
def position_encoding(length, depth,
min_timescale=1,
max_timescale=1e4):
"""
Create Tensor of sinusoids of different frequencies.
Args:
length (int): Length of the Tensor to create, i.e. Number of steps.
depth (int): Dimensions of embedding.
... | 46,380 |
def perform_exchange(ctx):
"""
Attempt to exchange attached NEO for tokens
:param ctx:GetContext() used to access contract storage
:return:bool Whether the exchange was successful
"""
attachments = get_asset_attachments() # [receiver, sender, neo, gas]
address = attachments[1]
neo_amo... | 46,381 |
def initialize_websocket_server(reactor, simulator, host, port, database):
"""Initialize the web socket server
Arguments:
reactor: a twisted reactor object
simulator: an Simulator object
host: the server host
port: the port to listen to
database: the database that contains the simulator dat... | 46,382 |
def Pose_2_Staubli_v2(H):
"""Converts a pose to a Staubli target target"""
x = H[0,3]
y = H[1,3]
z = H[2,3]
a = H[0,0]
b = H[0,1]
c = H[0,2]
d = H[1,2]
e = H[2,2]
if c > (1.0 - 1e-10):
ry1 = pi/2
rx1 = 0
rz1 = atan2(H[1,0],H[1,1])
elif c ... | 46,383 |
def convert_exchange_objects(elements: List[int]) -> List[int]:
"""Convert exchange objects to cadwork elements
Args:
elements (List[int]): element IDs
Returns:
List[int]: converted elements
""" | 46,384 |
def create_gru_model(fingerprint_input, model_settings, model_size_info,
is_training):
"""Builds a model with multi-layer GRUs
model_size_info: [number of GRU layers, number of GRU cells per layer]
Optionally, the bi-directional GRUs and/or GRU with layer-normalization
can be explored... | 46,385 |
def convergence_rates(N, solver_function, num_periods=8):
"""
Returns N-1 empirical estimates of the convergence rate
based on N simulations, where the time step is halved
for each simulation.
solver_function(I, V, F, c, m, dt, T, damping) solves
each problem, where T is based on simulation for
... | 46,386 |
def profile(fnc):
"""A decorator that uses cProfile to profile a function"""
def inner(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
retval = fnc(*args, **kwargs)
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.S... | 46,387 |
def _decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1):
"""Decodes the output of a softmax.
Can use either greedy search (also known as best path)
or a constrained dictionary search.
# Arguments
y_pred: tensor `(samples, time_steps, num_categories)`
containing th... | 46,388 |
def rand_xyz_box(image_arrays, label, n, depth, img_size):
"""Returns n number of randomly chosen box.
Args:
image_arrays: 3D np array of images.
label: label of images. normally is A or V
n: number of random boxes generated from this function.
depth : number of slices in Z... | 46,389 |
def pageviews_by_document(start_date, end_date, verbose=False):
"""Return the number of pageviews by document in a given date range.
* Only returns en-US documents for now since that's what we did with
webtrends.
Returns a dict with pageviews for each document:
{<document_id>: <pageviews>,
... | 46,390 |
def _SetDecomposeMethod(vm, decompose_method):
"""Set the parallel decomposition method if using multiple cores."""
logging.info('Using %s decomposition', decompose_method)
vm_util.ReplaceText(vm, 'method.*', 'method %s;' % decompose_method,
_GetPath(_DECOMPOSEDICT)) | 46,391 |
def format_time_string(seconds):
""" Return a formatted and translated time string """
def unit(single, n):
# Seconds and minutes are special due to historical reasons
if single == "minute" or (single == "second" and n == 1):
single = single[:3]
if n == 1:
return... | 46,392 |
def disconnect_db():
""" disconnect from the database """
app.logger.info('Disconnecting from the database')
DatabaseConnection.disconnect() | 46,393 |
def warp_grid(flow: Tensor) -> Tensor:
"""Creates a warping grid from a given optical flow map.
The warping grid determines the coordinates of the source pixels from which to take the color when inverse warping.
Args:
flow: optical flow tensor of shape (B, H, W, 2). The flow values are expected to... | 46,394 |
def FORMULATEXT(*args) -> Function:
"""
Returns the formula as a string.
Learn more: https//support.google.com/docs/answer/9365792.
"""
return Function("FORMULATEXT", args) | 46,395 |
def _check_kedroviz_running(context):
"""
Check that a service is running and responding appropriately
Args:
context (behave.runner.Context): Test context
"""
data_json = json.loads(download_url("http://localhost:4141/api/main"))
try:
assert context.result.poll() is None
... | 46,396 |
def test_pipeline_runner_main(pipeline_cache_reset):
"""Smoke test for pipeline runner main.
Strictly speaking this is an integration test, not a unit test.
"""
pipelinerunner.main(pipeline_name='smoke',
pipeline_context_input=None,
working_dir=working_di... | 46,397 |
def execute(strategy, instrument, sim_params, sim_days, sim_start='', sim_end=''):
"""Executes the simulation process with the specified params."""
# Sets global variables
global strat, pair, days, start_date, end_date, filename, variables, keys, vals, results
strat = strategy
pair = instrument
... | 46,398 |
def main(argv):
"""Launches the device temperature monitor.
Polls the devices for their battery and cpu temperatures and scans the
blacklist file every 60 seconds and uploads the data for monitoring
through infra's ts_mon. Fully qualified, the metric names would be
/chrome/infra/dev/(cpu|battery)/temperature... | 46,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.