content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_problem_set(dataset,LABELNAME,labels,i2s):
"""Aggregate labels and associated article/domain information by chosen classification task
Arguments
- dataset: a list of article text (the corpus)
- LABELNAME: a string given by user input identifying the classification task
- labels: a dict ... | 5,318,000 |
def hello_world(text: str) -> str:
"""Print and return input."""
print(text)
return text | 5,318,001 |
def NestedGroupKFold(model, X, y, parameter_grid, groups, class_weights, scorer=make_scorer(accuracy_score),
inner_cv=GroupKFold(n_splits=4), outer_cv=GroupKFold(n_splits=4)):
"""
Implements a nested version of GroupKFold cross-validation using GridSearchCV to evaluate models
that nee... | 5,318,002 |
def create_vespa_query(query, text_processor, number_videos):
"""
Create the body of a Vespa query.
:param query: a string representing the query.
:param text_processor: an instance of `TextProcessor` to convert string to embedding.
:param number_videos: Number of videos to return.
:return: bod... | 5,318,003 |
def set_balance(x, v):
"""App label callback.
Set the load-balancing method from label F5_n_BALANCE
"""
x.balance = v | 5,318,004 |
def _thumb_from_pixel_clusters(images, mask, h, w, use_distance_from_centroid=False):
""" Alternate implementation. Results are sharper, but noisier """
# 6-color
# colors = np.array([[1, 0, 1, 0], [1, 0, 0, 0], [1, 1, 0, 0],
# [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0]],
# ... | 5,318,005 |
def get_rtClock():
"""
Instanziiert ein Real Time Clock Objekt
"""
return rtc.SDL_DS3231() | 5,318,006 |
def _transform_spherical_gpforce(inode_xyz, unused_inode_gp, data, cid_transform, coord,
unused_xyz_cid0, unused_log):
"""helper method for transform_gpforce_to_globali"""
#xyzi = xyz_cid0[inode_xyz, :]
#rtp_cid = coord.xyz_to_coord_array(xyzi)
#theta = rtp_cid[:, 1]
... | 5,318,007 |
def create_draft(service, user_id, message_body):
"""Create and insert a draft email. Print the returned draft's message and id.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message_bo... | 5,318,008 |
def analyze_files(file_list):
"""return info for each file in a list that
if it passed in analyzedir? passed in basedir? the results are the same?"""
result = map(lambda f: (f,)+analyze(f, analyzedir, basedir), file_list)
return result | 5,318,009 |
def profiling(func):
"""Decorator to mark a function for profiling. The time and memory usage will be recorded and printed.
Example:
.. highlight:: python
.. code-block:: python
@profiling
def foo():
print(1)
"""
from . import default_logger
@wraps(func)
... | 5,318,010 |
def find_no_of_workers(maxworkers, sys_share=0):
"""
Find the optimal number of workers for MP such that system does not crash.
Parameters
----------
maxworkers : Int. Maximum number of workers allowed.
Returns
-------
workers : Int. Workers used.
sys_share: Float. System share.
... | 5,318,011 |
def from_rdflib(
graph: Graph,
literal_cleaning_func: Callable = None,
kg_name: str = None,
multi_value: Callable = None,
) -> KG:
"""Create forayer knowledge graph object from rdflib graph.
Parameters
----------
graph : rdflib.Graph
Rdflib graph to transform.
literal_cleani... | 5,318,012 |
def video_player(obj):
"""
Receives object with 'video' FileField and returns HTML5 player.
"""
return {'object': obj} | 5,318,013 |
def wait_for(scope, prompt):
"""
Waits until the response of the remote host contains the given pattern.
:type prompt: regex
:param prompt: The prompt pattern.
"""
conn = scope.get('__connection__')
conn.expect(prompt)
scope.define(__response__=conn.response)
return True | 5,318,014 |
def retry_temporary_errors(
download_func: Callable[[SelfWithConfig, DownloadRequest], T]
) -> Callable[[SelfWithConfig, DownloadRequest], T]:
"""Decorator function for handling server and connection errors"""
backoff_coefficient = 3
def new_download_func(self: SelfWithConfig, request: DownloadRequest)... | 5,318,015 |
def get_first_order_indices(param_names, sim_id_params, all_results):
"""
Sobol method - First Order Indices
Equations from https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis
TODO: CS: This is exploration and is not complete (or even correct).
"""
params_outcomes = [
(s... | 5,318,016 |
def render_list_categories():
"""
METHOD=GET.
Renders Category Page.
"""
categories = session.query(Category).order_by(asc(Category.name)).all()
return render_template('categories/list.html', categories=categories) | 5,318,017 |
def perform_install(pspec, is_upgrade=False, force=False, quiet=False):
"""
Args:
pspec (PackageSpec): Package spec to install
is_upgrade (bool): If True, intent is an upgrade (not a new install)
force (bool): If True, check latest version even if recently checked
quiet (bool): I... | 5,318,018 |
def test_v1_and_v2_module_installed_simultaneously(
tmpdir: py.path.local, snippetcompiler_clean, capsys, caplog, modules_dir: str
) -> None:
"""
When a module is installed both in V1 and V2 format, ensure that:
* A warning is logged
* The V2 module is loaded and not the V1 module.
"""
... | 5,318,019 |
def tokens_to_str(message, section='body'):
""" Takes one section of a message as specified by key param and
returns it in string format to be joined with other messages
for summarization, printing, id creation (future).
"""
body = message[section]
new_mess = ''
if isinstanc... | 5,318,020 |
def azip(*aiterables):
"""async version of izip with parallel iteration"""
return _azip(*aiterables, fillvalue=None, stop_any=True) | 5,318,021 |
def collect_data(
bids_dir,
participant_label,
bids_validate=True,
bids_filters=None,
):
"""
Uses pybids to retrieve the input data for a given participant
Examples
--------
>>> bids_root, _ = collect_data(str(datadir / 'ds054'), '100185',
... bids_va... | 5,318,022 |
def filter_features(input_features, **kwargs):
"""
Args:
input_features: A Geojson feature collection
Returns:
A json of two geojson feature collections: passed and failed
"""
if type(input_features) is DictType:
if input_features.get("features"):
return iterate... | 5,318,023 |
def polygon_wrapper(func):
"""
Wrapper function to perform the setup and teardown of polygon
attributes before and after creating the polygon.
Keyword arguments:
func (function) -- the function to draw the polygon.
"""
@functools.wraps(func)
def draw_polygon(self, *args, **kwargs):... | 5,318,024 |
def compose_base_find_query(user_id: str, administrator: bool, groups: list):
"""
Compose a query for filtering reference search results based on user read rights.
:param user_id: the id of the user requesting the search
:param administrator: the administrator flag of the user requesting the search
... | 5,318,025 |
def test_prevent_links():
"""Returning None from any callback should remove links or prevent them
from being created."""
def no_new_links(attrs, new=False):
if new:
return None
return attrs
def no_old_links(attrs, new=False):
if not new:
return None
... | 5,318,026 |
def intersection (l, r) :
"""Compute intersection of lists `l` and `r`.
>>> intersection (range (4), range (2,5))
[2, 3]
"""
r_set = set (r)
return [x for x in l if x in r_set] | 5,318,027 |
def update_wallet_info(wallet: dict) -> None:
"""
Update profile information like username, last seen time and height.
:param wallet: wallet to update
:return: None
"""
info = get_profile(wallet["address"])
if info["username"]:
wallet["username"] = info["username"]
wallet["las... | 5,318,028 |
def filter_df_on_ncases(df, case_id_glue="case:concept:name", max_no_cases=1000):
"""
Filter a dataframe keeping only the specified maximum number of cases
Parameters
-----------
df
Dataframe
case_id_glue
Case ID column in the CSV
max_no_cases
Maximum number of cases... | 5,318,029 |
def test_get_cds_codons_from_fasta_empty_fasta_file(tmp_file):
"""
Test :py:func:`riboviz.get_cds_codons.get_cds_codons_from_fasta`
with an empty FASTA file and GFF file
(:py:const:`TEST_GFF_CODONS_FILE`) raises an exception.
:param tmp_file: Temporary file
:type tmp_file: str or unicode
""... | 5,318,030 |
def test_tags():
"""
test list_tags -> tag_resource -> list_tags -> tag_resource -> list_tags -> untag_resource -> list_tags integration
"""
bucket_name = str(uuid4())
s3_conn = boto3.client("s3", _lambda_region)
s3_conn.create_bucket(Bucket=bucket_name)
zip_content = get_test_zip_file2()
... | 5,318,031 |
def authorization_check():
"""
check if IP filtering applied and API address is in whitelist also API Key is valid
Returns:
None or Abort(403) or Abort(401)
"""
# IP Limitation
if app.config["OWASP_HONEYPOT_CONFIG"]["api_client_white_list"]:
if flask_request.remote_addr not in a... | 5,318,032 |
async def test_invalid_calendar_yaml(
hass: HomeAssistant,
mock_token_read: None,
component_setup: ComponentSetup,
google_service: GoogleCalendarService,
calendars_config: list[dict[str, Any]],
mock_calendars_yaml: None,
mock_notification: Mock,
) -> None:
"""Test setup with missing enti... | 5,318,033 |
def welcome():
"""List all available api routes."""
return (
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/start<br/>"
f"/api/v1.0/start/end"
) | 5,318,034 |
def pdbDownload(
file_list, hostname=HOSTNAME, directory=DIRECTORY, prefix=PREFIX, suffix=SUFFIX
):
"""
Download all pdb files in file_list and unzip them.
"""
success = True
# Log into server
print("Connecting...")
ftp = ftplib.FTP()
ftp.connect(hostname)
ftp.login()
# Re... | 5,318,035 |
def run_game():
"""Initialize pygame, settings and screen object"""
pygame.init()
settings = Settings()
screen = pygame.display.set_mode(
(settings.screen_width, settings.screen_height))
pygame.display.set_caption("Jordan Catch")
button = Button(screen, "Play")
player... | 5,318,036 |
def test_lookup_datawriter(topic, publisher):
"""
This test checks:
- Publisher::lookup_datawriter
"""
datawriter = publisher.create_datawriter(
topic, fastdds.DATAWRITER_QOS_DEFAULT)
assert(datawriter is not None)
datawriter2 = publisher.lookup_datawriter('Complete')
assert... | 5,318,037 |
def decode(s):
"""doc me"""
for encoding in "utf-8-sig", "utf-16":
try:
return s.decode(encoding)
except UnicodeDecodeError:
continue
return s.decode("latin-1") | 5,318,038 |
def wcs_set_bladeactivepowercycle(device_id):
""" Power cycles or soft resets the blades
IMPORTANT! - Output formatted for compatibility with WcsCli
"""
try:
if device_id == 0:
mode = get_mode()
port_range = system_range(mode)
else:
port_range... | 5,318,039 |
def status():
""" Check the status """
# Read cofiguration file to cfg
cfg_dir = os.path.dirname(__file__).replace('fabfile','ymlfile')
cfg_file = cfg_dir + '/hadoop.yml'
f = open(cfg_file)
cfg = yaml.safe_load(f)
f.close()
# Set ssh user and have ssh not check .ssh/known_hosts
env.... | 5,318,040 |
def Quantum_Vibrational_S(Temperature, wavenumbers):
"""
Funciton to calculate the quantum vibrational entropy at a given temperature
**Required Inputs
Temperature = single temperature in Kelvin to determine the vibrational entropy (does not work at 0 K)
wavenumbers = array of wavenumber (in order w... | 5,318,041 |
def _open(full_path, state, year, variety, database='SID'):
"""Returns a handle using python's builtin open() function; however, it
will skip past any non-content rows as specified within.
This is necessary because HCUP files very occasionally have bonus
content, typically a data use notice, a... | 5,318,042 |
def control_problem(seed: tp.Optional[int] = None) -> tp.Iterator[Experiment]:
"""MuJoCo testbed. Learn linear policy for different control problems.
Budget 500, 1000, 3000, 5000."""
seedg = create_seed_generator(seed)
num_rollouts = 1
funcs = [
Env(num_rollouts=num_rollouts, random_state=se... | 5,318,043 |
def summon(self: Client, entity: str, pos: Vec3 = None,
nbt: dict = None) -> str:
"""Summons an entity."""
return self.run('summon', entity, pos, nbt) | 5,318,044 |
def get_inner_html(node):
"""Gets the inner HTML of a node, including tags."""
children = ''.join(etree.tostring(e).decode('utf-8') for e in node)
if node.text is None:
return children
return node.text + children | 5,318,045 |
def plot_sensitivity(img_path, model, args):
"""Function to save the sensitivity plot."""
img_tensor, img = load_image(img_path, args)
_mapped = sensitivity_analysis(model, img_tensor)
mapped = np.squeeze(_mapped, axis=0)
f, (ax1, ax2) = plt.subplots(1, 2)
ax1.set_title('Input Image')
ax1... | 5,318,046 |
def remove_whitespace(s):
"""Remove excess whitespace including newlines from string
"""
words = s.split() # Split on whitespace
return ' '.join(words) | 5,318,047 |
def get_first_group (match):
"""
Retrieves the first group from the match object.
"""
return match.group(1) | 5,318,048 |
def plot_from_region_frames(
frames: Dict[str, pd.DataFrame],
variable: str,
binning: Tuple[int, float, float],
region_label: str,
logy: bool = False,
legend_kw : Dict[str, Any] = None,
) -> Tuple[plt.Figure, plt.Axes, plt.Axes]:
"""create a histogram plot pdf from dataframes and a desired v... | 5,318,049 |
async def init_integration(hass, co2_sensor=True) -> MockConfigEntry:
"""Set up the Nettigo Air Monitor integration in Home Assistant."""
entry = MockConfigEntry(
domain=DOMAIN,
title="10.10.2.3",
unique_id="aa:bb:cc:dd:ee:ff",
data={"host": "10.10.2.3"},
)
if not co2_se... | 5,318,050 |
def decode(ciphered_text: str) -> str:
"""
Decode Atbash cipher
:param ciphered_text: Atbash cipher
:return: decoded text
"""
return ''.join(replace_char(char) for char in ciphered_text
if char in LOWERCASE or char in DIGITS) | 5,318,051 |
def text(label, default=None):
"""
@brief prompt and read a single line of input from a user
@retval string input from user
"""
display = label
if( default ):
display += " (default: " + str(default) + ")"
input = raw_input( display + ": " )
if input == '' and default:
i... | 5,318,052 |
def plot_by_date(data: _pd.DataFrame, date_col_name: str = 'Date'):
"""
plot line plots of numerical features on date
:param data: dataframe to analyze
:param date_col_name: date column name
"""
# loop over numeric features
for i, c in enumerate(data.select_dtypes('number').columns):
... | 5,318,053 |
def update_reservation(reservation, updatedSpots, comments):
"""
Update the reservation with the new spots needed
"""
newSpots = updatedSpots - reservation.seats_needed
reservation.seats_needed = updatedSpots
reservation.note=comments
db.session.commit()
flash("Reservation updated.")
... | 5,318,054 |
def qc_freq(species, geom, natom, atom, mult, charge, index=-1, high_level = 0):
"""
Creates a frequency input and runs it.
index: >=0 for sampling, each job will get numbered with index
"""
if index == -1:
job = str(species.chemid) + '_fr'
else:
job = str(species.c... | 5,318,055 |
def sample_to_timed_points(model, size):
"""As :func:`sample` but return in :class:`open_cp.data.TimedPoints`.
"""
t = [datetime.datetime(2017,1,1)] * size
pts = sample(model, size)
assert pts.shape == (size, 2)
return open_cp.data.TimedPoints.from_coords(t, *pts.T) | 5,318,056 |
def _per_image_standardization(image):
"""
:param image: image numpy array
:return:
"""
num_compare = 1
for dim in image.shape:
num_compare = np.multiply(num_compare, dim)
_standardization = (image - np.mean(image)) / max(np.std(image), 1 / num_compare)
return _standardization | 5,318,057 |
def unflatten_parameters(params, example, device):
"""Unflatten parameters.
:args params: parameters as a single 1D np array
:args example: generator of parameters (as returned by module.parameters()),
used to reshape params
:args device: where to store unflattened parameters
:returns: unfla... | 5,318,058 |
def pattern_to_regex(pattern):
"""
Convert the CODEOWNERS path pattern into a regular expression string.
"""
orig_pattern = pattern # for printing errors later
# Replicates the logic from normalize_pattern function in Gitlab ee/lib/gitlab/code_owners/file.rb:
if not pattern.startswith('... | 5,318,059 |
def register_extensions(app):
"""Register Flask extensions."""
assets.init_app(app)
bcrypt.init_app(app)
cache.init_app(app)
db.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
migrate.init_app(app, db)
flask_mail.init_app(app)
celery.conf.update(app.config)
... | 5,318,060 |
def unit2uniform(x, vmin, vmax):
"""
mapping from uniform distribution on parameter space
to uniform distribution on unit hypercube
"""
return vmin + (vmax - vmin) * x | 5,318,061 |
def adaptive_minmax(data, x_data=None, poly_order=None, method='modpoly',
weights=None, constrained_fraction=0.01, constrained_weight=1e5,
estimation_poly_order=2, method_kwargs=None, **kwargs):
"""
Fits polynomials of different orders and uses the maximum values as the b... | 5,318,062 |
def extractHachidoriTranslations(item):
"""
Parser for 'Hachidori Translations'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Charging Magic with a Smile' in item['tags']:
return buildReleaseMessageWithT... | 5,318,063 |
def create_build_tools_zip(lib):
"""
Create the update package file.
:param lib: lib object
:return:
"""
opera_script_file_name_dict = OPTIONS_MANAGER.opera_script_file_name_dict
tmp_dict = {}
for each in SCRIPT_KEY_LIST:
tmp_dict[each] = []
if opera_script_file_nam... | 5,318,064 |
def _tvgp_qvgp_optim_setup():
"""Creates a VGP model and a matched tVGP model"""
time_points, observations, kernel, noise_variance = _setup()
input_data = (
tf.constant(time_points),
tf.constant((observations > 0.5).astype(float)),
)
likelihood = Bernoulli()
tvgp = t_VGP(
... | 5,318,065 |
def get_average_rate(**options):
"""
gets average imdb rate of all movies.
:rtype: float
"""
return movies_stat_services.get_average_rate() | 5,318,066 |
def _uint_to_le(val, length):
"""Returns a byte array that represents an unsigned integer in little-endian format.
Args:
val: Unsigned integer to convert.
length: Number of bytes.
Returns:
A byte array of ``length`` bytes that represents ``val`` in little-endian format.
"""
retur... | 5,318,067 |
def extract_preposition(arg_number, postags, morph, lemmas, syntax_dep_tree):
""" Returns preposition for a word in the sentence """
#TODO: fix duplication
#TODO: there was a list of words for complex preposition, as we use the whole preposition as a feature
children = get_children(arg_number, syn... | 5,318,068 |
def batch_to_patches(x, patch_size, patches_per_image):
"""
:param x: torch tensor with images in batch (batsize, numchannels, height, width)
:param patch_size: size of patch
:param patches_per_image:
:return:
"""
device = x.device
assert(x.dim() == 4)
bats... | 5,318,069 |
def parse_json(json_data, category):
"""
Parses the <json_data> from intermediate value.
Args:
json_data (str): A string of data to process in JSON format.
category (str): The category ('all' / 'spam' / 'ham') to extract data from.
Returns:
(status_code, data), where status_cod... | 5,318,070 |
def get_dset_size(shape_json, typesize):
""" Return the size of the dataspace. For
any unlimited dimensions, assume a value of 1.
(so the return size will be the absolute minimum)
"""
if shape_json is None or shape_json["class"] == 'H5S_NULL':
return None
if shape_json["class"] ... | 5,318,071 |
def check_shapes(
feed: "Feed", *, as_df: bool = False, include_warnings: bool = False
) -> List:
"""
Analog of :func:`check_agency` for ``feed.shapes``.
"""
table = "shapes"
problems = []
# Preliminary checks
if feed.shapes is None:
return problems
f = feed.shapes.copy()
... | 5,318,072 |
def get_help_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
"""
session_attributes = {}
card_title = "OPM Status Help"
speech_output = "To begin, ask o. p. m. status an acceptable question. For example, " \
"Is the gov... | 5,318,073 |
def mm_clustering(sampler, state, float_names, fixed_df, total_df_names, fit_scale, runprops, obsdf,geo_obj_pos, best_llhoods, backend, pool, mm_likelihood, ndim, moveset, const = 50, lag = 10, max_prune_frac = 0.9):
"""
Determines if walkers in the ensemble are lost and removes them. Replacing them
with random line... | 5,318,074 |
def off_diagonal_min(A):
"""Returns the minimum of the off diagonal elements
Args:
A (jax.numpy.ndarray): A real 2D matrix
Returns:
(float): The smallest off-diagonal element in A
"""
off_diagonal_entries = off_diagonal_elements(A)
return jnp.min(off_diagonal_entries) | 5,318,075 |
async def sleepybot(time):
""" For .sleep command, let the userbot snooze for a few second. """
message = time.text
if " " not in time.pattern_match.group(1):
await time.reply("Syntax: `.sleep [seconds]`")
else:
counter = int(time.pattern_match.group(1))
await time.edit("`sleepin... | 5,318,076 |
def cli_cosmosdb_sql_stored_procedure_create_update(client,
resource_group_name,
account_name,
database_name,
co... | 5,318,077 |
def create(box=None,n=None,nr=None,nc=None,sr=1,sc=1,cr=None,cc=None,const=None) :
"""
Creates a new HDU
"""
if box is not None:
nr=box.nrow()
nc=box.ncol()
sc=box.xmin
sr=box.ymin
else :
if nr is None and nc is None :
try :
nr=n
... | 5,318,078 |
def gcd(num1, num2):
"""Return Greatest Common Divisor"""
# Euclidean Algorithm for GCD
a = max([num1, num2])
b = min([num1, num2])
while b != 0:
mod = a % b
a = b
b = mod
return a | 5,318,079 |
def compute_all_quality_measures_for_all_units_in_recordings(recordings, feature_names=None, verbose=False):
"""Computes all sorting quality measures of all tetrodes and
stores them in `analysis` field of each `unit` dictionary.
Measures are computed concurrently for the same unit across all individual Rec... | 5,318,080 |
def read_params_from_config(config: dict, _root_name: str = "") -> List[NamedPyParam]:
"""Reads params from the nested python dictionary.
Args:
config: a python dictionary with params definitions
_root_name: used internally
Returns:
params a list of NamedPyParam extracted from the ... | 5,318,081 |
def output_sqlite(
nemfile: Path,
outdir: Path = typer.Option(
DEFAULT_DIR,
exists=True,
file_okay=True,
dir_okay=True,
writable=True,
),
verbose: bool = typer.Option(False, "--verbose", "-v"),
five_min: bool = typer.Option(False, "--five-min", "-5"),
):
"... | 5,318,082 |
def dataParser (path):
"""
This function parses all files in the directory specified by
the path input variable. It is assumed that all said files are
valid .wav files.
"""
waves = []
rates = []
digits = []
speakers = []
files = [f for f in listdir (path) if isfile (join (path, f... | 5,318,083 |
def deserialize_function(serial, function_type):
"""Deserializes the Keras-serialized function.
(De)serializing Python functions from/to bytecode is unsafe. Therefore we
also use the function's type as an anonymous function ('lambda') or named
function in the Python environment ('function'). In the latter case... | 5,318,084 |
def _dataset(
dataset_type: str,
train_val_test: str = 'train'
) -> torch.utils.data.Dataset:
"""
Dataset:
voc2007
voc2012
"""
if dataset_type == "voc2007":
from src.datasets import VOC2007
if train_val_test == "val":
train_val_test = "trainval"
elif ... | 5,318,085 |
def disaggregate_forecast(history,
aggregated_history,
aggregated_forecast,
dt_units='D',
period_agg=7,
period_disagg=1,
x_reg=None,
x_fut... | 5,318,086 |
def generate_basic_db():
"""
generate database entries for tests
"""
genotype1 = Genotype.objects.create(name="1001genomes", version="1.2")
phenotype1 = Phenotype.objects.create(name="Length of something")
study1 = Study.objects.create(name="McIntosh et al., 2010", transformation="log", method="... | 5,318,087 |
async def test_duplicate_zerconf_ignored(hass: HomeAssistant) -> None:
"""Test that the duplicate zeroconf isn't shown."""
MockConfigEntry(
domain=DOMAIN,
data={"host": "192.168.1.123"},
source=config_entries.SOURCE_IMPORT,
unique_id="83747482",
).add_to_hass(hass)
resul... | 5,318,088 |
def get_path_cost(latency_dict, path):
"""
Cost of all links over a path combined
:param latency_dict:
:param path:
:return:
"""
cost = 0
for i in range(len(path) - 1):
cost += get_link_cost(latency_dict, path[i], path[i+1])
return cost | 5,318,089 |
def ami(
corpus_dir: Pathlike,
output_dir: Pathlike,
annotations: Pathlike,
mic: str,
partition: str,
max_pause: float,
):
"""AMI data preparation."""
prepare_ami(
corpus_dir,
annotations_dir=annotations,
output_dir=output_dir,
mic=mic,
partition=p... | 5,318,090 |
def main(compilation_db_path, source_files, verbose, formatter, iwyu_args):
""" Entry point. """
# Canonicalize compilation database path
if os.path.isdir(compilation_db_path):
compilation_db_path = os.path.join(compilation_db_path,
'compile_commands.json')... | 5,318,091 |
def qderiv(array): # TAKE THE ABSOLUTE DERIVATIVE OF A NUMARRY OBJECT
"""Take the absolute derivate of an image in memory."""
#Create 2 empty arrays in memory of the same dimensions as 'array'
tmpArray = np.zeros(array.shape,dtype=np.float64)
outArray = np.zeros(array.shape, dtype=np.float64)
# Ge... | 5,318,092 |
def add_community_as_node_attribute(
graph: nx.Graph, community_list: List[Dict], community_key: str = "community"
) -> None:
"""
This function adds the attribute 'community' to each node of the network.
It uses the output of the cdlib community detection function.
Modifies the input graph o... | 5,318,093 |
def byte(number):
"""Return the given bytes as a human friendly KB, MB, GB, or TB string"""
B = float(number)
KB = float(1024) # 1024 b, 1 千字节=1024 字节
MB = float(KB ** 2) # 1024 kb, 1 兆字节=1048576 字节
GB = float(KB ** 3) # 1024 mb, 1 千兆字节(GB)=1073741824 字节(B)
TB = float(KB ** 4) # 1024 gb
... | 5,318,094 |
def compute_optimal_warping_path_subsequence_dtw(D, m=-1):
"""Given an accumulated cost matrix, compute the warping path for
subsequence dynamic time warping with step sizes {(1, 0), (0, 1), (1, 1)}
Notebook: C7/C7S2_SubsequenceDTW.ipynb
Args:
D (np.ndarray): Accumulated cost matrix
m ... | 5,318,095 |
def test_run_forecast_json():
"""Tests:
- no coverage
- hourly data (2+ years)
- default `hyperparameter_grid` (all interaction terms enabled)
"""
# sets random state for consistent comparison
data = generate_df_for_tests(
freq="H",
periods=700*24)
df = data["train_df"... | 5,318,096 |
def _start_tracker(n_workers: int) -> Dict[str, Any]:
"""Start Rabit tracker """
env: Dict[str, Union[int, str]] = {'DMLC_NUM_WORKER': n_workers}
host = get_host_ip('auto')
rabit_context = RabitTracker(hostIP=host, n_workers=n_workers, use_logger=False)
env.update(rabit_context.worker_envs())
r... | 5,318,097 |
def get_type_path(type, type_hierarchy):
"""Gets the type's path in the hierarchy (excluding the root type, like
owl:Thing).
The path for each type is computed only once then cached in type_hierarchy,
to save computation.
"""
if 'path' not in type_hierarchy[type]:
type_path = []
... | 5,318,098 |
def get_builtin_intents(locale=None, signatureContains=None, nextToken=None, maxResults=None):
"""
Gets a list of built-in intents that meet the specified criteria.
This operation requires permission for the lex:GetBuiltinIntents action.
See also: AWS API Documentation
Exceptions
:exam... | 5,318,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.