content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def divide(x, y):
"""A version of divide that also rounds."""
return round(x / y) | 24,400 |
def mark_bad_wavelength_groups(src_file: H5File, filtered_paths: List[str]) -> None:
"""Sets the `isbad` attribute of each wavelength group to `True` if the group contains
one or more path that has been filtered.
Args:
src_file (H5File): The file containing the experimental data
filtered_pa... | 24,401 |
def create_root_ca_cert(root_common_name, root_private_key, days=365):
"""
This method will create a root ca certificate.
:param root_common_name: The common name for the certificate.
:param root_private_key: The private key for the certificate.
:param days: The number of days for which the certific... | 24,402 |
def hist1d(arr, bins=None, amp_range=None, weights=None, color=None, show_stat=True, log=False,\
figsize=(6,5), axwin=(0.15, 0.12, 0.78, 0.80),\
title=None, xlabel=None, ylabel=None, titwin=None):
"""Makes historgam from input array of values (arr), which are sorted in number of bins (bins) in... | 24,403 |
def format_validate_parameter(param):
"""
Format a template parameter for validate template API call
Formats a template parameter and its schema information from the engine's
internal representation (i.e. a Parameter object and its associated
Schema object) to a representation expected by the curre... | 24,404 |
def get_template(name):
"""Retrieve the template by name
Args:
name: name of template
Returns:
:obj:`string.Template`: template
"""
file_name = "{name}.template".format(name=name)
data = resource_string("pyscaffoldext.beeproject.templates", file_name)
return string.Template... | 24,405 |
def create_benefits_online(context):
""" Test creating a BenifitsOnline object """
context.benefits_online = BenefitsOnline(context.bol_username,
context.password) | 24,406 |
def run_kitti_native_script_with_05_iou(kitti_native_code_copy, checkpoint_name, score_threshold,
global_step):
"""Runs the kitti native code script."""
make_script = kitti_native_code_copy + '/run_eval_05_iou.sh'
script_folder = kitti_native_code_copy
results_d... | 24,407 |
def box3d_overlap(boxes, qboxes, criterion=-1, z_axis=1, z_center=1.0):
"""kitti camera format z_axis=1.
"""
bev_axes = list(range(7))
bev_axes.pop(z_axis + 3)
bev_axes.pop(z_axis)
# t = time.time()
# rinc = box_np_ops.rinter_cc(boxes[:, bev_axes], qboxes[:, bev_axes])
rinc = rotate_iou... | 24,408 |
def _apply_graph_transform_tool_rewrites(g, input_node_names,
output_node_names):
# type: (gde.Graph, List[str], List[str]) -> tf.GraphDef
"""
Use the [Graph Transform Tool](
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/
graph_transforms/README... | 24,409 |
def draw_embedding_rel_space(h_emb,
r_emb,
t_emb,
h_name,
r_name,
t_name,
resultpath,
algos,
... | 24,410 |
def big_bcast(comm, objs, root=0, return_split_info=False, MAX_BYTES=INT_MAX):
"""
Broadcast operation that can exceed the MPI limit of ~4 GiB.
See documentation on :meth:`big_gather` for details.
Parameters
----------
comm: mpi4py.MPI.Intracomm
MPI communicator to use.
objs: objec... | 24,411 |
def main(config):
""" setup """
working_dir = os.getcwd()
project_dir = hydra.utils.get_original_cwd()
folder_path = os.path.join(project_dir, config['input_dir'])
if config['anatomy'] == 'stanford_knees':
files = get_all_files(folder_path, pattern=f'*R{config["R"]}*.h5')
else:
... | 24,412 |
def get_task(appname, taskqueue, identifier):
"""Gets identified task in a taskqueue
Request
-------
```
GET http://asynx.host/apps/:appname/taskqueues/:taskqueue/tasks/:identifier
```
Parameters:
- appname: url param, string, the application name
under wh... | 24,413 |
def GetBuiltins(stdlib=True):
"""Get the "default" AST used to lookup built in types.
Get an AST for all Python builtins as well as the most commonly used standard
libraries.
Args:
stdlib: Whether to load the standard library, too. If this is False,
TypeDeclUnit.modules will be empty. If it's True, ... | 24,414 |
def assign_style_props(df, color=None, marker=None, linestyle=None,
cmap=None):
"""Assign the style properties for a plot
Parameters
----------
df : pd.DataFrame
data to be used for style properties
"""
if color is None and cmap is not None:
raise ValueErr... | 24,415 |
def to_dbtext(text):
"""Helper to turn a string into a db.Text instance.
Args:
text: a string.
Returns:
A db.Text instance.
"""
if isinstance(text, unicode):
# A TypeError is raised if text is unicode and an encoding is given.
return db.Text(text)
else:
try:
return db.Text(text, ... | 24,416 |
def write_vis_file_ring(numCameras,numNeighbors=1,visFilePath=Path('vis.dat')):
""" Generate a vis.dat file that pmvs2 expects for a camera array with
ring topology and a configurable number of neighbors to be used for reconstruction.
Inputs:
numCameras -- The number of cameras in the ring
num... | 24,417 |
def zmq_init(pub_port, sub_port_list):
"""
Initialize the ZeroMQ publisher and subscriber.
`My` publisher publishes `my` data to the neighbors. `My` subscriber listen
to the ports of other neighbors. `sub_port_list` stores all the possible
neighbors' TCP ports.
The data packs are wrap... | 24,418 |
def test_kb_invalid_entity_vector(nlp):
"""Test the invalid construction of a KB with non-matching entity vector lengths"""
mykb = KnowledgeBase(nlp.vocab, entity_vector_length=3)
# adding entities
mykb.add_entity(entity="Q1", freq=19, entity_vector=[1, 2, 3])
# this should fail because the kb's e... | 24,419 |
def convert(conf_dict):
"""
convert
"""
converter.run_convert(conf_dict) | 24,420 |
def initialise_harness_from_file(file_name = None):
"""Initialise interoperability test harness.
This function creates an instance of
:class:`prov_interop.harness.HarnessResources` and then configures
it using configuration loaded from a YAML file (using
:func:`prov_interop.files.load_yaml`). The file loaded... | 24,421 |
def register_uri_image_loader(scheme, loader):
"""
Image can be represented as "scheme://path", image will be retrived by calling
Image.open(loader(path)).
"""
logger.info(
"Register image loader for scheme: {} with loader: {}".format(scheme, loader)
)
_IMAGE_LOADER_REGISTRY[sche... | 24,422 |
def get_all_match_fractions(
residuals: Dict[str, np.ndarray],
roi_mask: np.ndarray,
hypotheses: np.ndarray,
parang: np.ndarray,
psf_template: np.ndarray,
frame_size: Tuple[int, int],
n_roi_splits: int = 1,
roi_split: int = 0,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
T... | 24,423 |
def test_predict_test_data():
""" Make sure the length of predictions matches the length of test_labels """
trees = 1000
random_state = 42
maxfeatures = float(1/3)
features = [[1]*6, [2]*6, [3]*6, [4]*6, [5]*6, [6]*6,[7]*6,[8]*6,[9]*6]
features = np.array(features)
labels = [1, 2, 3, 4, 5, 6, 7, 8, 9]
rf = cre... | 24,424 |
def test_tensorboard_dir_script_specify_tensorboard_dir():
""" In script mode, passing `export_tensorboard` and `tensorboard_dir` works. """
with ScriptSimulator(tensorboard_dir="/tmp/tensorboard_dir") as sim:
hook = smd.Hook(
out_dir=sim.out_dir, export_tensorboard=True, tensorboard_dir=sim... | 24,425 |
def dot(u, v):
"""
Returns the dot product of the two vectors.
>>> u1 = Vec([1, 2])
>>> u2 = Vec([1, 2])
>>> u1*u2
5
>>> u1 == Vec([1, 2])
True
>>> u2 == Vec([1, 2])
True
"""
assert u.size == v.size
sum = 0
for index, (compv, compu) in enumerate(zip(u.store,v.st... | 24,426 |
def isvalid(number, numbers, choices=2):
"""Meh
>>> isvalid(40, (35, 20, 15, 25, 47))
True
>>> isvalid(62, (20, 15, 25, 47, 40))
True
>>> isvalid(127, (182, 150, 117, 102, 95))
False
"""
return number in sums(numbers, choices) | 24,427 |
def from_rotation_matrix(rotation_matrix: type_alias.TensorLike,
name: str = "quaternion_from_rotation_matrix"
) -> tf.Tensor:
"""Converts a rotation matrix representation to a quaternion.
Warning:
This function is not smooth everywhere.
Note:
In the fol... | 24,428 |
def set_config(target_offload=None, allow_fallback_to_host=None, **sklearn_configs):
"""Set global configuration
Parameters
----------
target_offload : string or dpctl.SyclQueue, default=None
The device primarily used to perform computations.
If string, expected to be "auto" (the executi... | 24,429 |
def mark_text(text):
"""Compact rules processor"""
attrs = {}
rules = []
weight = 0
attrs['len'] = len(text)
text = text.replace('.', ' ').replace(',', ' ').replace(u'№', ' ').strip().lower()
words = text.split()
textjunk = []
spaced = 0
attrs['wl'] = len(words)
attrs['junkl'... | 24,430 |
def create_faucet(client):
"""Create a wallet using the testnet faucet"""
test_wallet = generate_faucet_wallet(client, debug=True)
return test_wallet | 24,431 |
async def test_loading_extra_values(hass, hass_storage):
"""Test we load extra data from the registry."""
hass_storage[entity_registry.STORAGE_KEY] = {
"version": entity_registry.STORAGE_VERSION,
"data": {
"entities": [
{
"entity_id": "test.named",... | 24,432 |
def handle_offer_creation(create_offer, header, state):
"""Handle Offer creation.
Args:
create_offer (CreateOffer): The transaction.
header (TransactionHeader): The header of the Transaction.
state (MarketplaceState): The wrapper around the context.
Raises:
InvalidTransacti... | 24,433 |
def kill_and_exit(all_p):
"""
Kills main, service and daemon's processes if one fails.
"""
for p in all_p:
try:
os.kill(p.pid, signal.SIGTERM)
except Exception as e:
print(e)
exit(1) | 24,434 |
def model_flux(t_dec,B,P_max,R,Ne,d_l,z,mp,me,e,c,sigma_t,time,nu,Gamma,E_k,
n,eps_b,eps_e,p,j_ang):
""" Function for deriving the flux for the spectrum or light curve at
given times and frequencies """
# calculate lorentz factors, characteristic frequencies and
# jet break time
gamma_m = Gamma*eps_e*((p-2)/(p-... | 24,435 |
def fix_lng_degrees(lng: float) -> float:
"""
For a lng degree outside [-180;180] return the appropriate
degree assuming -180 = 180°W and 180 = 180°E.
"""
sign = 1 if lng > 0 else -1
lng_adj = (abs(lng) % 360) * sign
if lng_adj > 180:
return (lng_adj % 180) - 180
elif lng_adj < -... | 24,436 |
def calibrate_healpix(pix,version,nside=64,redo=False):
"""
This program is a wrapper around NSC_INSTCAL_CALIBRATE
for all exposures in the same region of the sky.
It retrieves the reference catalogs ONCE which saves time.
Parameters
----------
pix The HEALPix pixel number.
versio... | 24,437 |
def log_train_val_stats(args: Namespace,
it: int,
train_loss: float,
train_acc: float,
valid,
log_freq: int = 10,
ckpt_freq: int = 50,
mdl_watch_log_... | 24,438 |
def create_code(traits):
"""Assign bits to list of traits.
"""
code = 1
result = {INVALID: code}
if not traits:
return result
for trait in traits:
code = code << 1
result[trait] = code
return result | 24,439 |
def clean(ctx):
"""Run all clean sub-tasks."""
pass | 24,440 |
def load_tensorrt_plugin():
"""load TensorRT plugins library."""
global plugin_is_loaded
lib_path = get_tensorrt_op_path()
if (not plugin_is_loaded) and os.path.exists(lib_path):
ctypes.CDLL(lib_path)
plugin_is_loaded = True | 24,441 |
def get_current_table(grid_id: str) -> List[Dict[Any, Any]]:
""" Get current Data from the grid
Args:
grid_id: Grid ID to retrieve data from.
Returns:
list: Exsiting grid data.
"""
current_table: Optional[List[dict]] = demisto.incidents()[0].get("CustomFields", {}).get(grid_id)
... | 24,442 |
def read_graph(filepath):
"""Creates a graph based on the content of the file at given filepath.
Parameters
----------
filename : filepath
Path to a file containing an adjacency matrix.
"""
g_data = np.loadtxt(open(filepath, "rb"), delimiter=",")
return nx.from_numpy_matrix(g_data) | 24,443 |
def test_decompose_basic_concat(namespace: TestNamespace, check: CheckFunc) -> None:
"""Test construction of ConcatenatedBits."""
ref0 = namespace.addArgument("R0", IntType.u(7))
ref1 = namespace.addArgument("R1", IntType.u(3))
ref2 = namespace.addArgument("R2", IntType.u(13))
concat = ConcatenatedB... | 24,444 |
def get_seed(seed=None):
"""Get valid Numpy random seed value"""
# https://groups.google.com/forum/#!topic/briansupport/9ErDidIBBFM
random = np.random.RandomState(seed)
return random.randint(0, 2147483647) | 24,445 |
def test_catalog_wrong_action_argument():
"""
Test if error is raised when wrong action argument is supplied
"""
with pytest.raises(ValueError):
ctlg = Catalog()
ctlg('wrong_action') | 24,446 |
def test_init(isolated_runner):
"""Test project initialization."""
runner = isolated_runner
# 1. the directory should be automatically created
new_project = Path('test-new-project')
assert not new_project.exists()
result = runner.invoke(cli.cli, ['init', 'test-new-project'])
assert 0 == res... | 24,447 |
def explain_predictions_best_worst(pipeline, input_features, y_true, num_to_explain=5, top_k_features=3,
include_shap_values=False, metric=None, output_format="text"):
"""Creates a report summarizing the top contributing features for the best and worst points in the dataset as mea... | 24,448 |
def resolve_lookup(
context: dict, lookup: str, call_functions: bool = True
) -> typing.Any:
"""
Helper function to extract a value out of a context-dict.
A lookup string can access attributes, dict-keys, methods without parameters and indexes by using the dot-accessor (e.g. ``person.name``)
This is... | 24,449 |
def app_config(
simple_config: Configurator, document: t.IO
) -> t.Generator[Configurator, None, None]:
"""Incremented fixture that loads the DOCUMENT above into the config."""
simple_config.pyramid_openapi3_spec(
document.name, route="/foo.yaml", route_name="foo_api_spec"
)
yield simple_con... | 24,450 |
def check_actions_tool(tool):
"""2.2.x to 2.3.0 upgrade step checker
"""
atool = getToolByName(tool, 'portal_actions')
try:
atool['user']['change_password']
except KeyError:
return True
try:
atool['global']['members_register']
except KeyError:
return True
... | 24,451 |
def integer_byte_length(number):
"""
Number of bytes needed to represent a integer excluding any prefix 0 bytes.
:param number:
Integer value. If num is 0, returns 0.
:returns:
The number of bytes in the integer.
"""
quanta, remainder = divmod(integer_bit_length(number), 8)
if remainder:
... | 24,452 |
def ones(input_dim, output_dim, name=None):
"""All zeros."""
initial = tf.ones((input_dim, output_dim), dtype=tf.float32)
return tf.Variable(initial, name=name) | 24,453 |
def enrichment_score2(mat, idx, line_width, norm_factors, distance_range=(20, 40), window_size=10,
stats_test_log=({}, {})):
"""
Calculate the enrichment score of a stripe given its location, width and the contact matrix
Parameters:
----------
mat: np.array (2D)
Contac... | 24,454 |
def paginate(data, page=1, per_page=None):
"""Create a paginated response of the given query set.
Arguments:
data -- A flask_mongoengine.BaseQuerySet instance
"""
per_page = app.config['DEFAULT_PER_PAGE'] if not per_page else per_page
pagination_obj = data.paginate(page=page, per_page=per_p... | 24,455 |
def test_cli_help(help_option, capfd):
"""
Test for the help option : -h, --help
:param help_option:
:param capfd:
:return:
"""
args = [__prog__, help_option]
cli = PlaybookGrapherCLI(args)
with pytest.raises(SystemExit) as exception_info:
cli.parse()
out, err = capfd.... | 24,456 |
def compute_mean_wind_dirs(res_path, dset, gids, fracs):
"""
Compute mean wind directions for given dset and gids
"""
with Resource(res_path) as f:
wind_dirs = np.radians(f[dset, :, gids])
sin = np.mean(np.sin(wind_dirs) * fracs, axis=1)
cos = np.mean(np.cos(wind_dirs) * fracs, axis=1)
... | 24,457 |
def plot_area_and_score(samples: SampleList, compound_name: str, include_none: bool = False):
"""
Plot the peak area and score for the compound with the given name
:param samples: A list of samples to plot on the chart
:param compound_name:
:param include_none: Whether samples where the compound was not found
s... | 24,458 |
def _raise_on_error(data: dict) -> None:
"""Raise appropriately when a returned data payload contains an error."""
if data["code"] == 0:
return
raise_error(data) | 24,459 |
def get_strides(fm: NpuFeatureMap) -> NpuShape3D:
"""Calculates STRIDE_C/Y/X"""
if fm.strides is not None:
return fm.strides
elem_size = fm.data_type.size_in_bytes()
if fm.layout == NpuLayout.NHWC:
stride_c = elem_size
stride_x = fm.shape.depth * stride_c
stride_y = fm.sh... | 24,460 |
def gram_linear(x):
"""Compute Gram (kernel) matrix for a linear kernel.
Args:
x: A num_examples x num_features matrix of features.
Returns:
A num_examples x num_examples Gram matrix of examples.
"""
return x.dot(x.T) | 24,461 |
def enable_maintenance(*app_list):
"""Enables a maintenance page for publishers and serves a 503"""
"""Only to be run on loadbalancers"""
if not fabric.contrib.files.exists(maintenance_config):
abort("Sorry this task can only currently be run on loadbalancers")
puppet.disable("Maintenance mode e... | 24,462 |
def to_feature(shape, properties={}):
"""
Create a GeoJSON Feature object for the given shapely.geometry :shape:.
Optionally give the Feature a :properties: dict.
"""
collection = to_feature_collection(shape)
feature = collection["features"][0]
feature["properties"] = properties
# remov... | 24,463 |
def test_py30303_disc():
"""Very basic testing."""
s = py30303_disc.d30303()
s.send_discovery()
s.end_discovery() | 24,464 |
def read_responses(file):
"""
Read dialogs from file
:param file: str, file path to the dataset
:return: list, a list of dialogue (context) contained in file
"""
with open(file, 'r') as f:
samples = f.read().split('<|endoftext|>')
samples = samples[1:] # responses = [i.strip() f... | 24,465 |
def build_parametric_ev(data, onset, name, value, duration=None,
center=None, scale=None):
"""Make design info for a multi-column constant-value ev.
Parameters
----------
data : DataFrame
Input data; must have "run" column and any others specified.
onset : string
... | 24,466 |
def test_alert_schedule(cinq_test_service):
"""
Test whether the auditor respects the alert schedule
"""
setup_info = setup_test_aws(cinq_test_service)
account = setup_info['account']
prep_s3_testing(cinq_test_service)
# Add resources
client = aws_get_client('s3')
bucket_name = db... | 24,467 |
def time_aware_indexes(t, train_size, test_size, granularity, start_date=None):
"""Return a list of indexes that partition the list t by time.
Sorts the list of dates t before dividing into training and testing
partitions, ensuring a 'history-aware' split in the ensuing classification
task.
Args:... | 24,468 |
def send_invite_mail(invite, request):
"""
Send an email invitation to user not yet registered in the system.
:param invite: ProjectInvite object
:param request: HTTP request
:return: Amount of sent email (int)
"""
invite_url = build_invite_url(invite, request)
message = get_invite_body... | 24,469 |
def copy_optimizer_params_to_model(named_params_model, named_params_optimizer):
""" Utility function for optimize_on_cpu and 16-bits training.
Copy the parameters optimized on CPU/RAM back to the model on GPU
"""
for (name_opti, param_opti), (name_model, param_model) in zip(named_params_optimize... | 24,470 |
def enable_extra_meshes():
"""
enable Add Mesh Extra Objects addon
https://docs.blender.org/manual/en/3.0/addons/add_mesh/mesh_extra_objects.html
"""
enable_addon(addon_module_name="add_mesh_extra_objects") | 24,471 |
def get_credentials(quota_project_id=None):
"""Obtain credentials object from json file and environment configuration."""
credentials_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
with open(credentials_path, "r", encoding="utf8") as file_handle:
credentials_data = file_handle.read()
... | 24,472 |
def create_model_file(path, dz, vp, vs, rho):
"""
Writing the 1D model to ascci file, to be used as input
by the Computer Programs in Seismology
"""
qp = np.zeros_like(dz)
qs = np.zeros_like(dz)
etap = np.zeros_like(dz)
etas = np.zeros_like(dz)
frefp = np.ones_like(dz)
frefs = np... | 24,473 |
async def test_file_inspection(make_file, loop):
""" Checks: Basic test file inspection """
content = """
RAMADA
RAMZAN
xd
bobby pin bobby pun
"""
make_file(content)
buffer = []
async for chunk in inspect(TEST_DIR / "test_file_read.txt", loop):
buffer.append(chunk)
ac... | 24,474 |
def update():
""" Update the feature with updates committed to develop.
This will merge current develop into the current branch.
"""
branch = git.current_branch(refresh=True)
develop = conf.get('git.devel_branch', 'develop')
common.assert_branch_type('feature')
common.git_checkout(develop)... | 24,475 |
def binary_n(total_N, min_n=50):
"""
Creates a list of values by successively halving the total length total_N
until the resulting value is less than min_n.
Non-integer results are rounded down.
Args:
total_N (int):
total length
Kwargs:
min_n (int):
minimal length after division
Ret... | 24,476 |
def thresholding(pred,label,thres):
""" Given the threshold return boolean matrix with 1 if > thres 0 if <= 1 """
conf =[]
for i in thres:
pr_th,lab_th = (pred>i),(label>i)
conf += confusion(pr_th,lab_th)
return np.array(conf).reshape(-1,4) | 24,477 |
def WriteWavFile(signal, sample_rate, file_name, bitdepth=16, normalize=True):
"""Write a .wav file from a numpy array.
Args:
signal: 2-dimensional numpy array, of size (num_samples, num_channels).
sample_rate: int. sample rate of the signal in Hz.
file_name: string. name of the destination file.
b... | 24,478 |
def set_pay_to_address_name_loop(context: X12ParserContext, segment_data: Dict) -> None:
"""
Sets the Billing Provider Pay to Address Name Loop 2010AB
:param context: The X12Parsing context which contains the current loop and transaction record.
:param segment_data: The current segment data
"""
... | 24,479 |
def unicode_test(request, oid):
"""Simple view to test funky characters from the database."""
funky = News.objects.using('livewhale').get(pk=oid)
return render(request, 'bridge/unicode.html', {'funky': funky}) | 24,480 |
def _field_to_schema_object(field: BaseType, apistrap: Optional[Apistrap]) -> Optional[Dict[str, Any]]:
"""
Convert a field definition to OpenAPI 3 schema.
:param field: the field to be converted
:param apistrap: the extension used for adding reusable schema definitions
:return: a schema
"""
... | 24,481 |
def linux_gcc_name():
"""Returns the name of the `gcc` compiler. Might happen that we are cross-compiling and the
compiler has a longer name.
Args:
None
Returns:
str: Name of the `gcc` compiler or None
"""
cc_env = os.getenv('CC')
if cc_env is not None:
if subpr... | 24,482 |
def drop_test(robot, *, z_rot: float, min_torque: bool, initial_height: float = 1.) -> Dict[str, Any]:
"""Params which have been tested for this task:
nfe = 20, total_time = 1.0, vary_timestep_with=(0.8,1.2), 5 mins for solving
if min_torque is True, quite a bit more time is needed as IPOPT refines things
... | 24,483 |
def login(api, key, secret):
"""
Authenticates with Coach.
Get your API key here: https://coach.lkuich.com/
"""
try:
id = api[0:5]
profile = coach.get_profile(api, id)
except Exception as e:
click.echo(f"Failed to authenticate:\n{e}")
return
if pr... | 24,484 |
def get_user_list(
*, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],
) -> Union[
List[AModel], HTTPValidationError,
]:
""" Get a list of things """
url = "{}/tests/".format(client.base_url)
headers: Dict[str, Any] = client.get_headers()
json_an_enum_value = []... | 24,485 |
def download_from_s3(source_path, outdir, s3_client=None):
"""Download a file from CreoDIAS S3 storage to the given location
(Works only when used from a CreoDIAS vm)
Parameters
----------
source_path:
CreoDIAS path to S3 object
target_path:
Path to write the product folder
... | 24,486 |
def old_func5(self, x):
"""Summary.
Bizarre indentation.
"""
return x | 24,487 |
def add_node_hash(node):
"""
Recursively adds all missing commitments and hashes to a verkle trie structure.
"""
if node["node_type"] == "leaf":
node["hash"] = hash([node["key"], node["value"]])
if node["node_type"] == "inner":
lagrange_polynomials = []
values = {}
fo... | 24,488 |
def set_(
computer_policy=None,
user_policy=None,
cumulative_rights_assignments=True,
adml_language="en-US",
):
"""
Set a local server policy.
Args:
computer_policy (dict):
A dictionary of "policyname: value" pairs of computer policies to
set. 'value' should... | 24,489 |
def get_dotenv_variable(var_name: str) -> str:
""" """
try:
return config.get(var_name)
except KeyError:
error_msg = f"{var_name} not found!\nSet the '{var_name}' environment variable"
raise ImproperlyConfigured(error_msg) | 24,490 |
def test_send_user_to_hubspot(mocker, settings):
"""
Tests that send_user_to_hubspot sends the correct data
"""
mock_requests = mocker.patch("authentication.pipeline.user.requests")
mock_log = mocker.patch("authentication.pipeline.user.log")
mock_request = mocker.Mock(COOKIES={"hubspotutk": "so... | 24,491 |
def load_dataset():
"""
Create a PyTorch Dataset for the images.
Notes
-----
- See https://discuss.pytorch.org/t/computing-the-mean-and-std-of-dataset/34949
"""
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.9720, 0.9720, 0.9720),
... | 24,492 |
def load():
"""Load list of available storage managers."""
storage_type = config.get("rights", "type")
if storage_type == "custom":
rights_module = config.get("rights", "custom_handler")
__import__(rights_module)
module = sys.modules[rights_module]
else:
root_module = __i... | 24,493 |
def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
"""Print stats on screen."""
global lineno
# totals
print_line("total bytes: sent: %-10s received: %s" \
% (bytes2human(tot_after.bytes_sent),
bytes2human(tot_after.bytes_recv))
)
print_line("... | 24,494 |
def vote(pred1, pred2, pred3=None):
"""Hard voting for the ensembles"""
vote_ = []
index = []
if pred3 is None:
mean = np.mean([pred1, pred2], axis=0)
for s, x in enumerate(mean):
if x == 1 or x == 0:
vote_.append(int(x))
else:
... | 24,495 |
def move(cardinal):
"""
Moves the player from one room to another if room exists and door is
open.
Parameters:
cardinal(str): String that points to a valid cardinal.
i.e {North, East, South, West}
"""
room_before_mov = __current_position()
room_after_mov = room_m.move(ca... | 24,496 |
def generate_master_flat(
science_frame : CCDData,
bias_path : Path,
dark_path : Path,
flat_path : Path,
use_cache : bool=True
) -> CCDData:
"""
"""
cache_path = generate_cache_path(science_frame, flat_path) / 'flat'
if use_cache and cache_path.is_dir():
... | 24,497 |
def submit_remote(c, node_count=int(env_values["CLUSTER_MAX_NODES"])):
"""This command isn't implemented please modify to use.
The call below will work for submitting jobs to execute on a remote cluster using GPUs.
"""
raise NotImplementedError(
"You need to modify this call before being able t... | 24,498 |
def natrix_mqttclient(client_id):
"""Generate a natrix mqtt client.
This function encapsulates all configurations about natrix mqtt client.
Include:
- client_id
The unique id about mqtt connection.
- username & password
Username is device serial number which used to identify who am I;
... | 24,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.