content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _test_path(fn):
"""Leads to files saved in the data folder
Parameters
----------
fn: str
The whole filename.
Returns
-------
The path of the file in the current working system.
"""
return Path(__file__).parent / "data" / fn | 5,301,000 |
def mirror_axis(cube,axis=-2):
"""Mirror one axis of an n-cube.
Parameters
----------
cube : array
Expected shape of cube: (...,nx,...).
axis : int
axis index to be mirrored. Default: -2. Mirroring assumes a
central columns of elements. See 'Returns' section.
Returns
... | 5,301,001 |
def lw(W, Wref=1.0e-12):
"""
Sound power level :math:`L_{w}` for sound power :math:`W` and reference power :math:`W_{ref}`.
:param W: Sound power :math:`W`.
:param Wref: Reference power :math:`W_{ref}`. Default value is :math:`10^{12}` watt.
"""
if type(W) is list:
W = np.array(W)
... | 5,301,002 |
def calc_hydrogen_bond_interactions(protein, mol, key_inters_defs, mol_key_inters,
filter_strict=False, exact_protein=False, exact_ligand=False):
""" Calculate H-bond interactions
Parameters:
protein (Molecule): The protein
mol (Molecule): The ligand to test
key_... | 5,301,003 |
def yes_or_no(msg, *params, yes=True, certain=False, third_choice=False):
"""Query yes, no or display with message.
Args:
msg (str): Message to be printed out.
yes (bool): Indicates whether the default answer is yes or no.
"""
choices = " [Y/n]?" if yes else " [yes/N]" if certain else ... | 5,301,004 |
def calc_Q_T_H_rad_d_t_i(Q_max_H_d_t_i, L_H_d_t_i):
"""1時間当たりの暖冷房区画iに設置された放熱器の処理暖房負荷
Args:
Q_max_H_d_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの1時間当たりの暖冷房区画𝑖に設置された放熱器の最大暖房出力
L_H_d_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの1時間当たりの暖房負荷(MJ/h)
Returns:
ndarray: 1時間当たりの暖冷房区画iに設置された放熱器の処理暖房負荷
"""
import ... | 5,301,005 |
def fetch_all_issue_by_entity_type(project_id,entity_type, entity_id):
"""
find all the issue in a project by entity type and entity id
"""
issues = Issue.query.filter_by(project_id=project_id, entity_type=entity_type,entity_id=entity_id).all()
return list(map(lambda issue: to_json(issue), issu... | 5,301,006 |
def test_f_strings():
"""
f literals are not really supported in Jedi. They just get ignored and an
empty string is returned.
"""
assert _eval_literal('f"asdf"') == ''
assert _eval_literal('f"{asdf}"') == ''
assert _eval_literal('F"{asdf}"') == ''
assert _eval_literal('rF"{asdf}"') == '' | 5,301,007 |
def bivariate_gaussian(true, pred):
"""
Stabilized rank-agnostic bivariate gaussian probability function (pdf)
Returns results of eq # 24 of http://arxiv.org/abs/1308.0850
:param true: truth values with at least [mu1, mu2]
:param pred: values predicted with at least [mu1, mu2, sigma1, sigma2, rho]
... | 5,301,008 |
def test_random_valid_mutation_without_terminal(GNB, pset):
""" Test if a valid mutation is applied at random.
I am honestly not sure of the best way to test this.
Because of the random nature, we repeat this enough times to ensure
each mutation is tried with probability >0.99999.
"""
# The tes... | 5,301,009 |
def gen_counters_and_filters_from_strategy(s, dimension, before_sleep, trigger_variable_name):
"""
生成counter列表,以及每个counter列表相关联的条件
:return: (counters, filters)
"""
counters = []
collect_counters = []
filters = []
sleep_found = False
for tid, t in enumerate(s.terms):
if t.l... | 5,301,010 |
def connect():
"""
connect to libvirt
must be called before any other calls in this library!
:return: boolean
"""
global is_init
global conn
if is_init is True:
return True
else:
conn = libvirt.open(None)
if conn is None:
raise Exception("Could not... | 5,301,011 |
def test_execute__output():
"""execute::output: should run echo command correctly"""
result = execute.output('echo "hi"')
assert result == "hi\n" | 5,301,012 |
def lemmatizeAndStem(word):
"""
Lemmatize and stem a word. Change a verb to its present tense, and reduce the word to its root forms.
Parameters:
word: string
The word the user wants to lemmatize and stem
Returns:
The lemmatized and stemmed word
"""
stemmer = Sno... | 5,301,013 |
def _magni_test_var_in_globals_func(*args, **kwargs):
"""Test function used in some tests."""
return 'magni_test_var' in globals() | 5,301,014 |
def overlap(layer, interval):
"""
calculate the thickness for a layer that overlapping with an interval
:param layer: (from_depth, to_depth)
:param interval: (from_depth, to_depth)
:return: the overlapping thickness
"""
res = 0
if layer[0] >= interval[0] and layer[1] <= interval[1]: # c... | 5,301,015 |
def wrap_class_callback(cls: type[ClassCallback]) -> Callable[..., Any]:
"""Function to wrap class callbacks in a function callback equivalent to:
1. Creating an instance of the class
2. Adding each argument as an attribute of the instance
3. calling `instance.handle()`
"""
sig = inspect.signatu... | 5,301,016 |
def main():
"""
CL arg parser and main runner
"""
parser = argparse.ArgumentParser(description='Use the largest connected components to run SVD on a graph')
parser.add_argument('ccfn', action="store")
parser.add_argument('roiRootName', action="store")
parser.add_argument('fgfn', action = 'store')
parser... | 5,301,017 |
def _LogRequest(*args, **kwargs):
"""Logs request arguments."""
# http.request has the following signature:
# request(self, uri, method="GET", body=None, headers=None,
# redirections=DEFAULT_MAX_REDIRECTS, connection_type=None)
uri = args[0]
method = 'GET'
body = ''
headers = {}
if len(args)... | 5,301,018 |
def _extract_info(archive, info):
"""
Extracts the contents of an archive info object
;param archive:
An archive from _open_archive()
:param info:
An info object from _list_archive_members()
:return:
None, or a byte string of the file contents
"""
if isinstance(ar... | 5,301,019 |
def _space_all_but_first(s: str, n_spaces: int) -> str:
"""Pad all lines except the first with n_spaces spaces"""
lines = s.splitlines()
for i in range(1, len(lines)):
lines[i] = " " * n_spaces + lines[i]
return "\n".join(lines) | 5,301,020 |
def filter_signal(
x: np.ndarray,
fs: float,
min_freq: float,
max_freq: float,
notch_freqs: list[float],
order: int = 5
) -> np.ndarray:
"""Filter sEMG signal with a Butterworth bandpass filter.
Parameters
----------
x: np.ndarray
sEMG data with shape (n_channels, n_samp... | 5,301,021 |
def get_colour(duration, duration_in_traffic):
"""Return a colour to provide an idea of the current traffic.
Gives a visual representation of the amount of traffic on route.
:param duration: A duration string, like "4 mins"
:param duration_in_traffic: A duration in traffic
"""
now = datetime.n... | 5,301,022 |
def get_all_translations(rna_sequence, genetic_code):
"""Get a list of all amino acid sequences encoded by an RNA sequence.
All three reading frames of `rna_sequence` are scanned from 'left' to
'right', and the generation of a sequence of amino acids is started
whenever the start codon 'AUG' is found. ... | 5,301,023 |
def get_gender_name_patterns() -> List[Dict[str, list]]:
"""Gets a list of all gendered first names in Denmark from DaCy, and converts to a list of lowercase spacy patterns.
Returns:
List[Dict[str, list]]: list of lowercase spacy match patterns
"""
from dacy.datasets import female_names, male_n... | 5,301,024 |
def _transform_coord_to_ref(cubes, ref_coord):
"""Transform coordinates of cubes to reference."""
try:
# Convert AuxCoord to DimCoord if necessary and possible
ref_coord = iris.coords.DimCoord.from_coord(ref_coord)
except ValueError:
pass
if not np.array_equal(np.unique(ref_coord... | 5,301,025 |
def parse_hue_api_response(response):
"""Take in the Hue API json response."""
data_dict = {} # The list of sensors, referenced by their hue_id.
# Loop over all keys (1,2 etc) to identify sensors and get data.
for key in response.keys():
sensor = response[key]
modelid = sensor['model... | 5,301,026 |
def fix_and_score_evidence(validated_evs, datasources_to_datatypes, evidence_manager):
"""take line as a dict, convert into an evidence object and apply a list of modifiers:
fix_evidence, and if valid then score_evidence, extend data and inject loci
"""
left, right = None, None
ev = Evidence(validat... | 5,301,027 |
def parse_args():
""" Parse command-line arguments."""
parser = argparse.ArgumentParser(description='''Identify family distribution with unmasked Ensembl ID''')
parser.add_argument(
'-i','--input', nargs='?', type=argparse.FileType('r'),
default=sys.stdin, help='An input file (CSV).')
pa... | 5,301,028 |
def fix_brackets(placeholder: str) -> str:
"""Fix the imbalanced brackets in placeholder.
When ptype is not null, regex matching might grab a placeholder with }
missing. This function fix the missing bracket.
Args:
placeholder: string placeholder of RuntimeParameter
Returns:
Placeholder with re-bal... | 5,301,029 |
async def test_callback_view_keyerror(hass, aiohttp_client, callback_view):
"""Test callback view with keyerror."""
client = await aiohttp_client(hass.http.app)
with patch(
"custom_components.tesla_custom.async_setup_entry", side_effect=KeyError
):
resp = await client.get(AUTH_CALLBACK_... | 5,301,030 |
def _generate_upsert_sql(mon_loc):
"""
Generate SQL to insert/update for Oracle.
"""
mon_loc_db = [(k, _manipulate_values(v, k in TIME_COLUMNS)) for k, v in mon_loc.items()]
all_columns = ','.join(col for (col, _) in mon_loc_db)
all_values = ','.join(value for (_, value) in mon_loc_db)
updat... | 5,301,031 |
def train(model, data, epochs, save_dir):
"""
Train model using MSE loss. Weights are saved each epoch.
:param model: model instance
:param data: iterable data
:param epochs: number of epochs to train
:param save_dir: Directory to save weights
"""
device = torch.device("cuda" if torch.c... | 5,301,032 |
def make_sparse(arr, kind='block', fill_value=nan):
"""
Convert ndarray to sparse format
Parameters
----------
arr : ndarray
kind : {'block', 'integer'}
fill_value : NaN or another value
Returns
-------
(sparse_values, index) : (ndarray, SparseIndex)
"""
arr = np.asarra... | 5,301,033 |
def preprocess_image(image, labels, prediction=False):
"""
format for tf model + open image and prepare it for resnet
"""
if prediction==False:
image = tf.io.read_file(image)
image = tf.io.decode_image(image, channels=3,expand_animations = False)
image = tf.cast(image, tf.float32) / ... | 5,301,034 |
def test_model_db_get(client):
"""Get index values"""
rpn = client.get('/geomodels/', follow_redirects=True)
print(rpn.data)
print(rpn) | 5,301,035 |
def delete_configuration_template(ApplicationName=None, TemplateName=None):
"""
Deletes the specified configuration template.
See also: AWS API Documentation
Exceptions
Examples
The following operation deletes a configuration template named my-template for an application named my-app:
E... | 5,301,036 |
def application(environ, start_response):
"""Do something fun"""
form = parse_formvars(environ)
huc12 = form.get("huc12", "000000000000")[:12]
scenario = int(form.get("scenario", 0))
start_response("200 OK", [("Content-type", "image/png")])
return [make_plot(huc12, scenario)] | 5,301,037 |
def all_peaks (timelags, std_score_dict, structural_delay_dict=None, minimal_synapse_delay=0):
"""
Return the largest standard score peak for each functional connection, rejecting false positives.
Implemented is the forward direction, that is looking for peaks at post-synaptic time lags
After convertin... | 5,301,038 |
def run(args):
"""
Run GPROF-NN algorithm.
Args:
args: The namespace object provided by the top-level parser.
"""
mp.set_start_method("spawn")
#
# Check and load inputs.
#
model = Path(args.model)
if not model.exists():
LOGGER.error("Given model is not an exist... | 5,301,039 |
def plot_batch_gains(
df,
kind="gain",
n=10,
models=None,
outcome_col="y",
treatment_col="w",
normalize=False,
figsize=(15, 5),
fontsize=20,
axis=None,
):
"""
Plots the batch gain chart: the cumulative batch gain predicted by a model given ranked treatment effects.
P... | 5,301,040 |
def security_bandit(session):
"""Check for security issues in dependencies."""
# Include all extras here to check all is safe for ci.
session.install(".[dev,lint,tests,security]")
session.run("python", "-m", "bandit", "-r", PACKAGE_DIR) | 5,301,041 |
def create_primitive_set(lib):
"""Create a DEAP primitive set from a dso.libraryLibrary."""
pset = gp.PrimitiveSet("MAIN", len(lib.input_tokens))
rename_kwargs = {"ARG{}".format(i): i for i in range(len(lib.input_tokens))}
for k, v in rename_kwargs.items():
# pset.renameArguments doesn't actua... | 5,301,042 |
def run():
"""
show
Show avilable encoders.
"""
encoders_pf = gget("encode.pf")
if (not len(encoders_pf)):
return
print(color.cyan("Encoders:"))
for encoder in encoders_pf.names():
print(f" {encoder}") | 5,301,043 |
def segmentation_to_rgb(seg_im, N, colors=None):
"""
Helper function to visualize segmentations as RGB frames.
NOTE: assumes that geom IDs go up to N at most - if not,
multiple geoms might be assigned to the same color.
"""
# ensure all values lie within [0, N]
seg_im = np.mod(seg_im, N)
... | 5,301,044 |
def async_debug_suite(suite, project, obj, report, config):
"""异步执行suite
"""
summary = debug_suite(suite, project, obj, config=config, save=False)
save_summary(report, summary, project) | 5,301,045 |
def a_1d_worse(a_1d):
"""a_1d worsened by constant offset."""
return a_1d + OFFSET | 5,301,046 |
def ParseRangeHeader(range_header):
"""Parse HTTP Range header.
Args:
range_header: A str representing the value of a range header as retrived
from Range or X-AppEngine-BlobRange.
Returns:
Tuple (start, end):
start: Start index of blob to retrieve. May be negative index.
end: None or ... | 5,301,047 |
def separate_cifs(filePath: str):
"""
Separate catenated CIF into individual datablocks within a temporary
directory.
Args
----
filePath: str
path to input file.
"""
fp = Path(filePath)
# create a temporary dictionary.
if not os.path.exists(fp.stem):
os... | 5,301,048 |
def create_router_ospf(tgen, topo=None, input_dict=None, build=False, load_config=True):
"""
API to configure ospf on router.
Parameters
----------
* `tgen` : Topogen object
* `topo` : json file data
* `input_dict` : Input dict data, required when configuring from testcase
* `build` : O... | 5,301,049 |
def _get_required_consent_subjects() -> set[Subject]:
"""Return the consent subjects required for this brand."""
return consent_subject_service.get_subjects_required_for_brand(g.brand_id) | 5,301,050 |
def test_prepare_markdown_fields_for_fetch_incidents():
"""
Scenario:Prepares markdown fields for incident.
Given:
- Dictionary of fields received in response of fetch incident.
When:
- Validating parameters.
Then:
- Proper table format of given parameters.
"""
from GoogleClo... | 5,301,051 |
def init_args(
cls: Any,
) -> List[str]:
""" Return the __init__ args (minus 'self') for @cls
Args:
cls: class, instance or callable
Returns:
The arguments minus 'self'
"""
# This looks insanely goofy, but seems to literally be the
# only thing that actually works. Your obv... | 5,301,052 |
def _unify_time_coordinates(cubes):
"""Make sure all cubes' share the same time coordinate.
This function extracts the date information from the cube and
reconstructs the time coordinate, resetting the actual dates to the
15th of the month or 1st of july for yearly data (consistent with
`regrid_tim... | 5,301,053 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Setup the sensor platform."""
data = hass.data[DOMAIN]
if not data.client.cars:
LOGGER.info("No Cars found.")
return
sensor_list = []
for car in data.client.cars:
for key, value in sorted(SWITCHES.items()):
... | 5,301,054 |
def create_repository(
input_filename: "githubcutter template" = "githubcutter.yml", **kwargs
):
"""
Create a GitHub repository.
"""
# parameters update
config = githubcutter.config.Config.load_from_yaml_file(input_filename)
# checking for parameters ovverriden by CLI
config.update(k... | 5,301,055 |
def analyse_start(deal: Deal, declarer_is_first: bool = False) -> int:
"""
Calculate the most tricks declarer can make.
:param deal: The deal to analyse
:param declarer_is_first: The algorithm assumes that the person who leads is to the left
of the declarer (as would be the case with the first card led
to a ha... | 5,301,056 |
def create_url(url):
"""
modifying the given url so that it returns JSON data when
we do a GET requests later in this script
"""
# extract the branch name from the given url (e.g master)
branch = re.findall(r"\/tree\/(.*?)\/", url)[0]
api_url = url.replace("https://github.com", "https://api.github.com/repos"... | 5,301,057 |
def generate_token_urlsafe(unique=False, nbytes=32):
"""Generate an URL-safe random token."""
return secrets.token_urlsafe(nbytes=nbytes) | 5,301,058 |
def get_challenge_phase_by_slug(request, slug):
"""
Returns a particular challenge phase details by pk
"""
try:
challenge_phase = ChallengePhase.objects.get(slug=slug)
except ChallengePhase.DoesNotExist:
response_data = {
"error": "Challenge phase with slug {} does not ex... | 5,301,059 |
def parse_multiline(element, poe_implicit_split = False):
""" Get data from a row & regroup tag-separated
string (<br/>) in a list
poe_implicit_split: <number>( to )<number>
for Implicit Mods extraction (optional)
"""
res = []
for data in element:
content = []
for x in data.strings:
if poe_imp... | 5,301,060 |
def pil_to_cv(pil):
""" Convert an image loaded from PIL to opencv format
The main difference is that PIL uses [R, G, B] and opencv uses
[B, G, R].
Args:
pil: An image loaded from PIL function
Returns:
cv_img: The corresponding image in opencv format
"""
pil... | 5,301,061 |
def get_characteristics(trajectory, dim):
"""
Function return characteristics for given scenario
:param char_set: enum, information about characteristic set scenario
:param path_to_file: str, path to file with trajectory
:param typ: str, type of diffusion i.e sub, super, rand
:param motion: str,... | 5,301,062 |
def binary_search(sorted_list: List[Any], value: Any, list_size: Optional[int] = None) -> int: # todo: remove?
"""
Performs binary search.
:param sorted_list: List with values in ascending order.
:param value: Value for which position in the list is searched.
:param list_size: Size of the sorted_l... | 5,301,063 |
def uncompress_file(infile, uncompressed, typeinfo=None):
"""
infile: input filename.
uncompressed: output filename.
typeinfo: output from the 'file' command; if None we'll run 'file'.
Returns: comptype
comptype: None if the file wasn't compressed, or 'gz' or 'bz2'.
"""
if typeinfo is None:
typeinfo = filety... | 5,301,064 |
def introspection():
"""Gets the base class for the introspection class.
We have to use the configured base back-end's introspection class
for this.
"""
return base_backend_instance().introspection.__class__ | 5,301,065 |
def _kickoff_df(fpl_data_dict, pos, footballer_func):
""" return kickoff from week df based on position"""
return _fetch_history_df(fpl_data_dict, pos, footballer_func,
{"kickoff_time": "kickoff_time"}) | 5,301,066 |
def read_json(file_path):
"""
Read a json file.
return: Dictionary or empty dictionary.
"""
if os.path.isfile(file_path):
with open(file_path, "r") as f:
try:
return json.load(f, object_hook=jsonKeys2int)
except json.decoder.JSONDecodeError:
... | 5,301,067 |
def score_sig_1D_base(true_signatures, pred_signatures):
"""
percent of mutations with the right signature
Parameters
----------
true_signatures: iterable
array-like of length N (number of mutations), with the
true signature for each mutation
pred_signat... | 5,301,068 |
def compute_apparent_power(f, j, seconds_per_file, values):
"""
Apparent power is the product of the voltage RMS and the current RMS.
"""
cs = [n for n in list(f) if 'current' in n]
apparent_power = dict()
for cs_i, _ in enumerate(cs):
if 'voltage' in list(f):
voltage_name ... | 5,301,069 |
def test_show_platform_psustatus(testbed_devices):
"""
@summary: Check output of 'show platform psustatus'
"""
ans_host = testbed_devices["dut"]
logging.info("Check PSU status using '%s', hostname: %s" % (CMD_PLATFORM_PSUSTATUS, ans_host.hostname))
psu_status = ans_host.command(CMD_PLATFORM_PSU... | 5,301,070 |
def test_csi_expansion_with_replica_failure(client, core_api, storage_class, pvc, pod_manifest): # NOQA
"""
Test expansion success but with one replica expansion failure
1. Create a new `storage_class` with `allowVolumeExpansion` set
2. Create PVC and Pod with dynamic provisioned volume from the Stora... | 5,301,071 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
Session.configure(bind=engine)
MailboxManager.init(settings['maildir_path'])
config = Configurator(settings=settings)
config.add_renderer(
... | 5,301,072 |
def charge_density(location, rho_bulk, charge, surface_potential, temperature=300, permittivity=80, species='Na'):
"""The density of ions near a charged surface.
Calculates the number density of ions of a species, at a distance of "location"
away from a metal/solution interface. The metal is charged, and thus the d... | 5,301,073 |
def _dict_decimal_to_float(my_dict):
"""If any values in dictionary are of dtype 'Decimal', cast
to float so can be JSONified.
"""
for key, val in my_dict.items():
if isinstance(val, decimal.Decimal):
my_dict[key] = float(val)
return my_dict | 5,301,074 |
def _add_tables(dset: "Dataset", rpt: "Report", figure_dir: "pathlib.PosixPath") -> None:
"""Add tables and related plots to report
Args:
dset: A dataset containing the data.
rpt: Report object.
figure_dir: Figure directory.
"""
rpt.add_text("\n# Number of GNSS ... | 5,301,075 |
def get_augment_preprocess(
augment_params: ml_collections.ConfigDict,
*,
colorjitter_params: Optional[ml_collections.ConfigDict] = None,
randerasing_params: Optional[ml_collections.ConfigDict] = None,
mean: Optional[tf.Tensor] = None,
std: Optional[tf.Tensor] = None,
basic_process: Callable... | 5,301,076 |
def cutmixup(img1, img2, mixup_prob=1.0, mixup_alpha=1.0,
cutmix_prob=1.0, cutmix_alpha=1.0): # (α1 / α2) -> 0.7 / 1.2
""" CutMix with the Mixup-ed image.
CutMix and Mixup procedure use hyper-parameter α1 and α2 respectively.
"""
c = _cutmix(img2, cutmix_prob, cutmix_alpha)
if c is None:
... | 5,301,077 |
def test_delete_two_children_root(test_bsts):
"""Test delete node with two children root."""
test_bsts[3].delete(5)
assert not test_bsts[3].contains(5)
assert test_bsts[3].size() is 6
assert test_bsts[3].root.val is 7 | 5,301,078 |
def is_pattern_match(s, exclude, include):
"""check if pattern match with 'include' and 'exclude' option
"""
if is_windows:
exclude = to_unix_path(exclude)
include = to_unix_path(include)
if exclude == None:
return True
elif include == None:
return (not pattern_match(... | 5,301,079 |
def draw_loading_bar(iter: int, total_iters: int, func_name: str):
"""Meant to be called every iteration of a loop to display the progress of a
test as an animated loading bar in the terminal.
Args:
iter (int): The iteration of the for loop *indexed from zero*.
total_iters (int): The total... | 5,301,080 |
def stitched_beads_on_nuclei_fresh_tissue(experiment_fpath:str,
client,
nuclei_tag:str='_ChannelCy3_Nuclei_',
beads_tag:str='_ChannelEuropium_Cy3_',
round_num:int = 1,
... | 5,301,081 |
def transit(state_record: StateRecord, heartbeat_reply: HeartbeatReply) -> None:
"""Participant state transition function on a heartbeat response. Updates the state record.
Args:
state_record (~xain_sdk.participant_state_machine.StateRecord): The updatable state record
of the participant.
... | 5,301,082 |
def translate_filter_titles(filters):
""" Translates filter titles according to the selected language
Args:
filters (dict): Contains the filters that shall be translated
Returns:
Returns the modified filters
"""
if filters.get("searchText", {}).get("title", "") != "":
filter... | 5,301,083 |
def print_available(key):
"""Return available models for certain parameter space
Parameters
----------
key : str
available parameters are [cloud, distance, gravity, metallicity, phase, temp]
Returns
-------
str, list
input key and list of available values
"""
return key, header[key].unique() | 5,301,084 |
def search(endpoint, query, sort=None, order=None, page=1, per_page=100, strict=False):
"""
`endpoint:str = 'users','repositories','commits'`
`query:str`
- users:
------
https://developer.github.com/v3/search/#search-users
https://help.github.com/en/github/searching-for-information-on-gith... | 5,301,085 |
def modify_docker_image_metadata(image_path: str,
output_docker_image: str):
"""
This context manager allow to modify the image metadata
This context manager expect a DockerscanReturnContextManager() exception to
get the wanted information from context excution.
T... | 5,301,086 |
def augment_Q(Q):
"""Augment the transition matrix Q such that it is in the from required in order
to solve. In essence this function gets M and b where:
- M = the transpose of {the transition matrix Q with the last column
replaced with a column of ones}
- b = a vector of the... | 5,301,087 |
def string2cycles(string):
"""
Convert string from user input to permutation in cycle notation as list
:param string: Permutation as string
:type string: string
:return: Returns permutation in cycle notation as list
:rtype: list
"""
groups = string.split(')(')
items = []
for i... | 5,301,088 |
def ddecal(msin, srcdb, msout=None, h5out=None, solint=120, nfreq=30,
startchan=0, nchan=0, minvisratio=0.6, mode='diagonal', uvlambdamin=500, subtract=True):
""" Perform direction dependent calibration with DPPP """
h5out = h5out or os.path.split(msin)[0] + '/ddcal.h5'
msbase = os.path.basename(... | 5,301,089 |
def gram_schmidt(basis):
"""
Performs Gram Schmidt Orthogonlization of a basis_o
:param basis: list of numpy ndarray of shape (2,M) of M samples
:rtype: list of numpy ndarray
:return basis_o: orthogonlized basis
"""
b1 = basis[0]
b2 = basis[1]
basis1 = b1 / sqrt(innerprod_q2(b1, b... | 5,301,090 |
def fetch_joke():
"""Fetch jokes"""
request = Request('http://api.icndb.com/jokes/random?limitTo=[nerdy]')
response = urlopen(request)
joke = json.loads(response.read())['value']['joke']
return joke | 5,301,091 |
def main() -> None:
"""Run main."""
fmt = "%(asctime)s %(levelname)s (%(threadName)s) [%(name)s] %(message)s"
logging.basicConfig(format=fmt, level=logging.DEBUG)
LOGGER.info("Starting client.")
try:
asyncio.run(run_client())
except KeyboardInterrupt:
LOGGER.info("Exiting client... | 5,301,092 |
def BuildAUTestTarball(buildroot, board, work_dir, version, archive_url):
"""Tar up the au test artifacts into the tarball_dir.
Args:
buildroot: Root directory where build occurs.
board: Board type that was built on this machine.
work_dir: Location for doing work.
version: Basic version of the buil... | 5,301,093 |
def create(reference_set_dict, monotone_relationship, minval=None, maxval=None):
"""
Create a scoring function that maps objects with N attributes to scores.
Required arguments:
reference_set_dict -- A reference set mapping objects to scores.
monotone_relationship -- A length-N vector with +1/-1 entries. +1 ... | 5,301,094 |
def create_load_balancer(LoadBalancerName=None, Listeners=None, AvailabilityZones=None, Subnets=None, SecurityGroups=None, Scheme=None, Tags=None):
"""
Creates a Classic Load Balancer.
You can add listeners, security groups, subnets, and tags when you create your load balancer, or you can add them later usi... | 5,301,095 |
def makeList_randomSplit(train_rate=0.9, variations=None, camera=0):
"""
creat list 'train.txt', 'val.txt'
Args:
train_rate:
variations: subset of [15-deg-left, 15-deg-right, 30-deg-left, 30-deg-right, clone, fog, morning, overcast, rain, sunset]
camera: 0 or 1
"""
if variat... | 5,301,096 |
def split_at_whitespace(string):
"""Like string.split(), but keeps empty words as empty words."""
return re.split(__WHITESPACE_SPLIT, string) | 5,301,097 |
def _make_list_value_pb(values):
"""Construct of ListValue protobufs.
:type values: list of scalar
:param values: Row data
:rtype: :class:`~google.protobuf.struct_pb2.ListValue`
:returns: protobuf
"""
return ListValue(values=[_make_value_pb(value) for value in values]) | 5,301,098 |
def test_directory_origin_csv_produce_less_file(sdc_builder, sdc_executor, csv_record_type, header_line):
""" Test Directory Origin in CSV data format. The sample CSV file has 3 lines and
the batch size is 1. The pipeline should produce the event, "new-file"
and 1 record
The pipelines looks like:
... | 5,301,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.