content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cleanup():
""" Cleanup after installation """
LOG.info("Cleaning up...")
subprocess.call(['systemctl', 'disable', 'install-clone'], stderr=DEVNULL)
OLD_FILE = os.path.join(tsconfig.PLATFORM_CONF_PATH, clone.CLONE_ISO_INI)
if os.path.exists(OLD_FILE):
os.remove(OLD_FILE)
if os.path.ex... | 5,316,000 |
def _parse_array(values):
""" parse a list of (string) values representing a fortran array
and return a python list
"""
assert type(values) is list
parsed_value = []
for v in values:
if '*' in v:
# 3* "a" === "a", "a", "a"
mult, val = v.split('*')
pars... | 5,316,001 |
def word_frequency(text: str, use_cases: bool = False) -> dict[str,int]:
"""
Returns a dictionary of the frequency of all words in given string.
All words turned to lowercase if use_cases left unspecified.
Parameters
------------
text: str
The text to find the word frequency of.
u... | 5,316,002 |
def param_to_string(metric) -> str:
"""Convert a list / tuple of parameters returned from IE to a string"""
if isinstance(metric, (list, tuple)):
return ', '.join([str(x) for x in metric])
else:
return str(metric) | 5,316,003 |
def fix_subtitle_hierarchy(ctx, text):
"""Fix subtitle hierarchy to be strict Language -> Etymology ->
Part-of-Speech -> Translation/Linkage."""
assert isinstance(ctx, Wtp)
assert isinstance(text, str)
# Known language names are in languages_by_name
# Known lowercase PoS names are in part_of_sp... | 5,316,004 |
def embed_dataset(id, source_folder, output_folder):
""" Here we are at the stage where the three splits starting from the training set have been computed.
We have then train.csv, valid.csv, test.csv files and the correspondent files with labels.
[train.csv, valid.csv, test.csv]
[train.n... | 5,316,005 |
def function_scope_seed(request):
"""A function scope fixture that manages rng seeds.
This fixture automatically initializes the python, numpy and mxnet random
number generators randomly on every test run.
def test_ok_with_random_data():
...
To fix the seed used for a test case mark the t... | 5,316,006 |
def showStitchedModels_Redundant(mods, ax=None,
cmin=None, cmax=None, **kwargs):
"""Show several 1d block models as (stitched) section."""
x = kwargs.pop('x', np.arange(len(mods)))
topo = kwargs.pop('topo', x*0)
nlay = int(np.floor((len(mods[0]) - 1) / 2.)) + 1
if c... | 5,316,007 |
def export_16(text_col, processed_col, input_filepath,
output_filepath, country):
"""Takes in a file with 8 different sheets containing extracted text.
It will perform mulitple steps to clean the extracted text
and split each sheet into two smaller sheets.
Then export them individ... | 5,316,008 |
def generate_signal(ders, n, sampling, initial_state=None, number_of_variables=1, number_of_perturbations=1, warmup_time=1000.0, tau=3.0, eps=0.5, dt=0.01):
"""generates signal for the oscillator driven by correlated noise from dynamical equations
:param ders: a list of state variable derivatives
:param n: length ... | 5,316,009 |
def test_error_model_options(
vmxi_protk_reindexed, tmpdir, options, expected, tolerances
):
"""Test different non-default command-line options with a single dataset.
Current values taken at 14.11.19"""
expt_1, refl_1 = vmxi_protk_reindexed
args = [refl_1, expt_1] + list(options)
run_one_scalin... | 5,316,010 |
async def test_siren(hass: HomeAssistant):
"""Test setup and state change of a siren device."""
entry = configure_integration(hass)
test_gateway = HomeControlMockSiren()
test_gateway.devices["Test"].status = 0
with patch(
"homeassistant.components.devolo_home_control.HomeControl",
si... | 5,316,011 |
def get_first_last_line(filePath, encoding=stdout.encoding):
"""Return the first and the last lines of file
The existence of filePath should be check beforehand.
Args:
filePath (str): the path of the file
encoding (str): the encoding of the file. Default stdout.encoding
Returns
... | 5,316,012 |
def test_deposit_no_account(client):
"""`GET /deposit` fails with no `account` parameter."""
response = client.get(f"/deposit?asset_code=NADA", follow=True)
content = json.loads(response.content)
assert response.status_code == 400
assert content == {"error": "`asset_code` and `account` are required... | 5,316,013 |
def register_dataset_instances(name, metadate, json_file, image_root):
"""
purpose: register dataset to DatasetCatalog,
register metadata to MetadataCatalog and set attribute
"""
DatasetCatalog.register(name, lambda: load_coco_json(json_file, image_root, name))
MetadataCatalog.get(name)... | 5,316,014 |
def save(data, filepath):
"""
Saves passed in data dictionary onto a file path
:param dict data:
:param str filepath:
.. note::
Will create missing directories
"""
if not data:
return
directory = os.path.dirname(filepath)
if not os.path.isdir(directory):
... | 5,316,015 |
def validate_is_document_type(option, value):
"""Validate the type of method arguments that expect a MongoDB document."""
if not isinstance(value, (MutableMapping, bson.RawBSONDocument)):
raise TypeError("%s must be an instance of dict, bson.son.SON, "
"bson.raw_bson.RawBSONDocum... | 5,316,016 |
def getReviewRedirect(entity, params):
"""Returns the redirect to review the specified entity.
"""
return '/%s/review/%s' % (
params['url_name'], entity.key().id_or_name()) | 5,316,017 |
def current_random_state():
"""Get or create the current global RNG of imgaug.
Note that the first call to this function will create a global RNG.
Returns
-------
imgaug.random.RNG
The global RNG to use.
"""
import imgaug.random
return imgaug.random.get_global_rng() | 5,316,018 |
def get_remote_station(s3, bucket, dataset_id=None, station_id=None, stn_key=None, version=3):
"""
"""
if isinstance(dataset_id, str):
stn_key = key_patterns[version]['station'].format(dataset_id=dataset_id, station_id=station_id)
try:
obj1 = s3.get_object(Bucket=bucket, Key=stn_key)
... | 5,316,019 |
def getURLitemBasename(url):
"""For a URL, absolute or relative, return the basename string.
e.g. "http://foo/bar/path/foo.dmg" => "foo.dmg"
"/path/foo.dmg" => "foo.dmg"
"""
url_parse = urlparse(url)
return os.path.basename(url_parse.path) | 5,316,020 |
def determine_smallest_atom_index_in_torsion(atom1: 'rdkit.Chem.rdchem.Atom',
atom2: 'rdkit.Chem.rdchem.Atom',
) -> int:
"""
Determine the smallest atom index in mol connected to ``atom1`` which is not ``atom2``.
Retur... | 5,316,021 |
def structured_array_generic_full(
request: Request,
reader=Depends(reader),
slice=Depends(slice_),
expected_shape=Depends(expected_shape),
format: Optional[str] = None,
serialization_registry=Depends(get_serialization_registry),
):
"""
Fetch a slice of array-like data.
"""
if re... | 5,316,022 |
def _get_api_key(api_url: str, username: str, password: str, save: bool) -> str:
"""Get an RGD API Key for the given user from the server, and save it if requested."""
resp = requests.post(f'{api_url}/api-token-auth', {'username': username, 'password': password})
resp.raise_for_status()
token = resp.jso... | 5,316,023 |
def fitness_func_large(vector):
""" returns a very large number for fitness"""
return 9999999999999999999 | 5,316,024 |
def create_implicit_binary_heap(key_type=float):
"""Create an implicit (array-based) binary heap.
:param key_type: the key type
:type key_type: float, int or object
:returns: the heap
:rtype: :py:class:`.Heap`
"""
heap_type = _HeapType.HEAP_TYPE_BINARY_IMPLICIT
return _create_and_wrap_... | 5,316,025 |
def remove_exist_subpkgs(ctx, folder, pkg):
"""
Remove residual packages from the earlier installations
:param ctx
:param folder: i.e. bootflash:/Image
:return: True or False
"""
pkg_conf = folder + '/packages.conf'
# Skip if no packages.conf
output = ctx.send('dir ' + pkg_conf)
... | 5,316,026 |
def Prob_APD_select_v2(
fitness: list,
uncertainty: list,
vectors: "ReferenceVectors",
penalty_factor: float,
ideal: list = None,
):
"""Select individuals for mating on basis of Angle penalized distance.
Args:
fitness (list): Fitness of the current population.
... | 5,316,027 |
def test_apply_bda_non_uvd_error():
"""Test error for not using a UVData object."""
# define parameters
uvd = "foo"
max_decorr = 0.1
pre_fs_int_time = 0.1 * units.s
corr_fov_angle = Angle(20.0, units.degree)
max_time = 30 * units.s
corr_int_time = 2 * units.s
# test using something ... | 5,316,028 |
def cleanup(doc: dict):
"""
Clean up some fields before saving.
"""
# Convert the fields that are CSV to the user but lists in the database
csv_to_list(doc, ['attorney_initials', 'admin_users'])
# Make sure we have the correct check digit
if 'client_ssn' in doc and 'client_dl' in doc:
... | 5,316,029 |
def set_env_aws_creds(account='default'):
"""
Parse ~/.aws/credentials for credentials
Allow OS environment variables to override (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY)
Exit script of neither can be found
"""
# grab creds from env
aws_key_env_var = "AWS_ACCESS_KEY_ID"
aws_secret_... | 5,316,030 |
def get_initial_band_powers(bands_min, bands_max, idx_zbin1, idx_zbin2):
"""
get_initial_band_powers(bands_min, bands_max, idx_zbin1, idx_zbin2)
Function supplying the initial guess for the requested {'EE', 'BB', 'EB'} band
powers for the current redshift bin correlation idx_zbin1 x idx_zbin2.
Par... | 5,316,031 |
def remove_prefix(s, pre):
"""
Remove prefix from the beginning of the string
Parameters:
----------
s : str
pre : str
Returns:
-------
s : str
string with "pre" removed from the beginning (if present)
"""
if pre and s.startswith(pre):
return s[len(pre):]
... | 5,316,032 |
def raw_screenshots_analysis(jobs, job_id):
"""
Returns a report (dict) with:
report["raw_screenshot_mse"] = 0. <- [0, 100], 0 meaning images are equal
report["raw_screenshot_ssim"] = 0. <- [0, 100], 100 meaning images are equal
report["raw_screenshot_diff_pixels"] = 0. <- [0, 100], 0 me... | 5,316,033 |
def test_route53resolver_delete_resolver_rule():
"""Test good delete_resolver_rule API calls."""
client = boto3.client("route53resolver", region_name=TEST_REGION)
created_rule = create_test_rule(client)
# Now delete the resolver rule and verify the response.
response = client.delete_resolver_rule(R... | 5,316,034 |
def py_pytest_test(
name,
# This argument exists for back-compatibility with earlier versions
pytest_args = [
"--ignore=external",
".",
"-p",
"no:cacheprovider",
],
**kwargs):
"""A macro that runs pytest tests by using ... | 5,316,035 |
def test_missing_pkgs_req():
"""Check for packages used in code but not in requirements.txt."""
mod_imports = analyze_imports(
package_root=PKG_ROOT, package_name=PKG_NAME, req_file=REQS_FILE
)
import_errs = {v for s in mod_imports.values() for v in s.unknown}
print("re module path:", re.__f... | 5,316,036 |
def build_docker(args):
"""Execute the docker build command with the specified arguments."""
command = ""
if os.getuid() != 0:
command += "sudo "
if args.tag.find(':') > 0:
tag = args.tag
else:
tag = 'escadrille:%s' % args.tag
command += ("docker build --rm -f %s --build-... | 5,316,037 |
def parseString(string, namespaces=True):
"""Parse a document from a string, returning the resulting
Document node.
"""
if namespaces:
builder = ExpatBuilderNS()
else:
builder = ExpatBuilder()
return builder.parseString(string) | 5,316,038 |
def get_transcript_border_annotations(tr_ids_dic, in_gtf, out_bed,
append=False):
"""
Get transcript border annotations and write border positions to
out_bed BED. Additional transcript annotations include:
A : transcript start
Z : transcript end
B : Exon bo... | 5,316,039 |
def vcs_dir_contents(path):
"""Return the versioned files under a path.
:return: List of paths relative to path
"""
repo = path
while repo != "/":
if os.path.isdir(os.path.join(repo, ".git")):
ls_files_cmd = [ 'git', 'ls-files', '--full-name',
os_pat... | 5,316,040 |
def prompt_present(nbwidget):
"""Check if an In prompt is present in the notebook."""
if WEBENGINE:
def callback(data):
global html
html = data
nbwidget.dom.toHtml(callback)
try:
return ' [ ]:' in html
except NameError:
re... | 5,316,041 |
def _search_range(elem, session, query=None):
"""Perform a range search for DA, DT and TM elements with '-' in them.
Parameters
----------
elem : pydicom.dataelem.DataElement
The attribute to perform the search with.
session : sqlalchemy.orm.session.Session
The session we are using ... | 5,316,042 |
def is_repo_user(repo_obj, username=None):
""" Return whether the user has some access in the provided repo. """
if username:
user = username
else:
if not authenticated():
return False
user = flask.g.fas_user.username
if is_admin():
return True
usergrps ... | 5,316,043 |
def emulate(
input_path: Path,
output_path: Path = None,
duration: float = None,
force_overwrite: bool = False,
use_cal_default: bool = False,
start_time: float = None,
set_target_io_lvl_conv: bool = False,
sel_target_for_io: bool = True,
sel_targe... | 5,316,044 |
def block_distance(p1, p2):
"""
Returns the Block Distance of a particular point from rest of the points in dataset.
"""
distance = 0
for i in range(len(p1)-1):
distance += abs(p1[i]-p2[i])
return distance | 5,316,045 |
def load_ids(test_files):
"""Generator function for loading the test set of images from disk
:param test_files:
:return:
"""
id_dict = test_files[IDS]
for key in id_dict.keys():
for id in id_dict[key]:
yield id | 5,316,046 |
def send_messages_to_consumer(producer, topic_name: str = "sample_customer_profile"):
"""Send messages from Kafka producer to consumer"""
data = get_fake_data()
for message in data:
print(f"Sending message from producer: {message}")
producer.send(topic_name, dumps(message).encode("utf-8"))
... | 5,316,047 |
def display_profiles():
"""
Function that returns all save profiles
"""
return Passwords.display_profiles() | 5,316,048 |
def mutate(
_data,
*args,
_keep="all",
_before=None,
_after=None,
**kwargs,
):
"""Adds new variables and preserves existing ones
The original API:
https://dplyr.tidyverse.org/reference/mutate.html
Args:
_data: A data frame
_keep: allows you to control which colu... | 5,316,049 |
def test_triangular_mesh():
"""An example of a cone, ie a non-regular mesh defined by its
triangles.
"""
n = 8
t = np.linspace(-np.pi, np.pi, n)
z = np.exp(1j * t)
x = z.real.copy()
y = z.imag.copy()
z = np.zeros_like(x)
triangles = [(0, i, i + 1) for i in range(1, n)]
x... | 5,316,050 |
def pos_tag(tokenized_text):
"""
Averaged perceptron tagger from NLTK (originally from @honnibal)
"""
return pos_tag_sents([tokenized_text])[0] | 5,316,051 |
def cabbeling(SA, CT, p):
"""
Calculates the cabbeling coefficient of seawater with respect to
Conservative Temperature. This function uses the computationally-
efficient expression for specific volume in terms of SA, CT and p
(Roquet et al., 2015).
Parameters
----------
SA : array-lik... | 5,316,052 |
def _variant_to_dsl_helper(tokens) -> Variant:
"""Convert variant tokens to DSL objects.
:type tokens: ParseResult
"""
kind = tokens[KIND]
if kind == HGVS:
return Hgvs(tokens[HGVS])
if kind == GMOD:
concept = tokens[CONCEPT]
return GeneModification(
name=co... | 5,316,053 |
def remove_empty(df):
"""
Drop all rows and columns that are completely null.
Implementation is shamelessly copied from `StackOverflow`_.
.. _StackOverflow: https://stackoverflow.com/questions/38884538/python-pandas-find-all-rows-where-all-values-are-nan # noqa: E501
Functional usage example:
... | 5,316,054 |
def calculate_serving_size_weight(
weight: Optional[float], number_of_servings: Optional[float]
) -> Optional[float]:
"""
Given a weight (representing the total weight of the
component included in a recipe) and a number of servings
(how many servings of the component are included),
returns a num... | 5,316,055 |
def validate_positive(value):
"""Check if number is positive."""
if value is not None and value <= 0:
raise ValidationError(f'Expected a positive number, but got {value}')
return value | 5,316,056 |
def main(args):
"""Process arguments and run validation"""
# Set variables for directory and list of studies
root_dir = args.root_directory
studies = args.list_of_studies
# If studies are filled in, create a list
if studies is not None:
list_studies = [str(study) for study in studies.s... | 5,316,057 |
def task_install():
"""Install python/R dependencies as needed"""
packrat = Path("packrat/packrat.lock")
if packrat.is_file():
yield {
'name': f"Install R dependencies using {packrat}",
'file_dep': [packrat],
'actions': [f"Rscript -e 'if (!require(packrat)) instal... | 5,316,058 |
def test_zmq_api_environment_open_close_3(re_manager): # noqa F811
"""
Test for `environment_open` and `environment_close` methods.
Closing the environment while a plan is running.
"""
resp1, _ = zmq_single_request("environment_open")
assert resp1["success"] is True
assert resp1["msg"] == "... | 5,316,059 |
def filter_invalid_matches_to_single_word_gibberish(
matches,
trace=TRACE_FILTER_SINGLE_WORD_GIBBERISH,
reason=DiscardReason.INVALID_SINGLE_WORD_GIBBERISH,
):
"""
Return a filtered list of kept LicenseMatch matches and a list of
discardable matches given a `matches` list of LicenseMatch by remov... | 5,316,060 |
def start_game(player1, player2, symbols=("O", "X")):
"""Starts a command line tic tac toe game between 2 players (bot or human)"""
assert len(symbols) == 2, "`symbols` must have exactly 2 elements"
gstate = TicTacToe("_________", symbols=symbols)
with open(GAME_TREE_FILE, "r") as gt_file:
gam... | 5,316,061 |
def test_simplest_dispatch():
""" Testing a very simple network without transformer for voltage
constraints with OPF """
# boundaries:
vm_max = 1.05
vm_min = 0.95
# create net
net = pp.create_empty_network()
pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.)
pp.creat... | 5,316,062 |
def despike_l1b_array(data, dqf, filter_width=7):
"""
Despike SUVI L1b data and return a despiked `numpy.ndarray`.
Parameters
----------
data : `numpy.ndarray`
Array to despike.
dqf : `numpy.ndarray`
Data quality flags array.
filter_width: `int`, optional.
The filter... | 5,316,063 |
def scrape(query: str,
listing_age: int = None,
relevance: str = None,
job_type: list = None,
experience: list = None,
locations: list = ['Singapore'],
limit: int = None,
**kwargs):
"""
:param query: str
Job search query
:... | 5,316,064 |
def connect(t1, t2, ax1, ax2):
"""Connect two tensors by setting a shared index for the specified
dimensions. This is an inplace operation that will also affect any tensor
networks viewing these tensors.
Parameters
----------
t1 : Tensor
The first tensor.
t2 :
The second ten... | 5,316,065 |
def test_prepare_makes_server_ready():
"""Check that prepare() makes the server ready, and stop() clears it."""
httpserver = HTTPServer(
bind_addr=(ANY_INTERFACE_IPV4, EPHEMERAL_PORT),
gateway=Gateway,
)
assert not httpserver.ready
assert not httpserver.requests._threads
httpse... | 5,316,066 |
def info( request ):
""" Returns basic info about the easyrequest_hay webapp.
Triggered by root easyrequest_hay url. """
log.debug( '\n\nstarting info(); request.__dict__, ```%s```' % request.__dict__ )
start = datetime.datetime.now()
context = {
'pattern_header': common.grab_pattern_hea... | 5,316,067 |
def delete_shy():
"""Destroy y-shadow object."""
glDeleteBuffers(1, [shy_vbo]) | 5,316,068 |
def run_command(arguments, parse_stdout=True):
"""Run a command
Args:
A list with the arguments to execute. For example ['ls', 'foo']
Returns:
stdout, return status.
"""
try:
cmd = sp.Popen(arguments, stdout=sp.PIPE, stderr=sp.STDOUT)
stdout, _ = cmd.communicate()
... | 5,316,069 |
def format_key(key):
"""
Format the key provided for consistency.
"""
if key:
return key if key[-1] == "/" else key + "/"
return "/" | 5,316,070 |
def get_random_parent_asset(instance_id: int, instance_start_id, instance_end_id) -> int:
"""
get random parent asset not linked to any child assets
:param instance_id: asset instance_id
"""
child_list = [instance_id]
child_list = get_child_assets_id(child_list, instance_id)
all_list = list... | 5,316,071 |
def organization_member_invite_get(
organization_id: UUID = typer.Argument(..., help="UUID of the organization"),
organization_member_invite_email: str = typer.Argument(..., help="E-mail of the organization member invite")
):
"""
Get organization member invite.
"""
client = Client(profile=gl... | 5,316,072 |
def main():
"""Program entrypoint, create CUI, wrapper object and start it
"""
root = py_cui.PyCUI(4,7)
root.set_title('2048')
root.toggle_unicode_borders()
cui_2048 = CUI2048(root)
root.start() | 5,316,073 |
async def _check_response_status(response, info_msg: str):
"""Check if the status of the response is valid.
Parameters:
response: the result of the made service-call.
info_msg: the message to return if something goes wrong during
service-call.
Raises:
if response has an... | 5,316,074 |
def logout() -> Response:
"""API call: logout of the system."""
config = CorporaAuthConfig()
client = get_oauth_client(config)
params = {"returnTo": config.redirect_to_frontend, "client_id": config.client_id}
response = redirect(client.api_base_url + "/v2/logout?" + urlencode(params))
# remove t... | 5,316,075 |
def elapsed_printer(func):
"""
**中文文档**
此包装器可以打印函数的输入参数, 以及运行时间。
"""
def _wrapper(*args, **kwargs):
print(">>> %s # Running ..." %
_text_of_func_args_and_kwargs(func, args, kwargs))
st = time.clock()
res = func(*args, **kwargs)
elapsed = time.clock() ... | 5,316,076 |
def get_init_fn():
"""Returns a function run by the chief worker to warm-start the training."""
checkpoint_exclude_scopes=["resnet_v1_101/logits","resnet_v1_101/fc","deconv32"]
exclusions = [scope.strip() for scope in checkpoint_exclude_scopes]
variables_to_restore = []
for var in... | 5,316,077 |
def buildings_from_polygon(polygon, retain_invalid=False):
"""
Get building footprints within some polygon.
Parameters
----------
polygon : Polygon
retain_invalid : bool
if False discard any building footprints with an invalid geometry
Returns
-------
GeoDataFrame
"""
... | 5,316,078 |
def proccess_save_car(car_instance_list: list) -> None:
"""
Helper for only saving car data
Args:
car_instance_list (list): Car instance list
"""
# Save all cars:
with open("data/cars.json", 'w') as cars_file:
cars_ = []
for car in car_instance_list:
cars_.ap... | 5,316,079 |
def _define_problem_with_groups(problem: Dict) -> Dict:
"""
Checks if the user defined the 'groups' key in the problem dictionary.
If not, makes the 'groups' key equal to the variables names. In other
words, the number of groups will be equal to the number of variables, which
is equivalent to no gro... | 5,316,080 |
def ljk(epsilon):
"""
Calculates ecliptic triad vectors with respect to BCRS-frame.
(Lindegren, SAG-LL-35, Eq.1)
:param epsilon: obliquity of the equator.
:return: np.array, np.array, np.array
"""
l = np.array([1,0,0])
j = np.array([0, np.cos(epsilon), np.sin(epsilon)])
k = np.arra... | 5,316,081 |
def send_mail(subject, message, recipient_list, request):
"""
Wrapper for send_mail() with logging and error messaging
:param subject: Message subject (string)
:param message: Message body (string)
:param recipient_list: Recipients of email (list)
:param request: Request object
:return: Amou... | 5,316,082 |
def position_result_list(change_list):
"""
Returns a template which iters through the models and appends a new
position column.
"""
result = result_list(change_list)
# Remove sortable attributes
for x in range(0, len(result['result_headers'])):
result['result_headers'][x]['sorted'] ... | 5,316,083 |
def _build_regex(pattern):
"""Compile regex pattern turn comma-separated list into | in regex."""
compiled_pattern = None
if pattern:
# Trip ' " at the beginning and end
pattern = re.sub("(^\"|^\'|\"$|\'$)", "", pattern)
# Escape
pattern = re.sub("/", r"\/", pattern)
# Change "a,b,c" into "(... | 5,316,084 |
def fpSub(rm, a, b, ctx=None):
"""Create a Z3 floating-point subtraction expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpSub(rm, x, y)
fpSub(RNE(), x, y)
>>> fpSub(rm, x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin(Z3_mk_fpa_sub... | 5,316,085 |
def reconstruct_contractility(simulation_folder, d_cyl, l_cyl, r_outer, scalef = 1000, scaleu = 1, scaleb = 1):
"""
Reconstruct the contractility of a given cylindric simulation. Also calculates residuum forces of Inclusion surface and matrix,
which shoould be equal (use to certify simulation and detect ... | 5,316,086 |
def categorical_sample(d):
"""Randomly sample a value from a discrete set based on provided probabilities.
Args:
d: A dictionary mapping choices to probabilities.
Returns:
One of the possible choices.
"""
choice_probs = list(d.items())
probs = [t[1] for t in choice_probs]
... | 5,316,087 |
def gaspari_cohn_mid(z,c):
"""
Gaspari-Cohn correlation function for middle distances (between c and 2*c)
Arguments:
- z: Points to be evaluated
- c: Cutoff value
"""
return 1./12*(z/c)**5 - 0.5*(z/c)**4 + 5./8*(z/c)**3 \
+ 5./3*(z/c)**2 - 5*z/c - 2./3*c/z + 4 | 5,316,088 |
def _PropertyGridInterface__Items(self):
"""
This attribute is a pythonic iterator over all items in this
`PropertyGrid` property container, excluding only private child
properties. Usage is simple::
for prop in propGrid.Items:
print(prop)
:see: `wx.propgrid.Pr... | 5,316,089 |
def put(local_file, remote_file, outmode, template, recursive, process):
"""
upload file
example:
pypssh -t 192.168.31.1 put /etc/yum.conf /etc/yum.conf
"""
def _progress(filename, size, sent, peername):
click.echo("(%s:%s) %s's progress: %.2f%% \r" % (
peername[0], peern... | 5,316,090 |
def match_hostname(cert, hostname):
"""Verify that *cert* (in decoded format as returned by
SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
rules are followed, but IP addresses are not accepted for *hostname*.
CertificateError is raised on failure. On success, the function
r... | 5,316,091 |
def home_view(request):
"""
DESCRIPTION:
The only FBV to redirect to the original home_view
"""
# image = {'image': 'https://picsum.photos/1024/756'}
image = {}
return render(request, 'home.html', image) | 5,316,092 |
def hparams_pb(hparams, trial_id=None, start_time_secs=None):
# NOTE: Keep docs in sync with `hparams` above.
"""Create a summary encoding hyperparameter values for a single trial.
Args:
hparams: A `dict` mapping hyperparameters to the values used in this
trial. Keys should be the names of `H... | 5,316,093 |
def test_list_saved_searches_command(mocker):
"""
Given:
- A LogAnalytics client object
- Arguments of azure-log-analytics-list-saved-searches command, representing we want
a single saved search from the first page of the list to be retrieved
When:
- Calling function list_s... | 5,316,094 |
async def test_get_start_entry_by_id_not_found(
event_loop: Any,
mocker: MockFixture,
start_entry_mock: dict,
) -> None:
"""Should raise StartEntryNotFoundException."""
mocker.patch(
"race_service.adapters.start_entries_adapter.StartEntriesAdapter.get_start_entry_by_id",
return_value... | 5,316,095 |
def create_agents(nagi, age_all, nr_infec, nr_immucmpr, nr_freeroam, nr_social):
"""
Creates the array of agents that will be used in the simulation
Parameters
----------
nagi : int
number of human agents that will be created.
age_all : numpy array of ints
distribution ... | 5,316,096 |
def get_top_level_data(end, start=20, get_fight_card_stats=False, both=True, avg_pause=.6):
"""
@param end: integer
@param start : integer
@param get_fight_card_stats :
@param both : boolean
@param avg_pause : float
"""
def add_d_set(df_use, name):
df = df_use.copy()
df... | 5,316,097 |
def compute_normalization_binary_search(activations,
t,
num_iters = 10):
"""Returns the normalization value for each example (t < 1.0).
Args:
activations: A multi-dimensional array with last dimension `num_classes`.
t: Temperat... | 5,316,098 |
def _match_units(filter_params, fps, fname):
"""
author: EM
The filtering thresholds must match the timeseries units. If the right
conversion is not possible, then check_ok is False, and the feature
summaries will not be calculated for this file.
"""
from copy import deepcopy
if filter... | 5,316,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.