content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main(
path_experiment,
path_table,
path_dataset,
path_output,
path_reference=None,
path_comp_bm=None,
min_landmarks=1.,
details=True,
allow_inverse=False,
):
""" main entry point
:param str path_experiment: path to experiment folder
:param str path_table: path to ass... | 5,336,100 |
def download_url(url: str, filename: Union[Path, str]) -> None:
"""Downloads data from url to file.
Args:
url: url to the data to download.
filename: path to the download location.
"""
with TqdmUpTo(unit="B", unit_scale=True, unit_divisor=1024, miniters=1) as t:
urlretrieve(url,... | 5,336,101 |
def fake_login(request):
"""Contrived version of a login form."""
if getattr(request, 'limited', False):
raise RateLimitError
if request.method == 'POST':
password = request.POST.get('password', 'fail')
if password is not 'correct':
return False
return True | 5,336,102 |
def register_scrapqd(app,
template=None,
register_sample_url=True,
redirect_root=True):
"""System add ScrapQD url to the Flask App and registers system defined crawlers."""
name = config.APP_NAME
if register_sample_url:
register_sample_p... | 5,336,103 |
def copytree(src, dst, symlinks=False, ignore=None):
"""like shutil.copytree() but ignores existing files
https://stackoverflow.com/a/22331852/1239986
"""
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore... | 5,336,104 |
def split_to_sentences(data):
"""
Split data by linebreak "\n"
Args:
data: str
Returns:
A list of sentences
"""
sentences = data.split('\n')
# Additional clearning (This part is already implemented)
# - Remove leading and trailing spaces from each sentence... | 5,336,105 |
def test_rollouts(do_print=False, time_for_test=3):
"""Do rollouts and see if the environment crashes."""
time_start = time()
while True:
if time() - time_start > time_for_test:
break
# obtaining random params
width = np.random.choice(np.arange(1, 20))
height = ... | 5,336,106 |
def velocity_N(
adata,
group=None,
recalculate_pca=True,
recalculate_umap=True,
del_2nd_moments=None,
):
"""use new RNA based pca, umap, for velocity calculation and projection for kinetics or one-shot experiment.
Note that currently velocity_N function only considers labeling data and remo... | 5,336,107 |
def wordcount(corpus: List[TokenisedCorpus]) -> None:
"""Calculate wordcounts for a corpus.
Calculates the average, standard deviation and variance of
a LyricsCorpus.
Args:
corpus: A list of TokenisedCorpus objects
"""
click.echo("Analysing Wordcount of song: ")
words = []
for... | 5,336,108 |
def test_type_args_propagation() -> None:
"""
It propagates type arguments to the generic's bases
"""
T = TypeVar("T", bound=float)
F = TypeVar("F", str, bytes)
S = TypeVar("S")
class Tuple(tuple[T, ...], Generic[F, T]):
pass
class TupleSubclass(Tuple[str, T], Generic[T, S]):
... | 5,336,109 |
def read_config_file(fp: str, mode='r', encoding='utf8', prefix='#') -> dict:
"""
读取文本文件,忽略空行,忽略prefix开头的行,返回字典
:param fp: 配置文件路径
:param mode:
:param encoding:
:param prefix:
:return:
"""
with open(fp, mode, encoding=encoding) as f:
ll = f.readlines()
ll = [i for i in... | 5,336,110 |
def PrepareForMakeGridData(
allowed_results, starred_iid_set, x_attr,
grid_col_values, y_attr, grid_row_values, users_by_id, all_label_values,
config, related_issues, hotlist_context_dict=None):
"""Return all data needed for EZT to render the body of the grid view."""
def IssueViewFactory(issue):
r... | 5,336,111 |
def custom_address_validator(value, context):
"""
Address not required at all for this example,
skip default (required) validation.
"""
return value | 5,336,112 |
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap, backoff=0, debug=False):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn using the new single line for left and right lane line method.
"""
lines = cv2.HoughLinesP(img, rho, ... | 5,336,113 |
def get_model(args) -> Tuple:
"""Choose the type of VQC to train. The normal vqc takes the latent space
data produced by a chosen auto-encoder. The hybrid vqc takes the same
data that an auto-encoder would take, since it has an encoder or a full
auto-encoder attached to it.
Args:
args: Dict... | 5,336,114 |
def get_launch_template_constraint_output(id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetLaunchTemplateConstraintResult]:
"""
Resource Type definition for AWS::ServiceCatalog::LaunchTemplateConstraint
"""
... | 5,336,115 |
def mag_var_scatter(model_dict, gradient_var_list, no_of_dims, rd = None, rev = None):
"""
Create a scatter plot of gradient of model vs. variance for each dimension
of the data
"""
f, axarr = plt.subplots(no_of_dims, 1, sharex=True, figsize=(12,20))
for i in range(no_of_dims):
grad_v_... | 5,336,116 |
def tail_ratio(returns):
"""
Determines the ratio between the right (95%) and left tail (5%).
For example, a ratio of 0.25 means that losses are four times
as bad as profits.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full... | 5,336,117 |
def get_trajectory_for_weight(simulation_object, weight):
"""
:param weight:
:return:
"""
print(simulation_object.name+" - get trajectory for w=", weight)
controls, features, _ = simulation_object.find_optimal_path(weight)
weight = list(weight)
features = list(features)
return {"w": ... | 5,336,118 |
def UnNT(X, Z, N, T, sampling_type):
"""Computes reshuffled block-wise complete U-statistic."""
return np.mean([UnN(X, Z, N, sampling_type=sampling_type)
for _ in range(T)]) | 5,336,119 |
def boolean_matrix_of_image(image_mat, cutoff=0.5):
"""
Make a bool matrix from the input image_mat
:param image_mat: a 2d or 3d matrix of ints or floats
:param cutoff: The threshold to use to make the image pure black and white. Is applied to the max-normalized matrix.
:return:
"""
if not i... | 5,336,120 |
def global_pool_1d(inputs, pooling_type="MAX", mask=None):
"""Pool elements across the last dimension.
Useful to convert a list of vectors into a single vector so as
to get a representation of a set.
Args:
inputs: A tensor of shape [batch_size, sequence_length, input_dims]
containing the s... | 5,336,121 |
def select_object(object):
""" Select specific object.
Parameters:
object (obj): Object to select.
Returns:
None
"""
object.select = True | 5,336,122 |
def _monte_carlo_trajectory_sampler(
time_horizon: int = None,
env: DynamicalSystem = None,
policy: BasePolicy = None,
state: np.ndarray = None,
):
"""Monte-Carlo trajectory sampler.
Args:
env: The system to sample from.
policy: The policy applied to the system during sampling.
... | 5,336,123 |
def pi_mult(diff: float) -> int:
"""
Функция, вычисляющая множитель, на который нужно домножить 2 pi, чтобы компенсировать разрыв фазы
:param diff: разность фазы в двух ячейках матрицы
:return : целое число
"""
return int(0.5 * (diff / pi + 1)) if diff > 0 else int(0.5 * (diff / pi - 1)) | 5,336,124 |
def get_integer(val=None, name="value", min_value=0, default_value=0):
"""Returns integer value from input, with basic validation
Parameters
----------
val : `float` or None, default None
Value to convert to integer.
name : `str`, default "value"
What the value represents.
min_v... | 5,336,125 |
def bb_moments_raincloud(region_idx=None, parcellation='aparc', title=''):
"""Stratify regional data according to BigBrain statistical moments (authors: @caseypaquola, @saratheriver)
Parameters
----------
region_idx : ndarray, shape = (n_val,)
Indices of regions to be included i... | 5,336,126 |
def release(cohesin, occupied, args):
"""
AN opposite to capture - releasing cohesins from CTCF
"""
if not cohesin.any("CTCF"):
return cohesin # no CTCF: no release necessary
# attempting to release either side
for side in [-1, 1]:
if (np.random.random() <... | 5,336,127 |
def validate_build_dependency(key: str, uri: str) -> None:
"""
Raise an exception if the key in dependencies is not a valid package name,
or if the value is not a valid IPFS URI.
"""
validate_package_name(key)
# validate is supported content-addressed uri
if not is_ipfs_uri(uri):
rai... | 5,336,128 |
def assert_allclose(actual: float, desired: numpy.float64, err_msg: str):
"""
usage.scipy: 1
usage.sklearn: 1
"""
... | 5,336,129 |
def set_uuids_from_yaml(args):
"""Set uuids from a yaml mapping. Useful for migration to uuids.
:param args: Argparse namespace object with filename
:type args: namespace
"""
with open(args.filename, 'r') as f:
mapping = yaml.safe_load(f)
for uuid, envdict in mapping.items():
p... | 5,336,130 |
def cosine(u, v):
"""
d = cosine(u, v)
Computes the Cosine distance between two n-vectors u and v,
(1-uv^T)/(||u||_2 * ||v||_2).
"""
u = np.asarray(u)
v = np.asarray(v)
return (1.0 - (np.dot(u, v.T) / \
(np.sqrt(np.dot(u, u.T)) * np.sqrt(np.dot(v, v.T))))) | 5,336,131 |
def get_data_from_redis_key(
label=None,
client=None,
host=None,
port=None,
password=None,
db=None,
key=None,
expire=None,
decompress_df=False,
serializer='json',
encoding='utf-8'):
"""get_data_from_redis_key
:param label: ... | 5,336,132 |
def main():
"""
TODO: create a "boggle" to match every exist vocabs in the dictionary with the 4x4 character input
"""
word_lst = []
# 排出一個 4 x 4 的方形字母若輸入不符合規定則顯示"illegal format"
for i in range(4):
word = input(str(i + 1) + " row of letters: ")
row_lst = []
if len(word) != 7:
print("Illegal input")
br... | 5,336,133 |
def _train_model(
train_iter: Iterator[DataBatch],
test_iter: Iterator[DataBatch],
model_type: str,
num_train_iterations: int = 10000,
learning_rate: float = 1e-5
) -> Tuple[Tuple[Any, Any], Tuple[onp.ndarray, onp.ndarray]]:
"""Train a model and return weights and train/test loss."""
batch = nex... | 5,336,134 |
def main(_args: Sequence[str]) -> int:
"""Main program."""
config = create_configuration()
generator = create_generator(config)
while True:
if os.path.exists(config.trigger_stop_file):
warning("Stopping due to existence of stop trigger file.")
return 0
debug('Gen... | 5,336,135 |
def test_ordered_node_next_child(db, version_relation, version_pids,
build_pid, recids):
"""Test the PIDNodeOrdered next_child method."""
parent_pid = build_pid(version_pids[0]['parent'])
ordered_parent_node = PIDNodeOrdered(parent_pid, version_relation)
assert ordered_p... | 5,336,136 |
def main(inargs):
"""Run the program."""
cube, history = gio.combine_files(inargs.infiles, inargs.var)
if inargs.annual:
cube = timeseries.convert_to_annual(cube, aggregation='mean', days_in_month=True)
if inargs.flux_to_mag:
cube = uconv.flux_to_magnitude(cube)
dim_coord_names = [... | 5,336,137 |
def swig_base_TRGBPixel_getMin():
"""swig_base_TRGBPixel_getMin() -> CRGBPixel"""
return _Core.swig_base_TRGBPixel_getMin() | 5,336,138 |
def archive_deleted_rows(context, max_rows=None):
"""Move up to max_rows rows from production tables to the corresponding
shadow tables.
:returns: Number of rows archived.
"""
# The context argument is only used for the decorator.
tablenames = []
for model_class in models.__dict__.itervalue... | 5,336,139 |
def load_wavefunction(file: TextIO) -> Wavefunction:
"""Load a qubit wavefunction from a file.
Args:
file (str or file-like object): the name of the file, or a file-like object.
Returns:
wavefunction (pyquil.wavefunction.Wavefunction): the wavefunction object
"""
if isinstance(fil... | 5,336,140 |
def delete_alias(request, DOMAIN, ID):
"""
Delete Alias based on ID
ENDPOINT : /api/v1/alias/:domain/:id
"""
FORWARD_EMAIL_ENDPOINT = f"https://api.forwardemail.net/v1/domains/{DOMAIN}/aliases/{ID}"
res = requests.delete(FORWARD_EMAIL_ENDPOINT, auth=(USERNAME, ''))
if res.status_code == 200:... | 5,336,141 |
def clear_old_changes_sources():
""" Delete the "-changes.tar.gz" lines from the "sources" file. """
with open('sources', 'r') as f:
lines = f.readlines()
with open('sources', 'w') as f:
for line in lines:
if '-changes.tar.gz' not in line:
f.write(line) | 5,336,142 |
def test_equals():
"""Test basic equality. Complex relationships are tested in test_material_run.test_deep_equals()."""
from citrine.resources.measurement_spec import MeasurementSpec as CitrineMeasurementSpec
from gemd.entity.object import MeasurementSpec as GEMDMeasurementSpec
gemd_obj = GEMDMeasurem... | 5,336,143 |
def _generate_input_weights(
N,
dim_input,
dist="custom_bernoulli",
connectivity=1.0,
dtype=global_dtype,
sparsity_type="csr",
seed=None,
input_bias=False,
**kwargs,
):
"""Generate input or feedback weights for a reservoir.
Weights are drawn by default from a discrete Bernou... | 5,336,144 |
def _get_variable_name(param_name):
"""Get the variable name from the tensor name."""
m = re.match("^(.*):\\d+$", param_name)
if m is not None:
param_name = m.group(1)
return param_name | 5,336,145 |
def addGlider(i, j, grid):
"""adds a glider with top left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider | 5,336,146 |
def np_gather(params, indices, axis=0, batch_dims=0):
"""numpy gather"""
if batch_dims == 0:
return gather(params, indices)
result = []
if batch_dims == 1:
for p, i in zip(params, indices):
axis = axis - batch_dims if axis - batch_dims > 0 else 0
r = gathe... | 5,336,147 |
def texture(data):
"""Compute the texture of data.
Compute the texture of the data by comparing values with a 3x3 neighborhood
(based on :cite:`Gourley2007`). NaN values in the original array have
NaN textures.
Parameters
----------
data : :class:`numpy:numpy.ndarray`
multi-dimensi... | 5,336,148 |
def joos_2013_monte_carlo(
runs: int = 100, t_horizon: int = 1001, **kwargs
) -> Tuple[pd.DataFrame, np.ndarray]:
"""Runs a monte carlo simulation for the Joos_2013 baseline IRF curve.
This function uses uncertainty parameters for the Joos_2013 curve calculated by
Olivie and Peters (2013): https://esd.... | 5,336,149 |
def pairwise_l1_loss(outputs, targets):
"""
"""
batch_size = outputs.size()[0]
if batch_size < 3:
pair_idx = np.arange(batch_size, dtype=np.int64)[::-1].copy()
pair_idx = torch.from_numpy(pair_idx).cuda()
else:
pair_idx = torch.randperm(batch_size).cuda()
#di... | 5,336,150 |
def get_mwis(input_tree):
"""Get minimum weight independent set
"""
num_nodes = input_tree['num_nodes']
nodes = input_tree['nodes']
if num_nodes <= 0:
return []
weights = [0, nodes[0][0]]
for idx, node_pair in enumerate(nodes[1:], start=1):
node_weight, node_idx = node_pair
... | 5,336,151 |
def info(tid, alternate_token=False):
"""
Returns transaction information for the transaction
associated with the passed transaction ID
:param id: String with transaction ID.
:return: Dictionary with information about transaction.
"""
if not tid:
raise Exception('info() requires id ... | 5,336,152 |
def find_extrema(array, condition):
"""
Advanced wrapper of numpy.argrelextrema
Args:
array (np.ndarray): data array
condition (np.ufunc): e.g. np.less (<), np.great_equal (>=) and etc.
Returns:
np.ndarray: indexes of extrema
np.ndarray: values of extrema
"""
# get indexes of extrema
indexes = argrelextr... | 5,336,153 |
def compute_all_metrics_statistics(all_results):
"""Computes statistics of metrics across multiple decodings."""
statistics = {}
for key in all_results[0].keys():
values = [result[key] for result in all_results]
values = np.vstack(values)
statistics[key + "_MEAN"] = np.mean(values, axis=0)
statist... | 5,336,154 |
def parse_pubkey(expr: str) -> Tuple['PubkeyProvider', str]:
"""
Parses an individual pubkey expression from a string that may contain more than one pubkey expression.
:param expr: The expression to parse a pubkey expression from
:return: The :class:`PubkeyProvider` that is parsed as the first item of ... | 5,336,155 |
def XOR(*conditions):
"""
Creates an XOR clause between all conditions, e.g.
::
x <> 1 XOR y <> 2
*conditions* should be a list of column names.
"""
assert conditions
return _querybuilder.logical_xor(conditions) | 5,336,156 |
def Interpolator(name=None, logic=None):
"""Returns an interpolator
:param name: Specify the name of the solver
:param logic: Specify the logic that is going to be used.
:returns: An interpolator
:rtype: Interpolator
"""
return get_env().factory.Interpolator(name=name, logic=logic) | 5,336,157 |
def trim_to_min_length(bits):
"""Ensures 'bits' have min number of leading zeroes.
Assumes 'bits' is big-endian, and that it needs to be encoded in 5 bit blocks.
"""
bits = bits[:] # copy
# make sure we can be split into 5 bit blocks
while bits.len % 5 != 0:
bits.prepend('0b0')
# Ge... | 5,336,158 |
def log_softmax(x, dim):
"""logsoftmax operation, requires |dim| to be provided.
Have to do some weird gymnastics to get vectorization and stability.
"""
if isinstance(x, torch.Tensor):
return F.log_softmax(x, dim=dim)
elif isinstance(x, IntervalBoundedTensor):
out = F.log_softmax(x.val, dim)
# U... | 5,336,159 |
def get_attributes_callback(get_offers_resp):
"""Callback fn for when get_attributes is called asynchronously"""
return AttributesProvider(get_offers_resp) | 5,336,160 |
def display(choices, slug):
"""
Get the display name for a form choice based on its slug. We need this function
because we want to be able to store ACS data using the human-readable display
name for each field, but in the code we want to reference the fields using their
slugs, which are easier to ch... | 5,336,161 |
def test_records_list_command(response, expected_result, mocker):
"""
Given:
- The records list command.
When:
- Mocking the response from the http request once to a response containing records, and once to a response with
no records.
Then:
- Validate that in the first ca... | 5,336,162 |
def autocorrelation(data):
"""Autocorrelation routine.
Compute the autocorrelation of a given signal 'data'.
Parameters
----------
data : darray
1D signal to compute the autocorrelation.
Returns
-------
ndarray
the autocorrelation of the signal x.
"""
n_points ... | 5,336,163 |
def yes_or_no(question, default="no"):
"""
Returns True if question is answered with yes else False.
default: by default False is returned if there is no input.
"""
answers = "yes|[no]" if default == "no" else "[yes]|no"
prompt = "{} {}: ".format(question, answers)
while True:
... | 5,336,164 |
def delete_old_participant_details():
"""
Submits a query request to Google BigQuery that runs a window funtion selecting only the most recently updated row per recipient id.
The resulting view is then materialized, the old recipient table deleted, and the new table renamed to replace the old one.
"""
... | 5,336,165 |
def query_airnow(param, data_period, bbox, key=None):
"""Construct an AirNow API query request and parse response.
Args:
param (str):
The evaluation parameter for which to query data.
data_period (list):
List with two elements, the first is the start date and time for
... | 5,336,166 |
def test_topic_name_case_change(volttron_instance, database_client):
"""
When case of a topic name changes check if they are saved as two topics
Expected result: query result should be cases insensitive
"""
clean_db(database_client)
agent_uuid = install_historian_agent(volttron_instance,
... | 5,336,167 |
def upload_to_py_pi():
"""
Upload the Transiter Python package inside the CI container to PyPI.
If this is not a build on master or a release tag, this is a no-op.
"""
if "pypi" not in get_artifacts_to_push():
return
print("Uploading to PyPI")
subprocess.run(
[
"... | 5,336,168 |
def compile(string):
"""
Compile a string to a template function for the path.
"""
return tokens_to_function(parse(string)) | 5,336,169 |
def flajolet_martin(data, k):
"""Estimates the number of unique elements in the input set values.
Inputs:
data: The data for which the cardinality has to be estimated.
k: The number of bits of hash to use as a bucket number. The number of buckets is 2^k
Output:
Returns the estimate... | 5,336,170 |
def makelist(filename, todo_default=['TODO', 'DONE']):
"""
Read an org-mode file and return a list of Orgnode objects
created from this file.
"""
ctr = 0
if isinstance(filename, str):
f = codecs.open(filename, 'r', 'utf8')
else:
f = filename
todos = set(todo_default) # ... | 5,336,171 |
def decode(encoded: list):
"""Problem 12: Decode a run-length encoded list.
Parameters
----------
encoded : list
The encoded input list
Returns
-------
list
The decoded list
Raises
------
TypeError
If the given argument is not of `list` type
"""
... | 5,336,172 |
def create_offset(set_point_value):
"""Docstring here (what does the function do)"""
offset_value = random.randint(-128, 128)
offset_value_incrementation = float(offset_value / 100)
return set_point_value - offset_value_incrementation | 5,336,173 |
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([s... | 5,336,174 |
def startpeerusersync(
server, user_id, resync_interval=OPTIONS["Deployment"]["SYNC_INTERVAL"]
):
"""
Initiate a SYNC (PULL + PUSH) of a specific user from another device.
"""
user = FacilityUser.objects.get(pk=user_id)
facility_id = user.facility.id
device_info = get_device_info()
com... | 5,336,175 |
def clean_url(str_text_raw):
"""This function eliminate a string URL in a given text"""
str_text = re.sub("url_\S+", "", str_text_raw)
str_text = re.sub("email_\S+", "", str_text)
str_text = re.sub("phone_\S+", "", str_text)
return(re.sub("http[s]?://\S+", "", str_text)) | 5,336,176 |
def compare_strategies(strategy, baseline=always_roll(5)):
""" Вернуть среднее отношение побед STRATEGY против BASELINE """
as_first = 1 - make_average(play)(strategy, baseline)
as_second = make_average(play)(baseline, strategy)
return (as_first + as_second) / 2 | 5,336,177 |
def process_geo(
path_geo_file: Path,
*,
add_pop: bool = True,
add_neighbors: bool = True,
add_centroids: bool = False,
save_geojson: bool = False,
path_pop_file: Path = PATH_PA_POP,
path_output_geojson: Path = PATH_OUTPUT_GEOJSON,
) -> geopandas.GeoDataFrame:
"""
Reads a given g... | 5,336,178 |
def pytest_itemcollected(item):
"""Attach markers to each test which uses a fixture of one of the resources."""
if not hasattr(item, "fixturenames"):
return
fixturenames = set(item.fixturenames)
for resource_kind in _resource_kinds:
resource_fixture = "_{}_container".format(resource_kin... | 5,336,179 |
def nml_poisson(X, sum_x, sum_xxT, lmd_max=100):
"""
Calculate NML code length of Poisson distribution. See the paper below:
yamanishi, Kenji, and Kohei Miyaguchi. "Detecting gradual changes from data stream using MDL-change statistics."
2016 IEEE International Conference on Big Data (Big Data). IEEE, ... | 5,336,180 |
def setup_metrics(app):
"""
Setup Flask app with prometheus metrics
"""
app.before_request(before_request)
app.after_request(after_request)
@app.route('/metrics')
def metrics():
# update k8s metrics each time this url is called.
global PROMETHEUS_METRICS
PROMETHEUS_M... | 5,336,181 |
def _getFormat(fileformat):
"""Get the file format constant from OpenSSL.
:param str fileformat: One of ``'PEM'`` or ``'ASN1'``.
:raises OpenSSLInvalidFormat: If **fileformat** wasn't found.
:returns: ``OpenSSL.crypto.PEM`` or ``OpenSSL.crypto.ASN1`` respectively.
"""
fileformat = 'FILETYPE_' +... | 5,336,182 |
def rewrite_tex_file(texpath, replacements, backup=False):
"""Rewrite a tex file, replacing ADS keys with INSPIRE keys.
Parameters
----------
texpath: PathLike
Path to tex file to rewrite
replacements: array of dict
Each dict has keys "ads_key", "insp_key", and "bib_str".
backup: ... | 5,336,183 |
def upload_file(_file, directory):
""" Upload yang model into session storage """
f = None
filename = None
try:
if not os.path.exists(directory):
logging.debug('Creating session storage ..')
os.makedirs(directory)
if not os.path.exists(directory):
log... | 5,336,184 |
def clip(
arg: ir.NumericValue,
lower: ir.NumericValue | None = None,
upper: ir.NumericValue | None = None,
) -> ir.NumericValue:
"""
Trim values at input threshold(s).
Parameters
----------
arg
Numeric expression
lower
Lower bound
upper
Upper bound
... | 5,336,185 |
def human_time_duration(seconds: int) -> str:
"""For a passed-in integer (seconds), return a human-readable duration string.
"""
if seconds <= 1:
return '<1 second'
parts = []
for unit, div in TIME_DURATION_UNITS:
amount, seconds = divmod(int(seconds), div)
if amount > 0:
... | 5,336,186 |
def reindex_network_nodes(network):
"""Reindex the nodes of a channel network."""
node_reindexer = SegmentNodeReindexer()
network.for_each(node_reindexer)
return network | 5,336,187 |
def check_header(argv=None):
"""Run aspell and report line number in which misspelled words are."""
argv = sys.argv[1:] if argv is None else argv
# Apparently the personal dictionary cannot be a relative path
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--exclude", nargs=1, type=_va... | 5,336,188 |
def center(win):
"""
centers a tkinter window
:param win: the root or Toplevel window to center
"""
win.update_idletasks()
width = win.winfo_width()
fm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * fm_width
height = win.winfo_height()
title_bar_height = win.wi... | 5,336,189 |
def test_d4_3_15v23_d4_3_15v23i(mode, save_output, output_format):
"""
naive xpathDefaultNamespace (exact uri of targetNamespace) test case
in complexType
"""
assert_bindings(
schema="ibmData/valid/D4_3_15/d4_3_15v23.xsd",
instance="ibmData/valid/D4_3_15/d4_3_15v23.xml",
clas... | 5,336,190 |
def avg_arrays_1d(data, axis=None, weights=None, **kws):
"""Average list of 1D arrays or curves by interpolation on a reference axis
Parameters
----------
data : lists of lists
data_fmt : str
define data format
- "curves" -> :func:`curves_to_matrix`
- "lists" -> :func:`curve... | 5,336,191 |
def _is_double(arr):
"""
Return true if the array is doubles, false if singles, and raise an error if it's neither.
:param arr:
:type arr: np.ndarray, scipy.sparse.spmatrix
:return:
:rtype: bool
"""
# Figure out which dtype for data
if arr.dtype == np.float32:
return False
... | 5,336,192 |
def every(delay, task, name):
"""
Executes a task every `delay` seconds
:param delay: the delay in seconds
:param task: the method to run. The method should return False if you want the loop to stop.
:return: None
"""
next_time = time.time() + delay
while True:
time.sleep(max(... | 5,336,193 |
def simulate_from_network_attr(edgelist_filename, param_func_list, labels,
theta,
binattr_filename=None,
contattr_filename=None,
catattr_filename=None,
sampler_func ... | 5,336,194 |
def HfcVd(M, far='default'):
"""
Computes the vitual dimensionality (VD) measure for an HSI
image for specified false alarm rates. When no false alarm rate(s) is
specificied, the following vector is used: 1e-3, 1e-4, 1e-5.
This metric is used to estimate the number of materials in an HSI scene... | 5,336,195 |
def cycle(sheduled_jobs):
"""
Start scheduled job worker. The worker will push deferred tasks to
redis queue
"""
queue = []
now = datetime.utcnow()
for when, job in sheduled_jobs:
if not hasattr(job, 'defer'):
raise RuntimeError('Job should have defer method')
qu... | 5,336,196 |
def load_multicenter_aids_cohort_study(**kwargs):
"""
Originally in [1]::
Siz: (78, 4)
AIDSY: date of AIDS diagnosis
W: years from AIDS diagnosis to study entry
T: years from AIDS diagnosis to minimum of death or censoring
D: indicator of death during follow up
... | 5,336,197 |
def bomb():
"""Bomb context appropriate for testing all simple wires cases."""
bomb = Bomb()
bomb.serial = 'abc123'
bomb.batteries = True
bomb.labels = ['FRK']
return bomb | 5,336,198 |
def process_replot_argument(replot_dir, results_dir):
"""Reads the args.json file in a results directory, copies it to an
appropriate location in the current results directory and returns the link
speed range and a list of RemyCC files."""
argsfilename = os.path.join(replot_dir, "args.json")
argsfil... | 5,336,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.