content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def p_ObjectLiteral(p):
"""ObjectLiteral : '{' PropertyNameAndValueList '}'
| '{' '}'"""
p[0] = "ObjectLiteral"
p[0] = list(p) | 5,339,500 |
def build_docs_for_packages(
current_packages: List[str],
docs_only: bool,
spellcheck_only: bool,
for_production: bool,
jobs: int,
verbose: bool,
) -> Tuple[Dict[str, List[DocBuildError]], Dict[str, List[SpellingError]]]:
"""Builds documentation for all packages and combines errors."""
a... | 5,339,501 |
def GetWorkingInTime():
""" Get the start frame of the working range.
The in time is guaranteed to be less than or equal to the out time.
@rtype: C{number}
"""
pass | 5,339,502 |
def _inspect_output_dirs_test(ctx):
"""Test verifying output directories used by a test."""
env = analysistest.begin(ctx)
# Assert that the output bin dir observed by the aspect added by analysistest
# is the same as those observed by the rule directly, even when that's
# under a config transition ... | 5,339,503 |
def wait(object_refs, num_returns=1, timeout=None):
"""Return a list of IDs that are ready and a list of IDs that are not.
This method is identical to `ray.wait` except it adds support for tuples
and ndarrays.
Args:
object_refs (List[ObjectRef], Tuple(ObjectRef), np.array(ObjectRef)):
... | 5,339,504 |
def test_nameserver_agents(nsproxy):
"""
Test the agents() method, which should return a list with the names of
the registered agents.
"""
# No agents registered
agents = nsproxy.agents()
assert len(agents) == 0
# One agent registered
run_agent('Agent0')
agents = nsproxy.agents()... | 5,339,505 |
def test_line_to_cols():
"""Test convert.line_to_cols"""
line = ["ID", "RA", "dec", "test1", "test2"]
actual_cols = convert.line_to_cols(line)
expected_cols = line
expected_cols[0] = "id"
expected_cols[1] = "ra"
assert expected_cols == actual_cols | 5,339,506 |
def train(
data,
feature_names,
tagset,
epochs,
optimizer,
score_func=perceptron_score,
step_size=1,
):
"""
Trains the model on the data and returns the parameters
:param data: Array of dictionaries representing the data. One dictionary for each data point (as created by the
... | 5,339,507 |
def summed_timeseries(timeseries):
"""
Give sum of value series against timestamps for given timeseries containing several values per one timestamp
:param timeseries:
:return:
"""
sum_timeseries = []
for i in range(len(timeseries)):
if len(timeseries[i])>1:
sum_timeserie... | 5,339,508 |
def path_check(path_to_check):
"""
Check that the path given as a parameter is an valid absolute path.
:param path_to_check: string which as to be checked
:type path_to_check: str
:return: True if it is a valid absolute path, False otherwise
:rtype: boolean
"""
path = pathlib.Path(path_... | 5,339,509 |
def _path2list(
path: Union[str, Sequence[str]],
boto3_session: boto3.Session,
s3_additional_kwargs: Optional[Dict[str, Any]],
last_modified_begin: Optional[datetime.datetime] = None,
last_modified_end: Optional[datetime.datetime] = None,
suffix: Union[str, List[str], None] = None,
ignore_su... | 5,339,510 |
def e_greedy_normal_noise(mags, e):
"""Epsilon-greedy noise
If e>0 then with probability(adding noise) = e, multiply mags by a normally-distributed
noise.
:param mags: input magnitude tensor
:param e: epsilon (real scalar s.t. 0 <= e <=1)
:return: noise-multiplier.
"""
if e and uniform(... | 5,339,511 |
def beam_area(*args):
"""
Calculate the Gaussian beam area.
Parameters
----------
args: float
FWHM of the beam.
If args is a single argument, a symmetrical beam is assumed.
If args has two arguments, the two arguments are bmaj and bmin,
the width of the major and min... | 5,339,512 |
def enerpi_daemon_logger(with_pitemps=False):
"""
Punto de entrada directa a ENERPI Logger con la configuración de DATA_PATH/config_enerpi.ini.
Se utiliza para iniciar ENERPI como daemon mediante 'enerpi-daemon start|stop|restart'
(en conjunción con enerpiweb, con user www-data: 'sudo -u www-data %(pat... | 5,339,513 |
def get_settlement_amounts(
participant1,
participant2
):
""" Settlement algorithm
Calculates the token amounts to be transferred to the channel participants when
a channel is settled.
!!! Don't change this unless you really know what you are doing.
"""
total_available_deposit ... | 5,339,514 |
def cli_parse_clippings():
"""解析clippings文本(对于此模块的功能还没有明确)
"""
question = [
inquirer.Path("file_path", path_type=inquirer.Path.FILE, exists=True,
message="Kindle Clippings文件路径"),
]
answer = inquirer.prompt(question, theme=GreenPassion())
# 获取到clipping文件路径之后,开始进行处理
... | 5,339,515 |
def test_attribute_passing_local(sb):
"""Should succeed everywhere as attribute passing needs no dependencies."""
sb.local = True
sb.test() | 5,339,516 |
def print_ranked_scores(obs, scores):
"""Returns numpy array with data points labelled as outliers
Parameters
----------
data:
no_of_clusters: numpy array like data_point
score: numpy like data
""" | 5,339,517 |
def test_url_req_case_mismatch_file_index(script, data):
"""
tar ball url requirements (with no egg fragment), that happen to have upper
case project names, should be considered equal to later requirements that
reference the project name using lower case.
tests/data/packages3 contains Dinner-1.0.ta... | 5,339,518 |
def timefunc(f):
"""Simple timer function to identify slow spots in algorithm.
Just import function and put decorator @timefunc on top of definition of any
function that you want to time.
"""
def f_timer(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
end = ... | 5,339,519 |
def rdr_geobox(rdr) -> GeoBox:
""" Construct GeoBox from opened dataset reader.
"""
h, w = rdr.shape
return GeoBox(w, h, rdr.transform, rdr.crs) | 5,339,520 |
def sequence(lst: Block[Result[_TSource, _TError]]) -> Result[Block[_TSource], _TError]:
"""Execute a sequence of result returning commands and collect the
sequence of their response."""
return traverse(identity, lst) | 5,339,521 |
def keyword_dct_from_block(block, formatvals=True):
""" Take a section with keywords defined and build
a dictionary for the keywords
assumes a block that is a list of key-val pairs
"""
key_dct = None
if block is not None:
block = ioformat.remove_whitespace(block)
key_va... | 5,339,522 |
def test_resolutions2ints_lists(resolutions, results):
"""Test transformation of resolutions to integer resolutions."""
assert results == utils.resolutions2ints(resolutions) | 5,339,523 |
def get_geocode(args):
"""
Returns GPS coordinates from Google Maps for a given location.
"""
result = Geocoder.geocode(args.address)
lat, lon = result[0].coordinates
lat = round(lat, 6)
lon = round(lon, 6)
return (lat, lon) | 5,339,524 |
def test_gui(mock_open_gui, check_no_board_connected):
"""Test the gui command."""
runner = CliRunner()
result = runner.invoke(cli.gui)
assert result.exit_code == 0, "Exit code 0"
assert mock_open_gui.call_count == 1, "open_gui() function called" | 5,339,525 |
def mice(data, **kwargs):
"""Multivariate Imputation by Chained Equations
Reference:
Buuren, S. V., & Groothuis-Oudshoorn, K. (2011). Mice: Multivariate
Imputation by Chained Equations in R. Journal of Statistical Software,
45(3). doi:10.18637/jss.v045.i03
Implementation follows th... | 5,339,526 |
def SaveFlagValues():
"""Returns copy of flag values as a dict.
Returns:
Dictionary mapping keys to values. Keys are flag names, values are
corresponding __dict__ members. E.g. {'key': value_dict, ...}.
"""
if hasattr(flags, '_FlagValues'): # pylint:disable=protected-access
# In OSS code we use te... | 5,339,527 |
def _decompile_marketplace_bp(mpi_name, version, project, name, source, with_secrets):
"""Decompiles marketplace manager blueprint"""
decompile_marketplace_bp(
name=mpi_name,
version=version,
project=project,
bp_name=name,
app_source=None,
with_secrets=with_secre... | 5,339,528 |
def PBH_RULE_update_field_set(
db,
table_name,
rule_name,
priority,
gre_key,
ether_type,
ip_protocol,
ipv6_next_header,
l4_dst_port,
inner_ether_type,
hash,
packet_action,
flow_counter
):
""" Set object field in PBH_RULE table """
ctx = click.get_current_cont... | 5,339,529 |
def estimate_purity_err(dim: int, op_expect: np.ndarray, op_expect_var: np.ndarray, renorm=True):
"""
Propagate the observed variance in operator expectation to an error estimate on the purity.
This assumes that each operator expectation is independent.
:param dim: dimension of the Hilbert space
:p... | 5,339,530 |
def test_linked_list_can_remove_value():
"""Test value can be removed."""
from linked_list import LinkedList
with pytest.raises(ValueError):
l = LinkedList()
for i in range(10):
l.push(i)
l.remove(l.search(6)) | 5,339,531 |
def get_next_code(seen, server_ticket=0):
"""Find next unused assertion code.
Called by: SConstruct and main()
Since SConstruct calls us, codes[] must be global OR WE REPARSE EVERYTHING
"""
if not codes:
(_, _, seen) = read_error_codes()
if server_ticket:
# Each SERVER ticket i... | 5,339,532 |
async def test_fixture_env_home_uses_default(env_home):
"""Provide xdg home directories if not set in the environemnt."""
unset_env(env_home)
config = await get_xdg_home()
home = await Path.home()
assert str(config['XDG_CONFIG_HOME']) == str(home / '.config')
assert str(config['XDG_CACHE_HOME'])... | 5,339,533 |
def getEnergyUsage():
"""Query plug for energy usage data. Runs as async task.
:return: json with device energy data
"""
energy_data = asyncio.run(plug.get_emeter_realtime())
return energy_data | 5,339,534 |
def collect_metrics(logger, settings, encrypt_key, collectors):
"""
This function fetch, encrypted and persist metrics data for each collector in the collector list. It will first
fetch and encrypt for each collector. Then, the data is persist to either local or remote database depending on
the configur... | 5,339,535 |
def get_sequence_from_kp(midi):
"""
Get the reduced chord sequence from a kp KP-corpus file.
Parameters
==========
midi : pretty_midi
A pretty_midi object representing the piece to parse.
Returns
=======
chords : list
The reduced chord sequence from the give... | 5,339,536 |
def step_payload():
"""
We define the type of payload we wish to send and create the final exploit file.
"""
global current_step
current_step = 5
show_step_banner('[5] Creating payload')
# Set IP -----------------
global connect_ip
show_prompt_text('Enter your IP (hit Enter to use current value {}):'.format(co... | 5,339,537 |
def get_bw_range(features):
"""
Get the rule-of-thumb bandwidth and a range of bandwidths on a log scale for the Gaussian RBF kernel.
:param features: Features to use to obtain the bandwidths.
:return: Tuple consisting of:
* rule_of_thumb_bw: Computed rule-of-thumb bandwidth.
* bws: Li... | 5,339,538 |
def _register_jsonschema(js_schema, model_id):
"""
Makes a jsonschema known to this viz
This was added to benefit ONAP/DCAE and is lightly tested at best.
TODO: Does not inject APV keys into messages.
"""
# import here to avoid circular dependency
from acumos_proto_viewer import data
_l... | 5,339,539 |
def gen_endpoint(endpoint_name, endpoint_config_name):
"""
Generate the endpoint resource
"""
endpoint = {
"SagemakerEndpoint": {
"Type": "AWS::SageMaker::Endpoint",
"DependsOn": "SagemakerEndpointConfig",
"Properties": {
"EndpointConfigName": ... | 5,339,540 |
def load_config():
""" Load configuration and set debug flag for this environment """
# Load global configuration
config = yaml.load(open(os.path.abspath('./conf/global.yaml'), 'r').read())
# Detect development or production environment and configure accordingly
if os.environ['SERVER_SOFTWARE'... | 5,339,541 |
def read_dataframe(df, smiles_column, name_column, data_columns=None):
"""Read molecules from a dataframe.
Parameters
----------
df : pandas.DataFrame
Dataframe to read molecules from.
smiles_column : str
Key of column containing SMILES strings or rdkit Mol objects.
name_column ... | 5,339,542 |
def dummy_awsbatch_cluster_config(mocker):
"""Generate dummy cluster."""
image = Image(os="alinux2")
head_node = dummy_head_node(mocker)
compute_resources = [
AwsBatchComputeResource(name="dummy_compute_resource1", instance_types=["dummyc5.xlarge", "optimal"])
]
queue_networking = AwsBat... | 5,339,543 |
def float_or_none(val, default=None):
"""
Arguments:
- `x`:
"""
if val is None:
return default
else:
try:
ret = float(val)
except ValueError:
ret = default
return ret | 5,339,544 |
def user_get_year_rating(user_id: int):
"""
Get the last step user was at
:param user_id:
:return: str
"""
try:
con = psconnect(db_url, sslmode='require')
cursor = con.cursor()
cursor.execute("SELECT year,rating FROM users WHERE uid = %s", (user_id,))
result = cur... | 5,339,545 |
def msg_with_data(config, filter_):
"""Creates :py:class:`pymco.message.Message` instance with some data."""
# Importing here since py-cov will ignore code imported on conftest files
# imports
from pymco import message
with mock.patch('time.time') as time:
with mock.patch('hashlib.sha1') as ... | 5,339,546 |
def csrf_protect(remainder, params):
"""
Perform CSRF protection checks. Performs checks to determine if submitted
form data matches the token in the cookie. It is assumed that the GET
request handler successfully set the token for the request and that the
form was instrumented with a CSRF token fie... | 5,339,547 |
def get_image_names():
"""
Returns (image_names, covid_image_names, normal_image_names,
virus_image_names), where each is a list of image names
"""
image_names = os.listdir(DEFAULT_IMG_PATH_UNEDITED)
# Remove directories
image_names.remove("COVID-19")
image_names.remove("Normal")
im... | 5,339,548 |
def api_connect_wifi():
""" Connect to the specified wifi network """
res = network.wifi_connect()
return jsonify(res) | 5,339,549 |
async def get_sinks_metadata(sinkId: str) -> List: # pylint: disable=unused-argument
"""Get metadata attached to sinks
This adapter does not implement metadata. Therefore this will always result
in an empty list!
"""
return [] | 5,339,550 |
def fn_lin(x_np, *, multiplier=3.1416):
""" Linear function """
return x_np * multiplier | 5,339,551 |
def task1(outfile, extra):
"""
First task
"""
# N.B. originate works with an extra parameter
helper(None, outfile) | 5,339,552 |
def get_MACD(df, column='Close'):
"""Function to get the EMA of 12 and 26"""
df['EMA-12'] = df[column].ewm(span=12, adjust=False).mean()
df['EMA-26'] = df[column].ewm(span=26, adjust=False).mean()
df['MACD'] = df['EMA-12'] - df['EMA-26']
df['Signal'] = df['MACD'].ewm(span=9, adjust=Fal... | 5,339,553 |
def from_pyGraphviz_agraph(A, create_using=None):
"""Returns a EasyGraph Graph or DiGraph from a PyGraphviz graph.
Parameters
----------
A : PyGraphviz AGraph
A graph created with PyGraphviz
create_using : EasyGraph graph constructor, optional (default=None)
Graph type to create. If g... | 5,339,554 |
def get_textbox_rectangle_from_pane(pane_rectangle: GeometricRectangle, texts: Collection[str],
direction: str) -> GeometricRectangle:
"""
Args:
pane_rectangle:
texts:
direction:
Returns:
"""
num_boxes: int = len(texts)
dimensions = ... | 5,339,555 |
def spawn_shell(shell_cmd):
"""Spawn a shell process with the provided command line. Returns the Pexpect object."""
return pexpect.spawn(shell_cmd[0], shell_cmd[1:], env=build_shell_env()) | 5,339,556 |
def analyze_image(data, err, seg, tab, athresh=3.,
robust=False, allow_recenter=False,
prefix='', suffix='', grow=1,
subtract_background=False, include_empty=False,
pad=0, dilate=0, make_image_cols=True):
"""
SEP/SExtractor analysis on ... | 5,339,557 |
def qr(tag):
"""
called by an AJAX request for cipherwallet QR code
this action is typically invoked by your web page containing the form, thru the code
in cipherwallet.js, to obtain the image with the QR code to display
it will return the image itself, with an 'image/png' content type, so you ... | 5,339,558 |
def get_experiment_table(faultgroup, faultname, tablename):
"""
Get anny table from a faultgroup
"""
node = faultgroup._f_get_child(faultname)
table = node._f_get_child(tablename)
return pd.DataFrame(table.read()) | 5,339,559 |
def kjunSeedList(baseSeed, n):
"""
generates n seeds
Due to the way it generates the seed, do not use i that is too large..
"""
assert n <= 100000
rs = ra.RandomState(baseSeed);
randVals = rs.randint(np.iinfo(np.uint32).max+1, size=n);
return randVals; | 5,339,560 |
def main():
"""
TODO:
"""
####################
print('Welcome to stanCode\"Anagram Generator\"( or -1 to quit)')
read_dictionary()
start, end = 0, 0
while True:
word = input('Find anagrams for: ')
if word == EXIT:
break
else:
start = time.t... | 5,339,561 |
def filter_sharpen(image):
"""Apply a sharpening filter kernel to the image.
This is the same as using PIL's ``PIL.ImageFilter.SHARPEN`` kernel.
Added in 0.4.0.
**Supported dtypes**:
* ``uint8``: yes; fully tested
* ``uint16``: no
* ``uint32``: no
* ``uint64``: no
... | 5,339,562 |
async def zha_client(hass, config_entry, zha_gateway, hass_ws_client):
"""Test zha switch platform."""
# load the ZHA API
async_load_api(hass)
# create zigpy device
await async_init_zigpy_device(
hass,
[general.OnOff.cluster_id, general.Basic.cluster_id],
[],
None,
... | 5,339,563 |
def summary_selector(summary_models=None):
"""
Will create a function that take as input a dict of summaries :
{'T5': [str] summary_generated_by_T5, ..., 'KW': [str] summary_generted_by_KW}
and randomly return a summary that has been generated by one of the summary_model in summary_model
if summary_models is none... | 5,339,564 |
def handle_collectd(root_dir):
"""Generate figure for each plugin for each hoster."""
result = collections.defaultdict(lambda: collections.defaultdict(dict))
for host in natsorted(root_dir.iterdir()):
for plugin in natsorted(host.iterdir()):
stats_list = natsorted(
[fname... | 5,339,565 |
def mfa_delete_token(token_name):
""" Deletes an MFA token file from the .ndt subdirectory in the user's
home directory """
os.remove(get_ndt_dir() + '/mfa_' + token_name) | 5,339,566 |
def create_policy_case_enforcement(repository_id, blocking, enabled,
organization=None, project=None, detect=None):
"""Create case enforcement policy.
"""
organization, project = resolve_instance_and_project(
detect=detect, organization=organization, project=projec... | 5,339,567 |
def svn_fs_new(*args):
"""svn_fs_new(apr_hash_t fs_config, apr_pool_t pool) -> svn_fs_t"""
return apply(_fs.svn_fs_new, args) | 5,339,568 |
def cam_pred(prefix, data_dir):
"""
"""
groundtruth_dict = read(os.path.join('../data/contrast_dataset', 'groundtruth.txt'))
cam = CAM(model=load_pretrained_model(prefix, 'resnet'))
if data_dir == '../data/split_contrast_dataset':
normalize = transforms.Normalize(mean=[0.7432, 0.661, 0.6283... | 5,339,569 |
def read_history_file(
store,
src_file,
store_file,
ignore_file=None,
mark_read=True):
"""Read in the history files."""
commands = _get_unread_commands(src_file)
output = []
if ignore_file:
ignore_rules = IgnoreRules.create_ignore_rule(ignore_file)
else:
ignore_r... | 5,339,570 |
def least_similar(sen, voting_dict):
"""
Find senator with voting record least similar, excluding the senator passed
:param sen: senator last name
:param voting_dict: dictionary of voting record by last name
:return: senator last name with least similar record, in case of a tie chooses first alphabe... | 5,339,571 |
def _send_req(wait_sec, url, req_gen, retry_result_code=None):
""" Helper function to send requests and retry when the endpoint is not ready.
Args:
wait_sec: int, max time to wait and retry in seconds.
url: str, url to send the request, used only for logging.
req_gen: lambda, no parameter function to generat... | 5,339,572 |
def load_file(path, types = None):
"""
load file in path if file format in types list
----
:param path: file path
:param code: file type list, if None, load all files, or not load the files in the list, such as ['txt', 'xlsx']
:return: a list is [path, data]
"""
ext = path.split(".")[-1]... | 5,339,573 |
def cdo_spatial_cut(path, file_includes, new_file_includes, lonmin, lonmax, latmin, latmax):
"""
loops through the given directory and and executes "cdo -sellonlatbox,lonmin,lonmax,latmin,latmax *file_includes* fileout.nc" appends "spatial_cut_*new_file_includes*" at the end of the filename
"""
for name... | 5,339,574 |
def get_dense_labels_map(values, idx_dtype='uint32'):
"""
convert unique values into dense int labels [0..n_uniques]
:param array values: (n,) dtype array
:param dtype? idx_dtype: (default: 'uint32')
:returns: tuple(
labels2values: (n_uniques,) dtype array,
values2labels: HashMap(dty... | 5,339,575 |
def delete_debug_file_from_orchestrator(
self,
filename: str,
) -> bool:
"""Delete debug file from Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - debugFiles
- POST
- /debugFiles/delete
:param... | 5,339,576 |
def _replace_fun_unescape(m: Match[str]) -> str:
""" Decode single hex/unicode escapes found in regex matches.
Supports single hex/unicode escapes of the form ``'\\xYY'``,
``'\\uYYYY'``, and ``'\\UYYYYYYYY'`` where Y is a hex digit. Only
decodes if there is an odd number of backslashes.
.. version... | 5,339,577 |
def delete_clip(cid: int) -> None:
"""
Deletes the specified clip.
:param cid: The clip's id.
"""
try:
Clip.objects.get(id=cid).delete()
except Clip.DoesNotExist:
pass | 5,339,578 |
def predict_next_location(game_data, ship_name):
"""
Predict the next location of a space ship.
Parameters
----------
game_data: data of the game (dic).
ship_name: name of the spaceship to predicte the next location (str).
facing: facing of the ship (tuple)
Return
------
predic... | 5,339,579 |
def mux_video_audio(videofile_path, audiofile_path, output_video_name):
"""
Add audio to video file
@param videofile_path: str - Input video file path
@param audiofile_path: str - Input audio file path
@param output_video_name: str - Output video file path
"""
input_video = ffmpeg.input(vide... | 5,339,580 |
def main(argv):
"""Find and report approximate size info for a particular built package."""
commandline.RunInsideChroot()
parser = _get_parser()
opts = parser.parse_args(argv)
opts.Freeze()
db = portage_util.PortageDB(root=opts.root)
if opts.packages:
installed_packages = portage_util.GenerateInsta... | 5,339,581 |
def get_absolute_filename(user_inputted_filename: str) -> Path:
"""Clean up user inputted filename path, wraps os.path.abspath, returns Path object"""
filename_location = Path(os.path.abspath(user_inputted_filename))
return filename_location | 5,339,582 |
def check_answer(guess, a_follower, b_follower):
"""Chcek if the user guessed the correct option"""
if a_follower > b_follower:
return guess == "a"
else:
return guess == "b" | 5,339,583 |
def command_line_arg_parser():
"""
Command line argument parser. Encrypts by default. Decrypts when --decrypt flag is passed in.
"""
parser = argparse.ArgumentParser(description='Parses input args')
parser.add_argument('input_file', type=str,
help='Path to input file location... | 5,339,584 |
def x(ctx, command):
"""run command on all containers (one for each deployment) within current
namespace. only show output when command succeeds
\b
examples:
\b
lain admin x -- bash -c 'pip3 freeze | grep -i requests'
"""
res = kubectl('get', 'po', '--no-headers', capture_output=Tr... | 5,339,585 |
async def output(ctx, metadata):
"""Create outputs - such as Ansible inventory."""
ctx.obj.init_metadata(metadata)
await generate_outputs(ctx) | 5,339,586 |
def respond(variables, Body=None, Html=None, **kwd):
"""
Does the grunt work of cooking up a MailResponse that's based
on a template. The only difference from the lamson.mail.MailResponse
class and this (apart from variables passed to a template) are that
instead of giving actual Body or Html param... | 5,339,587 |
def canonical_for_code_system(jcs: Dict) -> str:
"""get the canonical URL for a code system entry from the art decor json. Prefer FHIR URIs over the generic OID URI.
Args:
jcs (Dict): the dictionary describing the code system
Returns:
str: the canonical URL
"""
if "canonicalUriR4" ... | 5,339,588 |
def correspdesc_source(data):
"""
extract @source from TEI elements <correspDesc>
"""
correspdesc_data = correspdesc(data)
try:
return [cd.attrib["source"].replace("#", "") for cd in correspdesc_data]
except KeyError:
pass
try:
return [cd.attrib[ns_cs("source")].repla... | 5,339,589 |
def leaders(Z, T):
"""
(L, M) = leaders(Z, T):
For each flat cluster j of the k flat clusters represented in the
n-sized flat cluster assignment vector T, this function finds the
lowest cluster node i in the linkage tree Z such that:
* leaf descendents belong only to flat cluster j (i.e. T[p... | 5,339,590 |
def plot_visualize_mft_sources(fwdmag, stcdata, tmin, tstep,
subject, subjects_dir):
"""
Plot the MFT sources at time point of peak.
Parameters
----------
fwdmag: forward solution
stcdata: stc with ||cdv|| (point sequence as in fwdmag['source_rr'])
tmin, tstep... | 5,339,591 |
def wmca(instance: bot, message: trigger) -> None:
"""Expand a link to Wikimedia CentralAuth."""
try:
instance.say(
f'https://meta.wikimedia.org/wiki/Special:CentralAuth/{message.group(2).replace(" ", "_")}',
)
except AttributeError:
instance.say('Syntax: .wmca exampl... | 5,339,592 |
def create_unique_views(rows: list, fields: List[str]):
"""Create views for each class objects, default id should be a whole row"""
views = {}
for r in rows:
values = [r[cname] for cname in fields]
if any(isinstance(x, list) for x in values):
if all(isinstance(x, list) for x in v... | 5,339,593 |
def check_shape_function(invocations: List[Invocation]):
"""Decorator that automatically tests a shape function.
The shape function, which is expected to be named systematically with
`〇` instead of `.`, is tested against the corresponding op in
`torch.ops.*` function using the given invocations.
... | 5,339,594 |
def _prepare_images(ghi, clearsky, daytime, interval):
"""Prepare data as images.
Performs pre-processing steps on `ghi` and `clearsky` before
returning images for use in the shadow detection algorithm.
Parameters
----------
ghi : Series
Measured GHI. [W/m^2]
clearsky : Series
... | 5,339,595 |
def interleaved_code(modes: int) -> BinaryCode:
""" Linear code that reorders orbitals from even-odd to up-then-down.
In up-then-down convention, one can append two instances of the same
code 'c' in order to have two symmetric subcodes that are symmetric for
spin-up and -down modes: ' c + c '.
In ev... | 5,339,596 |
def nearest_neighbors(data, args):
"""
最近邻
"""
from sklearn.neighbors import NearestNeighbors
nbrs = NearestNeighbors(**args)
nbrs.fit(data)
# 计算测试数据对应的最近邻下标和距离
# distances, indices = nbrs.kneighbors(test_data)
return nbrs | 5,339,597 |
def test_selective_sync(m: Maestral) -> None:
"""
Tests :meth:`Maestral.exclude_item`, :meth:`MaestralMaestral.include_item`,
:meth:`Maestral.excluded_status` and :meth:`Maestral.excluded_items`.
"""
dbx_dirs = [
"/selective_sync_test_folder",
"/independent_folder",
"/select... | 5,339,598 |
def register_connection(
alias,
db=None,
name=None,
host=None,
port=None,
read_preference=READ_PREFERENCE,
username=None,
password=None,
authentication_source=None,
authentication_mechanism=None,
**kwargs
):
"""Register the connection settings.
: param alias: the nam... | 5,339,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.