content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_folder(path):
"""
Creates a folder if not already exists
Args:
:param path: The folder to be created
Returns
:return: True if folder was newly created, false if folder already exists
"""
if not os.path.exists(path):
os.makedirs(path)
return True
el... | 5,333,300 |
def extract_smaps(kspace, low_freq_percentage=8, background_thresh=4e-6):
"""Extract raw sensitivity maps for kspaces
This function will first select a low frequency region in all the kspaces,
then Fourier invert it, and finally perform a normalisation by the root
sum-of-square.
kspace has to be of... | 5,333,301 |
def tiff_to_mat_conversion(ms_path, pan_path, save_path, ms_initial_point=(0, 0), ms_final_point=(0, 0), ratio=4):
"""
Generation of *.mat file, starting from the native GeoTiFF extension.
Also, a crop tool is provided to analyze only small parts of the image.
Parameters
----------
... | 5,333,302 |
def is_member(musicians, musician_name):
"""Return true if named musician is in musician list;
otherwise return false.
Parameters:
musicians (list): list of musicians and their instruments
musician_name (str): musician name
Returns:
bool: True if match is made; otherwise False.... | 5,333,303 |
def _parse_client_dict(dataset: tf.data.Dataset,
string_max_length: int) -> Tuple[tf.Tensor, tf.Tensor]:
"""Parses the dictionary in the input `dataset` to key and value lists.
Args:
dataset: A `tf.data.Dataset` that yields `OrderedDict`. In each
`OrderedDict` there are two key, va... | 5,333,304 |
def init(command):
"""
We assume the first command from NASA is the rover
position. Assumetions are bad. We know that the
command conists of two numbers seperated by a space.
Parse the number so it matches D D
"""
if re.match('^[0-9]\s[0-9]\s[a-zA-Z]$', command):
pos = command.split... | 5,333,305 |
def add_small_gap_multiply(original_wf, gap_cutoff, density_multiplier, fw_name_constraint=None):
"""
In all FWs with specified name constraints, add a 'small_gap_multiply' parameter that
multiplies the k-mesh density of compounds with gap < gap_cutoff by density multiplier.
Useful for increasing the k-... | 5,333,306 |
def _get_backend(config_backend):
"""Extract the backend class from the command line arguments."""
if config_backend == 'gatttool':
backend = GatttoolBackend
elif config_backend == 'bluepy':
backend = BluepyBackend
elif config_backend == 'pygatt':
backend = PygattBackend
else... | 5,333,307 |
def kern_CUDA_sparse(nsteps,
dX,
rho_inv,
context,
phi,
grid_idcs,
mu_egrid=None,
mu_dEdX=None,
mu_lidx_nsp=None,
prog_bar=None):
... | 5,333,308 |
def patch_import(file_path: Union[str, Path]) -> None:
"""If multi-client package, we need to patch import to be
from ..version
and not
from .version
That should probably means those files should become a template, but since right now
it's literally one dot, let's do it the raw way.
"""
... | 5,333,309 |
def test_no_matching_credentials(coresys: CoreSys):
"""Test no matching credentials."""
docker = DockerInterface(coresys)
coresys.docker.config.registries = {
DOCKER_HUB: {"username": "Spongebob Squarepants", "password": "Password1!"}
}
assert not docker._get_credentials("ghcr.io/homeassista... | 5,333,310 |
def _to_sequence(x):
"""shape batch of images for input into GPT2 model"""
x = x.view(x.shape[0], -1) # flatten images into sequences
x = x.transpose(0, 1).contiguous() # to shape [seq len, batch]
return x | 5,333,311 |
def read_wav_kaldi(wav_file_path: str) -> WaveData:
"""Read a given wave file to a Kaldi readable format.
Args:
wav_file_path: Path to a .wav file.
Returns:
wd: A Kaldi-readable WaveData object.
"""
# Read in as np array not memmap.
fs, wav = wavfile.read(wav_file_path, False)
... | 5,333,312 |
def _testCheckSums(tableDirectory):
"""
>>> data = "0" * 44
>>> checkSum = calcTableChecksum("test", data)
>>> test = [
... dict(data=data, checkSum=checkSum, tag="test")
... ]
>>> bool(_testCheckSums(test))
False
>>> test = [
... dict(data=data, checkSum=checkSum+1, tag=... | 5,333,313 |
def read_img(path):
"""
读取图片,并将其转换为邻接矩阵
"""
# 对于彩色照片,只使用其中一个维度的色彩
im = sp.misc.imread(path)[:, :, 2]
im = im / 255.
# 若运算速度太慢,可使用如下的语句来缩减图片的大小
# im = sp.misc.imresize(im, 0.10) / 255.
# 计算图片的梯度,既相邻像素点之差
graph = image.img_to_graph(im)
beta = 20
# 计算邻接矩阵
graph.data = np... | 5,333,314 |
def createmarker(name=None, source='default', mtype=None,
size=None, color=None, priority=None,
viewport=None, worldcoordinate=None,
x=None, y=None, projection=None):
"""%s
:param name: Name of created object
:type name: `str`_
:param source: A marker... | 5,333,315 |
def get_parser(disable: List[str] = None ,
lang: str = 'en',
merge_terms: Optional[Set] = None,
max_sent_len: Optional[int] = None) -> Callable:
"""spaCy clinical text parser
Parameters
----------
disable
lang
merge_terms
max_sent_len
Return... | 5,333,316 |
def block_device_mapping_get_all_by_instance(context, instance_uuid,
use_slave=False):
"""Get all block device mapping belonging to an instance."""
return IMPL.block_device_mapping_get_all_by_instance(context,
... | 5,333,317 |
def add_rain(img, slant, drop_length, drop_width, drop_color, blur_value, brightness_coefficient, rain_drops):
"""
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.uint8):
slant (int):
drop_length:
drop_width:
drop_color:
... | 5,333,318 |
def test_controls_have_techniques(attck_fixture):
"""
All MITRE Enterprise ATT&CK Malware should have Actors
Args:
attck_fixture ([type]): our default MITRE Enterprise ATT&CK JSON fixture
"""
for control in attck_fixture.enterprise.controls:
if control.techniques:
assert... | 5,333,319 |
def vrctst_tml(file_name):
""" adds vrctst_tml extension, if missing
:param file_name: name of file
:type file_name: str
:returns: file with extension added
:rtype: str
"""
return _add_extension(file_name, Extension.VRC_TML) | 5,333,320 |
def get_pixel_coords(x, y, xres, yres, xmin, ymax):
"""
Translate x, y coordinates to cols, rows.
Example:
col, row = map_pixel(x, y, geotransform[1],
geotransform[-1], geotransform[0], geotransform[3])
Parameters
----------
x : float, numpy.ndarray
X coordinates.
... | 5,333,321 |
def _boundary_of_alternatives_indices(pattern):
"""
Determines the location of a set of alternatives in a glob pattern.
Alternatives are defined by a matching set of non-bracketed parentheses.
:param pattern: Glob pattern with wildcards.
:return: Indices of the innermost set of matching non-... | 5,333,322 |
def plot(model, featnames=None, num_trees=None, plottype='horizontal', figsize=(25,25), verbose=3):
"""Make tree plot for the input model.
Parameters
----------
model : model
xgboost or randomforest model.
featnames : list, optional
list of feature names. The default is None.
nu... | 5,333,323 |
def post_images(*, image_path: str,) -> dict:
"""
Convert Image to PDF
"""
logging.debug('image_path: ' + image_path)
try:
if(image_path.startswith(NEXTCLOUD_USERNAME+"/files")):
image_path = image_path[len(NEXTCLOUD_USERNAME+"/files"):]
logging.debug('image_path: ' +... | 5,333,324 |
def sim_DA_from_timestamps2_p2_2states(timestamps, dt_ref, k_D, R0, R_mean,
R_sigma, tau_relax, k_s, rg,
chunk_size=1000, alpha=0.05, ndt=10):
"""
2-states recoloring using CDF in dt and with random number caching
"""
dt = np.... | 5,333,325 |
def enabled_enhancements(config):
"""
Generator to yield the enabled new style enhancements.
:param config: Configuration.
:type config: :class:`certbot.interfaces.IConfig`
"""
for enh in _INDEX:
if getattr(config, enh["cli_dest"]):
yield enh | 5,333,326 |
def draw_heatmap(square_size: int, city: generation.City, data: ScreenData):
""" Draws the population heatmap to the screen in the given ScreenData """
x_max = math.ceil(config.SCREEN_RES[0] / square_size) + 1
y_max = math.ceil(config.SCREEN_RES[1] / square_size) + 1
for x in range(0, x_max):
f... | 5,333,327 |
def get_cross_track_error(data, rate, velocity):
"""Returns the final cross-track position (in nautical miles)
The algorithm simulates an aircraft traveling on a straight trajectory who
turns according to the data provided. The aircraft instantaneously updates
its heading at each timestep by Ω * Δt.
... | 5,333,328 |
def _download_files(download, kwargs):
"""
Helper function to download content from Salt Master.
:param download: (list or str) list of keys or comma separated string
of key names from kwargs to download
:param kwargs: (dict) dictionary with data to download
"""
saltenv = kwargs.get... | 5,333,329 |
async def get_list_address():
"""Get list of address
"""
return await service.address_s.all() | 5,333,330 |
def handle_usergroup_manifests(groups):
"""Creates usergroup manifests"""
for name in groups.keys():
usergroup_manifest = UsergroupManifest(name)
if usergroup_manifest.changed:
usergroup_manifest.save() | 5,333,331 |
def run_clustering(pss, cfg):
"""
key => value
"usuario" parameters["email"]
"dataset" parameters["dataset"]
"extension" parameters["ext"]
"model" parameters["mod"]
"algorithm" parameters["algorithm"]
"metric" parameters["metric"]
"optimizer" parameters["optimizer"]
"in... | 5,333,332 |
def test_deprecate_pandas_dtype_enum(schema_cls):
"""Test that using the PandasDtype enum raises a DeprecationWarning."""
for attr in pa.PandasDtype:
if not FLOAT_128_AVAILABLE and attr in {
"Float128",
"Complex256",
}:
continue
with pytest.warns(Depre... | 5,333,333 |
def load_xml_stream(
file_path: pathlib.Path, progress_message: Optional[str] = None
) -> progress.ItemProgressStream:
"""Load an iterable xml file with a progress bar."""
all_posts = ElementTree.parse(file_path).getroot()
return progress.ItemProgressStream(
all_posts, len(all_posts), prefix=" ... | 5,333,334 |
def SNR_band(cp, ccont, cb, iband, itime=10.):
"""
Calc the exposure time necessary to get a given S/N on a molecular band
following Eqn 7 from Robinson et al. 2016.
Parameters
----------
cp :
Planet count rate
ccont :
Continuum count rate
cb :
Background count r... | 5,333,335 |
def acquire_lease(lease_id, client_id, ttl=DEFAULT_LOCK_DURATION_SECONDS, timeout=DEFAULT_ACQUIRE_TIMEOUT_SECONDS):
"""
Try to acquire the lease. If fails, return None, else return lease object. The timeout is crudely implemented with backoffs and retries so the timeout is not precise
:param client_id: the... | 5,333,336 |
def create_index(conn, column_list, table='perfdata', unique=False):
"""Creates one index on a list of/one database column/s.
"""
table = base2.filter_str(table)
index_name = u'idx_{}'.format(base2.md5sum(table + column_list))
c = conn.cursor()
if unique:
sql = u'CREATE UNIQUE INDEX IF... | 5,333,337 |
def produce_hash(self: Type[PCell], extra: Any = None) -> str:
"""Produces a hash of a PCell instance based on:
1. the source code of the class and its bases.
2. the non-default parameter with which the pcell method is called
3. the name of the pcell
"""
# copy source code of class and all its a... | 5,333,338 |
def test_copy_keys_successful(
helpers, s3_mock, transactions, source_bucket, target_bucket, files
):
"""copy_keys should copy files to target location."""
# Arrange
helpers.create_s3_files({f: f for f in files["create_files"]}, bucket=source_bucket)
if source_bucket != target_bucket:
s3_moc... | 5,333,339 |
def move_upload_files_to_trash(study_id, files_to_move):
"""Move files to a trash folder within the study_id upload folder
Parameters
----------
study_id : int
The study id
files_to_move : list
List of tuples (folder_id, filename)
Raises
------
QiitaDBError
If f... | 5,333,340 |
def stopSimulation():
"""Application function to stop simulation run"""
sim.stopSimulation() | 5,333,341 |
def boxes3d_kitti_fakelidar_to_lidar(boxes3d_lidar):
"""
Args:
boxes3d_fakelidar: (N, 7) [x, y, z, w, l, h, r] in old LiDAR coordinates, z is bottom center
Returns:
boxes3d_lidar: [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center
"""
w, l, h, r = boxes3d_lidar[:, 3:4], bo... | 5,333,342 |
def combine_per_choice(*args):
"""
Combines two or more per-choice analytics results into one.
"""
args = list(args)
result = args.pop()
new_weight = None
new_averages = None
while args:
other = args.pop()
for key in other:
if key not in result:
result[key] = other[key]
else:... | 5,333,343 |
def prepare_input(dirty: str) -> str:
"""
Prepare the plaintext by up-casing it
and separating repeated letters with X's
"""
dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters])
clean = ""
if len(dirty) < 2:
return dirty
for i in range(len(dirty) - 1):
... | 5,333,344 |
def test_set_udp():
"""StatsClient.set works."""
cl = _udp_client()
_test_set(cl, 'udp') | 5,333,345 |
def calc_center_from_box(box_array):
"""calculate center point of boxes
Args:
box_array (array): N*4 [left_top_x, left_top_y, right_bottom_x, right_bottom_y]
Returns:
array N*2: center points array [x, y]
"""
center_array=[]
for box in box_array:
center_array.append... | 5,333,346 |
def fakeperson(bot, trigger):
"""Posts a not real person. 😱
Uses thispersondoesnotexist.com"""
url = "https://thispersondoesnotexist.com/image"
try:
image = requests.get(url)
filename = ''.join(
random.SystemRandom().choice(
string.ascii_letters +
... | 5,333,347 |
def getW3D(coords):
"""
#################################################################
The calculation of 3-D Wiener index based
gemetrical distance matrix optimized
by MOPAC(Not including Hs)
-->W3D
#################################################################
"""
temp = []
... | 5,333,348 |
def state_vectors(
draw: Any,
max_num_qudits: int = 3,
allowed_bases: Sequence[int] = (2, 3),
min_num_qudits: int = 1,
) -> StateVector:
"""Hypothesis strategy for generating `StateVector`'s."""
num_qudits, radixes = draw(
num_qudits_and_radixes(
max_num_qudits, allowed_bases... | 5,333,349 |
def ProcessChainsAndLigandsOptionsInfo(ChainsAndLigandsInfo, ChainsOptionName, ChainsOptionValue, LigandsOptionName = None, LigandsOptionValue = None):
"""Process specified chain and ligand IDs using command line options.
Arguments:
ChainsAndLigandsInfo (dict): A dictionary containing information
... | 5,333,350 |
def signal_declaration_check(args, func):
"""
FUNCTION: signal_decleration_check(a(), b str)
a: tupple containing the signal statements
b: string name of the design function
- Signal decleration check.
"""
# Python's variable declar... | 5,333,351 |
def test_update_pool(pool_api_setup):
"""Test the patch /pools/{pool_id} API EP"""
POOL_DICT["slots"] = 2
updated_pool = Pool(**POOL_DICT)
api_response = pool_api_setup.patch_pool(
"test_pool",
updated_pool,
)
logging.getLogger().info("%s", api_response)
print(f"{BCOLORS.OKGR... | 5,333,352 |
def oa_filter(x, h, N, mode=0):
"""
Overlap and add transform domain FIR filtering.
This function implements the classical overlap and add method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filtered as an ndarray
h : F... | 5,333,353 |
def get_languages(translation_dir: str, default_language: Optional[str] = None) -> Iterable[str]:
"""
Get a list of available languages.
The default language is (generic) English and will always be included. All other languages will be read from
the folder `translation_dir`. A folder within... | 5,333,354 |
def calculate_direction(a, b):
"""Calculates the direction vector between two points.
Args:
a (list): the position vector of point a.
b (list): the position vector of point b.
Returns:
array: The (unnormalised) direction vector between points a and b. The smallest magnitude of an e... | 5,333,355 |
def argmin(a, axis=None, out=None, keepdims=None, combine_size=None):
"""
Returns the indices of the minimum values along an axis.
Parameters
----------
a : array_like
Input tensor.
axis : int, optional
By default, the index is into the flattened tensor, otherwise
along ... | 5,333,356 |
def parse_game_state(gs_json: dict) -> game_state_pb2.GameState:
"""Deserialize a JSON-formatted game state to protobuf."""
if 'provider' not in gs_json:
raise InvalidGameStateException(gs_json)
try:
map_ = parse_map(gs_json.get('map'))
provider = parse_provider(gs_json['provider'])
round_ = par... | 5,333,357 |
def run():
"""
Main processing function.
"""
pref = mmcommon.pref('TimeMachine')
if pref is not None:
processTM(pref) | 5,333,358 |
def state2bin(s, num_bins, limits):
"""
:param s: a state. (possibly multidimensional) ndarray, with dimension d =
dimensionality of state space.
:param num_bins: the total number of bins in the discretization
:param limits: 2 x d ndarray, where row[0] is a row vector of the lower
limit... | 5,333,359 |
def _fix_json_agents(ag_obj):
"""Fix the json representation of an agent."""
if isinstance(ag_obj, str):
logger.info("Fixing string agent: %s." % ag_obj)
ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}}
elif isinstance(ag_obj, list):
# Recursive for complexes and similar.
... | 5,333,360 |
def fuzz(input_corpus, output_corpus, target_binary):
"""Run fuzzer."""
prepare_fuzz_environment(input_corpus)
# Note: dictionary automatically added by run_fuzz().
# Use a dictionary for original afl as well.
print('[run_fuzzer] Running AFL for original binary')
src_file = '{target}-normalize... | 5,333,361 |
def vflip(img):
"""Vertically flip the given CV Image.
Args:
img (CV Image): Image to be flipped.
Returns:
CV Image: Vertically flipped image.
"""
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
return cv2.flip(img, 1) | 5,333,362 |
def request_download(session, product_id, outdir, override=False,
progressbar=False):
"""Request download to ESA and interpret the response."""
product_url = _dl_url(product_id)
r = session.get(product_url, stream=True)
# Product is not available
if r.status_code == 404:
... | 5,333,363 |
def list_pending_tasks():
"""List all pending tasks in celery cluster."""
inspector = celery_app.control.inspect()
return inspector.reserved() | 5,333,364 |
def setDifficulty():
"""sets the difficulty"""
global difficultyFactor
scrollMenu(
" _____ _ __ __ _ _ _ \n | __ \(_)/ _|/ _(_) | | | \n | | | |_| |_| |_ _ ___ _ _| | |_ _ _ \n | | | | | _| _| |/ __| | | | | __| | | |\n | |__| | | | | | | | (__| |_| |... | 5,333,365 |
def get_attack(attacker, defender):
"""
Returns a value for an attack roll.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being attacked
Returns:
attack_value (int): Attack roll value, compared against a defense value
to determine whe... | 5,333,366 |
def colored(s, color=None, attrs=None):
"""Call termcolor.colored with same arguments if this is a tty and it is available."""
if HAVE_COLOR:
return colored_impl(s, color, attrs=attrs)
return s | 5,333,367 |
def _combine_by_cluster(ad, clust_key='leiden'):
"""
Given a new AnnData object, we want to create a new object
where each element isn't a cell, but rather is a cluster.
"""
clusters = []
X_mean_clust = []
for clust in sorted(set(ad.obs[clust_key])):
cells = ad.obs.loc[ad.obs[clust_k... | 5,333,368 |
def print_table(table):
"""Print the list of strings with evenly spaced columns."""
# print while padding each column to the max column length
col_lens = [0] * len(table[0])
for row in table:
for i, cell in enumerate(row):
col_lens[i] = max(len(cell), col_lens[i])
formats = ["{0:<%d}" % x for x in ... | 5,333,369 |
def test_serialization(mockplan):
"""Test serialization of test results."""
pool = ProcessPool(name="ProcPool", size=2)
mockplan.add_resource(pool)
mockplan.schedule(
target="make_serialization_mtest",
module="test_pool_process",
path=os.path.dirname(__file__),
resource="... | 5,333,370 |
def subsample_data(features, scaled_features, labels, subsamp): # This is only for poker dataset
""" Subsample the data. """
# k is class, will iterate from class 0 to class 1
# v is fraction to sample, i.e. 0.1, sample 10% of the current class being iterated
for k, v in subsamp.items():
ix = n... | 5,333,371 |
def anomary_scores_ae(df_original, df_reduced):
"""AEで再生成された特徴量から異常度を計算する関数"""
"""再構成誤差を計算する異常スコア関数
Args:
df_original(array-like): training data of shape (n_samples, n_features)
df_reduced(array-like): prediction of shape (n_samples, n_features)
Returns:
pd.Series: 各データごとの異常スコア... | 5,333,372 |
def merge_runs(input_dir1, input_dir2, map_df, output, arguments):
"""
:param input_dir1: Directory 1 contains mutation counts files
:param input_dir2: Directory 2 contains mutation counts files
:param map_df: A dataframe that maps the samples to be merged
:param output: output directory to save mer... | 5,333,373 |
def handle_left(left_entry_box, right_entry_box, mqtt_sender):
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negative of the speed in the left entry box.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: co... | 5,333,374 |
def latest_res_ords():
"""Get last decade from reso and ords table"""
filename = 'documentum_scs_council_reso_ordinance_v.csv'
save_path = f"{conf['prod_data_dir']}/documentum_scs_council_reso_ordinance_v"
df = pd.read_csv(f"{conf['prod_data_dir']}/{filename}",
low_memory=False)
df['DOC_DA... | 5,333,375 |
def test_plot_density_no_subset():
"""Test plot_density works when variables are not subset of one another (#1093)."""
model_ab = from_dict(
{
"a": np.random.normal(size=200),
"b": np.random.normal(size=200),
}
)
model_bc = from_dict(
{
"b": np... | 5,333,376 |
def langevin_coefficients(temperature, dt, friction, masses):
"""
Compute coefficients for langevin dynamics
Parameters
----------
temperature: float
units of Kelvin
dt: float
units of picoseconds
friction: float
collision rate in 1 / picoseconds
masses: array... | 5,333,377 |
def get_description():
"""
Read full description from 'README.md'
:return: description
:rtype: str
"""
with open('README.md', 'r', encoding='utf-8') as f:
return f.read() | 5,333,378 |
def qt_matrices(matrix_dim, selected_pp_indices=[0, 5, 10, 11, 1, 2, 3, 6, 7]):
"""
Get the elements of a special basis spanning the density-matrix space of
a qutrit.
The returned matrices are given in the standard basis of the
density matrix space. These matrices form an orthonormal basis
unde... | 5,333,379 |
def find_continous_edits(instance):
"""Helper processing step that identifies continuous edits"""
instance['tgt_token_diffs'] = list(group_by_continuous(instance['tgt_token_diff']))
instance['src_token_diffs'] = list(group_by_continuous(instance['src_token_diff']))
yield instance | 5,333,380 |
def get_signed_value(bit_vector):
"""
This function will generate the signed value for a given bit list
bit_vector : list of bits
"""
signed_value = 0
for i in sorted(bit_vector.keys()):
if i == 0:
signed_value = int(bit_vector[i])
else:
signed_... | 5,333,381 |
def sign_table(data, sec_key, metadata_hash="!sdata_sha3_256_table", metadata_hash_signature="!sdata_sha3_256_table_signature"):
"""sign Data.table
:param data:
:param sec_key:
:param metadata_hash: (default="!sdata_sha3_256_table")
:param metadata_hash_signature: (default="!sdata_sha3_256_table_si... | 5,333,382 |
def values_to_colors(values, cmap, vmin=None, vmax=None):
"""
Function to map a set of values through a colormap
to get RGB values in order to facilitate coloring of meshes.
Parameters
----------
values: array-like, (n_vertices, )
values to pass through colormap
cmap: array-like, (n... | 5,333,383 |
def _clean_sys_argv(pipeline: str) -> List[str]:
"""Values in sys.argv that are not valid option values in Where
"""
reserved_opts = {pipeline, "label", "id", "only_for_rundate", "session", "stage", "station", "writers"}
return [o for o in sys.argv[1:] if o.startswith("--") and o[2:].split("=")[0] not i... | 5,333,384 |
def get_number_from_user_input(prompt: str, min_value: int, max_value: int) -> int:
"""gets a int integer from user input"""
# input loop
user_input = None
while user_input is None or user_input < min_value or user_input > max_value:
raw_input = input(prompt + f" ({min_value}-{max_value})? ")
... | 5,333,385 |
def test_cli_run_rl_dueling_dqn(cli_args):
"""Test running CLI for an example with default params."""
from pl_bolts.models.rl.dueling_dqn_model import cli_main
cli_args = cli_args.split(' ') if cli_args else []
with mock.patch("argparse._sys.argv", ["any.py"] + cli_args):
cli_main() | 5,333,386 |
async def test_template_static(opp, caplog):
"""Test that we allow static templates."""
with assert_setup_component(1, lock.DOMAIN):
assert await setup.async_setup_component(
opp,
lock.DOMAIN,
{
"lock": {
"platform": "template",
... | 5,333,387 |
def word_saliency(topic_word_distrib, doc_topic_distrib, doc_lengths):
"""
Calculate word saliency according to [Chuang2012]_ as ``saliency(w) = p(w) * distinctiveness(w)`` for a word ``w``.
.. [Chuang2012] J. Chuang, C. Manning, J. Heer. 2012. Termite: Visualization Techniques for Assessing Textual Topic
... | 5,333,388 |
def parse_cl_items(s):
"""Take a json string of checklist items and make a dict of item objects keyed on
item name (id)"""
dispatch = {"floating":Floating,
"weekly":Weekly,
"monthly": Monthly,
"daily":Daily
}
if len(s) == 0:
return ... | 5,333,389 |
def get_queue(queue, flags=FLAGS.ALL, **conn):
"""
Orchestrates all the calls required to fully fetch details about an SQS Queue:
{
"Arn": ...,
"Region": ...,
"Name": ...,
"Url": ...,
"Attributes": ...,
"Tags": ...,
"DeadLetterSourceQueues": ...,
... | 5,333,390 |
def draw(
x,
x_extents=(-100, 100),
y_extents=(-100, 100),
landmarks=None,
observations=None,
particles=None,
weights=None,
ellipses=None,
fig=None,
):
"""Draw vehicle state x = [x, y, theta] on the map."""
xmin, xmax = x_extents
ymin, ymax = y_extents
tick_spacing = ... | 5,333,391 |
def mixed_float_frame():
"""
Fixture for DataFrame of different float types with index of unique strings
Columns are ['A', 'B', 'C', 'D'].
"""
df = DataFrame(tm.getSeriesData())
df.A = df.A.astype('float32')
df.B = df.B.astype('float32')
df.C = df.C.astype('float16')
df.D = df.D.ast... | 5,333,392 |
def create_parsetestcase(durationstring, expectation, format, altstr):
"""
Create a TestCase class for a specific test.
This allows having a separate TestCase for each test tuple from the
PARSE_TEST_CASES list, so that a failed test won't stop other tests.
"""
class TestParseDuration(unittest.... | 5,333,393 |
async def test_reauth_auth_failed(hass: HomeAssistantType, fritz: Mock):
"""Test starting a reauthentication flow with authentication failure."""
fritz().login.side_effect = LoginError("Boom")
mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
mock_config.add_to_hass(hass)
result = ... | 5,333,394 |
def convert_train_run_repeat():
"""
12/13/16
Basically a run of the almost complete package on repeat: convert, train, then run.
:return: combined outputs of 3 functions
"""
n = input('Number of repitions? -> ')
try:
n = int(n)
for i in range(0, n):
convert_trai... | 5,333,395 |
def environment(cluster: str, service: str, arguments: Sequence[str]) -> None:
"""
Show or modify environment variables.
If no arguments are given, prints all environment variable name/value
pairs.
If arguments are given, set environment variables with the given names to
the given values. If ... | 5,333,396 |
def draw_data_from_db(host, port=None, pid=None, startTime=None, endTime=None, system=None, disk=None):
"""
Get data from InfluxDB, and visualize
:param host: client IP, required
:param port: port, visualize port data; optional, choose one from port, pid and system
:param pid: pid, visualize pi... | 5,333,397 |
def get_sample_generator(filenames, batch_size, model_config):
"""Set data loader generator according to different tasks.
Args:
filenames(list): filenames of the input data.
batch_size(int): size of the each batch.
model_config(dict): the dictionary containing model configuration.
... | 5,333,398 |
def execute_batch(table_type, bulk, count, topic_id, topic_name):
"""
Execute bulk operation. return true if operation completed successfully
False otherwise
"""
errors = False
try:
result = bulk.execute()
if result['nModified'] != count:
print(
"bulk ... | 5,333,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.