content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def generate_id():
"""Generate Hexadecimal 32 length id."""
return "%032x" % random.randrange(16 ** 32) | 5,327,500 |
def show_final_report(found_files: int,
optimized_files: int,
src_size: int,
bytes_saved: int,
time_passed: float):
"""
Show a final report with the time spent and filesize savings
:param found_files: number of found im... | 5,327,501 |
def __charge_to_sdf(charge):
"""Translate RDkit charge to the SDF language.
Args:
charge (int): Numerical atom charge.
Returns:
str: Str representation of a charge in the sdf language
"""
if charge == -3:
return "7"
elif charge == -2:
return "6"
elif charge ... | 5,327,502 |
def validate(epoch, model,gmm, ema=None):
"""
- Deploys the color normalization on test image dataset
- Evaluates NMI / CV / SD
# Evaluates the cross entropy between p_data and p_model.
"""
print("Starting Validation")
model = parallelize(model)
gmm = parallelize(gmm)
model.to... | 5,327,503 |
async def fail_detect(state):
"""
Async method to detect a failure in a node (forced a failure to detect for testing)
Accepts: state which is an empty object from the udp_broadcast class
Returns: nothing, it pops nodes from dictionary if node fails and
notifies if popped node is coordinator... | 5,327,504 |
def print_process_acro_found_help():
"""Prints acronym handling user commands help"""
print(_(" y: Aceptar - Guarda el acrónimo con la información mostrada y actualiza la base de datos."))
print(_(" n: Saltar - Descarta el acrónimo y continúa al siguiente."))
print(_(" e: Editar - M... | 5,327,505 |
def show_diff_popup(git_gutter, **kwargs):
"""Show the diff popup.
Arguments:
git_gutter (GitGutterCommand):
The main command object, which represents GitGutter.
kwargs (dict):
The arguments passed from GitGutterDiffPopupCommand
to GitGutterCommand.
"""
... | 5,327,506 |
def gctx2gct_main(args):
""" Separate from main() in order to make command-line tool. """
in_gctoo = parse_gctx.parse(args.filename, convert_neg_666=False)
if args.output_filepath is None:
basename = os.path.basename(args.filename)
out_name = os.path.splitext(basename)[0] + ".gct"
else... | 5,327,507 |
def save_str(self=str(''),
filename=str('output.txt'),
permissions=str('w')):
"""Save a given string to disk using a given file name.
Args:
self(str): String to save to disk. (default str(''))
filename(str): File name to use when saving to disk. (default str('output.tx... | 5,327,508 |
def balanced(banked_chemicals):
"""return true if all non-ore chemicals have non-negative amounts."""
def _enough(chemical):
return chemical == "ORE" or banked_chemicals[chemical] >= 0
return all(map(_enough, banked_chemicals)) | 5,327,509 |
def add_log(log, logfile):
"""It sets the formatter for the handle and add that handler to the logger.
Args:
log(Logging.logger): The logger object used for logging.
logfile(str): path for the log file.
Returns:
None
"""
dir = os.path.dirname(logfile)
if not os.path.exists(di... | 5,327,510 |
def test_default_params(frames: Tuple[Request, Response]) -> None:
"""Test frame attributes."""
for frame in frames:
assert frame.recipient == BROADCAST_ADDRESS
assert frame.message == b""
assert frame.sender == ECONET_ADDRESS
assert frame.sender_type == ECONET_TYPE
asser... | 5,327,511 |
def dict2json(thedict, json_it=False, compress_it=False):
"""if json_it convert thedict to json
if compress_it, do a bzip2 compression on the json"""
if compress_it:
return bz2.compress(json.dumps(thedict).encode())
elif json_it:
return json.dumps(thedict)
else:
return thedic... | 5,327,512 |
def parse_arguments():
"""
Parse command line arguments.
"""
import argparse
parser = argparse.ArgumentParser(
description="Python script for minimizing unit cell."
)
subparser = parser.add_subparsers(dest='command')
subparser.required = True
yaml_parse = subparser.a... | 5,327,513 |
def get_image(roidb, config):
"""
preprocess image and return processed roidb
:param roidb: a list of roidb
:return: list of img as in mxnet format
roidb add new item['im_info']
0 --- x (width, second dim of im)
|
y (height, first dim of im)
"""
num_images = len(roidb)
proces... | 5,327,514 |
def compoundedInterest(fv, p):
"""Compounded interest
Returns: Interest value
Input values:
fv : Future value
p : Principal
"""
i = fv - p
return i | 5,327,515 |
def get_volumetric_scene(self, data_key="total", isolvl=0.5, step_size=3, **kwargs):
"""Get the Scene object which contains a structure and a isosurface components
Args:
data_key (str, optional): Use the volumetric data from self.data[data_key]. Defaults to 'total'.
isolvl (float, optional): Th... | 5,327,516 |
def intercept(on=True):
"""
enable or disable tracking/interecpting of matplotlib calls
"""
global _intercept, _intercept_user
_intercept = on
_intercept_user = on | 5,327,517 |
def test_generic_command_positive_value_key(requests_mock, client):
"""
Given:
- API resource /applications
When:
- Running the generic command
Then:
- Ensure outputs are as expected
"""
applications_res = load_test_data('applications.json')
requests_mock.get(
... | 5,327,518 |
def encode_labels(x, features):
"""
Maps strings to integers
"""
from numpy import concatenate
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OrdinalEncoder
encoder = ColumnTransformer([("", OrdinalEncoder(), features)], n_jobs=-1)
x[:, features] = encod... | 5,327,519 |
def get_jogframe(
conx: Connection, idx: int, group: int = 1, include_comment: bool = False
) -> t.Tuple[Position_t, t.Optional[str]]:
"""Return the jog frame at index 'idx'.
:param idx: Numeric ID of the jog frame.
:type idx: int
:param group: Numeric ID of the motion group the jog frame is
as... | 5,327,520 |
def rotate(arr, bins):
"""
Return an array rotated by 'bins' places to the left
:param list arr: Input data
:param int bins: Number of bins to rotate by
"""
bins = bins % len(arr)
if bins == 0:
return arr
else:
return np.concatenate((arr[bins:], arr[:bins])) | 5,327,521 |
def clear_list(items: Iterable[Optional[Typed]]) -> List[Typed]:
""" return unique items in order of first ocurrence """
return list(OrderedDict.fromkeys(i for i in items if i is not None)) | 5,327,522 |
def chords(labels):
"""
Transform a list of chord labels into an array of internal numeric
representations.
Parameters
----------
labels : list
List of chord labels (str).
Returns
-------
chords : numpy.array
Structured array with columns 'root', 'bass', and 'interv... | 5,327,523 |
def reduce_aet_if_dry(aet, wat_lev, fc):
""" Reduce actual evapotranspiration if the soil is dry. If the water level
in a cell is less than 0.7*fc, the rate of evapo-transpiration is
reduced by a factor. This factor is 1 when wat_lev = 0.7*fc and
decreases linearly to reach 0 when wat_lev... | 5,327,524 |
def merge_sort(array):
"""
Sort array via merge sort algorithm
Args:
array: list of elements to be sorted
Returns:
Sorted list of elements
Examples:
>>> merge_sort([1, -10, 21, 3, 5])
[-10, 1, 3, 5, 21]
"""
if len(array) == 1:
return array[:]
mi... | 5,327,525 |
def inline_query(update: Update, _):
"""Translate LaTeX to unicode, then send it using the inline mode."""
result = replace(update.inline_query.query).strip()
if not result:
return
update.inline_query.answer(
[
InlineQueryResultArticle(
id="result",
... | 5,327,526 |
def cmd_update( package ):
"""Updates a package"""
curpath = os.getcwd()
with cd( "build/tools/%s" % package.subdir ):
update( package )
build_and_install( package, curpath ) | 5,327,527 |
def create_monitored_session(target: tf.train.Server, task_index: int,
checkpoint_dir: str, save_checkpoint_secs: int, config: tf.ConfigProto=None) -> tf.Session:
"""
Create a monitored session for the worker
:param target: the target string for the tf.Session
:param task_in... | 5,327,528 |
def sun_rise_set_times(datetime_index, coords):
"""
Return sunrise and set times for the given datetime_index and coords,
as a Series indexed by date (days, resampled from the datetime_index).
"""
obs = ephem.Observer()
obs.lat = str(coords[0])
obs.lon = str(coords[1])
# Ensure datetime... | 5,327,529 |
def running_mean(iterable, kind='arithmetic'):
"""
Compute the running mean of an iterable. After `n` items, the mean
of the first `n` items are yielded.
Parameters
----------
iterable : iterable
An iterable object.
kind : str
The type of mean to compute, either `arithme... | 5,327,530 |
def get_n1_event_format():
"""
Define the format for the events in a neurone recording.
Arguments: None.
Returns:
- A Struct (from the construct library) describing the
event format.
"""
# Define the data format of the events
# noinspection PyUnresolvedReferences
r... | 5,327,531 |
def test_writer_validate_be():
"""System endianness and shb endianness should match"""
shb = define_testdata().valid_shb_le
_sysle = Writer._Writer__le
Writer._Writer__le = False
try:
writer = Writer(fobj, shb=shb) # noqa
except Exception as e:
assert isinstance(e, ValueError)... | 5,327,532 |
def idzp_rid(eps, m, n, matveca):
"""
Compute ID of a complex matrix to a specified relative precision using
random matrix-vector multiplication.
:param eps:
Relative precision.
:type eps: float
:param m:
Matrix row dimension.
:type m: int
:param n:
M... | 5,327,533 |
def update_position(request, space_url):
"""
This view saves the new note position in the debate board. Instead of
reloading all the note form with all the data, we use the partial form
"UpdateNotePosition" which only handles the column and row of the note.
"""
place = get_object_or_404(Space, ... | 5,327,534 |
def main(X_train_path, X_test_path, y_train_path, y_test_path):
"""
Transforms train data and performs evaluation of multiple models with selecting one model with the best scores
Parameters:
----------
X_train_path : path for csv file with X_train data
X_test_path : path for csv file with X_tes... | 5,327,535 |
def _initialized( ):
"""
初期化
"""
ts = bpy.types.Scene
ts.temp_align_objects_object = bpy.props.PointerProperty(name="Target Object", description="Target Object", type=bpy.types.Object)
ts.temp_align_objects_object_subtarget = bpy.props.StringProperty(name="Target Object's Sub Target", descr... | 5,327,536 |
def LOG_WARN_NOPUSH( msg ):
"""
Log a warning, don't push it to the list of warnings to be echoed at the end of compilation.
:param msg: Text to log
:type msg: str
"""
LOG_MSG( terminfo.TermColor.YELLOW, "WARN", msg, 3 ) | 5,327,537 |
def tan(x):
"""Return the tangent of *x* radians."""
return 0.0 | 5,327,538 |
def init_wandb(cfg) -> None:
"""
Initialize project on Weights & Biases
Args:
cfg (Dict) : Configuration file
"""
wandb.init(
name=cfg["LOGGING"]["NAME"],
config=cfg,
project=cfg["LOGGING"]["PROJECT"],
resume="allow",
id=cfg["LOGGING"]["ID... | 5,327,539 |
def entropy(p):
""" Calculates the Shannon entropy for a marginal distribution.
Args:
p (np.ndarray): the marginal distribution.
Returns:
(float): the entropy of p
"""
# Since zeros do not contribute to the Shannon entropy by definition, we
# ignore them t... | 5,327,540 |
def test_sens_dc():
"""Sensitivity analysis axes (DC)."""
solutions = run(
dedent_multiline(
"""
Test simulation
R1 n1 0 1k
V1 n1 0 DC 1
.sens V(n1, n2)
.end
"""
)
)
assert list(solutions.keys()) == ["sen... | 5,327,541 |
def format_to_str(*a, **kwargs):
""" Formats gotten objects to str. """
result = ""
if kwargs == {}:
kwargs = {'keepNewlines': True}
for x in range(0, len(a)):
tempItem = a[x]
if type(tempItem) is str:
result += tempItem
elif type(tempItem) in [list, dict, tup... | 5,327,542 |
def get_all_files_in_tree_with_regex(basedir: str, regex_str: str) -> List[str]:
"""
Returns a list of paths such that each path is to a file with
the provided suffix. Walks the entire tree of basedir.
"""
r = re.compile(regex_str)
data_files = []
for root, dirs, files in os.walk(basedir):
... | 5,327,543 |
def zero_corrected_countless(data):
"""
Vectorized implementation of downsampling a 2D
image by 2 on each side using the COUNTLESS algorithm.
data is a 2D numpy array with even dimensions.
"""
# allows us to prevent losing 1/2 a bit of information
# at the top end by using a bigger type. Wi... | 5,327,544 |
def test_bidirectionallstm(backend: Backend):
"""Test forward rewrite of bidirectionallstm."""
check_backend(backend)
bilstm = get_bidirectionallstm_model()
bilstm.cpu().eval()
deploy_cfg = mmcv.Config(
dict(
backend_config=dict(type=backend.value),
onnx_config=dict(... | 5,327,545 |
def update_custom_field(dev_name, os_version):
"""
Update a custom field in NetBox
"""
# Connect to NetBox environment
# Disable warnings for self-signed certs if using HTTPS with NetBox
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
session = requests.Session()
se... | 5,327,546 |
def mnn_synthetic_data(
n_samples: int = 1000,
n_features: int = 100,
n_batches: int = 2,
n_latent: int = 2,
n_classes: int = 3,
proportions: np.ndarray = None,
sparsity: float = 1.0,
scale: Union[int, float] = 5,
batch_scale: float = 0.1,
bio_batch_angle: Union[float, None] = No... | 5,327,547 |
def then_response(result, response_json: dict):
""" Check entire response """
if response_json is not None:
print('actual:\n{}'.format(json.dumps(result['response'].json(), indent=4)))
print('expected:\n{}'.format(json.dumps(response_json, indent=4)))
assert result['response'].json() == ... | 5,327,548 |
def send_command(rtr2, cmd):
"""
take the cmd and print output
"""
rtr2.send(cmd)
time.sleep(2)
output = rtr2.recv(MAX_BUFFER)
print output | 5,327,549 |
def create_labeled_pair(img, gt_center, prop_center, gt_radius, scale):
"""
Given a crater proposal and ground truth label,
this function creates a labeled pair.
Returns X, Y, where X is an image, and Y is a set of ground truths.
img: an array
gt_center: the known ground-truth center point (x, y... | 5,327,550 |
def loader_to_dask(loader_array):
"""
Map a call to `dask.array.from_array` onto all the elements in ``loader_array``.
This is done so that an explicit ``meta=`` argument can be provided to
prevent loading data from disk.
"""
if len(loader_array.shape) != 1:
raise ValueError("Can only ... | 5,327,551 |
def list_to_sentences(string):
""" Splits text at newlines and puts it back together after stripping new-
lines and enumeration symbols, joined by a period.
"""
if string is None:
return None
lines = string.splitlines()
curr = ''
processed = []
for line in lines:
stripped = line.strip()
# empty line
... | 5,327,552 |
def decode_locations_one_layer(anchors_one_layer, offset_bboxes):
"""decode the offset bboxes into center bboxes
Args:
anchors_one_layer: ndarray represents all anchors coordinate in one layer,
encode by [y,x,h,w]
offset_bboxes: A tensor with any shape ,the shape of l... | 5,327,553 |
def test_select_subset():
"""Test SelectSubset widget events."""
src_items = ["one", "two", "three"]
sel_subs = nbw.SelectSubset(source_items=src_items, default_selected=["one"])
check.equal(sel_subs._select_list.options, ("one",))
sel_subs._w_filter.value = "t"
for item in sel_subs._source_lis... | 5,327,554 |
def FormatReserved(enum_or_msg_proto):
"""Format reserved values/names in a [Enum]DescriptorProto.
Args:
enum_or_msg_proto: [Enum]DescriptorProto message.
Returns:
Formatted enum_or_msg_proto as a string.
"""
reserved_fields = FormatBlock('reserved %s;\n' % ','.join(
map(str, sum([list(range(r... | 5,327,555 |
def upgrade_input_dir(inputs_dir):
"""
Upgrade an input directory.
"""
def rename_file(old_name, new_name, optional_file=True):
old_path = os.path.join(inputs_dir, old_name)
new_path = os.path.join(inputs_dir, new_name)
if optional_file and not os.path.isfile(old_path):
... | 5,327,556 |
def test_install_package_with_root():
"""
Test installing a package using pip install --root
"""
env = reset_env()
root_dir = env.scratch_path/'root'
result = run_pip('install', '--root', root_dir, '-f', find_links, '--no-index', 'simple==1.0')
normal_install_path = env.root_path / env.site_... | 5,327,557 |
def download_pepper(load=True): # pragma: no cover
"""Download scan of a pepper (capsicum).
Originally obtained from Laser Design.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be ... | 5,327,558 |
def getAllSerial():
"""get all device serials found by command adb devices"""
_, msgs = shell_command("adb devices")
devices = [line for line in msgs if "\tdevice\n" in line]
serials = sorted([dev.split()[0] for dev in devices], key=len)
return serials | 5,327,559 |
def generate_labgraph_monitor(graph: lg.Graph) -> None:
"""
A function that serialize the graph topology
and send it using to LabGraphMonitor Front-End
using Labgraph Websocket API
@params:
graph: An instance of the computational graph
"""
# Local variables
nodes: List[LabgraphM... | 5,327,560 |
def create_directory(list_path_proj: list, dir_name: str):
"""
:return:
Directory created at
c:\\users\\$Env:USER\\projects\\automate-ssas-build\\examples/bi-project_name-olap/queries/
c:\\users\\$Env:USER\\projects\\automate-ssas-build\\examples/bi-two-olap/queries/
"""
list_path_proj_with_... | 5,327,561 |
def plot_points(points):
"""Generate a plot with a varying number of randomly generated points
Args:
points (int): a number of points to plot
Returns: An svg plot with <points> data points
"""
# data for plotting
data = np.random
data = np.random.rand(points, 2)
fig = Figure()
... | 5,327,562 |
def bisect_status():
"""Reproduce the status line git-bisect prints after each step."""
return "Bisecting: {} revisions left to test after this (roughly {} steps).".format(
ceil((bisect_revisions() - 1) / 2), bisect_steps_remaining() - 1,
) | 5,327,563 |
def echo_view():
"""Call echo() with the Flask request."""
return echo(flask.request) | 5,327,564 |
def read_bytes_offset_file(f,n_bytes,v=0):
"""
Used to skip some offset when reading a binary file.
Parameters
----------
f : file handler
(sys.stdin).
n_words : int
number of words of type TYPE_WORD.
v : int
[0 by default] verbose mode if 1.
"""
wo... | 5,327,565 |
def person_relationship_dates(node):
"""Find the nearest start/end dates related to a node's person."""
person = node.people.single()
rel = node.people.relationship(person)
if rel.start_date is not None:
return {'start_date': rel.start_date, 'end_date': rel.end_date}
elif rel.start_date is N... | 5,327,566 |
def oops():
"""Lazy way to return an oops reponse."""
return make_response('oops', 400) | 5,327,567 |
def test_single_missing_atom_line_invalid_atom_indices(
single_missing_atom_line_v3000_sdf: Pathy,
) -> None:
"""An sdf block with a missing atom line has invalid indices.
That means that the number of atoms is fewer than the counts line.
Args:
single_missing_atom_line_v3000_sdf: pytest fixtur... | 5,327,568 |
def test_nested_cache(session):
"""Tests whether the sample pulled."""
browser = Browser(session)
browser.use_cache = True
st_from_session = session.SampleType.find(1)
sample_from_session = st_from_session.samples[0]
sample = browser.find(sample_from_session.id, "Sample")
st = browser.find... | 5,327,569 |
def get_lowest_energy_conformer(
name,
mol,
gfn_exec=None,
settings=None,
):
"""
Get lowest energy conformer of molecule.
Method:
1) ETKDG conformer search on molecule
2) xTB `normal` optimisation of each conformer
3) xTB `opt_level` optimisation of lowest energy con... | 5,327,570 |
def apply_settings(app, settings):
"""
From a dict of settings, save them locally and set up any necessary child systems from those settings
:param app: aiohttp Application to add settings to
:param settings: Dict of settings data
"""
settings["base_path"] = pathlib.Path(settings["base_path"... | 5,327,571 |
def set_deal_products(deal_id, payload, product_list):
"""
Устанавливает (создаёт или обновляет) товарные позиции сделки;
из руководства Битрикс24: товарные позиции сделки, существующие
до момента вызова метода crm.deal.productrows.set, будут заменены
новыми.
returns : None
rtype : None
... | 5,327,572 |
def dictize_params(params):
"""
Parse parameters into a normal dictionary
"""
param_dict = dict()
for key, value in params.iteritems():
param_dict[key] = value
return param_dict | 5,327,573 |
def dot(x, y, sparse=False):
"""Wrapper for tf.matmul (sparse vs dense)."""
if sparse:
res = tf.sparse_tensor_dense_matmul(x, y)
else:
res = tf.matmul(x, y)
return res | 5,327,574 |
def test_Archive_get_status_code(db, client, oauth2):
"""Test the Archive's get method with error on Archivematica."""
sip = SIP.create()
ark = Archive.create(sip=sip, accession_id='id',
archivematica_id=uuid.uuid4())
ark.status = ArchiveStatus.WAITING
db.session.commit()
... | 5,327,575 |
def get_python3_status(classifiers):
"""
Search through list of classifiers for a Python 3 classifier.
"""
status = False
for classifier in classifiers:
if classifier.find('Programming Language :: Python :: 3') == 0:
status = True
return status | 5,327,576 |
def drawBeta(s, w, size=1):
"""Draw beta from its distribution (Eq.9 Rasmussen 2000) using ARS
Make it robust with an expanding range in case of failure"""
#nd = w.shape[0] 用于多维数据
lb = 0.0
flag = True
cnt = 0
while flag:
xi = lb + np.logspace(-3 - cnt, 1 + cnt, 200) # update range i... | 5,327,577 |
def get_unique_map_to_pullback(p, p_a, p_b, z_a, z_b):
"""Find a unique map to pullback."""
z_p = dict()
for value in p:
z_keys_from_a = set()
if value in p_a.keys():
a_value = p_a[value]
z_keys_from_a = set(keys_by_value(z_a, a_value))
z_keys_from_b = set()
... | 5,327,578 |
def f1_score(
pred: torch.Tensor,
target: torch.Tensor,
num_classes: Optional[int] = None,
class_reduction: str = 'micro',
) -> torch.Tensor:
"""
Computes the F1-score (a.k.a F-measure), which is the harmonic mean of the precision and recall.
It ranges between 1 and 0, where ... | 5,327,579 |
def PyramidPoolingModule(inputs, feature_map_shape):
"""
Build the Pyramid Pooling Module.
"""
interp_block1 = InterpBlock(inputs, 1, feature_map_shape)
interp_block2 = InterpBlock(inputs, 2, feature_map_shape)
interp_block3 = InterpBlock(inputs, 3, feature_map_shape)
interp_block6 = Interp... | 5,327,580 |
def order(ord):
"""
`order` is decorator to order the pipeline classes. This decorator specifies a property named "order" to the member function so that we can use the property to order the member functions.
This `order` function can be combined with the decorator `with_transforms` which orders the member ... | 5,327,581 |
def single_node_test(ctx, config):
"""
- ceph-deploy.single_node_test: null
#rhbuild testing
- ceph-deploy.single_node_test:
rhbuild: 1.2.3
"""
log.info("Testing ceph-deploy on single node")
if config is None:
config = {}
overrides = ctx.config.get('overrides', {})
... | 5,327,582 |
def collisionIndicator(egoPose, egoPoly, objPose, objPoly):
"""
Indicator function for collision between ego vehicle and moving object
Param:
egoPose: ego vehicle
objPose: pose of object
Return:
col_indicator: (float) collision indicator between two object
"""
dMean = np.... | 5,327,583 |
def test_version_dataset(temp_config, dataset_name, dataset_version, dataset_metadata, entity):
"""
GIVEN: A mocked dataset folder to track, a dataset version to track, metadata to track, and a backend to use
WHEN: This dataset is registered or versioned on W&B
THEN: The dataset shows up as a run on the... | 5,327,584 |
def lookup_listener(param):
"""
Flags a method as a @lookup_listener. This method will be updated on the changes to the lookup. The lookup changes
when values are registered in the lookup or during service activation.
@param param: function being attached to
@return:
"""
def decor(func):
... | 5,327,585 |
async def read_multi_analog_inputs(app, addr):
"""
Execute a single request using `ReadPropertyMultipleRequest`.
This will read the first 40 analog input values from the remote device.
:param app: An app instance
:param addr: The network address of the remote device
:return:
"""
read_acc... | 5,327,586 |
def lookupBlock(blockName):
""" Look up block name string in name list
data value (e.g. color) override may be appended to the end
e.g. stained_hardened_clay_10
Note: block name lookup is case insensitive
"""
blockName = blockName.upper()
try:
try:
na... | 5,327,587 |
def deploy_on_host(shell, migrate, collectstatic, dependencies, deploy_django, deploy_react, django_branch,
react_branch, meta=dict()):
"""
Args:
shell: Connection object to connect to the shell.
migrate: bool. Weather migration have to be done or not.
collectstatic: b... | 5,327,588 |
def factorize(values, sort=False, na_sentinel=-1, size_hint=None):
"""Encode the input values as integer labels
Parameters
----------
values: Series, Index, or CuPy array
The data to be factorized.
na_sentinel : number, default -1
Value to indicate missing category.
Returns
... | 5,327,589 |
def make_proc(code, variables, path, *, use_async=False): # pylint: disable=redefined-builtin
"""Compile this code block to a procedure.
Args:
code: the code block to execute. Text, will be indented.
vars: variable names to pass into the code
path: the location where the code is stored... | 5,327,590 |
def ratings_std(df):
"""calculate standard deviation of ratings from the given dataframe
parameters
----------
df (pandas dataframe): a dataframe cotanis all ratings
Returns
-------
standard deviation(float): standard deviation of ratings, keep 4 decimal
"""
std_value = df['ratings... | 5,327,591 |
def save(objct, fileoutput, binary=True):
"""
Save 3D object to file. (same as `write()`).
Possile extensions are:
- vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, vti, mhd, png, bmp.
"""
return write(objct, fileoutput, binary) | 5,327,592 |
def read_pfm(fname):
"""
Load a pfm file as a numpy array
Args:
fname: path to the file to be loaded
Returns:
content of the file as a numpy array
"""
file = open(fname, 'rb')
color = None
width = None
height = None
scale = None
endian = None
header = fi... | 5,327,593 |
def broaden_spectrum(spect, sigma):
"""
Broadens a peak defined in spect by the sigma factor and
returns the x and y data to plot.
Args:
----
spect (np.ndarray) -- input array containing the peak info for
the individual peak to be broadened.
sigma (float) -- gaussian... | 5,327,594 |
def mv_audio(serial_id, audio_setting):
"""
This function will change the audio recording settings to {audio_setting} in the meraki dashboard for the mv camera
with the {serial_id}
:param: serial_id: the serial id for the meraki mv camera
:param: audio_setting: 'true' to turn on audio recording, 'fa... | 5,327,595 |
def lsp_text_edits(changed_file: ChangedFile) -> List[TextEdit]:
"""Take a jedi `ChangedFile` and convert to list of text edits.
Handles inserts, replaces, and deletions within a text file
"""
old_code = (
changed_file._module_node.get_code() # pylint: disable=protected-access
)
new_co... | 5,327,596 |
def _hash(file_name, hash_function=hashlib.sha256):
"""compute hash of file `file_name`"""
with open(file_name, 'rb') as file_:
return hash_function(file_.read()).hexdigest() | 5,327,597 |
def prepare_cmf(observer='1931_2deg'):
"""Safely returns the color matching function dictionary for the specified observer.
Parameters
----------
observer : `str`, {'1931_2deg', '1964_10deg'}
the observer to return
Returns
-------
`dict`
cmf dict
Raises
------
... | 5,327,598 |
def plotAssemblyTypes(
blueprints,
coreName,
assems=None,
plotNumber=1,
maxAssems=None,
showBlockAxMesh=True,
):
"""
Generate a plot showing the axial block and enrichment distributions of each assembly type in the core.
Parameters
----------
bluepprints: Blueprints
... | 5,327,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.