content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def bond(fn: Callable[..., Array],
displacement_or_metric: DisplacementOrMetricFn,
static_bonds: Optional[Array]=None,
static_bond_types: Optional[Array]=None,
ignore_unused_parameters: bool=False,
**kwargs) -> Callable[..., Array]:
"""Promotes a function that acts on a si... | 1,600 |
def clean_repeated_symbols(text):
"""
Filters text, replacing symbols repeated more than twice (not allowed
in most languages) with a single repetition of the symbol.
:param text: the text to be filtered
:type: str
:return: the filtered text
:type: str
"""
pattern = re.compile(r"(.)\... | 1,601 |
def sample(x,y, numSamples):
"""
gives numSamples samples from the distribution funciton fail
parameters
"""
y /= y.sum()
return np.random.choice(x, size=numSamples, replace=True, p=y) | 1,602 |
def make_path_strictly_increase(path):
"""
Given a warping path, remove all rows that do not
strictly increase from the row before
"""
toKeep = np.ones(path.shape[0])
i0 = 0
for i in range(1, path.shape[0]):
if np.abs(path[i0, 0] - path[i, 0]) >= 1 and np.abs(path[i0, 1] - path[i, 1]... | 1,603 |
def generate_frequency_spectrum(samples, wild_threshold):
"""
Generates the site frequency spectrum for a given set of samples
:param samples: List of sample accession codes
:param wild_threshold: The index position of the last wild sample (used for resolving group membership)
:return:
"""
... | 1,604 |
def set_group_selector(*args):
"""set_group_selector(sel_t grp, sel_t sel) -> int"""
return _idaapi.set_group_selector(*args) | 1,605 |
def callCisLoops(
predir,
fout,
log,
eps=[2000, 5000],
minPts=[5, 10],
cpu=1,
cut=0,
mcut=-1,
plot=False,
max_cut=False,
hic=False,
filter=False,
ucsc=False,
juicebox=False,
washU=False,
emPai... | 1,606 |
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_latency_characteristictraffic_property_name_get(uuid, node_uuid, node_rule_group_uuid, traffic_property_name): # noqa: E501
"""data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uui... | 1,607 |
def upgrade_db():
"""Run any outstanding migration scripts"""
_run_alembic_command(['--raiseerr', 'upgrade', 'head']) | 1,608 |
def assert_is_quantized_sequence(note_sequence):
"""Confirms that the given NoteSequence proto has been quantized.
Args:
note_sequence: A music_pb2.NoteSequence proto.
Raises:
SequenceNotQuantizedException: If the sequence is not quantized.
"""
# If the QuantizationInfo message has a non-zero steps_... | 1,609 |
def getPendingReviewers(db, review):
"""getPendingReviewers(db, review) -> dictionary
Returns a dictionary, like the ones returned by getReviewersAndWatchers(), but
with details about remaining unreviewed changes in the review. Changes not
assigned to a reviewer are handled the same way."""
cursor = db.curso... | 1,610 |
def base64_encode_string(string):
# type: (str or bytes) -> str
"""Base64 encode a string
:param str or bytes string: string to encode
:rtype: str
:return: base64-encoded string
"""
if on_python2():
return base64.b64encode(string)
else:
return str(base64.b64encode(string)... | 1,611 |
def get_error_signature(error_type, n_top, **kwargs):
"""Generates a signature for the specified settings of pose error
calculation.
:param error_type: Type of error.
:param n_top: Top N pose estimates (with the highest score) to be evaluated
for each object class in each image.
:return: Gene... | 1,612 |
def clean_text_from_multiple_consecutive_whitespaces(text):
"""Cleans the text from multiple consecutive whitespaces, by replacing these with a single whitespace."""
multi_space_regex = re.compile(r"\s+", re.IGNORECASE)
return re.sub(multi_space_regex, ' ', text) | 1,613 |
def run(filename):
"""
MUST HAVE FUNCTION!
Begins the plugin processing
Returns a list of endpoints
"""
run_results = set()
r_rule = re.compile(r"(Route\(\"[^,)]+)", flags=re.IGNORECASE)
for line in filename:
try:
route_match = r_rule.search(line)
if rout... | 1,614 |
async def setup_script(hass, notify_q, notify_q2, now, source, config=None):
"""Initialize and load the given pyscript."""
conf_dir = hass.config.path(FOLDER)
file_contents = {f"{conf_dir}/hello.py": source}
Function.hass = None
mock_open = MockOpen()
for key, value in file_contents.items():... | 1,615 |
def get_assignment_grade_summaries(course_id):
""" return a list of a course's assignments with a grade summary for each
https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.course_assignments """
assignments = api.get_list('courses/{}/analytics/assignments'.format(course_id))
... | 1,616 |
def test_is_square_invalid():
"""Input must be a matrix."""
with np.testing.assert_raises(ValueError):
is_square(np.array([-1, 1])) | 1,617 |
def _list_descriptors():
"""Return a list of all registered XModuleDescriptor classes."""
return sorted(
[
desc for (_, desc) in XModuleDescriptor.load_classes()
] + XBLOCK_CLASSES,
key=str
) | 1,618 |
def e3p0(tof,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10):
"""
Background function for TOF spectra
Parameters
----------
tof : array-like
The time-of-flight spectrum
p1 : float
constant background
p2 : float
multiplier on 1st exponential
p3 : float
multiplier on time-... | 1,619 |
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
global word_dict
with open(FILE, "r") as f:
for line in f:
line = line.strip()
word_dict.append(line) | 1,620 |
def padre_response_and_code_jump(context, response, connection):
"""
I expect a response and to jump to a point in the code in two separate
messages
"""
num_expected_results = len(context.table.rows) + 1
results = read_results(
num_expected_results, context.connections[int(connection)][0... | 1,621 |
def dice_coefficient(pred, gt):
"""
Computes dice coefficients between two masks
:param pred: predicted masks - [0 ,1]
:param gt: ground truth masks - [0 ,1]
:return: dice coefficient
"""
d = (2 * np.sum(pred * gt) + 1) / ((np.sum(pred) + np.sum(gt)) + 1)
return d | 1,622 |
def test_generic_data_wrapper_verifier_failure():
"""
Test that a GenericData used in constraints fails
the verifier when constraints are not satisfied.
"""
with pytest.raises(VerifyException) as e:
ListDataWrapper(
[ListData([BoolData(True),
ListData([Bool... | 1,623 |
def get_keep_score(source_counts, prediction_counts, target_counts):
"""Compute the keep score (Equation 5 in the paper)."""
source_and_prediction_counts = source_counts & prediction_counts
source_and_target_counts = source_counts & target_counts
true_positives = sum((source_and_prediction_counts & sour... | 1,624 |
def run_decode_generator(gc, env):
"""Run the decode table generator"""
if env == None:
return (1, ['no env!'])
xedsrc = env.escape_string(env['src_dir'])
build_dir = env.escape_string(env['build_dir'])
debug = ""
other_args = " ".join(env['generator_options'])
gen_extra_args =... | 1,625 |
def dict_comparator(first_dict, second_dict):
"""
Функция проверяет на совпадение множеств пар ключ-значение для двух словарей
Возвращает True в случае совпадения, иначе False
"""
if set(first_dict.keys()) != set(second_dict.keys()):
return False
for key, value in first_dict.item... | 1,626 |
def word_check(seq1,seq2,word):
"""Returns False and aborts if seq2 contains a substring of seq1 of length word. Returns True otherwise"""
for i in range(len(seq1)-word+1):
if seq2.find(seq1[i:i+word])>-1: return seq2.find(seq1[i:i+word])
return -1 | 1,627 |
def plasma_parameter(N_particles, N_grid, dx):
"""
Estimates the plasma parameter as the number of particles per step.
Parameters
----------
N_particles : int, float
Number of physical particles
N_grid : int
Number of grid cells
dx : float
grid step size
"""
... | 1,628 |
def get_ious_and_iou_loss(inputs,
targets,
weight=None,
loss_type="iou",
reduction="none"):
"""
Compute iou loss of type ['iou', 'giou', 'linear_iou']
Args:
inputs (tensor): pred values
t... | 1,629 |
def _worker(exit_e: threading.Event, e_conf: threading.Event,
job_q: queue.Queue, res_q: queue.Queue, max_closed: int) -> None:
"""Worker thread -> consumes jobs that are executed in a Solver thread."""
sol = solver.Solitaire()
while not exit_e.is_set():
try:
seed, draw_coun... | 1,630 |
def load_chembl():
"""Downloads a small subset of the ChEMBL dataset.
Returns
-------
ic50_train: sparse matrix
sparse train matrix
ic50_test: sparse matrix
sparse test matrix
feat: sparse matrix
sparse row features
"""
# load bioactivity and features
ic5... | 1,631 |
def test_skip(schema, schemas, expected_schema):
"""
GIVEN given schema, schemas and expected schema
WHEN merge is called with the schema and schemas and skip name
THEN the expected schema is returned.
"""
skip_name = "RefSchema"
return_schema = helpers.all_of.merge(
schema=schema, ... | 1,632 |
def validate_name_dynamotable(table_name):
"""Validate if table name matches DynamoDB naming standards."""
if not isinstance(table_name, str):
ValueError('Input argument \"name\" must a string')
if table_name.__len__() < 3 or table_name.__len__() > (255 - 5):
# note: deduct 5 chars to allow... | 1,633 |
def test_compute():
"""Tests that it works for a simple example."""
activation_layers = [
FullyConnectedLayer(np.eye(2), np.ones(shape=(2,))),
ReluLayer(),
FullyConnectedLayer(2.0 * np.eye(2), np.zeros(shape=(2,))),
ReluLayer(),
]
value_layers = activation_layers[:2] + [
... | 1,634 |
def kill(ctx, *args, **kw_args):
"""Kill existing running servers."""
# Get the config parser object.
config = ctx.obj["config_obj"]
s = Server(config)
print("Killing ...", end="")
s.kill()
print("... Done") | 1,635 |
def delete_item(item_id):
"""
The method deletes item with the provided id.
:param item_id: id of the item to be deleted
:return: http response
"""
try:
if DATA_CONTROLLER.delete_bucketlist_item(item_id):
return make_response("", 200)
else:
return make_r... | 1,636 |
def test_child_class():
"""It can use method of child class normally"""
client = app.test_client()
resp = client.post('/child-class/')
eq_(b"POST", resp.data) | 1,637 |
def fix_all_workspace_info(
ws_url, auth_url, token, max_id, outfile=DEFAULT_OUTPUT_FILE
):
"""
Iterates over all workspaces available at the ws_url endpoint, using the given admin token,
and applies _fix_single_workspace_info to each.
ws_url = endpoint for the workspace service to modify
auth_u... | 1,638 |
def import_from_text_file(filename, defaultExt, readDataFcn, verbose=False):
"""
Opens a given text file and reads data using the specified function
Parameters
----------
filename : str
the path of a file
defaultExt : str
the default extension of the file
readDataFcn : calla... | 1,639 |
def is_template_definition(metric_name):
"""Return if the given metric name is a template definition by
convention."""
fields = metric_name.split('/')
return fields[0].lower() == TEMPLATE_DEFINITION_PREFIX | 1,640 |
def _cm_ramp_points_and_voltages(abf):
"""
Return [points, voltages] if the sweep contains a ramp suitable for
capacitance calculation using a matching doward and upward ramp.
points is a list of 3 numbers depicting index values important to this
ramp. The first number is the index at the start of ... | 1,641 |
def single_model_embeddings_specify(single_model_embeddings):
"""Returns an instance of MultiTaskLSTMCRF initialized with the default configuration file,
loaded embeddings and single specified model."""
single_model_embeddings.specify()
return single_model_embeddings | 1,642 |
def load_json(filename):
"""
Load a JSON file that may be .bz2 or .gz compressed
"""
if '.bz2' in filename:
import bz2
with bz2.open(filename, 'rt') as infile:
return json.load(infile)
elif '.gz' in filename:
import gzip
with gzip.open(filename, 'rt') as i... | 1,643 |
def get_future_contracts(underlying_symbol, date=None):
"""
获取某期货品种在策略当前日期的可交易合约标的列表
:param security 期货合约品种,如 ‘AG’(白银)
:return 某期货品种在策略当前日期的可交易合约标的列表
"""
assert underlying_symbol, "underlying_symbol is required"
dt = to_date_str(date)
return JQDataClient.instance().get_future_contracts(... | 1,644 |
def rodeo_query(fc, pallet): # 3.5-4 seconds for 150 elem
"""
Get pd DataFrame with info from rodeo about pallet/tote in TS Out.
:param fc: str
:param pallet: Pallet or Tote are accepted.
:return: df or "No data was found" if status_code = 200, "There was an error ... | 1,645 |
def plan_to_joint_configuration(robot, qgoal, pname='BiRRT', max_iters=20,
max_ppiters=40, try_swap=False):
"""
Plan a trajectory to the given `qgoal` configuration.
Parameters
----------
robot: orpy.Robot
The OpenRAVE robot
qgoal: array_like
The goal... | 1,646 |
def _get_texinfo(data):
"""Return the texture information of a texture data.
Arguments:
* data: the texture data as an array.
Returns:
* texinfo: a dictionary with the information related to the texture data.
"""
assert data.ndim == 3
size = data.shape[:2]
if siz... | 1,647 |
def test_get_idn(switch_driver):
"""
to check if the instrument attributes are set correctly after getting
the IDN
"""
assert switch_driver.IDN() == {
"vendor": "Keysight",
"model": "34980A",
"serial": "1000",
"firmware": "0.1"
} | 1,648 |
def set_featured_notebooks(notebook_ids): # noqa: E501
"""set_featured_notebooks
:param notebook_ids: Array of notebook IDs to be featured.
:type notebook_ids: List[str]
:rtype: None
"""
update_multiple(ApiNotebook, [], "featured", False)
if notebook_ids:
update_multiple(ApiNote... | 1,649 |
def speed_to_cadences(bicycle, speed, digits=None):
"""
Return cadences in hertz (revolutions per second).
Speed is measured in kilometers per hour.
Assume the following bicycle attributes are non-null and non-empty:
- front_cogs
- rear_cogs
- crank_length
- rear_wheel
Raise a ``V... | 1,650 |
def _gen_version(fields):
"""Looks at BotGroupConfig fields and derives a digest that summarizes them.
This digest is going to be sent to the bot in /handshake, and bot would
include it in its state (and thus send it with each /poll). If server detects
that the bot is using older version of the config, it woul... | 1,651 |
def getopt(clf, ret_val, isbool=False):
""" Command Line Option input parser"""
found = []
def getCLO(flag):
iindx = sys.argv.index(flag)
sys.argv.pop(iindx)
return sys.argv.pop(iindx)
if isbool: return (clf in sys.argv)
while clf in sys.argv: found.append(getCLO(clf))
if... | 1,652 |
def pay_and_save_financing(req: request, request_json, account_id):
"""Set up the financing statement, pay if there is an account id, and save the data."""
# Charge a fee.
token: dict = g.jwt_oidc_token_info
statement = FinancingStatement.create_from_json(request_json, account_id, token.get('username', ... | 1,653 |
def resolve_cmds_path(cmds, singlesrv_mode):
"""Resolve the cmds path if in single server mode.
Args:
cmds: A list of sender/receiver commands.
singlesrv_mode: A bool on whether running in single server mode.
Returns:
The commands that path has been resolved if needed
(in s... | 1,654 |
def _encode_base64(data: str) -> str:
"""Base 64 encodes a string."""
ebytes = base64.b64encode(data.encode("utf-8"))
estring = str(ebytes, "utf-8")
return estring | 1,655 |
def downgrade():
"""schema downgrade migrations go here."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("answers")
op.drop_table("questions")
# ### end Alembic commands ### | 1,656 |
def workflow_spec(
dag: DAG,
workflow: Workflow,
) -> Mapping[str, Any]:
"""
Return a minimal representation of a WorkflowSpec for the supplied DAG and metadata.
Spec: https://github.com/argoproj/argo-workflows/blob/v3.0.4/docs/fields.md#workflowspec
Parameters
----------
dag
... | 1,657 |
def redirect(request):
"""
Handling what happens when the groupcode is submitted by user and handles input from user's when they are answering
questions.
:param request:
:return: The methods returns the student view page which is the actual game to the user if they entered a correct
groupcode, i... | 1,658 |
def test_plDensity():
"""Test the plDensity function."""
mass, radius = 1, 1
assert isinstance(plDensity(mass, radius), float)
assert round(plDensity(mass, radius), 2) == 1.33
assert plDensity(0, radius) == 0
with pytest.raises(ZeroDivisionError):
plDensity(mass, 0) | 1,659 |
def build_test_fn(policy, optim, log_dir, model_name, train_collector, save_train_buffer, obs_shape, stack_num, env_id,
num_episodes):
""" Build custom test function for maze world environment """
def custom_test_fn(epoch, env_step):
# Save agent
print(f"Epoch = {epoch}")
... | 1,660 |
def decode_2bit(iterable: Iterable[int], palette: Sequence[Color]) \
-> Iterable[int]:
"""For every two bytes consumed from the given iterable, generates 8 decoded
RGB8 colors based on the palette.
:param iterable: 2-bit grayscale encoded image.
:param palette: List of colors used to decode the... | 1,661 |
def check_score(encoding, min_qual, qual_str):
"""Return True if the average quality score is at least min_qual
"""
qscores = [encoding[q] for q in qual_str]
return sum(qscores) >= min_qual * len(qscores) | 1,662 |
def add_unsafe_warning(func, fig):
"""
Generate warning if not supported by Paxplot
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
if fig._show_unsafe_warning:
warnings.warn(
f'The function you have called ({func.__name__}) is not '
'offi... | 1,663 |
def update_dask_partitions_shuffle(
ddf: dd.DataFrame,
table: str,
secondary_indices: List[str],
metadata_version: int,
partition_on: List[str],
store_factory: StoreFactoryType,
df_serializer: DataFrameSerializer,
dataset_uuid: str,
num_buckets: int,
sort_partitions_by: Optional[... | 1,664 |
def edit_paycheck(paycheck_id):
""" Edit a paycheck """
paycheck = Paycheck.query.get(paycheck_id)
form = PaycheckForm(obj=paycheck)
return render_template('pay/edit_paycheck.jinja', form=form, paycheck_id=paycheck_id) | 1,665 |
def flake8(session):
"""Lint code with Flake8."""
session.run("flake8", *SOURCES, external=True) | 1,666 |
def is_meeting_approved(meeting):
"""Returns True if the meeting is approved"""
if meeting.session_set.first().status.slug == 'apprw':
return False
else:
return True | 1,667 |
def get_data_rows_after_start(
worksheet,
start_row,
start_col,
end_col,
page_size=SHEETS_VALUE_REQUEST_PAGE_SIZE,
**kwargs,
):
"""
Yields the data rows of a spreadsheet starting with a given row and spanning a given column range
until empty rows are encountered.
Args:
w... | 1,668 |
def F(
u,
v,
kappa,
rho,
cp,
convection,
source,
r,
neumann_bcs,
robin_bcs,
my_dx,
my_ds,
stabilization,
):
"""
Compute
.. math::
F(u) =
\\int_\\Omega \\kappa r
\\langle\\nabla u, \\nabla \\frac{v}{\\rho c_p}\\rangle
... | 1,669 |
def test_define_with_non_symbol_as_variable():
"""TEST 4.12: Defines require the first argument to be a symbol."""
with assert_raises_regexp(DiyLangError, "not a symbol"):
evaluate(parse("(define #t 42)"), Environment()) | 1,670 |
def check_radarr():
"""
Connects to an instance of Radarr and returns a tuple containing the instances status.
Returns:
(str) an instance of the Status enum value representing the status of the service
(str) a short descriptive string representing the status of the service
"""
try:
... | 1,671 |
def reversebits5(max_bits, num):
""" Like reversebits4, plus optimizations regarding leading zeros in
original value. """
rev_num = 0
shifts = 0
while num != 0 and shifts < max_bits:
rev_num |= num & 1
num >>= 1
rev_num <<= 1
shifts += 1
rev_num >>= 1
rev_... | 1,672 |
def rescale(img, thresholds):
"""
Linear stretch of image between two threshold values.
"""
return img.subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) | 1,673 |
def X_n120() -> np.ndarray:
"""
Fixture that generates a Numpy array with 120 observations. Each
observation contains two float values.
:return: a Numpy array.
"""
# Generate train/test data
rng = check_random_state(2)
X = 0.3 * rng.randn(120, 2)
return X | 1,674 |
def get_shp(shp_str):
"""
Return a shapely geometry in WGS84 lon/lat
input: shp_str - a string corresponding to an iso-3166-1 or -2 administrative area for admin-level 1 (countries) and -2 (states/provinces) respectively
"""
if len(shp_str.split('-'))>1:
load_fts = json.load(open(os.path.j... | 1,675 |
def int_to_bytes(n: uint64, length: uint64) -> bytes:
"""
Return the ``length``-byte serialization of ``n`` in ``ENDIANNESS``-endian.
"""
return n.to_bytes(length, ENDIANNESS) | 1,676 |
def upper_to_title(text, force_title=False):
"""Inconsistently, NiH has fields as all upper case.
Convert to titlecase"""
if text == text.upper() or force_title:
text = string.capwords(text.lower())
return text | 1,677 |
def test_ens_reverse_lookup(ethereum_manager):
"""This test could be flaky because it assumes
that all used ens names exist
"""
reversed_addr_0 = to_checksum_address('0x71C7656EC7ab88b098defB751B7401B5f6d8976F')
reversed_addr_1 = ethereum_manager.ens_lookup('lefteris.eth')
expected = {revers... | 1,678 |
def pairwise_negative(true, pred):
"""Return p_num, p_den, r_num, r_den over noncoreferent item pairs
As used in calcualting BLANC (see Luo, Pradhan, Recasens and Hovy (2014).
>>> pairwise_negative({1: {'a', 'b', 'c'}, 2: {'d'}},
... {1: {'b', 'c'}, 2: {'d', 'e'}})
(2, 4, 2, 3)
... | 1,679 |
def reptile_resurgence_links(tar_url, max_layer, max_container="", a_elem="a", res_links=[], next_url="", callback=None):
"""
爬虫层次挖掘,对目标 URL 进行多层挖链接
参数:目标 URL | 最大层数 | 爬取范围 | 爬取的a标签选择器 | 内部使用,返回列表 | 内部使用 下一个目标
"""
if next_url != "" and next_url[:4] in 'http':
res_links.append(next_url)
i... | 1,680 |
def _swap(list_, a, b):
"""
Swap items in positions a and b of list_.
list_ -- a list
a -- an index in list_
b -- an index in list_
"""
list_[a], list_[b] = list_[b], list_[a] | 1,681 |
def random_uniform(seed_tensor: Tensor,
shape: Tuple[int, ...],
low: float = 0.0,
high: float = 1.0,
dtype: dtypes.dtype = dtypes.float32):
"""
Randomly sample from a uniform distribution with minimum value `low` and maximum value `high... | 1,682 |
def pipelines_as_gdf():
"""
Return pipelines as geodataframes
"""
from shapely import wkt
def wkt_loads(x):
try:
return wkt.loads(x)
except Exception:
return None
df_fossil_pipelines = load_fossil_pipelines().query("route==route")
# Manual transform to... | 1,683 |
def historico(
historia="",sintomas="",medicamentos=""
):
"""Histótia: Adicionar os relatos de doenças anteriores do paciente,\n incluindo sintomas antigos e histórico de doenças familiares
\n Sintomas: Descrever os atuais sintomas do paciente
\n Medicamentos: Remédios e tratame... | 1,684 |
def com_ec2_sync_cmdb():
"""数据同步"""
com_ec2_list = get_ec2_list()
with DBContext('w') as session:
session.query(ComEc2).delete(synchronize_session=False) # 清空数据库的所有记录
for com_ec2 in com_ec2_list:
instance_id = com_ec2.get("InstanceId", "")
ami_id = com_ec2.get("Image... | 1,685 |
def plot_beam_ts(obs, title=None, pix_flag_list=[], reg_interest=None,
plot_show=False, plot_save=False, write_header=None,
orientation=ORIENTATION):
"""
plot time series for the pipeline reduction
:param obs: Obs or ObsArray or list or tuple or dict, can be the object
... | 1,686 |
def getcallargs(func, *positional, **named):
"""Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'."""
args, varargs, varkw, d... | 1,687 |
def get_qos():
"""Gets Qos policy stats, CLI view"""
return render_template('qos.html', interfaces=QueryDbFor.query_interfaces(device),
interface_qos=QueryDbFor.query_qos(device)) | 1,688 |
def test_add_columns():
"""Test the behavior of AraDefinition.add_columns"""
empty = empty_defn()
empty.config_uid = uuid4()
# Check the mismatched name error
with pytest.raises(ValueError) as excinfo:
empty.add_columns(
variable=TerminalMaterialInfo(name="foo", headers=["bar"],... | 1,689 |
def create_multiaction(action_name: str, subactions: List[str], description: str = '') -> Callable[[Context, Any], Any]:
"""Creates and registers an action that only executes the subactions in order.
Dependencies and allowation rules are inferred from subactions.
Subactions must be defined first, because th... | 1,690 |
def phase_amp_seq_to_complex():
"""
This constructs the function to convert from phase/magnitude format data,
assuming that data type is simple with two bands, to complex64 data.
Returns
-------
callable
"""
def converter(data):
if not isinstance(data, numpy.ndarray):
... | 1,691 |
def Regress_model(x_train,y_train,x_test=None,y_test=None,degree=2,test_size=0.1):
"""[summary]
DESCRIPTION :-
Regressin Model selection.
This Model will compare all the different Regression models, and will return model with highest Rsq value.
It also shows perf... | 1,692 |
def test_store_and_retrieve(sirang_instance):
"""Test store and retrieve functions."""
# Declare database/collection names
db = 'db'
collection = 'store_and_retrieve'
# Store tests
assert sirang_instance.store(db, collection, {'_id': 0}) == '0'
assert sirang_instance.store(db, collection, {... | 1,693 |
async def get_group_list_all():
"""
获取所有群, 无论授权与否, 返回为原始类型(列表)
"""
bot = nonebot.get_bot()
self_ids = bot._wsr_api_clients.keys()
for sid in self_ids:
group_list = await bot.get_group_list(self_id=sid)
return group_list | 1,694 |
def experiences_task():
"""Re-schedule self before executing `tasks.update_experiences`."""
schedule.enter(UPDATE_FREQ_EXPERIENCES, 1, experiences_task)
tasks.update_experiences() | 1,695 |
def merge(array, left, right):
"""
Perform Merge Operation between arrays.
Time Complexity: Theta(nLogn)
Auxiliary Space: O(n)
:param array: Iterable of elements
:param left: left limit for merge sort
:param right: right limit for merge sort
:return: no returns, merges arrays.
"""
... | 1,696 |
def emcee_schools_model(data, draws, chains):
"""Schools model in emcee."""
import emcee
chains = 10 * chains # emcee is sad with too few walkers
y = data["y"]
sigma = data["sigma"]
J = data["J"] # pylint: disable=invalid-name
ndim = J + 2
pos = np.random.normal(size=(chain... | 1,697 |
def _agefromarr(arr, agelist):
"""Measures the mean age map of a timeslice array.
:param arr: A timeslice instance's data array.
:param agelist: List of age sampling points of array.
:return:
:agemap: Light- or mass-weighted (depending on weight_type in the timecube()) mean metallicity of t... | 1,698 |
def undo_download_dir_patch():
"""
Provide a way for certain tests to not have tmp download dir.
"""
oridir = os.environ["SUNPY_DOWNLOADDIR"]
del os.environ["SUNPY_DOWNLOADDIR"]
yield
os.environ["SUNPY_DOWNLOADDIR"] = oridir | 1,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.