content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _findCentralBond(mol, distmat):
""" Helper function to identify the atoms of the most central bond.
Arguments:
- mol: the molecule of interest
- distmat: distance matrix of the molecule
Return: atom indices of the two most central atoms (in order)
"""
from numpy import std
# ge... | 5,326,000 |
def check_python_version(program: str) -> None:
"""Report issues with the Python used to run mypy, dmypy, or stubgen"""
# Check for known bad Python versions.
if sys.version_info[:2] < (3, 5):
sys.exit("Running {name} with Python 3.4 or lower is not supported; "
"please upgrade to 3... | 5,326,001 |
def transform(data, transformer):
"""This hook defines how DataRobot will use the trained object from fit() to transform new data.
DataRobot runs this hook when the task is used for scoring inside a blueprint.
As an output, this hook is expected to return the transformed data.
The input parameters are p... | 5,326,002 |
def fill_diagonal(a, val, wrap=False):
"""Fills the main diagonal of the given array of any dimensionality.
For an array `a` with ``a.ndim > 2``, the diagonal is the list of
locations with indices ``a[i, i, ..., i]`` all identical. This function
modifies the input array in-place, it does not return a v... | 5,326,003 |
async def sign_params(params, certificate_file, private_key_file):
"""
Signs params adding client_secret key, containing signature based on `scope`, `timestamp`, `client_id` and `state`
keys values.
:param dict params: requests parameters
:param str certificate_file: path to certificate file
:pa... | 5,326,004 |
def sum_of_fourth_powers(matrix):
"""
:param matrix: (numpy.ndarray) A numpy array.
:return: The fourth power of the four-norm of the matrix. In other words,
the sum of the fourth power of all of its entries.
"""
squared_entries = matrix * matrix
return np.sum(squared_entries * squared_e... | 5,326,005 |
def record_agreement_to_terms(user_id):
"""Records that the user has agreed to the license terms."""
user_settings = get_user_settings(user_id, strict=True)
user_settings.last_agreed_to_terms = datetime.datetime.utcnow()
_save_user_settings(user_settings) | 5,326,006 |
def key_in_direction(start: Key, direction: str, keypad: Keypad) -> Key:
"""
Return the value of the key in the given direction.
"""
row = next(r for r in keypad if start in r)
x_pos = row.index(start)
col = [c[x_pos] for c in keypad]
y_pos = col.index(start)
directions: Dict[str, Key] ... | 5,326,007 |
def plot_trajectory(
df,
plot_heading=False,
position="head",
invert_y_axis=True,
title="Trajectory",
):
"""
:param df: Raw (or cropped) dataframe of body positions over time
:param bool plot_heading: Plot direction of animal at each point
:param str position: Plot position of 'head... | 5,326,008 |
def vectorize_args(nums):
"""
Decorator for vectorization of arguments of a function.
The positions of the arguments are given in the tuple nums.
See numpy.vectorize.
"""
def wrap(func):
@wraps(func)
def wrapped(*args, ** kwargs):
args = list(args)
for i,... | 5,326,009 |
def parse_lambda_config(x):
"""
Parse the configuration of lambda coefficient (for scheduling).
x = "3" # lambda will be a constant equal to x
x = "0:1,1000:0" # lambda will start from 1 and linearly decrease
# to 0 during the first 1000 iterations
... | 5,326,010 |
def format_cols(colname, direction='in'):
"""Formats columns beween human-readable and pandorable
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
...
if direction == 'in':
... | 5,326,011 |
def convert_decimal_to_binary(number):
"""
Parameters
----------
number: int
Returns
-------
out: str
>>> convert_decimal_to_binary(10)
'1010'
"""
return bin(number)[2:] | 5,326,012 |
def fetch_tgz(
dataname: str,
urlname: str,
subfolder: Optional[str] = None,
data_home: Optional[str] = None,
) -> pathlib.Path:
"""Fetch tgz dataset.
Fetch a tgz file from a given url, unzips and stores it in a given
directory.
Parameters
----------
dataname: string
... | 5,326,013 |
def evaluate_coco_PRC(model, dataset, coco, eval_type="bbox", limit=0, image_ids=None):
"""Runs official COCO evaluation.
dataset: A Dataset object with valiadtion data
eval_type: "bbox" or "segm" for bounding box or segmentation evaluation
limit: if not 0, it's the number of images to use for evalu... | 5,326,014 |
def choisir_action():
"""Choisir action de cryptage ou de décryptage
Entree : -
Sortie: True pour cryptage, False pour décryptage"""
action_est_crypter = True
action = input("Quelle est l'action, crypter ou décrypter ? \n<Entrée> pour crypter, autre touche pour decrypter, ou <Crtl> + Z ou X pour arréter.\n")
... | 5,326,015 |
def σ(u, p, μ):
"""Stress tensor of isotropic Newtonian fluid.
σ = 2 μ (symm ∇)(u) - p I
This method returns a UFL expression the whole stress tensor. If you want
to plot, extract and interpolate or project what you need. For example,
to plot the von Mises stress::
from dolfin import ... | 5,326,016 |
async def cycle(command: Command, switches: PowerSwitch, name: str, portnum: int):
"""cycle power to an Outlet"""
command.info(text=f"Cycle port {name}...")
for switch in switches:
current_status = await switch.statusAsJson(name, portnum)
if current_status:
break
# print(... | 5,326,017 |
def createDummyRoot():
""" Creates dummy root in labelDict for a hierarchy that is not rooted, i.e. one with multiple top level nodes. """
global labelDict
root = {'parents':[], 'children':[]}
for label in labelDict:
if len(labelDict[label]['parents']) == 0:
root['children'].append(l... | 5,326,018 |
def zk_delete_working_node(zk_client, server):
"""删除服务节点"""
node_path, root_path = get_path_to_current_working_node(server)
zk_client.ensure_path(root_path)
result = zk_client.delete(node_path, ephemeral=True)
return result | 5,326,019 |
def test_dimension_estimation():
"""
Test the dimension selection procedures
"""
from numpy.random import randn
k = 2
x = 10*np.dot(np.dot(randn(100,k),np.eye(k)),randn(k,10))
x += randn(100,10)
ek = infer_latent_dim(x)
print k, ek
assert(k==ek) | 5,326,020 |
async def give_wc_roles(member: discord.Member, score: int):
"""
Updates the WC roles of a member based on their latest total score
"""
got_role: bool = False
for min_score, role_id in common.ServerConstants.WC_ROLES:
if score >= min_score and not got_role:
# This is the role to ... | 5,326,021 |
def hesitations_difference(hesitations, signal_len, hesitations_mean, path):
"""Plot hesitations count comparison"""
hesitations = hesitations.shape[0] / signal_len * 60
fig, ax = gauge(['Nízký', 'Normální', 'Vysoký'], ['C0', 'C2', 'C1'], value=hesitations,
min_val=hesitations_mean[0] -... | 5,326,022 |
def construct_filters_from_2d(matrix, filter_starts, decomp_level):
"""
construct the filters in the proper shape for the DWT inverse forward step
Parameters
----------
matrix
filter_starts
decomp_level
Returns
-------
"""
exp = filter_starts[0]
low = matrix[: exp ** 2... | 5,326,023 |
def minpoly(firstterms):
"""
Return the minimal polynomial having at most degree n of of the
linearly recurrent sequence whose first 2n terms are given.
"""
field = ring.getRing(firstterms[0])
r_0 = uniutil.polynomial({len(firstterms):field.one}, field)
r_1 = uniutil.polynomial(enumerate(rev... | 5,326,024 |
def scale_gradient(tensor, scale):
"""Scales the gradient for the backward pass."""
return tf.add(tensor * scale ,tf.stop_gradient(tensor) * (1 - scale)) | 5,326,025 |
def get_cluster_assignments(args, model, dataset, groups):
"""
"""
# pseudo-labels are confusing
dataset.sub_classes = None
# swith to eval mode
model.eval()
# this process deals only with a subset of the dataset
local_nmb_data = len(dataset) // args.world_size
indices = torch.aran... | 5,326,026 |
def foo(a, d=1):
"""
:param a:
:param d:
"""
pass | 5,326,027 |
def t_rename_local_variables(the_ast, all_sites=False):
"""
Local variables get replaced by holes.
"""
changed = False
candidates = []
for node in ast.walk(the_ast):
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
if node.id not in [ c.id for c in candidate... | 5,326,028 |
def get_scale(notes: List[str]) -> int:
"""Convert a list of notes to a scale constant.
# Args
- *notes*: list of notes in the scale. This should be a list of string
where each string is a note ABC notation. Sharps should be
represented with a pound sign preceding the note e.g. '#A' and fl... | 5,326,029 |
def cam_keyboard(message):
"""Start cam selection keyboard"""
keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=True, row_width=1)
keys = [types.KeyboardButton(k.upper()) for k in CAMS]
keyboard.add(*keys)
msg = bot.reply_to(message, 'Escolha uma câmera:', reply_markup=keyboard) | 5,326,030 |
def slurm_format_bytes_ceil(n):
""" Format bytes as text.
SLURM expects KiB, MiB or Gib, but names it KB, MB, GB. SLURM does not handle Bytes, only starts at KB.
>>> slurm_format_bytes_ceil(1)
'1K'
>>> slurm_format_bytes_ceil(1234)
'2K'
>>> slurm_format_bytes_ceil(12345678)
'13M'
>... | 5,326,031 |
def factory_payment_account(corp_number: str = 'CP0001234', corp_type_code: str = 'CP',
payment_system_code: str = 'PAYBC'):
"""Factory."""
return PaymentAccount(
corp_number=corp_number,
corp_type_code=corp_type_code,
payment_system_code=payment_system_code,
... | 5,326,032 |
def p_l_species_input_geos(wd, ver='1.7', rm_multiple_tagged_rxs=False, debug=False):
"""
Extract prod/loss species (input.geos) and reaction tags (globchem.dat)
Parameters
----------
wd (str): Specify the wd to get the results from a run.
debug (boolean): legacy debug option, replaced by pytho... | 5,326,033 |
def foo():
"""多参数函数的传参书写格式, 和类实例化的格式"""
ret = foo_long(a=1, b=2, c=3, d=4,
e=5, f=6, g=7, h=8)
# 类实例化,传多个参数的格式
object_ = ClassName(
a=1, b=2, c=3, d=4,
e=5, f=6, g=7, h=8
)
return ret | 5,326,034 |
def posture_seq(directory,postures,sampling_fraction):
"""posture_seq grabs samples locomotion files from a directory and
converts them to strings of posture_sequences
Input:
directory = the directory containing locomotion files
postures = the mat file or numpy array of template postur... | 5,326,035 |
def membrane_diag(voxel_size=1, bound='dct2', dim=None, weights=None):
"""Diagonal of the membrane regulariser.
If no weight map is provided, the diagonal of the membrane regulariser
is a scaled identity with scale `2 * alpha`, where
`alpha = vx.reciprocal().square().sum()`
However, is a weight map... | 5,326,036 |
def openpty(mode=None, winsz=None, name=False):
"""openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible."""
master_fd, slave_fd = os.openpty()
if mode:
tty.tcsetattr(slave_fd, tty.TCSAFLUSH, mode)
if tty.HAVE_WINSZ and winsz:
tty.tcsetwins... | 5,326,037 |
def get_groups(parsed, store, conf):
"""
Return groups based on argument provided
:param Namespace parsed: arguments parsed
:param store: Otter scaling group collection
:param dict conf: config
:return: Deferred fired with list of {"tenantId": .., "groupId": ..} dict
"""
log = mock_log... | 5,326,038 |
def get_content_details(site_code, release_uuid, content_type, content_key):
""" get_content_details """
publisher_api = PublisherAPI()
content_release = None
try:
if release_uuid:
# get ContentRelease
content_release = WSSPContentRelease.objects.get(
si... | 5,326,039 |
def find_pgdb(root):
"""Find all the personal geodatabases below root"""
for folder, _, file_names in os.walk(root):
for file_name in file_names:
if is_access_file(file_name):
path = os.path.join(folder, file_name)
print(path)
if is_pgdb(file_n... | 5,326,040 |
def _czt(x, M=None, W=None, A=1.0):
"""Calculate CZT (Stripped down to the basics)."""
# Unpack arguments
N = len(x)
if M is None:
M = N
if W is None:
W = np.exp(-2j * np.pi / M)
A = np.complex128(A)
W = np.complex128(W)
# CZT algorithm
k = np.arange(max(M, N))
... | 5,326,041 |
def measure_link_vsize(output_file, args):
"""
Execute |args|, and measure the maximum virtual memory usage of the process,
printing it to stdout when finished.
"""
proc = subprocess.Popen(args)
t = threading.Thread(target=measure_vsize_threadfunc,
args=(proc, output_fil... | 5,326,042 |
def build_obs_act_forward_fc(
n_out: int,
depth: int,
hidden: int,
act_layer: Any,
last_layer: Optional[Any] = None,
) -> hk.Transformed:
"""Build a simple fully-connected forward step that takes an observation & an action.
Args:
n_out (int): Number of outputs.
depth (int): ... | 5,326,043 |
def backup_files(srcs, dests):
"""
Write each given file to a pool of destination directories. If the
filename being written to the destination already exists there it is
renamed with a timestamp before any file-writes take place.
Args:
srcs: List of src files
dests: List of destina... | 5,326,044 |
def update_nested(key, d, other):
"""Update *d[key]* with the *other* dictionary preserving data.
If *d* doesn't contain the *key*, it is updated with *{key: other}*.
If *d* contains the *key*, *d[key]* is inserted into *other[key]*
(so that it is not overriden).
If *other* contains *key* (and poss... | 5,326,045 |
def quicksort(arr, low, high):
""" Quicksort function uses the partition helper function.
"""
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low, pi-1)
quicksort(arr, pi+1, high)
return arr | 5,326,046 |
def make_word_dict():
"""read 'words.txt ' and create word list from it
"""
word_dict = dict()
fin = open('words.txt')
for line in fin:
word = line.strip()
word_dict[word] = ''
return word_dict | 5,326,047 |
def voidobject(key_position: int, offset: int) -> HitObject:
"""
引数から判定のないヒットオブジェクト(シングルノーツのみ)のHitObjectクラスを生成します
引数
----
key_position : int
-> キーポジション、1から入れる場合はkey_assetから参照したものを入れてください
offset : int
-> (配置する)オフセット値
戻り値
------
HitObject
-> 空ノーツのHitObjectクラス
"""
return HitObject(key_position, max_off... | 5,326,048 |
def visualize_gts(
run_dir,
dataset,
inference_config,
show_bbox=True,
show_scores=False,
show_class=True,
):
"""Visualizes gts."""
# Create subdirectory for gt visualizations
vis_dir = os.path.join(run_dir, "gt_vis")
utils.mkdir_if_missing(vis_dir)
# Feed images one by one
... | 5,326,049 |
def mock_user_save():
"""Функция-пустышка для эмуляции исключения во время записи пользователя."""
def user_save(*args, **kwargs):
raise IntegrityError
return user_save | 5,326,050 |
def system(command, ignore_status=False):
"""Run a command. """
out = system_output(command, ignore_status)
if out:
logging.debug(out) | 5,326,051 |
def index():
"""首页"""
banners = Banner.query_used()
page = request.args.get("page", 1, type=int) # 指定的页码
per_page = current_app.config["MYZONE_ARTICLE_PER_PAGE"] # 每页的文章数
pagination = Article.query_order_by_createtime(page, per_page=per_page) # 创建分页器对象
articles = pagination.items # 从分页器中获取查询... | 5,326,052 |
async def test_legacy_config_entry_diagnostics(
hass, hass_client, config_entry, setup_base_platform
):
"""Test config entry diagnostics for legacy integration doesn't fail."""
with patch("homeassistant.components.nest.legacy.Nest"):
await setup_base_platform()
assert await get_diagnostics_for... | 5,326,053 |
def create_temporal_vis(ldf, col):
"""
Creates and populates Vis objects for different timescales in the provided temporal column.
Parameters
----------
ldf : lux.core.frame
LuxDataFrame with underspecified intent.
col : str
Name of temporal column.
Returns
----... | 5,326,054 |
def load(inputs):
"""load(inputs) -> data
Loads the contents of a file, an iterable of files, or an iterable of
:py:class:`bob.io.base.File`'s into a :py:class:`numpy.ndarray`.
**Parameters:**
``inputs`` : various types
This might represent several different entities:
1. The name of a file (full ... | 5,326,055 |
def num_neighbours(skel) -> np.ndarray:
"""Computes the number of neighbours of each skeleton pixel.
Parameters
----------
skel : (H, W) array_like
Input skeleton image.
Returns
-------
(H, W) array_like
Array containing the numbers of neighbours at each skeleton pixel and ... | 5,326,056 |
def test_e():
"""
put and rename
:return:
"""
c2 = LRUCache(10000)
c2.cache_object("X", 50, 10)
for x in [100, 200, 300, 400, 500, 600, 700]:
c2.cache_object('a_%r' % x, x, x)
assert(c2.check_sanity())
# now get, remove and reput x
c2.get_cached("X", 800)
assert(... | 5,326,057 |
def FakeSubject(n=300, conc=0.1, num_reads=400, prevalences=None):
"""Makes a fake Subject.
If prevalences is provided, n and conc are ignored.
n: number of species
conc: concentration parameter
num_reads: number of reads
prevalences: numpy array of prevalences (overrides n and conc)
"... | 5,326,058 |
async def add(gc: GroupControl, slaves):
"""Add speakers to group."""
click.echo("Adding to existing group: %s" % slaves)
click.echo(await gc.add(slaves)) | 5,326,059 |
def build_results_candidate_people():
"""
Return DataFrame containing results, candidates, and people joined
"""
people = pd.read_csv('data/people.csv')
candidates = pd.read_csv('data/candidates.csv')
results = pd.read_csv('data/results.csv')
results_candidates = pd.merge(
results ... | 5,326,060 |
def div(lhs: Value, rhs: Value) -> Value:
""" Divides `lhs` by `rhs`. """
return lhs.run() // rhs.run() | 5,326,061 |
def test_max(n, result):
"""Test max for some value of n."""
from src.max_min import max_cw
assert max_cw(n) == result | 5,326,062 |
def get_seat_total_per_area(party_id: PartyID) -> dict[AreaID, int]:
"""Return the number of seats per area for that party."""
area_ids_and_seat_counts = db.session \
.query(
DbArea.id,
db.func.count(DbSeat.id)
) \
.filter_by(party_id=party_id) \
.outerjoi... | 5,326,063 |
def toCamelCase(string: str):
"""
Converts a string to camel case
Parameters
----------
string: str
The string to convert
"""
string = str(string)
if string.isupper():
return string
split = string.split("_") # split by underscore
final_split = []
for... | 5,326,064 |
def sync_command(args: argparse.Namespace):
"""
Copy all files for `submission-id` from `deployment` to `dst-deployment`.
"""
src = Staging[args.deployment].ssds
dst = Staging[args.dst_deployment].ssds
for _ in ssds.sync(args.submission_id, src, dst):
pass | 5,326,065 |
def reject():
"""
Respond with red.
"""
api.respond(color = _colors.fail) | 5,326,066 |
def aggregate_testsuite(testsuite):
""" Compute aggregate results for a single test suite (ElemTree node)
:param testsuite: ElemTree XML node for a testsuite
:return: AggregateResult
"""
if testsuite is None:
return None
tests = int(testsuite.attrib.get('tests') or 0)
failures = int... | 5,326,067 |
def _print_message(message, file=None):
"""
"""
if message:
if file is None:
file = sys.stdout
file.write(message) | 5,326,068 |
def test_corner_case():
"""tricky corner case where some variable may have a
name attribute
"""
class Person:
name = "hello"
p = Person()
with pytest.raises(TypeError):
manifest = Manifest(p) | 5,326,069 |
def rowwidth(view, row):
"""Returns the number of characters of ``row`` in ``view``.
"""
return view.rowcol(view.line(view.text_point(row, 0)).end())[1] | 5,326,070 |
def patch_broken_pipe_error():
"""
Monkey patch BaseServer.handle_error to not write a stack trace to stderr
on broken pipe: <http://stackoverflow.com/a/22618740/362702>
"""
import sys
try:
from SocketServer import BaseServer
except:
from socketserver import BaseServer
fr... | 5,326,071 |
def dry_query(event, *args):
"""Handles running a dry query
Args:
url: dry_query?page&page_length&review_id
body:
search: search dict <wrapper/input_format.py>
Returns:
{
<wrapper/output_format.py>
}
"""
# try:
body = json.loads(event["bo... | 5,326,072 |
def fixed_prior_to_measurements(coords, priors):
"""
Convert the fixed exchange and met conc priors to measurements.
"""
fixed_exchange = get_name_ordered_overlap(coords, "reaction_ind", ["exchange", "fixed_x_names"])
fixed_met_conc = get_name_ordered_overlap(coords, "metabolite_ind", ["metabolite",... | 5,326,073 |
def get_batch_size():
"""Returns the batch size tensor."""
return get_global_variable(GraphKeys.BATCH_SIZE) | 5,326,074 |
def get_dataloader(config: ExperimentConfig, tfms: Tuple[List, List] = None):
""" get the dataloaders for training/validation """
if config.dim > 1:
# get data augmentation if not defined
train_tfms, valid_tfms = get_data_augmentation(config) if tfms is None else tfms
# check number of ... | 5,326,075 |
def retournerTas(x,numéro):
"""
retournerTas(x,numéro) retourne la partie du tas x qui commence à
l'indice numéro
"""
tasDuBas = x[:numéro]
tasDuHaut = x[numéro:]
tasDuHaut.reverse()
result = tasDuBas + tasDuHaut
# print(result)
return result | 5,326,076 |
def AddReplaceCustomAdvertisementArgs(parser, resource_str):
"""Adds common arguments for replacing custom advertisements."""
parser.add_argument(
'--advertisement-mode',
choices=_MODE_CHOICES,
type=lambda mode: mode.upper(),
metavar='MODE',
help="""The new advertisement mode for this... | 5,326,077 |
def path_complete(self, text, line, begidx, endidx):
"""
Path completition function used in various places for tab completion
when using cmd
"""
arg = line.split()[1:]
# this is a workaround to get default extension into the completion function
# may (hopefully) gets replaced.
try:
... | 5,326,078 |
def test_config_attributes_with_cli_args(config_with_cli_args):
"""Asserts that the class attributes of a config.Config object are of the expected value/type after
object initialization, taking into account command line arguments, which take precedence over
config arguments.
"""
# check that we get ... | 5,326,079 |
def test():
"""Terraform: Up & Running - Why Terraform - Web Server"""
import terrascript
import terrascript.provider
import terrascript.resource
USER_DATA = "#!/bin/bash\nsudo service apache2 start"
config = terrascript.Terrascript()
config += terrascript.provider.aws(region="us-east-2",... | 5,326,080 |
def test_find_maxima():
"""
Not yet a test, Just a cool demo (FYI the maximum of the function is 10, so the printed value should be around -10)
:return:
"""
er = ExperimentRunner([blueprint.MaximaKnowledgeDiscovery], log=True)
er.run() | 5,326,081 |
def nback(n, k, length):
"""Random n-back targets given n, number of digits k and sequence length"""
Xi = random_state.randint(k, size=length)
yi = np.zeros(length, dtype=int)
for t in range(n, length):
yi[t] = (Xi[t - n] == Xi[t])
return Xi, yi | 5,326,082 |
def makeStateVector(sys, start_time=0):
"""
Constructs the initial state vector recursively.
Parameters
----------
sys: inherits from control.InputOutputSystem
start_time: float
Returns
-------
list
"""
x_lst = []
if "InterconnectedSystem" in str(type(sys)):
for... | 5,326,083 |
def test_create_OK(mock_category, mock_send, mock_exists):
"""Create and update object."""
vf = Vf()
vsp = Vsp()
vendor = Vendor()
vsp._identifier = "1232"
vf.vsp = vsp
vsp.vendor = vendor
vsp._csar_uuid = "1234"
expected_data = '{\n "artifacts": {},\n "attributes": [],\n "c... | 5,326,084 |
def make_random_tensors(spec_structure, batch_size = 2):
"""Create random inputs for tensor_spec (for unit testing).
Args:
spec_structure: A dict, (named)tuple, list or a hierarchy thereof filled by
TensorSpecs(subclasses).
batch_size: If None, we will have a flexible shape (None,) + shape. If <= 0
... | 5,326,085 |
def simulate(robot, task, opt_seed, thread_count, episode_count=1):
"""Run trajectory optimization for the robot on the given task, and return the
resulting input sequence and result."""
robot_init_pos, has_self_collision = presimulate(robot)
if has_self_collision:
return None, None ... | 5,326,086 |
def config_worker():
"""
Enable worker functionality for AIO system.
:return: True if worker-config-complete is executed
"""
if utils.get_system_type() == si_const.TIS_AIO_BUILD:
console_log("Applying worker manifests for {}. "
"Node will reboot on completion."
... | 5,326,087 |
def generate_coverage_page(results, page_name):
"""Generate the code coverage HTML page with measured content."""
template = Template(filename="template/{template}".format(template=page_name))
generated_page = template.render(**results.__dict__)
with open(page_name, "w") as fout:
fout.write(gene... | 5,326,088 |
def test_gen_loremipsum_1():
"""Create a complete lorem ipsum string."""
result = gen_iplum()
assert result == LOREM_IPSUM_TEXT
assert result.startswith('Lorem ipsum') | 5,326,089 |
def convert_dict_to_df(dict_data: dict):
"""
This method is used to convert dictionary data to pandas data frame
:param dict_data:
:return:
"""
# create df using dict
dict_data_df = pd.DataFrame.from_dict([dict_data])
# return the converted df
return dict_data_df | 5,326,090 |
def sec2msec(sec):
"""Convert `sec` to milliseconds."""
return int(sec * 1000) | 5,326,091 |
async def _request(session:aiohttp.ClientSession, url:str, headers:dict[str,str]) -> str:
"""
获取单一url的愿望单页面
"""
async with session.get(url=url, headers=headers, proxy=PROXY) as resp:
try:
text = await resp.text()
except Exception as err:
text = ""
logg... | 5,326,092 |
def get_pretrained_i2v(name, model_dir=MODEL_DIR):
"""
Parameters
----------
name
model_dir
Returns
-------
i2v model: I2V
"""
if name not in MODELS:
raise KeyError(
"Unknown model name %s, use one of the provided models: %s" % (name, ", ".join(MODELS.keys(... | 5,326,093 |
def object_get_HostChilds(obj):
"""Return List of Objects that have set Host(s) to this object."""
# source:
# FreeCAD/src/Mod/Arch/ArchComponent.py
# https://github.com/FreeCAD/FreeCAD/blob/master/src/Mod/Arch/ArchComponent.py#L1109
# def getHosts(self,obj)
hosts = []
for link in obj.InLis... | 5,326,094 |
def authorize_access(cache_id, token_id):
"""
Given a cache ID and token ID, authorize that the token has permission to access the cache.
Raises:
- caching_service.exceptions.UnauthorizedAccess if it is unauthorized.
- exceptions.MissingCache if the cache ID does not exist.
"""
meta... | 5,326,095 |
def remove_entrance_exam_milestone_reference(request, course_key):
"""
Remove content reference for entrance exam.
"""
course_children = modulestore().get_items(
course_key,
qualifiers={'category': 'chapter'}
)
for course_child in course_children:
if course_child.is_entra... | 5,326,096 |
def add_xray_lines(outfil, infil=None, stop=True):
""" Pre-pend X-ray lines (as necessary)
Parameters
----------
outfil : str
Output file.
infil : str, optional
Starting file. Should use latest llist_vX.X.ascii
"""
if infil is None:
fils = glob.glob(lt_path+'/lists/sets... | 5,326,097 |
def collate_fn(batch):
"""
Collate function for combining Hdf5Dataset returns
:param batch: list
List of items in a batch
:return: tuple
Tuple of items to return
"""
# batch is a list of items
numEntries = [];
allTensors = [];
allLabels = [];
for item in batch:... | 5,326,098 |
def baseNgenerator(base=10, keylength=5, step=1):
"""Generate keys of base <base> and length <keylength>"""
assert int(base) <= BASE
assert int(keylength) > 0
while 1:
yield to_base(random.randrange(base**(keylength-1), base**keylength), base) | 5,326,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.