content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_sudoers(machine_name):
"""
This function returns a list of usernames that are sudoers on the machine
passed as a parameter.
"""
machine_name = _unicode_to_str(machine_name)
con = get_binded_connection()
sudoers = con.search_s("%s,%s" % (settings.ADMINS_OU, settings.DC),
... | 5,295,000 |
def get_speakers(data: list, num=3):
"""获取差异大的说话人,说话人之间相互的embed的余弦相似度最大。"""
sim_mat = pairwise_distances(data, metric='cosine')
sim_vec = np.mean(sim_mat, axis=0)
targets = list(range(len(sim_vec)))
idx = np.argmax(sim_vec)
outs = [idx]
targets.remove(idx)
while 1:
sim_vec = np.m... | 5,295,001 |
def preprocess_documents(tmp_dir, tag_name, url):
"""
Prepares the data to be used by the document generation
:param docs: pandasdataframe
:return:
"""
URL = url
compressed_filename = os.path.basename(URL)
download_path = generator_utils.maybe_download(tmp_dir, compressed_filename, URL)
... | 5,295,002 |
def iterify(x):
"""Return an iterable form of a given value."""
if isinstance(x, Iterable):
return x
else:
return (x,) | 5,295,003 |
def get_regression_estimate(X, neuron_idx):
"""
Estimates the connectivity matrix using lasso regression.
Args:
X (np.ndarray): our simulated system of shape (n_neurons, timesteps)
neuron_idx (int): a neuron index to compute connectivity for
Returns:
V (np.ndarray): estimated ... | 5,295,004 |
def read_messpf_temps(pf_path):
""" Obtain the temperatures from the MESSPF file
"""
# Obtain the temperatures, remove the 298.2 value
temps, _, _, _ = read_messpf(pf_path)
temps = [temp for temp in temps if not numpy.isclose(temp, 298.2)]
return temps | 5,295,005 |
def fitsin(fits):
"""Read in a fits file and retun the data
Parameters
----------
fits : str
fits file name to read
Returns
----------
data : np.array
data arry of input fits file
"""
data = pyfits.getdata(fits)
return data | 5,295,006 |
def test_particles_jf008_particles_jf008_v(mode, save_output, output_format):
"""
TEST :3.9.1 The Particle Schema Component [ check length of element
information items ] : Particle Derivation OK (elt:Any) element R
drived by restriction from wildcard (any) B : B's namespace=##any, R's
targetNamespac... | 5,295,007 |
def get_subfolder(path, subfolder, init=True):
"""
Check if subfolder already exists in given directory, if not, create one.
:param path: Path in which subfolder should be located (String)
:param subfolder: Name of the subfolder that must be created (String)
:param init: Initialize folder with ... | 5,295,008 |
def _destination_sample(
primary_purpose,
trips,
alternatives,
model_settings,
size_term_matrix,
skims,
alt_dest_col_name,
estimator,
chunk_size,
trace_label):
"""
Note: trips with no viable destination receive no sample rows
(... | 5,295,009 |
def test_bin():
""" Test if you can bin the periodogram
"""
lc = LightCurve(time=np.arange(1000), flux=np.random.normal(1, 0.1, 1000), flux_err=np.zeros(1000)+0.1)
p = lc.to_periodogram()
assert len(p.bin(binsize=10).frequency) == len(p.frequency)//10 | 5,295,010 |
def zeros(axes=None, dims=None, shape=None, dtype=float):
""" Initialize an array filled with zeros. See empty for doc.
>>> zeros(dims=('time','items'), shape=(2, 3))
dimarray: 6 non-null elements (0 null)
0 / time (2): 0 to 1
1 / items (3): 0 to 2
array([[0., 0., 0.],
[0., 0., 0.]])... | 5,295,011 |
def get_textcellfont(size, face, color, bold, italic,
uline, vertical, antialiased):
"""テキストセル用のフォントを生成し、
(font, lineheight)を返す。
"""
font = cw.imageretouch.Font(face, -size, bold, italic)
if uline:
font.set_underline(True)
return font, font.get_linesize() | 5,295,012 |
def choose_boundary() -> str:
"""Random boundary name."""
return binascii.hexlify(os.urandom(16)).decode("ascii") | 5,295,013 |
def center(E, out=None):
"""
Adjusts the ensemble to zero mean.
"""
u = np.mean(E, axis=1).reshape(E.shape[0], 1)
return np.subtract(E, u, out=out) | 5,295,014 |
def load_ignore(fname):
"""Loads patterns signalling lines to ignore
Args:
fname: File name containing patterns
Returns:
A list of patterns
"""
values = []
with open(fname, 'r') as f:
lines = f.readlines()
for line in lines:
values.append(line.rstrip('\n'))
return values | 5,295,015 |
def check_path(filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the given path, printing out any warnings detected."""
try:
with open(filename, 'U') as f:
codestr = f.read() + '\n'
except UnicodeError:
reporter.unexpected_error(filename, ... | 5,295,016 |
def test_bokehserver_apps_folder_generation(
bake_custom_project, bokehserver_app_files
):
"""Test generation and rendering of cookiecutter project template."""
result = bake_custom_project
proj_dir = result.project
bokehserver_app_dir = proj_dir.join("mybokehserverapp")
assert bokehserver_app_d... | 5,295,017 |
def test_cache_stop_and_load(cache_mode):
"""
title: Test for stopping and loading cache back with dynamic cache mode switching.
description: |
Validate the ability of the CAS to switch cache modes at runtime and
check if all of them are working properly after switching and
... | 5,295,018 |
def test_init_creates_config_file(app_without_root: RootlessApp) -> None:
"""init must create .slipbox/config.cfg."""
app = app_without_root
commands.init(app)
assert app.root is not None
hidden = app.root/".slipbox"
assert hidden.is_dir()
assert hidden.joinpath("config.cfg").is_file() | 5,295,019 |
def line_to_tensor(line):
"""
Convert a line to a tensor (line_len x 1 x 57)
:param line: line in string format
:return: tensor in one hot vector
>>> line
>>> 'ツバサ'
>>> tensor
>>> (0 ,.,.) =
>>> Columns 0 to 18
>>> 1 0 0 0 ..
>>> (1 ,.,.) =
>>> Columns 0 to 18
... | 5,295,020 |
def load_output(variable, scenario='p16a_F_Hist_2000', season='annual', apply_sf=True):
"""
Load annual/seasonal data for a specific variable and scenario.
Args:
variable: string of variable name to load (e.g. 'SWCF_d1', or 'FSNTOA+LWCF')
scenario: string scenario (default 'p16a_F_Hist_2000... | 5,295,021 |
def bind(binding, name, mixin_modules=None):
"""Generates a client binding for the resource identified by ``name``, using the resource
definition specified by ``binding``.
:param binding: The resource bundle to bind, specified as either (a) a binding module, either
pre-generated or generated throug... | 5,295,022 |
def _validate_query_params(params, valid_params, route_type):
"""Validates query params for Smash.gg requests"""
for param in params:
if param not in valid_params:
error_msg = """
'{0}' is not a valid query param for route of type: {1}.
Valid types are [{2}].
... | 5,295,023 |
def build_dictionary(training_datasets, dict_path, params):
"""
Extract vocabulary and build dictionary.
"""
warnings.warn('Start building a new dictionary.')
word_counter = collections.Counter()
for i, dataset in enumerate(training_datasets):
dataset = dataset['data']
for exam... | 5,295,024 |
def format_status(report_status):
"""
For readability purposes, both failed and
erroneous tests will be displayed as failed.
"""
if report_status in (Status.FAILED, Status.ERROR):
return Status.FAILED.title()
return report_status.title() | 5,295,025 |
def compose_email(in_dict):
"""Composes email to send to attending if tachycardic
If the patient is exhibiting symptoms of tachycardia,
ie an increased heart rate, further action from the
physician might be necessary. As such, the physician
must be notified.
Args:
in_dict (dict): input... | 5,295,026 |
def _parse_xtekct_file(file_path):
"""Parse a X-tec-CT file into a dictionary
Only = is considered valid separators
Parameters
----------
file_path : string
The path to the file to be parsed
Returns
-------
string
A dictionary containing ... | 5,295,027 |
def log_to_file(path=None, io=False, level='INFO'):
"""
Install a new :class:`logging.Handler` writing applications logs to the
filesystem. Useful when debugging slave IO problems.
Parameters to this function may be overridden at runtime using environment
variables. See :ref:`logging-env-vars`.
... | 5,295,028 |
async def test_camera_sound_event(hass):
"""Test a pubsub message for a camera sound event."""
events = async_capture_events(hass, NEST_EVENT)
subscriber = await async_setup_devices(
hass,
"sdm.devices.types.CAMERA",
create_device_traits(["sdm.devices.traits.CameraSound"]),
)
... | 5,295,029 |
def get_on_demand_price(instance_type, region_name):
"""
Get on demand price at current instant of an instance in a
given region
:param instance_type: EC2 instance type
:param region_name: AWS regions name
:return: a floating point number - on demand price
"""
price = ON_DEMAND_PRICES.lo... | 5,295,030 |
def reportsActionMissingImagesDeactivateProduct(objectId: str):
"""
Deactivate a product with missing images and then redirect back to
the missing images report.
:param objectId: The master product object id.
"""
ok = thk.products.setProductActive(objectId=objectId, active=False)
... | 5,295,031 |
def test_HindcastEnsemble_multidim_initialized_lessdim_verif(hindcast_hist_obs_1d):
"""Test to see if HindcastEnsemble allow broadcast over dimensions in initialized but not in observations, e.g. model dim which is not available in observations."""
initialized = hindcast_hist_obs_1d.get_initialized()
obs = ... | 5,295,032 |
def store_math(raw='', html=''):
""" MathFields must be stored in the database as a string containing both
the raw math and html.
Arguments:
* raw: this is your raw math as either LaTeX or just regular text
* html: if you already know the html, there's no sense in calculat... | 5,295,033 |
def processAndWriteThumbnailQImage(qImage, options):
"""
Takes a Qimage processes it, and writes it to a file based on the supplied
options (from Manager.thumbnailSpecification), returns the path or an empty
string if the write failed.
"""
## @todo This isn't a good method as it won't work in batch (when... | 5,295,034 |
def slerp(
t: Union[float, np.ndarray],
v0: Union[float, list, tuple, np.ndarray],
v1: Union[float, list, tuple, np.ndarray],
dot_threshold: float = 0.9995) -> np.ndarray:
"""
Spherical linear interpolation between v0 (starting) and v1 (final) vectors; for optimal
results, us... | 5,295,035 |
def removeObstacle(numRows, numColumns, lot):
"""
See shortestMazePath for more info. This is similar to shortestMazePath with
slightly different conditions.
1 <= numRows, numColumns <= 1000
"""
possible_paths = {
'left': [-1, 0],
'right': [1, 0],
'up': [0, 1],
'd... | 5,295,036 |
def get_defaults(*, local: Namespace = Namespace()) -> Configuration:
"""Constructs arguments from local and system defaults."""
logger.debug(f'core -- Prepairing to build arguments.')
return harvest(local=local, **prepare({'system': DEFAULTS}, MAPPING)) | 5,295,037 |
def cmd_ok(cmd) -> bool:
"""Returns True if cmd can be run."""
try:
sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE)
except sp.CalledProcessError:
# bwa gives return code of 1 with no argument
pass
except FileNotFoundError:
logger.error(f"{cmd} not found, skipping")
... | 5,295,038 |
def states():
"""Returns different possible states a VM can have."""
return defer.maybeDeferred( _getController().states ) | 5,295,039 |
def validate_email(value):
"""
Validate an email input.
Parameters:
value (any): Input value
Returns:
boolean: True if value has email format or is empty string
"""
return isinstance(value, str) and (email_regex.match(value) or value == "") | 5,295,040 |
def counter(trans, player, spell, target=None):
"""cancels the effect of the previously played magic cone."""
hist = trans['history']
hist.append({'player': player, 'kind': spell, 'magic': {spell: -1},})
i = -2
while (hist[i+1].get('kind', None) == 'counter') and (i > -len(hist)):
hist[i]['c... | 5,295,041 |
def random_box_jitter(box, landmarks, ratio=0.05):
"""Randomly jitter bounding box.
Arguments:
box: a float tensor with shape [4].
landmarks: a float tensor with shape [num_landmarks, 2].
ratio: a float number.
The ratio of the box width and height that the corners can jitte... | 5,295,042 |
def test_PostureBuffer_filter():
"""Test PostureBuffer filtering."""
rvec = np.array([[0.1], [0.2], [0]])
tvec = np.array([[0.2], [0.1], [0]])
c = camera_fusion.CameraCorrected(0, 0)
frvec, ftvec = c.board_post.update(rvec, tvec)
frvec, ftvec = c.board_post.update(rvec * 0.1, tvec * 0.1)
frv... | 5,295,043 |
def net_revenue(gross_revenue, tax_rate=0.2):
"""Returns total net revenue based on gross revenue and tax rate.
Args:
gross_revenue (float): Gross revenue.
tax_rate (float, optional): Product tax as decimal, i.e. 0.2 for 20% tax. Default is 0.2.
Returns:
net_revenue (float): Total ... | 5,295,044 |
def convert_sklearn_one_hot_encoder(scope: Scope, operator: Operator,
container: ModelComponentContainer):
"""
Converts *OneHotEncoder* into ONNX.
It supports multiple inputs of types
string or int64.
"""
ohe_op = operator.raw_operator
if len(operator.inp... | 5,295,045 |
def main():
"""Execute WORC Tutorial experiment."""
# ---------------------------------------------------------------------------
# Input
# ---------------------------------------------------------------------------
# The minimal inputs to WORC are:
# - Images
# - Segmentations
# -... | 5,295,046 |
def _read_stimtime_AFNI(stimtime_files, n_C, n_S, scan_onoff):
""" Utility called by gen_design. It reads in one or more stimulus timing
file comforming to AFNI style, and return a list
(size of ``[number of runs \\* number of conditions]``)
of dictionary including onsets, durations and weig... | 5,295,047 |
def run_constrained_prim(experiments, y, issignificant=True,
**kwargs):
""" Run PRIM repeatedly while constraining the maximum number of dimensions
available in x
Improved usage of PRIM as described in `Kwakkel (2019) <https://onlinelibrary.wiley.com/doi/full/10.1002/ffo2.8>`_.
... | 5,295,048 |
def process_data(data_path='../input/train.csv',
output_name='train'):
"""
"""
spark = SparkSession.builder.getOrCreate()
min_word_TF = 10
min_word_DF = 2
vocabulary_size = 30000
start_time = time.time()
df = spark.read.csv(data_path,
header=True)
df = df.withColumn('new_relevance',df['relevance'].cast... | 5,295,049 |
def _write_caero3(model: Union[BDF, OP2Geom], name: str,
caero_ids: List[int], ncards: int,
op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int:
"""
Aerodynamic panel element configuration.
Word Name Type Description
1 EID I Element identificatio... | 5,295,050 |
def isok(num: int):
"""주어진 인수가 0과 1로만 이루어져 있을 경우 참 반환"""
cnv = set(int(n) for n in str(num))
return all(e in {0, 1} for e in cnv) | 5,295,051 |
def ConvertHexadecimalToDecimal (hexadecimal: str) -> int:
"""
Convert hexadecimal string to integer
:type hexadecimal: str
:rtype: int
"""
if not isinstance(hexadecimal, str):
raise Exceptions.IncorrectTypeException(hexadecimal, "hexadecimal", (str,))
return int(hexadecimal, 16) | 5,295,052 |
def from_fig_to_array(fig: plt.Figure) -> np.ndarray:
"""
:param fig: a matplotlib figure that we want to convert to an array
:return: 3D array of the figure
"""
fig.canvas.draw()
image_from_plot = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
image_from_plot = image_from_plot.re... | 5,295,053 |
def hfDistPlots(update=False):
"""
div for heat flux distribution plots
if update is False, just return an empty div, so that nothing happens on
page load. If update=True, get qDivs and update the plot.
This is called at the end of a HEAT run (runHEAT callback) button click
"""
if update=... | 5,295,054 |
def get_total_evaluation(pred: np.ndarray, mask: np.ndarray, require_edge:bool=True) -> Tuple:
"""
Get whole evaluation of all metrics
Return Tuple, (value_list, name_list)
"""
gala = get_vi(pred, mask)
if require_edge:
metric_values = [get_pixel_accuracy(pred, mask), get_mean_... | 5,295,055 |
def get_uniques(constraints):
"""Get unique key(s) given constraint list"""
uniques = {}
if constraints:
for name, constraint in constraints.items():
if constraint["type"] == UNIQUE and len(constraint['columns']) == 1:
column = constraint['columns'][0]
uni... | 5,295,056 |
def query_volumes(entry_link) -> list:
"""
Query volume list from @entry_link
"""
url = f'{BASE_URL}{entry_link}'
page = httpclient.get_page(url)
volumes = regex.multi_match(VOLUME_PATTERN, page)
return [(volume, link) for link, volume in volumes] | 5,295,057 |
def _compute_R(order, factor):
"""
computes the R matrix with entries
given by the first equation on page 8 of [1]
This is used to update the differences matrix when step size h is varied according
to factor = h_{n+1} / h_n
Note that the U matrix also defined in the same section can be also be... | 5,295,058 |
def close_code_review(name):
""" Closes a code review
Args:
name (str): Name of code review to close
"""
refhash = None
closed_ref = "/".join([CLOSED_REVIEWS, name])
open_ref = "/".join([OPEN_REVIEWS, name])
proc = Popen(["git", "show-ref", "-s", open_ref],
stderr=... | 5,295,059 |
def _complement_CS_CS(m1, m2, dtype, name):
"""CS-CS"""
return pair(one(m1.parent).new() | one(m2.parent).new()).new(dtype, name=name) | 5,295,060 |
def imeanstd_plusStats( iterable ):
"""Return the mean and stddev of an iterable, as well as
counts of values (total and the non-nan values on which
this is based),
or (nan,nan) if there are no values. If iterable yields
sequence values, then return (mean,std) for each column
of the sequence.""... | 5,295,061 |
def heapsort(values):
"""Heapsorts a list of values in nondecreasing order."""
length = len(values)
def pick_child(parent):
left = parent * 2 + 1
if left >= length:
return None
right = left + 1
if right == length or values[left] >= values[right]:
ret... | 5,295,062 |
def pd_remove_no_mol2smiles( pdr, smiles_id = 'SMILES'):
"""
Find not working smiles codes
"""
s = pdr[ smiles_id].tolist()
fail_list = get_mol2smiles( s)
pdr = jutil.pd_remove_faillist_ID( pdr, fail_list)
return pdr | 5,295,063 |
def MarkerPairSet_getClassName():
"""MarkerPairSet_getClassName() -> std::string const &"""
return _tools.MarkerPairSet_getClassName() | 5,295,064 |
def anaSi(spc, det, digits=2, display=True):
"""anaSi
Strip continuum and analyze a spectrum for Si
Parameters
----------
spc: A DTSA-II scriptable spectrum
The spectrum to process
det: The detector
Returns
-------
A dictionary of tuples for C and Si where each tuple is the
peak integral (in counts/nA-se... | 5,295,065 |
def batch_pairwise_dot(arr, batch_size=1024):
"""
Computes dot product between all pairs in arr, returned as a vector-form distance matrix as returned by scipy's
squareform (i.e. overall, very similar to pdist). Computation is performed in batches to avoid "RuntimeError: nnz
of the result is too large" ... | 5,295,066 |
def construct_include(loader: Loader, node: yaml.Node) -> Any:
"""Include file referenced at node."""
filename = os.path.abspath(
os.path.join(loader._root, loader.construct_scalar(node)))
extension = os.path.splitext(filename)[1].lstrip('.')
with open(filename, 'r', encoding='utf-8', errors='i... | 5,295,067 |
def merge_test_metadata(
gdspath: Path = CONFIG["mask_gds"], labels_prefix: str = "opt"
) -> DictConfig:
"""Returns a test metadata dict config of labeled cells
Args:
gdspath
labels_prefix
"""
gdspath = pathlib.Path(gdspath)
mask_metadata_path = gdspath.with_suffix(".yml")
... | 5,295,068 |
def clear_system_log(ip, login_account, login_password, system_id, type):
"""Clear system log
:params ip: BMC IP address
:type ip: string
:params login_account: BMC user name
:type login_account: string
:params login_password: BMC user password
:type login_password: string
:params sy... | 5,295,069 |
def test_point_cloud_conversion_dataframe():
"""
Create fake and right point cloud and test points_cloud_conversion_dataframe
"""
llh = np.load(absolute_data_path("input/rasterization_input/llh.npy"))
# points_cloud_conversion expects a list of points
llh = np.reshape(llh, (-1, 3))
utm_df =... | 5,295,070 |
def on_lscolors_change(key, oldvalue, newvalue, **kwargs):
"""if LS_COLORS updated, update file_color_tokens and corresponding color token in style"""
if newvalue is None:
del file_color_tokens[key]
else:
file_color_tokens[key] = color_token_by_name(newvalue) | 5,295,071 |
def load_caffe_graph(prototxt_path: str, caffemodel_path: str) -> BaseGraph:
"""
从一个指定位置加载 caffe 计算图,注意该加载的计算图尚未经过调度,此时所有算子被认为是可量化的
load caffe graph from the specified location
Args:
prototxt_path (str): caffe prototxt的保存位置 the specified location of caffe prototxt
caffemodel_path... | 5,295,072 |
def test_process_get_details_timeout(cbcsdk_mock):
"""Test the timeout of a get_details request."""
cbcsdk_mock.mock_request("POST", "/api/investigate/v2/orgs/test/processes/detail_jobs",
POST_PROCESS_DETAILS_JOB_RESP)
cbcsdk_mock.mock_request("GET",
... | 5,295,073 |
def to_timezone(tz):
"""Parse the timezone.
Strings are parsed by `pytz` and `dateparser`, while integers and floats are treated as hour offsets.
If the timezone object can't be checked for equality based on its properties,
it's automatically converted to `datetime.timezone`."""
if isinstance(tz, ... | 5,295,074 |
def add_func(serde_scope: SerdeScope, func_name: str, func_code: str, globals: Dict) -> None:
"""
Generate a function and add it to a SerdeScope's `funcs` dictionary.
* `serde_scope`: the SerdeScope instance to modify
* `func_name`: the name of the function
* `func_code`: the source code of the fun... | 5,295,075 |
def get_array_info(subs, dictofsubs):
"""
Returns information needed to create and access members of the numpy array
based upon the string names given to them in the model file.
Parameters
----------
subs : Array of strings of subscripts
These should be all of the subscript names that a... | 5,295,076 |
def get_mean_stderr_annots_in_nested_dict(nested_dict,
as_string=True,
dict_level: int = 2) -> dict:
"""
Returns means and standard errors of the values inside a nested dictionary.
Parameters
----------
nested_dict... | 5,295,077 |
def test_list_hex_binary_pattern_nistxml_sv_iv_list_hex_binary_pattern_1_2(mode, save_output, output_format):
"""
Type list/hexBinary is restricted by facet pattern with value
[0-9A-F]{22} [0-9A-F]{70} [0-9A-F]{66} [0-9A-F]{2} [0-9A-F]{30}
[0-9A-F]{38}.
"""
assert_bindings(
schema="nistD... | 5,295,078 |
def iter_tasks(num_workers, num_ps) -> typing.Iterable[str]:
"""Iterate the tasks in a TensorFlow cluster.
Note that ``"evaluator"`` is not part of the cluster.
"""
yield "chief:0"
yield from (f"worker:{task_id}" for task_id in range(num_workers))
yield from (f"ps:{task_id}" for task_id in rang... | 5,295,079 |
def verifierVoeuxAvecInternat(formation: GroupeAffectation):
""" P2 respect ordre appel et classement internat pour les voeux avec internat.
Si un candidat C1 précède un candidat C2
à la fois dans l'ordre d'appel d'une formation F
et dans un classement d'internat I
et si C1 a un voeu en attente pou... | 5,295,080 |
def extractHeroicNovels(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [
('id', 'ID – The Greatest Fusion Fantasy', 'translated'),
('Magician City',... | 5,295,081 |
def box_iou_xywh(box1: np.ndarray, box2: np.ndarray) -> float:
"""Calculate iou by xywh"""
assert box1.shape[-1] == 4, "Box1 shape[-1] should be 4."
assert box2.shape[-1] == 4, "Box2 shape[-1] should be 4."
b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
b1_y1, b1_y2 = box1... | 5,295,082 |
def _encode_selected_predictions_recordio_protobuf(predictions):
"""Encode predictions in recordio-protobuf format.
For each prediction, a new record is created. The content is populated under the "label" field
of a record where the keys are derived from the selected content keys. Every value is encoded
... | 5,295,083 |
def tscheme_penup():
"""Raise the pen, so that the turtle does not draw."""
_tscheme_prep()
turtle.penup() | 5,295,084 |
def async_check_significant_change(
hass: HomeAssistant,
old_state: str,
old_attrs: dict,
new_state: str,
new_attrs: dict,
**kwargs: Any,
) -> Optional[bool]:
"""Test if state significantly changed."""
if new_state != old_state:
return True
return False | 5,295,085 |
def subscribe(polygonID, varIDs=(tc.VAR_SHAPE,), begin=0, end=2**31-1):
"""subscribe(string, list(integer), double, double) -> None
Subscribe to one or more polygon values for the given interval.
"""
traci._subscribe(tc.CMD_SUBSCRIBE_POLYGON_VARIABLE, begin, end, polygonID, varIDs) | 5,295,086 |
def _format_truncated_traceback(traceback, max_num_chars=2000):
"""Truncate the traceback to the given character length."""
n = 0
for i, line in enumerate(reversed(traceback)):
n += len(_strip_ansi_codes(line)) + 2 # add 2 for newline control characters
if n > max_num_chars:
bre... | 5,295,087 |
def validate_nonempty(ctx, param, value):
"""Validate parameter is not an empty string."""
if not value.strip():
raise click.BadParameter('value cannot be empty')
return value | 5,295,088 |
def resetdb():
"""Recreates database tables (same as issuing 'dropdb' and then 'syncdb')
"""
dropdb()
syncdb() | 5,295,089 |
def get_genres_from_soup(soup):
"""Get the genres of a book.
Parameters
----------
soup : BeautifulSoup
BeautifulSoup object created from a book page.
Returns
-------
list
Book genres.
"""
genres_elements = soup.find_all('a', {'href': re.compile('/genres/')}, class_... | 5,295,090 |
def escape_str(input) :
"""Just makes it so the string won't be evaluated oddly in eval_str."""
return re.sub(r"\[|\]|\$|{|}", _escape_str, input) | 5,295,091 |
def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
args = parse_args(args)
setup_logging(args.loglevel)
_logger.debug("Starting trender")
config = get_configuration()
default = config['default']
tweets_file = defaul... | 5,295,092 |
def truncate(string, length, extra=0, add_whitespace=True):
"""
Add whitespace to strings shorter than the length, truncate strings
longer than the length, replace the last few characters with ellipsis
"""
# Strip whitespace
base = string.strip()
difference = length-(len(base))
if diffe... | 5,295,093 |
def cleanup_job(context, session):
"""Send all new sticker to the newsfeed chats."""
threshold = datetime.now() - timedelta(hours=3)
full_cleanup(session, threshold)
return | 5,295,094 |
def edit_get(u_id):
"""Render an edit form for the logged in user.
Login required.
Argument:
u_id (int): the id of the desired user.
"""
return render_template('edit_user.html') | 5,295,095 |
def dfs_loop(graph: Mapping[str, Iterable[str]], nodes: Iterable[str], tracker: Tracker):
"""Depth First Search Loop"""
for node in nodes:
if node not in tracker.explored:
tracker.current_source = node
dfs(graph, node, tracker) | 5,295,096 |
def ModelCheckpoint(filepath='model.{epoch:02d}-{val_loss:.2f}.pt', save_model_params_only=False,
monitor='val_loss', save_best_only=False, mode='auto', period=1, min_delta=0):
"""Save the model after every epoch. `filepath` can contain named formatting options, which will be filled any
values from stat... | 5,295,097 |
def is_walrus(s3_url):
""" Return True if it's Walrus endpoint, not S3
We assume anything other than *.amazonaws.com is Walrus"""
if s3_url is not None:
o = urlparse(s3_url)
return not o.netloc.endswith('amazonaws.com')
else:
return False | 5,295,098 |
def word_search(tree, string=''):
"""
Exercise 2: Implement a word search using either DFS or BFS.
Why did you choose one algorithm or the other?
"""
if tree is None:
return []
string += tree.value
results = []
if is_word(string):
results.append(string)
results += ... | 5,295,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.