content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def make_ip_thermostat(
device: hm_device.HmDevice, device_address: str, group_base_channels: list[int]
) -> list[hm_entity.BaseEntity]:
"""Creates IPThermostat entities."""
return make_custom_entity(
device=device,
device_address=device_address,
custom_entity_class=CeIpThermostat,
... | 5,307,600 |
def deepmap(func, obj):
"""Deep traverse obj, and apply func to each of its non-Iterable
elements"""
if isinstance(obj, Iterable):
return [deepmap(func, x) for x in obj]
else:
return func(obj) | 5,307,601 |
def download_historical_data():
""" Explanation about the download procedure of historical data """
print("""To download historical data (updated every quarter) : \n
1. go on https://drive.google.com/drive/folders/1sqt3kvw_Y5yOfF6HLG_xfAXae0LsVZWH\n
2. download one of the separate zip file \n
... | 5,307,602 |
def test_returns_tx_on_success(tester, accounts):
"""returns a TransactionReceipt on success"""
tx = tester.revertStrings(5)
assert type(tx) == TransactionReceipt | 5,307,603 |
def user_create( name, passwd=None, home=None, uid=None, gid=None, shell=None, uid_min=None, uid_max=None):
"""Creates the user with the given name, optionally giving a specific password/home/uid/gid/shell."""
options = ["-m"]
if passwd:
method = 6
saltchars = string.ascii_letters + string.d... | 5,307,604 |
def shufflenet_g1_wd4(**kwargs):
"""
ShuffleNet 0.25x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights f... | 5,307,605 |
def pep(tRES):
"""
Show best epoch as a function of period
"""
ax = gca()
x = tRES.PG
y = tRES.epoch
c = tRES.s2n
sid = argsort(c)
x = x[sid]
y = y[sid]
c = c[sid]
ax.scatter(x,y,c=c,cmap=cm.gray_r,edgecolors='none',vmin=7) | 5,307,606 |
def generate_images(data_x, data_y, batch_size, length=255):
"""
Generates images containing numbers from MNIST with random translations.
"""
while True:
x_batch = []
y_numbers_batch = []
y_results = []
for _ in range(batch_size):
x = [np.zeros((28, 0))... | 5,307,607 |
def glType(typ, *args):
"""return ctypes array of GLwhatever for Pyglet's OpenGL interface. (This
seems to work for all types, but it does almost no type conversion. Just
think in terms of "C without type casting".)
typ -> ctype or GL name for ctype; see pyglet.gl.GLenum through GLvoid
args -> ... | 5,307,608 |
def FisherRao_dist(X1, X2):
"""
Compute the Fisher-Rao distance between two curves in R³
...
"""
# #alignement des centres
# X2 = X2 - fs.curve_functions.calculatecentroid(np.transpose(X2))
# #rotations
# X2_new = fs.curve_functions.find_best_rotation(np.transpose(X1), np.transpose(X2))[... | 5,307,609 |
def plot_line(
line: Union[do.Line, Sequence[do.Line]],
ax: Union[mpl.axes.Axes, None] = None,
**kwargs,
) -> mpl.axes.Axes:
"""Plot a Line Dataobject
Parameters
----------
line : Union[do.Line, Sequence[do.Line]]
ax : Union[mpl.axes.Axes, None], optional
mpl.Axes object to plot... | 5,307,610 |
def serialize(obj):
"""JSON serializer for objects not serializable by default json code"""
try:
return obj.__dict__
except AttributeError:
return None | 5,307,611 |
def _get_monitor_value_from_hdf5(image, monitor_key):
"""Return the monitor value from an HDF5 image using an header key.
The monotor_key is a path from the image path containing:
- A dataset containing a scalar (a constant monitor)
- A dataset containing a vector of values (it must containes enougth ... | 5,307,612 |
def collect_preset_for_args():
"""
Collect presets that relevant for args testing only.
This used for testing arguments for specific presets that defined in the
definitions (args_test under Presets).
:return: preset(s) list
"""
for pn in Def.Presets.args_test:
assert pn, Def.Consts.A... | 5,307,613 |
def restart(production=False):
"""Restart staging or primary (production) database."""
instance = 'primary' if production else 'staging'
run('ec services restart --instance {instance} web'.format(instance=instance)) | 5,307,614 |
def test_stats_aggs(pipeline, clean_db):
"""
Verify that combines work on stats aggs
"""
q = """
SELECT x::integer % 10 AS k,
regr_sxx(x, y::float8), stddev(x) FROM stream0 GROUP BY k;
"""
desc = ('x', 'y')
pipeline.create_stream('stream0', x='int', y='float8')
pipeline.create_cv('test_stats_aggs', ... | 5,307,615 |
def create_MultiRNNCell(hidden_sizes, keep_prob, num_proj=None,
memory=None, memory_seq_lengths=None,
reuse=False):
"""
Only the last layer has projection and attention
Args:
hidden_sizes: a list of hidden sizes for each layer
num_proj: the ... | 5,307,616 |
def expand_time(data: pd.DataFrame):
"""
扩展时间纬度信息
"""
tmp = pd.DataFrame(columns=data.columns)
tmp['Time'] = pd.date_range(
data['Time'].values[0],
data['Time'].values[-1],
freq='4H'
)
tmp = tmp.merge(wipe_anomaly(data), how='outer').groupby('Time').max()
return ... | 5,307,617 |
def test_set_index():
"""Testing the SetIndex pipeline stage."""
df = pd.DataFrame(
data=[[8, 'a', 4], [5, 'b', 92]],
index=[1, 2],
columns=['num', 'char', 'w']
)
res_df = SetIndex('num', drop=True).apply(df)
assert 'w' in res_df.columns
assert 'num' not in res_df.columns... | 5,307,618 |
def _EffectiveActiveConfigName():
"""Gets the currently active configuration.
It checks (in order):
- Flag values
- Environment variable values
- The value set in the activator file
Returns:
str, The name of the active configuration or None if no location declares
an active configuration.
... | 5,307,619 |
def test_set_main_service_as_module__adding_second_main_service_throws_error():
"""
Adding a second main service, as module, should throw an error.
"""
inline = InlineServices()
inline.add_service_by_module(
'multi_requester',
import_python_file_from_cwd(MULTI_REQUESTER_PATH)
)
... | 5,307,620 |
def generate_keys():
""" Generate a pair of keys.
This is an utility command that generates a valid pair of keys to
encrypt communication with clients.
The first key is a public key that must be shared across clients
connecting to the Remofile server and the second key is the private
key that ... | 5,307,621 |
def initialize():
"""Create the database and table if they don't exist"""
db.connect()
db.create_tables([Subject, Test, Question], safe=True) | 5,307,622 |
def svn_repos_get_fs_build_parser2(*args):
"""
svn_repos_get_fs_build_parser2(svn_repos_t * repos, svn_boolean_t use_history, enum svn_repos_load_uuid uuid_action,
svn_stream_t * outstream, char const * parent_dir, apr_pool_t pool) -> svn_error_t
"""
return _repos.svn_repos_get_fs_build_parser2(*ar... | 5,307,623 |
def plotting_context(
context: str = "notebook", font_scale: float = 1.5, rc: dict = None
):
"""
创建默认画图板样式
参数
---
:param context: seaborn 样式
:param font_scale: 设置字体大小
:param rc: 配置标签
"""
if rc is None:
rc = {}
rc_default = {"lines.linewidth": 1.5}
# 如果没有默认设置,增加... | 5,307,624 |
def arc(c,rp=False,sn=False,e=False,n=False,samplereverse=False):
"""
Construct an arc by copying an eisting arc or specifying a center ``c`` and various optional parameters.
"""
if isarc(c):
return deepcopy(c)
elif ispoint(c):
cen = point(c)
w=-1
if samplereverse:
... | 5,307,625 |
def factorial(num):
"""Finds the factorial of the input integer.
:arg num: an integer
"""
#If the number provided is zero then the factorial is 1
if num == 0:
fact = 1
#Otherwise set fact to 1 and begin finding the factorial r is
#used to find each num-n for n=0 to n=num each v... | 5,307,626 |
def MaybeEmulateMultiBleu(nltk_target_fn):
"""Includes emulate_multibleu argument into nltk_target_fn if necessary.
The signature of the NLTK functions corpus_bleu and sentence_bleu depend on
the NLTK version. This function works around version differences encountered
in the public and internal environments.
... | 5,307,627 |
def incoming_cloudwatch_alarm(event, _):
"""
Standard AWS Lambda entry point for receiving CloudWatch alarm notifications.
"""
print(event)
try:
updated_timestamp = int(time.time())
ddb_table_name = ALARMS_TABLE_NAME
ddb_resource = boto3.resource('dynamodb', config=MSAM_BOTO3... | 5,307,628 |
def sort_data_into_spectrum(
ions: np.ndarray, bin_start: int, bin_end: int
) -> np.ndarray: # pragma: nocover
"""Sort ion data in 1D array into an overall array and sum them up.
:param ions: Arrival time of the ions - number of time bin
:param bin_start: First bin of spectrum
:param bin_end: Last... | 5,307,629 |
def RX_partitioning_replicates_extended(data_arr,ind,perc,Issues=[],Skip=False,extension=0,Cap=None,ll=0):
"""
partition sequence trace using tape measure
processes involved:
find tape measure peaks (peak_finder)
extract sequencing traces between tape measure peaks
calculate bin width... | 5,307,630 |
def has_same_sign_or_zero(data):
"""Evaluate whether the array has all elements with the same sign or zero.
Args:
data (np.array): An array.
Returns:
bool: Boolean with the evaluation.
Examples:
>>> data = np.array([(1,2,3),(2,3,4)])
>>> has_same_sign_or_ze... | 5,307,631 |
def showLogin():
"""Login page view."""
state = ''.join(
random.choice(string.ascii_uppercase + string.digits)
for x in xrange(32))
login_session['state'] = state
return render_template('home/login.html', STATE=state) | 5,307,632 |
def dump_svlengths_report_data(bed_ifs):
"""Given input-file-stream of BED,
return JSON string of svlengths_report_data.
"""
with BedReader(bed_ifs) as reader:
return json.dumps(get_svlengths_report_data(reader)) | 5,307,633 |
def auto_delete_file_on_delete(sender, instance, **kwargs):
"""Deletes file from filesystem
when corresponding `BookModel` object is deleted.
"""
def remove_if_exist(fields=[]):
for field in fields:
if field:
if os.path.isfile(field.path):
os.remov... | 5,307,634 |
def tree_left_fa_fun(t, assignment=None):
"""Given some tree node `t`, do FA assuming the left branch is the
function."""
result = tree_fa_fun_abstract(t[0], t[1], assignment)
if result is None:
raise TypeMismatch(t[0], t[1], "FA/left")
return BinaryComposite(t[0], t[1], result, source=t) | 5,307,635 |
def test_stringify_raw_cmd():
"""
Use for debugging - ensure that the shell command generated is sensible.
"""
cmd = RawCmd()
cmd.jar = get_tlc_path()
args = TlcArgs()
args.cleanup = True
args.workers = "auto"
args.config = "HelloWorld.cfg"
args.file = "HelloWorld.tla"
cmd.ar... | 5,307,636 |
def main():
""" Install xact and override xaudio2_7 to native
"""
print('Applying fixes for Portal Knights')
# install xact
util.protontricks('xact')
# set xaudio2_7.dll to native
util.winedll_override('xaudio2_7', 'n') | 5,307,637 |
def init_prompt(n, kw):
"""run before each command"""
# -R reset terminal state:
lp.sprun('tmux send-keys -R -t %s:1' % n)
lp.sprun('tmux clear-history -t %s:1' % n)
lp.sprun("tmux send-keys -t %s:1 '' Enter" % n)
t0 = now()
p = prompt(kw)
while now() - t0 < 2:
res = lp.sprun('tm... | 5,307,638 |
async def test_relay_toggle(serial_mock, bus):
"""Check that relays can be toggled"""
relay = bus.relay(1, 3)
assert relay.off
_, packet1, packet2 = await gather(
relay.toggle(), serial_mock.read(), serial_mock.read()
)
assert packet1 == Packet(1, 3, False)
assert packet2 == Packet(1... | 5,307,639 |
def test_chol3():
"""[summary]"""
l3 = [[0.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]]
m3 = np.array(l3)
Q = chol_ext(len(m3))
assert not Q.factorize(m3)
ep = Q.witness()
assert Q.p == (0, 1)
assert Q.v[0] == 1.0
assert ep == 0.0 | 5,307,640 |
def list_statistic_ids(
hass: HomeAssistant, statistic_type: str | None = None
) -> list[dict[str, str] | None]:
"""Return statistic_ids and meta data."""
units = hass.config.units
statistic_ids = {}
with session_scope(hass=hass) as session:
metadata = _get_metadata(hass, session, None, stat... | 5,307,641 |
def GetFirmwareBinaryVersion(path):
"""Gets the version stored in RO_FRID section of the firmware binary.
Args:
path: Path to the firmware binary.
Returns:
The extracted firmware version as a string; or None if the function fails to
extract version.
"""
result = None
try:
return fmap.Firmw... | 5,307,642 |
def user_post_sequence_info_fail(msg):
"""
Adds information to be displayed to the user at the end of the sequence if the tests fail or error.
This information will be displayed in the order that post sequence info calls are made and will remove duplicates
:param msg: String as it should be displayed
... | 5,307,643 |
def parse_alpino_file(path: str) -> list[Proof]:
"""
Parses an Alpino file containing a single sentence and returns a list of proofs.
"""
with open(path, 'r') as f:
etree = parse(path)
name = etree.find('sentence').attrib['sentid']
trees = prepare_for_extraction(etree, name)
retu... | 5,307,644 |
def symlink_libraries(self, source, destination):
""" Creates a smybolic link for libraries.
An ant_glob is executed on the source node using "*" + result of get_dynamic_lib_extension to determine all the libraries that need to be linked into the destination. If the package is being built for a release co... | 5,307,645 |
def integrator(int_alg,timestep,pos,veloc,accel,molec,grad_method):
""" Selects the type of integration algorithm to propagate the trajectories
Only velocity Verlet implemented (date: 05/23/17 - LAC)
Parameters:
----------
string int_alg -- Integrator Algorith to be used
... | 5,307,646 |
def generate_detail_link_dict(instance: Dict) -> Dict:
"""
Generate a dictionary that consists of this instance's provider discriminators, so that we can convert it to a link
to the instance detail page.
:param instance: A dict representing an instance, that contains `provider` keys and keys for all di... | 5,307,647 |
def get_cookie_expiry_datetime(cookie):
"""
example cookie:
sessionid=XXXXXXXXXXXXXXXXXXXXX; expires=Wed, 16-Mar-2011 17:52:10 GMT; Max-Age=2592000; Path=/, ds_user=USERNAME; Max-Age=2592000; Path=/, ds_user_id=USERID; Max-Age=2592000; Path=/
"""
try:
start = cookie.lower().find('expires') +... | 5,307,648 |
def update_connectivity_info(ConnectivityInfo=None, ThingName=None):
"""
Updates the connectivity information for the core. Any devices that belong to the group which has this core will receive this information in order to find the location of the core and connect to it.
See also: AWS API Documentation
... | 5,307,649 |
def colorize_groups(figure, group=None, saturations_map=None):
"""Colorize groups representations."""
nr_colors = figure.shape[0]
assert nr_colors in [4], 'color map assumes four groups.'
color_conv = 1 - GROUP_COLORS
if group is not None:
new_figure = np.dot(color_conv[[group]].T, figure.... | 5,307,650 |
def combine_targets_and_zeros(target_strings, php_zero_strings, zero_strings, n_collisions):
"""Combines the zero strings with the target strings until the desired number of collisions is reached"""
i = 0
ret = []
while True:
for php_zero in php_zero_strings:
for middle_zeros in ite... | 5,307,651 |
def get_all_links(url: str) -> LinksType:
"""
Sends http request to url, downloads all data,
extract links
Args:
url: url of website we want to search
Returns:
list of all links
"""
# create response object
r = requests.get(url)
# create beautiful-sou... | 5,307,652 |
def basic_sweep() -> Sequence[ensemble_plus.EnsembleConfig]:
"""Basic sweep over hyperparams."""
sweep = []
for num_ensemble in [1, 3, 10, 30, 100]:
sweep.append(ensemble_plus.EnsembleConfig(
num_ensemble=num_ensemble,
))
return tuple(sweep) | 5,307,653 |
def create_event(slope, plateau, tau, dt, alpha=1e-3, smothing_length=None):
"""
Create an artificial event.
Parameters
----------
slope: float
Slope of the rising.
plateau: float
Time of the middle plataue.
tau: float
Time constant of the capacitor behavior.
dt:... | 5,307,654 |
def query_object(*,
select: Optional[str] = fastapi.Query(
None,
title='The list of fields to select.',
description='Example: `[id, login, { users: {... } }]`. JSON or YAML.',
),
join: Optional[str] = fastapi.Query(
None,
title='The lis... | 5,307,655 |
def get_storm_track_colours():
"""Returns list of colours to use in plotting storm tracks.
:return: rgb_matrix: 10-by-3 numpy array. rgb_matrix[i, 0] is the red
component of the [i]th colour; rgb_matrix[i, 1] is the green component
of the [i]th colour; rgb_matrix[i, 2] is the blue component of... | 5,307,656 |
def postprocess_individual_report(file, final_dict, data_source=None):
"""Postprocesses individual report
Args:
file: output dict for individual reports
final_dict: Dict for storing all the reports
"""
try:
temp_dict = {}
temp_dict['text'] = " ".join(file[... | 5,307,657 |
def philippines_calibration(max_seconds, run_id):
"""Run Malaysia COVID model calibration."""
run_philippines_covid_calibration_chain(max_seconds, run_id) | 5,307,658 |
def calc_delta_lampam_mp(ss, multipanel, constraints, inner_step=-1):
"""
returns the lamination parameters associated with a group of plies of a
multi-panel structure
OUTPUTS
- delta_lampam: array storing the sublaminate partial lamination parameters
INPUTS
- ss: array storing the subla... | 5,307,659 |
def load_model(model_class):
"""This function is for loading the saved model"""
# Define the file directory for each model
if model_class == 'mlp':
filedir = './mtn/mlp'
elif model_class == 'mlp_angle':
filedir = './mtn/mlp_angle'
elif model_class == 'lstm':
filedir = './mtn/... | 5,307,660 |
def rvabs_for_orders(ww_all,ff_all,orders,v,M,v2_width=25.,plot=True,ax=None,bx=None,verbose=True,n_points=40):
"""
Same as rvabs, except loop for different orders. Useful for error estimation
EXAMPLE:
v = np.linspace(-120,120,2000)
rr1, rr2 = rvabs_for_orders(ww_all_targ,ff_all_targ,[4... | 5,307,661 |
def test_v1_0_workflow_top_level_sf_expr_array() -> None:
"""Test for the correct error when converting a secondaryFiles expression (array form) in a workflow level input."""
with raises(WorkflowException, match=r".*secondaryFiles.*"):
result, modified = traverse0(
parser.load_document(
... | 5,307,662 |
def test_invoke_method(restApiId=None, resourceId=None, httpMethod=None, pathWithQueryString=None, body=None, headers=None, clientCertificateId=None, stageVariables=None):
"""
Simulate the execution of a Method in your RestApi with headers, parameters, and an incoming request body.
See also: AWS API Docum... | 5,307,663 |
def placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None):
"""Instantiates a placeholder tensor and returns it.
# Arguments
shape: Shape of the placeholder
(integer tuple, may include `None` entries).
ndim: Number of axes of the tensor.
At least one of ... | 5,307,664 |
def gen_dataset_from_txt(path_prefix, in_txt_f_path, dst_root, out_txt_f_path):
"""
:param path_prefix:
:param in_txt_f_path:
:param dst_root:
:param out_txt_f_path:
:return:
"""
if not os.path.isfile(in_txt_f_path):
print('[Err]: invalid input txt file.')
return
if ... | 5,307,665 |
def fiup(ctx, collection, path, registry, dest, pool_size):
"""Collect files in a study by COLLECTION (accession number or "ALL") using a
PATH REGISTRY, and send to DEST."""
services = ctx.obj.get('services')
click.echo(click.style('Upload Registered Files by Accession Number',
... | 5,307,666 |
def test_documentation():
"""
Does nothing.
""" | 5,307,667 |
def test_clean_valid_token(client_admin_invite_factory):
"""
If the token provided to the form is valid, the clean method should
save the associated invite on the form instance.
"""
invite = client_admin_invite_factory()
form = forms.ClientAdminInviteAcceptForm(invite.token)
form.clean()
... | 5,307,668 |
def save_json_db_data():
"""Saves database tables containing data information, such as 'events_with_value' or 'prosensing_paf' events, to a
json file. 'num_entries' for each table specifies how many data rows are in the file for the table, making
iterative parsing much easier.
Example File (indentatio... | 5,307,669 |
def make_output_dir(outdir):
"""Make the output_dir if it doesn't exist.
Parameters
----------
outdir : output directory to create
"""
if not os.path.exists(os.path.abspath(outdir)):
# XXX Should this use os.makedirs which will make any
# necessary parent directories? I di... | 5,307,670 |
def remove_sentiment(sentiment):
"""
Removes the given sentiment
:param: sentiment
Sentiment to be removed
"""
db.session.delete(sentiment)
db.session.commit() | 5,307,671 |
def create_p12(logger, ctx, name, pem, key, password, config, force, verbose, debug):
"""
\b
Create a simple p12
Need key file and pem file
\f
:param logger:
:param ctx:
:param name:
:param pem:
:param key:
:param password:
:param config:
:param force:
:param ver... | 5,307,672 |
async def on_ready():
"""Set up variables and logging
"""
log.debug('Running {}'.format(on_ready.__name__))
await bot.wait_until_ready()
log.debug('Logged in as {}'.format(bot.user.name))
channel = bot.get_channel(int(CHANNEL))
log.debug('Channel is {}'.format(channel))
with open("MES... | 5,307,673 |
def replace_number_chunks(msg, tar='?'):
""" Replace digits and adjacent alphabets with the given term
@param msg: Input message
@type msg: String
@param tar: New term to replace
@type tar: String
@return: Replaced message
@rtype: String
"""
def find_first_digit(msg):
f... | 5,307,674 |
def sortino(rp: torch.Tensor, rf: torch.Tensor) -> torch.Tensor:
"""Returns the sortino ratios for p portfolios
Args:
rp (torch.Tensor): p-by-n matrix where the (i, j) entry corresponds to
the j-th return of the i-th portfolio
rf (torch.Tensor): Scalar risk-free rate (as a 0-D tensor)... | 5,307,675 |
def rl_decon(
im: np.ndarray,
background: Union[int, Literal["auto"]] = 80,
n_iters: int = 10,
shift: int = 0,
save_deskewed: bool = False,
output_shape: Optional[Tuple[int, int, int]] = None,
napodize: int = 15,
nz_blend: int = 0,
pad_val: float = 0.0,
dup_rev_z: bool = False,
)... | 5,307,676 |
def create_execution_directory(project, suite_name, timestamp):
"""Create report directory for a suite execution.
Directory should have the following path:
<testdir>/projects/<project>/reports/<suite_name>/<timestamp>/
"""
directory = suite_execution_path(project, suite_name, timestamp)
if not ... | 5,307,677 |
def all_gates(QuantumCircuit, nr_qubits, initial):
"""This function determines the matrix which corresponds to applying the whole circuit.
Input
-----
QuantumCircuit: np.array
The quantum circuit in the form of a numpy array
nr_qubits: int
... | 5,307,678 |
def fuse_single_qubit_operators(
qubits: Iterable[int],
operators: Iterable[torch.Tensor],
):
"""Multiply together gates acting on various single qubits.
Suppose that we have a sequence of single-qubit gates that
should act, one after the other, on designated qubits.
If any qubit repeat... | 5,307,679 |
def pprint_c(*outcomes):
"""print casualties of winner"""
a1w = [x for x in outcomes if x[0][0] != 0] #excludes mutual destruction
a2w = [x for x in outcomes if x[0][1] != 0]
totala1 = sum([x[1] for x in a1w])
totala2 = sum([x[1] for x in a2w])
print("attacker casualties when victorious:")
... | 5,307,680 |
def make_message(subject="", body="", from_email=None, to=None, bcc=None,
attachments=None, headers=None, priority=None):
"""
Creates a simple message for the email parameters supplied.
The 'to' and 'bcc' lists are filtered using DontSendEntry.
If needed, the 'email' attribute can ... | 5,307,681 |
def noneof(*items):
""" noneof(*items) → Return the result of “not any(…)” on all non-`None` arguments """
return negate(any)(item for item in items if item is not None) | 5,307,682 |
def process_normal_file_message(
ddb_table,
dynamodb_client,
sns_client,
sqs_client,
correlation_id,
collection_name,
snapshot_type,
export_date,
shutdown_flag,
reprocess_files,
sns_topic_arn,
sqs_queue_url,
file_name,
):
"""Processes an individual normal files me... | 5,307,683 |
def test_chunks():
"""Test the chunk creation utility function."""
assert list(chunks('123456', 2)) == ['12', '34', '56']
assert list(chunks('1234567', 2)) == ['12', '34', '56', '7']
assert list(chunks('1234567', [1, 2, 3])) == \
['1', '23', '456', '7']
assert list(chunks('123', [1, 2, 3, 4]... | 5,307,684 |
def parse_visitor_score(d):
""" Used to parse score of visiting team.
"""
string_value = d.get("uitslag", " 0- 0")
(_, v) = string_value.replace(" ", "").split("-")
return int(v) | 5,307,685 |
def getNumberSameAsIndex(nums):
"""数组中数值和下标相等的元素
单调递增的数组里的每一个元素都是整数并且唯一,找出数组中任意一个数值等于其下标的元素
"""
pass | 5,307,686 |
def local_action_PauseOnGroup(arg=None):
"""{"group": "Playback - Group", "schema": {"type": "object", "title": "Args", "properties": {
"group": {"type": "number", "order": 2, "title": "Group"}}}}"""
query = 'G%sPA\r' % arg['group']
queue.request(lambda: udp.send(query),
lambda resp: hand... | 5,307,687 |
def get_written_file_path(line):
"""
Handles the acquisition of the path string for a written file.
It is used to handle linux problems with windows style path strings.
:param line: current line of the pandalog
:return: path to the written file
"""
fixed_substring = u'filename,'
index ... | 5,307,688 |
def ring2nest(nside, ipix):
"""Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`."""
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
return ring_to_nested(ipix, nside) | 5,307,689 |
def get_key_info_for_fmap_assignment(json_file, matching_parameter):
"""
Gets key information needed to assign fmaps to other modalities.
(Note: It is the responsibility of the calling function to make sure
the arguments are OK)
Parameters:
----------
json_file : str or os.path
path... | 5,307,690 |
def tag_index(idx):
"""Return a mapping of tag names to index items.
"""
tagidx = dict()
for i in idx:
for t in i.tags:
if t not in tagidx:
tagidx[t] = set()
tagidx[t].add(i)
return tagidx | 5,307,691 |
def plot_states_over_time(states_over_time, time_steps, plot_title='', u=[]):
""" Plot the states over time.
"""
# Height and vertical velocity over time:
plt.figure();
plt.plot(time_steps, states_over_time[:,0], label='z');
plt.plot(time_steps, states_over_time[:,1], label='v_z');
plt.... | 5,307,692 |
def node_text(node):
"""Needed for things like abstracts which have internal tags (see PMID:27822475)"""
if node.text:
result = node.text
else:
result = ""
for child in node:
if child.tail is not None:
result += child.tail
return result | 5,307,693 |
def hollow(x1, y1, z2, x2, y2, z2, b):
"""Build a hollow enclosure"""
mc.setBlocks(x1, y1, z1, x2, y2, z2, b)
mc.setBlocks(x1+1, y1+1, z1+1, x2-1, y2-1, z2-1, block.AIR.id) | 5,307,694 |
def read_stc(filepath):
"""Read an STC file from the MNE package
STC files contain activations or source reconstructions
obtained from EEG and MEG data.
Parameters
----------
filepath: string
Path to STC file
Returns
-------
data: dict
The STC structure. It has the... | 5,307,695 |
def opd_drift_nogood(opd, drift, nterms=8, defocus_frac=0.8):
"""
Add some WFE drift (in nm) to an OPD image.
Parameters
------------
opd : ndarray
OPD images (can be an array of images).
header : obj
Header file
drift : float
WFE drift in nm
Returns
-------... | 5,307,696 |
def test_regression_yaw_added_recovery(sample_inputs_fixture):
"""
Tandem turbines with the upstream turbine yawed and yaw added recovery
correction enabled
"""
sample_inputs_fixture.floris["wake"]["properties"][
"velocity_model"
] = VELOCITY_MODEL
sample_inputs_fixture.floris["wake"... | 5,307,697 |
def created_health_check_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.create_health_check` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: ... | 5,307,698 |
def map_nn(names):
"""
A function used to wrap choices as nn.Module for non-one-shot space definition
Parameters
----------
name : list of anything
the names of module, can be any type
"""
return [StrModule(x) for x in names] | 5,307,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.