content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _create_issue_body(command: str) -> str:
"""Generate a Github issue body based on given exception and command.
Args:
command: The command causing the exception to get thrown,
e.g. 'django-cloud-deploy new'.
Returns:
Github issue body in string.
"""
template_env = ji... | 5,311,700 |
def saturated_vapour_pressure_inst(t_air_i):
"""Like :func:`saturated_vapour_pressure` but as an instantaneous value
Parameters
----------
t_air_i : float
instantaneous air temperature
:math:`T_{a,i}`
[C]
Returns
-------
svp_i : float
instantaneous saturated... | 5,311,701 |
def test_read_nonexisting_xmlfile_novalidator():
"""
Test reading an xml file from not available path without
storing the results from the validation process
"""
# Setup
the_xml_filename = "aecg/data/nonexisting.xml"
the_zip_container = ""
aecg_schema_filename = "aecg/data/hl7/2003-12 Sc... | 5,311,702 |
def main():
"""
This application creates and starts the server for both the RPC routes
handled by opentrons.server.rpc and HTTP endpoints defined here
"""
log_init()
arg_parser = ArgumentParser(
description="Opentrons application server",
prog="opentrons.server.main"
)
a... | 5,311,703 |
def histogram_degree(file, dmin, dmax):
"""
Renvoie l'histgramme du nombre de protéine de certains degré suivant des bornes indiquées
:param file: tableau contenant un graphe
:type file: dataframe
:param dmin: degré minimal
:type dmin: int
:param dmax: degré maximal
:type dmax: int
:... | 5,311,704 |
def format_timestamp_range(
timestamp_range: Tuple[int, int],
timestamp_unit: Optional[str],
timestamp_format: Optional[str]
) -> str:
"""
Format a time range with unit.
:param timestamp_range: range of timestamps
:param timestamp_unit: timestamp unit, can be: formatted_timestam... | 5,311,705 |
def make_eeg_average_ref_proj(info, activate=True, verbose=None):
"""Create an EEG average reference SSP projection vector
Parameters
----------
info : dict
Measurement info.
activate : bool
If True projections are activated.
verbose : bool, str, int, or None
If not None... | 5,311,706 |
def generate_degree2_invariants_from_different(coeffs1, coeffs2):
"""
Generate degree 2 invariants from density projection coefficients.
Parameters
----------
coeffs1 : array[num_envs, num_species, nmax1, (lmax+1)**2]
Density projection coefficients. This could include the spherical
... | 5,311,707 |
def ts_css(text):
"""applies nice css to the type string"""
return '<span class="ts">%s</span>' % text | 5,311,708 |
def PG(Date, Radiosonde_Flight_Num, LaunchTime, Window=1):
"""Plots the potential gradient from the RUAO +- 1 hour around launch time.
Parameters
----------
Date : datetime object
The datetime you want to start collecting the data from. Should have the format
datetime(%Y, %m, %d, %H) where %H can be either 0... | 5,311,709 |
def noop(val: typing.Any, *_args, **_kwargs) -> typing.Any:
"""A function does nothing.
>>> noop(1)
1
"""
return val | 5,311,710 |
def consolidate_mouse_probes(data_containers, filename_or_fileobj, object_name='mouse_data_frame', poobah_column='poobah_pval', poobah_sig=0.05):
""" ILLUMINA_MOUSE specific probes (starting with 'rp' for repeat sequence or 'mu' for murine)
stored as data_container.mouse_data_frame.
saves as a dataframe ju... | 5,311,711 |
def method_detect(method: str):
"""Detects which method to use and returns its object"""
if method in POSTPROCESS_METHODS:
if method == "rtb-bnb":
return RemovingTooTransparentBordersHardAndBlurringHardBorders()
elif method == "rtb-bnb2":
return RemovingTooTransparentBord... | 5,311,712 |
def normalized_difference():
"""
Returns class instance of `NormalizedDifference`.
For more details, please have a look at the implementations inside `NormalizedDifference`.
Returns
-------
NormalizedDifference :
Class instance implementing all 'normalized_difference' processes.
""... | 5,311,713 |
def detect_event_no_plot(VLMuscle, VRMuscle, Time, Threshold):
"""
This function calculates the start, end and duration of swimming episode, as defined by a threshold.
Does not plot the result
:param VLMuscle: list or 1-D numpy array
:param VRMuscle: list or 1-D numpy array
:param Time: list or... | 5,311,714 |
def test_rock():
"""Test module rock.py by downloading
rock.csv and testing shape of
extracted data has 48 rows and 4 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = rock(test_path)
try:
assert x_train.shape == (48, 4)
except:
shutil.rmtree(test_path)
raise() | 5,311,715 |
def build_dgl_graph_v15(nodes, edges, sent_nodes):
"""
Build DGL homogeneous graph based on New Graph structure.
1112: checked graph through visualisation
1116: qo_node feature: [-10, opt id]
1201: hotpotQA, store node separately and combine
"""
# split entity nodes and q_opt nodes
entit... | 5,311,716 |
def get_large_rand_ary_tfrecord(n_samples=100000, n_features=2000, dtype=np.float32):
"""
Args:
n_samples (int)
n_features (int)
Returns:
str: tfrecord data folder for training
str: tfrecord data path for prediction (finally generating embedding)
dict: {}
"""
X = get_rand_ary(n_samples, n_features... | 5,311,717 |
def entropy_bubble(signal, delay=1, dimension=3, alpha=2, **kwargs):
"""**Bubble Entropy (BubblEn)**
Introduced by Manis et al. (2017) with the goal of being independent of parameters such as
*Tolerance* and *Dimension*. Bubble Entropy is based on :func:`permutation entropy <entropy_permutation>`,
but ... | 5,311,718 |
def test_get_nonexistent_dataset():
"""Unit test for trying to fetch a nonexistent dataset"""
response = client.get(f"{PREFIX}/datasets/daflkadsjflkajdflkadfadadfadsfad")
assert response.status_code == 404 | 5,311,719 |
async def test_flow_import_single_instance_allowed(hass: HomeAssistant) -> None:
"""Test import step single instance allowed."""
entry = MockConfigEntry(domain=DOMAIN, data=CONF_DATA)
entry.add_to_hass(hass)
with patch_config_flow_tautulli(AsyncMock()):
result = await hass.config_entries.flow.a... | 5,311,720 |
def delete_transform_from_nodes(nodes):
""" Deletes the dag object transform node found from the given nodes
:param shape: nodes names
:type shape: list
"""
for node in nodes:
try:
shape = [x for x in cmds.listHistory(node, future=True)
if x not in cmds.lis... | 5,311,721 |
def open_set(dataset_class: ClassVar, public_classes: Sequence[str],
private_classes: Optional[Sequence[str]] = ()) -> ClassVar:
"""
Convert a dataset into its open-set version.
In other words, those samples which doesn't belong to `private_classes` will be marked as "unknown".
Be aware th... | 5,311,722 |
def generate_random_string(length,
using_digits=False,
using_ascii_letters=False,
using_punctuation=False):
"""
Example:
opting out for 50 symbol-long, [a-z][A-Z][0-9] string
would yield log_2((26+26+50)^50) ~= 334 ... | 5,311,723 |
def get_blocking_times_of_all_states_using_direct_approach(
lambda_1, mu, num_of_servers, threshold, system_capacity, buffer_capacity
):
"""Solve M*X = b using numpy.linalg.solve() where:
M = The array containing the coefficients of all b(u,v) equations
b = Vector of constants of equations
... | 5,311,724 |
def create_read_only_text(title: str, example: str, value: str, layout: QLayout) -> QLineEdit:
"""
Creates and returns a read-only one-line text widget (QLineEdit)
with the given title, example contents and value in the given layout.
"""
widget = create_text(title, example, value, layout)
widget... | 5,311,725 |
def find_lane_pixels_around_poly(binary_warped, left_fit, right_fit, margin = 100):
"""
Returns the pixel coordinates contained within a margin from left and right polynomial fits.
Left and right fits shoud be from the previous frame.
PARAMETER
* margin: width around the polynomial fit
"""
#... | 5,311,726 |
def log_softmax_v2(logits, axis=None, name=None):
"""Computes log softmax activations.
For each batch `i` and class `j` we have
logsoftmax = logits - log(reduce_sum(exp(logits), axis))
Args:
logits: A non-empty `Tensor`. Must be one of the following types: `half`,
`float32`, `float64`.
axis... | 5,311,727 |
def start_nsfocus_loophole_spider():
"""
爬取freebuf漏洞
:return:
"""
os.system("scrapy crawl nsfocus_loophole_spider -s JSONFILE_BASEDIR=D:/data/mmscrapy/nsfocus") | 5,311,728 |
def graphs_tuple_to_broadcasted_sharded_graphs_tuple(
graphs_tuple: jraph.GraphsTuple,
num_shards: int) -> ShardedEdgesGraphsTuple:
"""Converts a `GraphsTuple` to a `ShardedEdgesGraphsTuple` to use with `pmap`.
For a given number of shards this will compute device-local edge and graph
attributes, and add... | 5,311,729 |
def apply_reflection(reflection_name, coordinate):
"""
Given a reflection type and a canonical coordinate, applies the reflection
and describes a circuit which enacts the reflection + a global phase shift.
"""
reflection_scalars, reflection_phase_shift, source_reflection_gates = reflection_options[
... | 5,311,730 |
def _get_vcpus_from_pricing_file(instance_type):
"""
Read pricing file and get number of vcpus for the given instance type.
:param instance_type: the instance type to search for.
:return: the number of vcpus or -1 if the instance type cannot be found
"""
with open(pricing_file) as f:
in... | 5,311,731 |
def route_from_text(obj, route):
"""
Recursive function to look for the requested object
:param obj:
:param route:
:return:
"""
_LOG.debug(f'Looking for {route} in {obj}')
if len(route) > 1 and ':' in route[0]:
_LOG.debug('Is a dictionary nested inside a list')
res = [d f... | 5,311,732 |
def rot_mol(rot, struct, wrt="origin", degrees=True, seq="xyz"):
"""
Rotate molecule using rotation matrix.
Arguments
---------
rot: array
Can be either a list of 3 euler angles in the given order or a 3,3
rotation matrix.
wrt: str
Rotation performed with respect... | 5,311,733 |
def list_tags_for_resource(ResourceArn=None):
"""
Gets the set of key-value pairs (metadata) that are used to manage the resource.
See also: AWS API Documentation
Exceptions
:example: response = client.list_tags_for_resource(
ResourceArn='string'
)
:type ResourceA... | 5,311,734 |
async def _send_multipart(data: Dict[str, str], boundary: str,
headers: HeadersType,
chunk_size: int = _CHUNK_SIZE) -> bytes:
"""Send multipart data by streaming."""
# TODO: precalculate body size and stream request, precalculate file sizes by os.path.getsize
... | 5,311,735 |
def fit_naive_bayes_model(matrix, labels):
"""Fit a naive bayes model.
This function should fit a Naive Bayes model given a training matrix and labels.
The function should return the state of that model.
Feel free to use whatever datatype you wish for the state of the model.
Args:
matrix... | 5,311,736 |
def get_checkBox_entry(checkBox: etree._Element) -> str:
"""Create text representation for a checkBox element.
:param checkBox: a checkBox xml element
:returns:
1. attempt to get ``checked.w:val`` and return "\u2610" or "\u2612"
2. attempt to get ``default.w:val`` and return "\u2610" or "\u... | 5,311,737 |
def test_read_json_param_and_implement_reform(reform_file, set_year):
"""
Test reading and translation of reform file into a reform dictionary
that is then used to call implement_reform method.
NOTE: implement_reform called when policy.current_year == policy.start_year
"""
policy = Policy()
... | 5,311,738 |
def assert_lamson_settings(func):
"""Used to make sure that the func has been setup by a routing decorator."""
assert has_lamson_settings(func), "Function %s has not be setup with a @route first." % func.__name__ | 5,311,739 |
def use_scratch_dir(original_wf, scratch_dir):
"""
For all RunVaspCustodian tasks, add the desired scratch dir.
Args:
original_wf (Workflow)
scratch_dir (path): Path to the scratch dir to use. Supports env_chk
Returns:
Workflow
"""
for idx_fw, idx_t in get_fws_and_tasks(... | 5,311,740 |
def Regression_plot(df,column=''):
"""Regression plot: with pearsonr correlation value """
cor = round(df[['SalePrice',column]].corr().iloc[0,1], 3)
sns.jointplot(x= df[column], y = df['SalePrice'], kind= 'reg',
label = 'r: '+str(cor),color='blue')
plt.legend()
#plt.title('Regressi... | 5,311,741 |
def infer_tests_wrapper(
weight_path: str, model_name: str, dataset: COCO_Dataset, test_name: str,
handler_constructor: type,
data_dump_dir: str=None, video_dump_dir: str=None, img_dump_dir: str=None,
skip_if_data_dump_exists: bool=False,
show_preview: bool=False,
show_pbar: bool=True
):
"""... | 5,311,742 |
def auto_peak_finder(prominence, x_data, y_data):
"""
automatic peak finding routine which finds peaks given a user supplied prominence, and presents the peaks until user
is happy
:param prominence: height from noise to tip of peaks
:param x_data: x_data as np array
:param y_data: y_data a... | 5,311,743 |
def dataframe_reg_as_panel(df,against='index',regfunc='OLS'):
"""
Perform regression for each of the columns of the dataframe, and return
the regression result as panel.
Parameters:
-----------
against: the variable used as the independent variable in the regression,
default is the ... | 5,311,744 |
def serve_pyr(name, url, root_path, config='config.ini'):
"""Serve the Pyramid app locally in a separate thread that forks a
subprocess that invokes the pserve executable. Return a function that stops
serving the Pyramid app.
"""
process = _fork_server_process(url, root_path, config=config)
thre... | 5,311,745 |
def order_line_needs_automatic_fulfillment(line_data: OrderLineInfo) -> bool:
"""Check if given line is digital and should be automatically fulfilled."""
digital_content_settings = get_default_digital_content_settings()
default_automatic_fulfillment = digital_content_settings["automatic_fulfillment"]
co... | 5,311,746 |
def docker_setup(project_path: str) -> bool:
""" Tries to find evidence of a docker setup in the project. """
_file_names = ['[Dd]ockerfile', '[Dd]ocker-compose.yml']
for name in _file_names:
_findings = search_filename(
base_folder=project_path,
file_name=name,
... | 5,311,747 |
def prac_q_count(year, month, day, hour, qtemplate):
""" Fetch the practice count for the given time/qtemplate or return
False if not found. Can be used when deciding if to INSERT or UPDATE.
Note: may return 0 if count is zero, is not same as not exist (False)
"""
sql = """SELECT "qtemplate"... | 5,311,748 |
def do_graph(clustering,num_elems_of_traj_2,std_deviations,filename):
"""
"""
graph = digraph()
labels = populate_nodes_with_labels(clustering, num_elems_of_traj_2,std_deviations, graph)
prob_matrix = calculate_probability_matrix(clustering)
add_graph_edges(graph,labels,clustering,prob_matrix)
... | 5,311,749 |
def get_headers(gargs):
"""Get the required headers. """
headers = {
'Content-type': 'application/json'
}
if gargs.no_passwd:
return headers
if gargs.passwdfile is not None:
passwd = open(gargs.passwdfile, "r").read().strip()
auth_str = "%s:%s" % (gargs.user, passwd... | 5,311,750 |
def CSVLogRead(CSVFile):
"""Esta funcao lee o Log da imagem"""
global UserNameTypeList
UserNameTypeList = []
if os.path.exists(ActImagesFolder + '/' + LogFolder) == False:
os.mkdir(ActImagesFolder + '/' + LogFolder)
if os.path.isfile(CSVFile) == True:
with open(CSVFile, 'rb') as f... | 5,311,751 |
def highest_prob_class(y_predicted: torch.Tensor, y_true: torch.Tensor, **kwargs) -> _TensorOrTensors:
"""
Get the index of class with highest probability.
"""
y_predicted = y_predicted.max(dim=-1)[1]
assert y_true.shape == y_predicted.shape
return y_predicted, y_true | 5,311,752 |
def vectorized_local_axes(three_atoms_coords):
"""
Takes as an argument a Nx3x3 block of reference atom coordinates to construct N local axes systems (Nx3x3)
"""
u12 = vectorized_unit_vector(three_atoms_coords[:, [0,1], :])
u23 = vectorized_unit_vector(three_atoms_coords[:, [1,2], :])
if np.any(... | 5,311,753 |
def _makedirs_recursive(path, mode):
"""Recursive part of makedirs. Calls itself to ensure head
of path exists, and then makes a new directory at path. Returns
an Exception if it can't make a directory at path."""
if os.path.isdir(path): return
head, tail = os.path.split(path)
if not tail:
head, tail = os.path.... | 5,311,754 |
def set_option(option, value):
"""Set a single option using the flat format, i.e ``section.option``
Parameters
----------
option: str
Option name in the ``section.option`` format
value:
Value to set
Example
-------
.. ipython:: python
@suppress
from xoa... | 5,311,755 |
def dict_to_capabilities(caps_dict):
"""Convert a dictionary into a string with the capabilities syntax."""
return ','.join("%s:%s" % tpl for tpl in caps_dict.items()) | 5,311,756 |
async def reverse_all_ips_in_range(iprange: str, callback: Callable, nameservers: Optional[List[str]] = None) -> None:
"""
Reverse all the IPs stored in a network range.
All the queries are made concurrently.
Parameters
----------
iprange: str.
An IPv4 range formated as 'x.x.x.x/y'.
... | 5,311,757 |
def delta(flag, F, K, t, r, sigma):
"""Returns the Black delta of an option.
:param flag: 'c' or 'p' for call or put.
:type flag: str
:param F: underlying futures price
:type F: float
:param K: strike price
:type K: float
:param t: time to expiration in years
:type t: floa... | 5,311,758 |
def main(X, Y, X0, Y0, depth, omegaX, omegaY, omegaZ, ax, ay, az, opening, nu, verbose=False):
"""
Test CDM with test input parameters
X0, Y0, depth: define the position of the dislocation
omegaX, omegaY, omegaZ: define the orientation (clockwise rotations) of the dislocation
ax, ay, az: define the ... | 5,311,759 |
def snapshot_cmd(jail, name):
"""Get a list of jails and print the property."""
lgr = logging.getLogger('ioc_cli_snapshot')
jails, paths = IOCList("uuid").list_datasets()
pool = IOCJson().json_get_value("pool")
date = datetime.utcnow().strftime("%F_%T")
_jail = {tag: uuid for (tag, uuid) in ja... | 5,311,760 |
def extend_view(response, fetch_page_data, fetch_multimedia, raise_errors):
"""
Extends view query results with pronunciation URLs, multimedia URLs, and extended hanja
information by scraping the dictionary website.
This function modifies the response in-place, and returns the modified object.
See ... | 5,311,761 |
def mean(vector):
"""
Calculates the arithmetic mean of the given vector.
Args:
-----
vector : list
A non-empty list/array of numbers to be averaged.
Returns:
--------
mean : float
The arithmetic mean of the given vector.
"""
return sum(vector) /... | 5,311,762 |
def main():
"""
Composes a BLAST command from a (DataTable) AJAX request, forwarded from
molmod endpoint /blast_run, and executes the command using subprocess.
"""
#
# Format the BLAST command - return an error if the input form is missing
# required values.
#
try:
form = r... | 5,311,763 |
def get_hamming_window(w, h, rot, sx, sy, out_size_w, out_size_h):
"""
A hamming window map
:param w: init ellipse w
:param h: init ellipse h
:param rot: rotation angle(rad)
:param sx: center x coordinate of the window
:param sy: center y-coordinate of the window
:param out_size_w: outpu... | 5,311,764 |
def IsStrip(topology): # real signature unknown; restored from __doc__
"""
IsStrip(topology)
Check whether or not this is a strip-type topology.
:param Topology t: The topology to check.
:return: ``True`` if it describes a strip topology, ``False`` for a list.
:rtype: ``bool``
"""
... | 5,311,765 |
def main(
context, subject, debug, no_colors, repo,
dolist, update, min_score, search_score):
"""
Eh is a terminal program that will provide you with
quick reminders about a subject.
To get started run: eh help
To figure out what eh knows about run: eh list
To update the list ... | 5,311,766 |
def reconstructimage(lpyramid, f):
""" Reconstruct image from Laplacian pyramid
Args:
lpyramid: Laplacian pyramid
f: 2d filter kernel
Returns:
Reconstructed image as (H, W) np.array clipped to [0, 1]
"""
#
# You code here
#
lpyramid_flip = np.flip(lpyramid)
g... | 5,311,767 |
def parse_findings(output_file, scanner):
""" Parse findings (code from dusty 1.0) """
log.debug("Parsing findings")
nscan = parse(output_file)
root = nscan.getroot()
# Check validity
if "nmaprun" not in root.tag:
log.error("Exception during Nmap findings processing: invalid XML file")
... | 5,311,768 |
def convert_to_pressure_levels(mv, plevs, dataset, var, season):
"""
Given either test or reference data with a z-axis,
convert to the desired pressure levels.
"""
mv_plv = mv.getLevel()
# var(time,lev,lon,lat) convert from hybrid level to pressure
if mv_plv.long_name.lower().find('hybrid') ... | 5,311,769 |
def verify_all_steps_command_alignment(layout, links_dict):
"""
<Purpose>
Iteratively checks if all expected commands as defined in the
Steps of a Layout align with the actual commands as recorded in the Link
metadata.
Note:
Command alignment is a weak guarantee. Because a functionary can eas... | 5,311,770 |
def matrix2xzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray:
"""
Ry(k3) @ Rz(k2) @ Rx(k1) = [[c2c3, -c1s2c3+s1s3, s1s2c3+c1s3],
[s2, c1c2, -s1c2],
[-c2s3, c1s2s3+s1c3, -s1s2s3+c1c3]]
"""
rotation_matrices = rotation_matrices.resha... | 5,311,771 |
def do_auth():
"""
perform authentication using API_KEY,
stores token and stored timestamp in integration context,
retrieves new token when expired
"""
auth = demisto.getIntegrationContext()
now_epoch = int(datetime.today().strftime('%s'))
if ("token" in auth or "stored" in auth) and in... | 5,311,772 |
def main():
"""Command line:
python result_eval.py <path_to_reference_file> <path_to_candidate_file>
"""
if len(sys.argv) == 3:
path_to_reference = sys.argv[1]
path_to_candidate = sys.argv[2]
else:
print('Usage: result_eval.py <reference ranking> <candidate ranking>')
... | 5,311,773 |
async def write_credential_def(controller, schema_id):
"""
Writes Credential Definition to the ledger
Parameters:
----------
controller: AriesController
The aries_cloudcontroller object
Schema id
Returns:
-------
write_cred_response :dict
"""
write_cred_response =... | 5,311,774 |
def guess_cloudwatch_log_group(alarm_name):
"""
Guess the name of the CloudWatch log group most likely to contain
logs about the error.
"""
if alarm_name.startswith("loris-"):
return "platform/loris"
if alarm_name.startswith("catalogue-api-romulus"):
return "ecs/catalogue_api_gw... | 5,311,775 |
def save_fig(fig: Figure, path: Union[str, Path], make_dir: bool = True, ext: str = "png", **kwargs: Any) -> None:
"""
Save a figure.
Parameters
----------
fig
Figure to save.
path
Path where to save the figure. If path is relative, save it under :attr:`scanpy.settings.figdir`.
... | 5,311,776 |
def optional_convert_i010_to_p010(config, idest, dest):
"""convert i010 to p010, but only if needed"""
if dest.codec == "P010":
if idest.codec == "I010":
with open(dest.name, "wb") as p010_file:
with open(idest.name, "rb") as i010_file:
convert_i010_to_p01... | 5,311,777 |
def update_attrs(orig, keys, override):
"""Utility function for altering and adding the specified attributes to a particular repository rule invocation.
This is used to make a rule reproducible.
Args:
orig: dict of actually set attributes (either explicitly or implicitly)
by a particu... | 5,311,778 |
def _check_for_existing_display_name(display_name, account_number):
"""
check to see if a display name already exists for an account, and raise an exception if so.
"""
query = SystemBaseline.query.filter(
SystemBaseline.account == account_number,
SystemBaseline.display_name == display_n... | 5,311,779 |
def GetCreateLabelsFlag(extra_message='', labels_name='labels',
validate_values=True):
"""Makes the base.Argument for --labels flag."""
value_type = VALUE_FORMAT_VALIDATOR if validate_values else None
format_help = [KEY_FORMAT_HELP]
if validate_values:
format_help.append(VALUE_FORMAT... | 5,311,780 |
def unflatten(d, splitter='tuple', inverse=False):
"""Unflatten dict-like object.
Parameters
----------
d : dict-like object
The dict that will be unflattened.
splitter : {'tuple', 'path', Callable}
The key splitting method. If a Callable is given, the Callable will be
used ... | 5,311,781 |
def toggle_state(state, should_set):
"""
.. deprecated:: 0.5.0
Alias of :func:`toggle_flag`"""
toggle_flag(state, should_set) | 5,311,782 |
def get_mapped_to_elements(mapper):
"""
The mapper list contains all the element names that have been mapped to by
other elements
"""
mapper_list = []
for element in mapper:
for list_element in mapper[element]:
if list_element not in mapper_list:
mapper_list.a... | 5,311,783 |
def psd(time, rate, norm='leahy'):
"""
Returns power spectral density from a (real) time series
with Leahy normalization.
Args:
time: array of times (evenly binned).
rate: array of rate in counts/s.
Kwargs:
norm: Normalization (only Leahy for ... | 5,311,784 |
async def session_fetch(
handle: SessionHandle, category: str, name: str, for_update: bool = False
) -> EntrySetHandle:
"""Fetch a row from the Store."""
category = encode_str(category)
name = encode_str(name)
return await do_call_async(
"askar_session_fetch",
handle,
categor... | 5,311,785 |
def test_is_authorized_current_user_unavailable_permissions(client_request_authenticated):
"""
gets a value indicating that the current user
is not authorized for given permissions.
"""
authorized = authorization_services.is_authorized([PERMISSION_TEST_FOUR,
... | 5,311,786 |
def login(hostname, username, password):
"""Login to the switch and return the console with the prompt at `#`"""
try_again = True
alternatives = [r'[\r\n]+.+#',
"Permission denied",
"[Pp]assword: *",
">",
"(ibmnos-cli/iscli):*",... | 5,311,787 |
def _ComputeImageDiff(failure_image, golden_image):
"""Compute mask showing which pixels are different between two images."""
return (ImageChops.difference(failure_image, golden_image)
.convert('L')
.point(lambda i: 255 if i else 0)) | 5,311,788 |
def load_pytest_conf(path, parser):
"""loads a ``pytestconf.py`` file and update default parser
and / or tester.
"""
namespace = {}
exec(open(path, 'rb').read(), namespace)
if 'update_parser' in namespace:
namespace['update_parser'](parser)
return namespace.get('CustomPyTester', PyTe... | 5,311,789 |
def svn_client_import3(*args):
"""
svn_client_import3(svn_commit_info_t commit_info_p, char path, char url,
svn_depth_t depth, svn_boolean_t no_ignore,
svn_boolean_t ignore_unknown_node_types, apr_hash_t revprop_table,
svn_client_ctx_t ctx,
apr_pool_t pool) -> svn_error_t
"... | 5,311,790 |
def labs(**kwargs):
"""
Change plot title, axis labels and legend titles.
Parameters
----------
kwargs:
A list of new names in the form aesthetic='new name',
e.g. title='Plot title' or aes-name='Scale label'
Returns
--------
Axis label specification.
Note
-... | 5,311,791 |
def _filter(paths, cgroups, rgroups):
""" Keep only paths with the appropriate cgroups and/or rgroups
"""
kept = []
for path in paths:
valid_cgroup = (cgroups is None or _cname(path) in cgroups)
valid_rgroup = (rgroups is None or _rname(path) in rgroups)
if valid_cgroup and valid... | 5,311,792 |
def patch(target, new):
"""Simplified module monkey patching via context manager.
Args:
target: Target class or object.
new: Object or value to replace the target with.
"""
def _import_module(target):
components = target.split('.')
import_path = components.pop(0)
... | 5,311,793 |
def _prepare_factor_cols(dfs: List[h2o.H2OFrame], colnames: List[str]) -> None:
"""Saves the original columns in the dfs as <col>_original and converts the <col> to factors.
Args:
dfs (list of h2o.H2OFrame): the H2O dataframes where the columns need to be changed to factors
colnames (list of st... | 5,311,794 |
def _load_with_pydub(filename, audio_format):
"""Open compressed audio file using pydub. If a video file
is passed, its audio track(s) are extracted and loaded.
This function should not be called directely, use :func:`from_file`
instead.
:Parameters:
`filename`:
path to audio file.
... | 5,311,795 |
def get_storage(store: Optional[StorageEngine] = None) -> StorageEngine:
"""Get current storage method."""
if store is not None:
return store
else:
if _storage_stack.top is not None:
out: StorageEngine = _storage_stack.top
return out
else:
raise Ru... | 5,311,796 |
def UniformDot(d=100, p=100, tol=1e-2):
"""
Let U be a random `d` x `p` matrix with i.i.d. uniform
entries. Then Sigma = ``cov2corr``(U^T U)
"""
U = np.random.uniform(size=(d, p))
V = np.dot(U.T, U)
V = cov2corr(V)
return cov2corr(shift_until_PSD(V, tol=tol)) | 5,311,797 |
def get_supported_eline_list(*, lines=None):
"""
Returns the list of the emission lines supported by ``scikit-beam``
Parameters
----------
lines : list(str)
tuple or list of strings, that defines, which emission lines are going to be included
in the output list (e.g. ``("K",)`` or ... | 5,311,798 |
def visualize_test(test_data_full, test_data, thetas):
"""
Visualize Test for Testing Results
:param test_data_full: the test data set (full) with labels and data
:param thetas: model parameters
:return: fig
"""
fig, ax = plt.subplots()
ax.scatter(test_data_full... | 5,311,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.