content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_objects(bucket, **kwargs):
"""
Lists objects for a bucket in AWS S3,
with the same syntax as client.list_objects_v2,
only handling pagination. See here for full details:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.list_objects_v2
Paramet... | 5,298,000 |
def on(
event: str,
type: EventTypes = EventTypes.COMMAND,
func: typing.Callable = None,
):
"""A proxy decorator for registering commands. This decorator will add a number of attributes within the object.
You can use this decorator to register commands with ``.register_command`` function on the main... | 5,298,001 |
def code_project_exponentiation():
"""
7 Code project
Exponentiation
Exponentiation is the raising of one number to the power of another.
This operation is performed using two asterisks **.
Let's use exponentiation to solve a known problem.
You are offered a choice of either $1.000.000 or $0.01 (one penny) double... | 5,298,002 |
def validate_readme(session):
"""Ensures the linter version in 'requirements.txt' matches 'readme.md'."""
requirements_file = pathlib.Path(__file__).parent / "requirements.txt"
readme_file = pathlib.Path(__file__).parent / "README.md"
lines = requirements_file.read_text(encoding="utf-8").splitlines(kee... | 5,298,003 |
def get_current_time()->int:
"""
Returns current timestamp in milliseconds
"""
return int(datetime.datetime.now().timestamp() * 1000) | 5,298,004 |
def tokenize(sentence):
"""
Using the bag words algorithm, every sentence has to be deconstructed to a
list of relevant particles. This function ecibes a sequence and uses the
nltk.word_tokenize() functtion to return a tokenized list.
>>>tokenize('How are you?')
['how', 'are', 'you', '?']
"""
return nltk.word_... | 5,298,005 |
def write_MOM6_supergrid_file(mom6_grid):
"""Save the MOM6 supergrid data into its own file."""
nx = mom6_grid['supergrid']['nx']
ny = mom6_grid['supergrid']['ny']
string_len = len(mom6_grid['netcdf_info']['tile_str'])
with netCDF4.Dataset(mom6_grid['filenames']['supergrid'], 'w', format='N... | 5,298,006 |
def d_key_pressed(environment, ambient=0.001):
""" Takes user input for theta and updates display. Function called
after 'd' pressed during interactive mode.
"""
environment.clearSources()
environment.updateAmbient(ambient)
dir_mag = 1.0
dir_phi = 5 * np.pi / 4
while True:
... | 5,298,007 |
def format_duration(dur: float) -> str:
"""Formats duration (from minutes) into a readable format"""
if float(dur) >= 1.0:
return "{} min".format(int(dur))
else:
return "{} sec".format(int(round(dur * 60))) | 5,298,008 |
def get_displacement_spectra_coeffs(tr_disp, tr_noise_disp=None, plot_switch=False, return_spectra_data=False, manual_fixed_fc_Hz=None, apply_Brune_fit_bounds=False, manual_fixed_t_star=None):
"""Function to get long-period spectral level, for calculating moment. Also finds the corner frequency and
travel-time... | 5,298,009 |
def unpack(structure, data):
"""
Unpack little endian hexlified binary string into a list.
"""
return struct.unpack('<' + structure, bytes.fromhex(data)) | 5,298,010 |
def generate_setup(field_height, cleared_rows, shape, shape_x, shape_y):
"""Generate field (in list form) to find setups for a shape at x,y that clears cleared_rows.
Todo: this whole thing needs some error handling, especially the drop-in part
"""
# initialize with all margin cells
field = [[3]... | 5,298,011 |
def detect():
"""
perform detecton.
"""
# ホスト信号のロード
sr, host_signal = wavfile.read(HOST_SIGNAL_FILE)
# 埋め込み済みの音声ファイルを開く
_, eval_signal = wavfile.read(WATERMARK_SIGNAL_FILE)
eval_signal = eval_signal.astype(np.float64)
signal_len = len(eval_signal)
# フレームの移動量
frame_shift = ... | 5,298,012 |
def parse_episodes(
podcast: Podcast, items: list[rss_parser.Item], batch_size: int = 500
) -> None:
"""Remove any episodes no longer in feed, update any current and
add new"""
qs = Episode.objects.filter(podcast=podcast)
# remove any episodes that may have been deleted on the podcast
qs.exclu... | 5,298,013 |
def identify_missing(df=None):
"""Detect missing values.
Identify the common missing characters such as 'n/a', 'na', '--'
and '?' as missing. User can also customize the characters to be
identified as missing.
Parameters
----------
df : DataFrame
Raw data formatted in Data... | 5,298,014 |
def mergeSplitAssets(path: str, allDirectories=False):
"""
合并拆分资产
"""
if allDirectories:
splitFiles = [fp for fp in listAllFiles(path) if fp[-7:] == ".split0"]
else:
splitFiles = [os.path.join(path, fp) for fp in os.listdir(path) if fp[-7:] == ".split0"]
for splitFile in ... | 5,298,015 |
def get_recall(indices, targets):
""" Calculates the recall score for the given predictions and targets
Args:
indices (Bxk): torch.LongTensor. top-k indices predicted by the model.
targets (B): torch.LongTensor. actual target indices.
Returns:
recall (float): the recall score
"... | 5,298,016 |
def fixture_encode_wav_s24():
"""fixture_encode_wav_s24"""
wav_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"test_audio",
"ZASFX_ADSR_no_sustain.wav",
)
audio = tf.audio.decode_wav(tf.io.read_file(wav_path))
value = audio.audio * (1 << 31)
value = tf.c... | 5,298,017 |
def test_matrix_load(tmpdir):
"""
Test loading multiple reports
:return:
"""
textmatrix = matrix.TextReportMatrix()
textmatrix.add_report(get_filepath("junit-simple_suite.xml"))
textmatrix.add_report(get_filepath("junit-simple_suites.xml"))
textmatrix.add_report(get_filepath("junit-unico... | 5,298,018 |
def get_collection_no(row):
"""Get the collection number from an expedition row."""
if row.get('collector_number'):
return row.collector_number
num = row.get('collector_number_numeric_only', '')
verb = row.get('collector_number_verbatim', '')
if verb and len(num) < 2:
return row.coll... | 5,298,019 |
def add_header(filename, header):
"""Add header to a single file."""
with open(header, 'r') as f_in:
header_str = f_in.read()
with open(filename, 'r+') as f_out:
file_contents = f_out.read()
if file_contents.startswith(header_str):
print(f" Skipping {filename} which al... | 5,298,020 |
def log_ux_action(action_type, experiment=None, data={}):
"""Save a new UX action in the database.
:arg string action_type: The type of action that was performed.
:arg string experiment: The name of the experiment as part of which the action has been made.
:arg json data: Additional action-specific dat... | 5,298,021 |
def main():
"""
Set an attribute on a given file
"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('filepath',
help='Path of the file of which you want to print tags'
)
parser.add_argument('name',
... | 5,298,022 |
def main(directory: str, distinct: bool):
"""Find all packages and print to console."""
packages = package_collection(distinct)
for path in search_dir(directory):
if path.as_posix().rpartition('.')[-1] == 'py':
with open(path.as_posix(), 'r') as f:
file_content = "".join(... | 5,298,023 |
def _mi_dr(X, Y, sigma, n_bases, maxiter):
"""Estimate mutual information between X and Y using density ratio estimation.
Parameters
----------
X : array-like, shape (n_samples, n_features_x) or (n_samples)
Observations of a variable.
Y : array-like, shape (n_samples, n_features_y) or (n_sa... | 5,298,024 |
def save_git_info(git_info, new_version):
"""
Save git info(changes) to change log file
:param git_info: is mapping name packages to changes(list of commits)
:type git_info: ABC MutableMapping
:param new_version: new version from which will be created tag
:type new_version: str
"""
mode... | 5,298,025 |
def subject():
"""Contains commands for retrieving information about subjects."""
pass | 5,298,026 |
def _flag_check_srr(block):
"""Checks whether or not the given block has flags set that are not
supported by this application."""
if block.flags & ~block.SUPPORTED_FLAG_MASK: # Bitwise Inversion
_fire(MsgCode.UNSUPPORTED_FLAG, message="Warning: Unsupported "
"flag value encountered in SRR file. This file... | 5,298,027 |
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
Input
- cm : 计算出的混淆矩阵的值
- classes : 混淆矩阵中每一行每一列对应的列
- normalize : True:显示百分... | 5,298,028 |
def normalizeRows(x):
""" Row normalization function
Implement a function that normalizes each row of a matrix to have
unit length.
"""
### YOUR CODE HERE
x_sum = np.sum(x)
x = x / x_sum
### END YOUR CODE
return x | 5,298,029 |
def setup():
"""Global initialization."""
pass | 5,298,030 |
def retrieve_cluster_info(cluster_type, cluster_name):
"""
获取指定集群的信息
:param cluster_type: 集群类型
:param cluster_name: 集群名
:return: 集群信息
"""
url = "{}/storekit/clusters/{}/{}/".format(DATAHUB_API_ROOT, cluster_type, cluster_name)
res = requests.get(url=url)
if res.status_code == HTTP_S... | 5,298,031 |
def _run_horovod(trainer_options, on_gpu=False):
"""Execute the training script across multiple workers in parallel."""
num_processes = trainer_options.get('gpus', 2)
# gpus trainer argument does not apply for horovod
trainer_options.update(gpus=None)
tutils.reset_seed()
cmdline = [
'hor... | 5,298,032 |
def merge_titles(existing_work: Work, inserting_work: Work) -> Union[str, None]:
"""
Merge two titles into the best possible option
:return: string if best is changed from existing else None
"""
if existing_work.title == inserting_work.title:
best_title = None
elif not existing_w... | 5,298,033 |
def HzanalCirc(sig, f, I, a, flag):
"""
Hz component of analytic solution for half-space (Circular-loop source)
Src and Rx are on the surface and receiver is located at the center of the loop.
.. math::
H_z = -\\frac{I}{k^2a^3} \
\\left( 3 -(3+\\imath\\ k... | 5,298,034 |
def _get_versioned_config(config, version = ""):
"""select version from config
Args:
config: config
version: specified version, default is "".
Returns:
updated config with specified version
"""
versioned_config = {}
versioned_config.update(config)
used_version = co... | 5,298,035 |
async def test_switch_release(serial_mock, bus):
"""Check that switches can be released"""
switch = bus.switch(1, 2)
_, packet = await gather(switch.release(), serial_mock.read())
assert packet == Packet(1, 2, True)
assert switch.released | 5,298,036 |
def fitDtm(initWorkingSetName,
stepName,
requestInfo,
jobId,
outputFolder,
dsmFile,
outputPrefix,
iterations=None,
tension=None):
"""
Run a Girder Worker job to fit a Digital Terrain Model (DTM) to a
Digital Surface Mode... | 5,298,037 |
def deserialize_timestamp_from_kraken(time: Union[str, FVal, int, float]) -> Timestamp:
"""Deserializes a timestamp from a kraken api query result entry
Kraken has timestamps in floating point strings. Example: '1561161486.3056'.
If the dictionary has passed through rlk_jsonloads the entry can also be an F... | 5,298,038 |
def anti_alias_filter(x,params):
"""
Anti_aliasing: use Nyquist frequ cutoff low-pass filter
:return: anti-aliased signal
"""
fs = params['fs']
assert(type(x)==np.ndarray)
# def build_aa_filter(fs):
# """
# :param fs: sampling rate
# :return: 1D array ... | 5,298,039 |
def test_currency_precision_2():
"""test_currency_precision_2."""
test_currency = (Currency(0.1) + Currency(0.1) + Currency(0.1))
assert test_currency == Currency(0.3)
assert test_currency.amount == CONTEXT.create_decimal('0.3')
assert test_currency.__str__() == '0.30' | 5,298,040 |
def build_config(config_file, args):
"""Build a ``Configuration`` instance and populate it with file data and
user inputs."""
config = Configuration()
if os.path.exists(config_file):
config.load_from_file(config_file)
config.load_from_arguments(args)
return config | 5,298,041 |
def get_optimizer(optimizer_name: str, *args, **kwargs) -> torch.optim.Optimizer:
"""
A simple utility function for retrieving the desired optimizer.
Not the most optimized algorithm, but the number of optimizers should never
exceed even 100 in my opinion so a linear time algorithm is acceptable.
Ar... | 5,298,042 |
def rand_unselected_dut(request, duthosts, rand_one_dut_hostname):
"""
Return the left duthost after random selection.
Return None for non dualtor testbed
"""
dut_hostnames = generate_params_dut_hostname(request)
if len(dut_hostnames) <= 1:
return None
idx = dut_hostnames.index(rand_... | 5,298,043 |
def test_ft_sflow_docker_restart():
"""
Author Details:
Name: Sreenivasula Reddy Vennapusa
Email: sreenivasula.reddy@broadcom.com
Objective - FtOpSfFn015 : Verify that sFlow functionality after sflow docker restart
Test bed details:
TG1(192.168.1.1)---(192.168.1.2)Partner(192.168.2.1/24)---... | 5,298,044 |
def query_author_by_org(Session, orgs):
"""Return a query that, if run, would return all RFCs whose authors'
organizations match every string in `orgs`.
The matching on `orgs` is case-insensitive. Asterisks (*) in passed orgs
are replaced with percent signs (%) to function as wildcards in the actual
... | 5,298,045 |
def _prompt_for_option_name (ARG_config_object: configparser.ConfigParser, ARG_section: str) -> Union[str, None]:
"""Prompts the user to enter a valid option name. Checks that option name exists.
Parameters
----------
ARG_config_object : configparser.ConfigParser
The settings, which have been r... | 5,298,046 |
def test_user1_biosamples_access(user1_token):
""""
Make sure user1 has access to open1, open2, registered3 and controlled 4
"""
response = helper_get_katsu_response(user1_token, f"{KATSU_URL}/api/biosamples")
assert response.status_code == 200
response_json = response.json()
assert response... | 5,298,047 |
def read_leader(f: Union[str, BinaryIO]) -> Tuple[Vocab, Vectors]:
"""Read vectors from a leader file.
This is our fully binary vector format.
The first line is a header for the leader format and it is a 3-tuple.
The elements of this tuple are: A magic number, the size of the vocabulary,
and the s... | 5,298,048 |
def find_direct_conflicts(pull_ops, unversioned_ops):
"""
Detect conflicts where there's both unversioned and pulled
operations, update or delete ones, referering to the same tracked
object. This procedure relies on the uniqueness of the primary
keys through time.
"""
return [
(pull_... | 5,298,049 |
def unknown_id_to_symbol(unknown_id, header="X"):
"""Get the symbol of unknown whose id is |unknown_id|.
:type unknown_id: int
:type header: str
:param unknown_id: The ID of the unknown.
:param header: The symbol header.
:rtype : str
:return: A string that contains the symbol.
"""
... | 5,298,050 |
def SurfaceEnergy(images, natoms, calc, fmax=0.01, debug=False):
"""Calculate the surface energy from a list of slab images.
Parameters
----------
images: List of slab images which the calculation is based on. The x and
y dimensions of the images unit cell must be conserved.
natoms: Number of ... | 5,298,051 |
def get_bulk_subgraphs(bulk_structure_sg):
"""
Get all subgraphs of molecules that within or crosses the boundary of
original bulk.
Parameters:
-----------
bulk_structure_sg: StructureGraph.
The structure graph of bulk with local env strategy.
Returns:
--------
super_graphs... | 5,298,052 |
def main(instrument=None, runfile=None, **kwargs):
"""
Main function for apero_explorer.py
:param instrument: str, the instrument name
:param runfile: str, the run file to run (see the /run/ folder)
:param kwargs: additional keyword arguments
:type instrument: str
:type runfile: str
:... | 5,298,053 |
def _get_git_revision_hash():
""" ref: https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script """
return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip() | 5,298,054 |
def markdown_to_doxygen(string):
"""Markdown to Doxygen equations"""
long_equations = re.sub(
r"(?<!\\)\$\$(.*?)(?<!\\)\$\$", r"\\f[\g<1>\\f]", string, flags=re.DOTALL
)
inline_equations = re.sub(r"(?<!(\\|\$))\$(?!\$)", r"\\f$", long_equations)
return inline_equations | 5,298,055 |
def dijkstra(graph, src, dest):
"""Find shortest path from src to dest
graph:
dict[list[(int, int)]]: {node: [adj_node1, adj_node2,...]}
src (int):
dest (int):
"""
to_process = PriorityQueue()
# Start with the source and zero cost
to_process.put((0, src))
# Now as y... | 5,298,056 |
def convert_3_class(data_dir, out_dir='three_class/'):
"""
Transform attribute labels in the dataset in data_dir to create a separate prediction class for not visible attributes
"""
def filter_not_visible(d):
certainty = np.array(d['attribute_certainty'])
not_visible_idx = np.where(cert... | 5,298,057 |
def get_jobs_to_register(name):
"""Get cron job handlers defined in `notifications` package.
Get cron job handlers defined in `notifications` package as `name`. Note
that handlers will be returned only if `NOTIFICATIONS_ENABLED` flag in
settings is set to `True` value.
Args:
name (str): A name of job ha... | 5,298,058 |
def is_network_exists(vca_client, network_name):
"""
network already exist
"""
return bool(vca_client.get_network(get_vcloud_config()['vdc'],
network_name)) | 5,298,059 |
def xml_dict_to_point(data: dict) -> Point:
"""
Create a Point from a dict representing a location in KML
Args:
data: xml dict data
Returns:
Point
"""
point = Point()
point.description = data['description']
point.name = data['name']
point.style = data['styleUrl']
... | 5,298,060 |
def randprime(a, b):
"""Return a random prime number in the range [a, b)"""
n = random.randint(a-1, b)
p = nextprime(n)
if p >= b:
p = prevprime(b)
if p < a:
raise ValueError("no primes exist in the specified range")
return p | 5,298,061 |
def pep8ify(name):
"""PEP8ify name"""
import re
if '.' in name:
name = name[name.rfind('.') + 1:]
if name[0].isdigit():
name = "level_" + name
name = name.replace(".", "_")
if '_' in name:
return name.lower()
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return ... | 5,298,062 |
def add_iwdump_to_l(d, links, ifces, w):
"""
"""
for i in w.values():
for m in i.keys():
n = find_node_by_address(d, 'ether', m)
if n and 'id' in n:
for l in links:
if 'id' in l and l['id'] == n['id'] and l['viaDev'] in ifces \
... | 5,298,063 |
def grip_availability(day: date, area: int = 803) -> Optional[List[Dict[str, str]]]:
"""Get the availability for date"""
response = requests.get(
GRIP_URL,
params={
"date": day.isoformat(),
"areas": [area],
"show_all": 0,
},
)
try:
data... | 5,298,064 |
def recover_instance_ha(self, image, flavor, computes,
volume_args=None,
floating_network=None,
use_floating_ip=True,
force_delete=False,
stop_instance=False,
disruptor_cmd=Non... | 5,298,065 |
def write_file(file_name):
"""
Create a file and returns the reference of it
:param file_name: The relative path of the file to be created
:return: The reference of the created file
"""
file_name = os.path.join(dir_name, file_name)
file = open(file_name, "w+")
return file | 5,298,066 |
def main():
"""CLI interface."""
string = input()
print(compress(string)) | 5,298,067 |
def update_block_state():
"""
Loops through all immature and non-orphaned blocks.
First checks to see if blocks are orphaned,
then it checks to see if they are now matured.
"""
# Select all immature & non-orphaned blocks
immature = Block.query.filter_by(mature=False, orphan=False)
for bl... | 5,298,068 |
def read_expected_result(test_name):
"""
:param test_name:
:return:
"""
data_file_path = path.join(
get_test_data_prefix(test_name),
"Result.xlsx"
)
return pd.read_excel(
data_file_path
) | 5,298,069 |
def read_tri_file_rows(fobj, n=None, dtype='f8', upper=False, keep=None,
progress=False):
"""
Iterate over partial rows of a matrix stored in a file in flattened
triangular format.
Given a file containing distance matrix data in the non-redundant form
created by :func:`.write_tri_file`, yie... | 5,298,070 |
def reduce_slice(obj, sliceobj):
"""generic factory for Slice nodes"""
assert isinstance(sliceobj, SlicelistObject)
if sliceobj.fake_rulename == 'slice':
start = sliceobj.value[0]
end = sliceobj.value[1]
return ast.Slice(obj, consts.OP_APPLY, start, end, sliceobj.lineno)
else:
... | 5,298,071 |
def skip_while(self, predicate):
"""Bypasses elements in an observable sequence as long as a specified
condition is true and then returns the remaining elements. The
element's index is used in the logic of the predicate function.
1 - source.skip_while(lambda value: value < 10)
2 - source.skip_while... | 5,298,072 |
def files_inout_handler(ctx, param, value):
"""Process and validate input file names"""
return tuple(file_in_handler(ctx, param, item) for item in value[:-1]) + tuple(value[-1:]) | 5,298,073 |
def car_to_apply(conf):
"""
查询申请车辆的信息
:param conf: 配置
:return: 车辆信息
"""
carlist = get_enter_car_list(conf)
licenseno = conf['User']['licenseno']
for car in carlist:
if car.get('licenseno') == licenseno:
return car
raise FatalError('车牌号:{}在系统中未找到,请在APP中注册。carlist={... | 5,298,074 |
def plugin_reconfigure(handle, new_config):
""" Reconfigures the plugin
it should be called when the configuration of the plugin is changed during the operation of the South device service;
The new configuration category should be passed.
Args:
handle: handle returned by the plugin initialisat... | 5,298,075 |
def get_code_objects_in_code_partition(from_opened_file, code_partition_desc: CodePartitionDescriptor,
debug_prints=False):
"""
:param from_opened_file: an opened file handle; e.g. from open(filename,...). It does not have to be cue'd to any
par... | 5,298,076 |
def get_timeline():
"""
This function returns the timeline, i.e. time axis data.
Returns:
[List] -- time axis data.
"""
# init timeline
timeline = []
# Import one file @ DATASET_PATH (the "anchor_file")
files = os.listdir(DATASET_PATH)
time_anchor_file_name = files[0]
... | 5,298,077 |
def calc_min(arr, idx, win_size):
"""Recalculate the window min based on data, index and window size."""
start = max(0, idx - win_size + 1)
nfinite = 0
result = numpy.nan
for i in range(start, idx + 1):
value = arr[i]
nfinite, result = put_min(value, nfinite, result)
return nfin... | 5,298,078 |
def rotation_3d_matrix(theta: float, axis: np.ndarray) -> np.ndarray:
"""Creates a rotation matrix: Slow method.
Inputs are rotation angle theta and rotation axis axis.
The rotation matrix correspond to a rotation of angle theta
with respect to axis axis."""
axis = axis / np.sqrt(np.dot(axis, axis)... | 5,298,079 |
def get_pipeline(xml_node: XmlNode) -> RenderingPipeline:
"""Resolves pipeline by namespace and name or by namespace"""
key = f'{xml_node.namespace}.{xml_node.name}'
try:
return resolve(RenderingPipeline, key)
except DependencyError:
try:
return resolve(RenderingPipeline, xml... | 5,298,080 |
def send_message_title(title, message):
"""Create a subprocess to call the notify-send command with a title and a message"""
subprocess.Popen(['notify-send', '-t', '5000', title, message])
return | 5,298,081 |
def plotTempature(xi, yi, zi, save_dir='.'):
"""
功能:
绘制温度等值线
输入:
xi: 插值格点后的经向numpy array
yi: 插值格点后的纬向numpy array
zi: 经过matplotlib.mlab.griddata插值后的二维numpy array
输出:
save_dir/tempfile.png
"""
fig = plt.figure(frameon=False)
... | 5,298,082 |
def configure(app):
"""Configure Markdown for Bert-E's Flask server."""
md = Markdown(app)
md.register_extension(CodeHiliteExtension)
md.register_extension(FencedCodeExtension)
md.register_extension(SmartEmphasisExtension)
md.register_extension(SmartyExtension)
md.register_extension(TableExt... | 5,298,083 |
def make_file_struct(ROOT,CLASS1, CLASS2):
"""
Fuction that makes the desired file structure
@param: ROOT - name of root directory as a String
CLASS1 - name of first label as a String
ClASS2 - name of second label as a String
@output: void - New file structure (relateive to proje... | 5,298,084 |
def genomics_core_testdata(filename):
"""Gets the path to a testdata named filename in util/testdata.
Args:
filename: The name of a testdata file in the core genomics testdata
directory. For example, if you have a test file in
"third_party/nucleus/util/testdata/foo.txt", filename should be
"f... | 5,298,085 |
def check_version():
"""
Log error and exit when the installed version of paddlepaddle is
not satisfied.
"""
err = "PaddlePaddle version 1.6.1 or higher is required, " \
"or a suitable develop version is satisfied as well. \n" \
"Please make sure the version is good with your cod... | 5,298,086 |
def get_authorization(client):
"""
Define authorization arguments for rsync command
:param client: String
:return: String
"""
_ssh_key = None
if not client:
return ''
if 'ssh_key' in system.config[client]:
_ssh_key = system.config[mode.Client.ORIGIN]['ssh_key']
_ssh... | 5,298,087 |
def set_logging():
"""
Method for setting the logging levels
Parameters
----------
Returns
--------
"""
logging.basicConfig(level=args.log.upper(), format='%(asctime)s -> [%(levelname)s] %(message)s')
logging.Formatter('%(asctime)s -> [%(levelname)s] %(message)s')
logger = logging.getLogger()
... | 5,298,088 |
def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-s... | 5,298,089 |
def frames(response: Response) -> Iterator[bytes]:
"""Returns each frame from multiplexed payload, all results are expected in the payload.
The stdout and stderr frames are undifferentiated as they are returned.
"""
length = len(response.content)
index = 0
while length - index > 8:
head... | 5,298,090 |
def handle_new_pebble():
"""
When pebble starts:
* we must inspect the new pebble roots
When pebble restarts
* the database may have old pebble data
"""
process_pebble_roots()
archive_pebble_data() | 5,298,091 |
def select_topk(args, logits, force_no_eos_id=None):
"""
Applies topk sampling decoding.
"""
if force_no_eos_id is not None:
logits[:, force_no_eos_id] = float('-inf')
indices_to_remove = logits < \
torch.topk(logits, args.top_k, axis=-1)[0][
..., -1, None]
... | 5,298,092 |
def exportStlAscii(obj, filename, exportJoints = False):
"""
This function exports MakeHuman mesh and skeleton data to stereolithography ascii format.
Parameters
----------
obj:
*Object3D*. The object whose information is to be used for the export.
filename:
... | 5,298,093 |
def from_file(input, output_path=None, options=None):
"""
Convert HTML file or files to PDF document
:param input: path to HTML file or list with paths or file-like object
:param output_path: (optional) path to output PDF file. If not provided, PDF will be returned as string
:param options: (option... | 5,298,094 |
def get_date(fmt='%Y%m%d', delta_day=0):
""" 获取日期字符串,包含 年 + 月 + 日
@param fmt 返回的日期格式
"""
day = datetime.datetime.today()
if delta_day:
day += datetime.timedelta(days=delta_day)
str_d = day.strftime(fmt)
return str_d | 5,298,095 |
def detect_real_traffic_light(image_path):
"""
run traffic light detection using traffic light detection model trained testing real image on the given image
"""
checkpoint_path = './inference_graph/tf_1.7.0/ssd_mobilenet_v2_tl_real_3_classes.pb'
labels_path = './labelmaps/annotated_label_map_3.pbtxt... | 5,298,096 |
def init(input_mgr, user_data, logger):
"""Initialize the example source tool."""
# Get the selected value from the GUI and save it for later use in the user_data
user_data.val = float(input_mgr.workflow_config["Value"])
# Display info on the selected value
logger.display_info_msg(f"The value selec... | 5,298,097 |
async def log(*args, **kwargs):
"""
Logging data in sqlite
:param args:
:param kwargs:
request - request to the route
result - dict with answer to the client
time - processing time
code - http response code
:return:
"""
request = kwargs.get("request", None)
if request is ... | 5,298,098 |
def test_cli_args():
"""Test the CLI arguments."""
runner = CliRunner()
result = runner.invoke(
cli.main,
"-o tests/out.csv -t 2 -e mp4,avi".split(" ")
)
print(result.output)
assert "1/2 faulty videos detected 🚨" in result.output
assert "OVER ✅" in str(result.output)
as... | 5,298,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.