content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_rr_Lix(N, Fmat, psd, x):
"""
Given a rank-reduced decomposition of the Cholesky factor L, calculate
L^{-1}x where x is some vector. This way, we don't have to built L, which
saves memory and computational time.
@param N: Vector with the elements of the diagonal matrix N
@param Fma... | 44,800 |
def ParameterSet_Create(*args):
"""
Create() -> ParameterSet
ParameterSet_Create(std::string const & publicID) -> ParameterSet
"""
return _DataModel.ParameterSet_Create(*args) | 44,801 |
def resend_pending_email(session, userobj, email):
"""Resend to the user the confirmation email for the provided email
address.
"""
other_user = search_user(session, email=email)
if other_user and other_user != userobj:
raise pagure.exceptions.PagureException(
"Someone else has a... | 44,802 |
def set_processors_count(processors: int) -> None:
"""
Set the (maximal) number of processors to use in parallel.
The default value of ``0`` means using all the available physical processors. Note that if
hyper-threading is enabled, this would be less than (typically half of) the number of logical
... | 44,803 |
def generate_html_from_cli_args(cli_dict_for_command):
"""
Turn the dict into an html representation of the cli args and options.
:param cli_dict_for_command:
:return str:
"""
# def arg_md(opt, long_opt, default, help):
# return f"*) {opt}, {long_opt}, {help}\n"
text = ""
# ev... | 44,804 |
def conical_sigma_Mach_walldeflection(Mach, deflection, gamma=defg._gamma):
"""computes shock angle sigma from upstream Mach number and wall deflection
Args:
Mach: param deflection:
gamma: Default value = defg._gamma)
deflection:
Returns:
"""
def local_def(sig):
"""inte... | 44,805 |
def gtrr(a, b, c, register):
"""
(greater-than register/register) sets register C to 1 if register A is greater than register B. Otherwise, register C is set to 0.
"""
register[c] = 1 if register[a] > register[b] else 0 | 44,806 |
def get_hashrate_info(results, miner, algo):
"""
Get Hashrate Information for a particular Miner and Algo
Returns:
dict
"""
# do the lookup
hashrate_info = results.get_hashrate_info(miner, algo)
if hashrate_info is None:
logger.warning("Model/Algo combination does not ex... | 44,807 |
def verify_verification_code(doctype, document_name, verification_code):
"""This method verfies the user verification code by fetching the originally sent code by the system from cache.
Args:
doctype (str): Name of the DocType.
document_name (str): Name of the document of the DocType.
v... | 44,808 |
def version() -> None:
"""Display current version tags for Poetry, Git and Docker"""
click.echo(f"Poetry: {get_version()}")
click.echo(f"Git: {get_latest_git_tag()}")
click.echo(f"Docker: {get_latest_docker_tag()}") | 44,809 |
def orient1(ppos, apos, bpos):
"""
ORIENT1 return orientation of PP wrt. the line [PA, PB].
"""
#---------------------------------------------- calc. det(S)
smat = np.empty(
(2, 2, ppos.shape[0]), dtype=ppos.dtype)
smat[0, 0, :] = \
apos[:, 0] - ppos[:, 0]
smat[0, 1, :] = \
... | 44,810 |
def get_storm_data(storm_path):
""" Obtain raster grid of the storm with rasterio
Arguments:
*storm_path* (string) -- path to location of storm
"""
with rio.open(storm_path) as src:
# Read as numpy array
array = src.read(1)
array = np.array(array,dtype='flo... | 44,811 |
def test_certonly_webroot(context: IntegrationTestsContext) -> None:
"""Test the certonly verb with webroot plugin"""
with misc.create_http_server(context.http_01_port) as webroot:
certname = context.get_domain('webroot')
context.certbot(['certonly', '-a', 'webroot', '--webroot-path', webroot, '... | 44,812 |
def setLogLevel(level: Union[str, int]):
"""Changes the volume of messages printed in the console (stdout)
:param level:
* TRACE: Print all messages.
* DEBUG: Print debug messages and above.
* INFO: Print info messages and above.
* WARN: Print warnings and errors.
* ERR:... | 44,813 |
def wrap_with_spectral_norm(module_class,
sn_kwargs=None,
pow_iter_collection=None):
"""Returns a constructor for the inner class with spectral normalization.
This function accepts a Sonnet AbstractModule class as argument (the class,
*not* an instance of t... | 44,814 |
def ask_daemon_sync(view, ask_type, ask_kwargs, location=None):
"""Jedi sync request shortcut.
:type view: sublime.View
:type ask_type: str
:type ask_kwargs: dict or None
:type location: type of (int, int) or None
"""
daemon = _get_daemon(view)
return daemon.request(
ask_type,
... | 44,815 |
def _etl_epacems(etl_params, datapkg_dir, pudl_settings, ds_kwargs):
"""Extract, transform and load CSVs for EPA CEMS.
Args:
etl_params (dict): ETL parameters required by this data source.
datapkg_dir (path-like): The location of the directory for this
package, wihch will contain a ... | 44,816 |
def test_read_file_gmi():
"""
Read GMI match file and ensure that all latitudes roughly match
CONUS coordinates.
"""
path = DATA_PATH / "gmi" / "mrms" / TEST_FILE_GMI
ms = MRMSMatchFile(path)
assert np.all(ms.data["latitude"] > 20.0)
assert np.all(ms.data["latitude"] < 70.0)
assert ... | 44,817 |
def test_job_repeat_route(cl_operator, job):
"""repeat route test"""
form = cl_operator.get(url_for('scheduler.job_repeat_route', job_id=job.id)).form
response = form.submit()
assert response.status_code == HTTPStatus.FOUND
assert len(json.loads(job.assignment)['targets']) == Target.query.count() | 44,818 |
def GetNvccOptions(argv):
"""Collect the -nvcc_options values from argv.
Args:
argv: A list of strings, possibly the argv passed to main().
Returns:
1. The string that can be passed directly to nvcc.
2. The leftover options.
"""
parser = ArgumentParser()
parser.add_argument('-nvcc_options', n... | 44,819 |
def show_node(request, name='', path='', revision=''):
"""
View for show_node page, which provides context for show_node.html
Shows description for yang modules.
:param request: Array with arguments from webpage data submition.
:param module: Takes first argument from url if request does not
con... | 44,820 |
def compute_F1(TP, TN, FP, FN):
"""
Return the F1 score
"""
numer = 2 * TP
denom = 2 * TP + FN + FP
F1 = numer/denom
Acc = 100. * (TP + TN) / (TP + TN + FP + FN)
return F1, Acc | 44,821 |
def name_full_data():
"""Full name data."""
return {
"name": "Doe, John",
"given_name": "John",
"family_name": "Doe",
"identifiers": [
{
"identifier": "0000-0001-8135-3489",
"scheme": "orcid"
}, {
"identifier... | 44,822 |
def platypus(in_file, data):
"""Filter Platypus calls, removing Q20 filter and replacing with depth and quality based filter.
Platypus uses its own VCF nomenclature: TC == DP, FR == AF
Platypus gVCF output appears to have an 0/1 index problem so the reference block
regions are 1 base outside regions o... | 44,823 |
def delete(i):
"""
Input: { See 'rm' function }
Output: { See 'rm' function }
"""
return rm(i) | 44,824 |
def _get_remote_image_id(s3_object) -> str:
"""
Get the image id of the docker cache which is represented by the S3 object
:param s3_object: S3 object
:return: Image id as string or None if object does not exist
"""
try:
if S3_METADATA_IMAGE_ID_KEY in s3_object.metadata:
cach... | 44,825 |
def steps_factory(step, args, paths):
"""
Function for executing specific step of the script.
"""
start = time()
LOGGER.info(f"Executing step '{step}'")
if step == "prepare":
step_prepare(
path_interactions=paths.interactions,
path_train=paths.train,
... | 44,826 |
def test_circuit_str(default_compilation_configuration):
"""Test function for `__str__` method of `Circuit`"""
def f(x):
return x + 42
x = hnp.EncryptedScalar(hnp.UnsignedInteger(3))
inputset = range(2 ** 3)
circuit = hnp.compile_numpy_function(f, {"x": x}, inputset, default_compilation_c... | 44,827 |
def mixed_generator(n):
"""
mixed_generator yields 3 values, then if next is called again throws StopIteration exception
https://stackoverflow.com/questions/1756096/understanding-generators-in-python#1756156
:param n:
:return: yielded value
"""
# yield on first call to next
yield n
#... | 44,828 |
def add_game():
"""Adds game to database"""
check_admin()
add_game = True
form = GameForm()
# Checks if form is valid
if form.validate_on_submit():
game = Game(name=form.name.data)
try:
db.session.add(game)
db.session.commit()
fl... | 44,829 |
def requires_moderation(page):
"""Returns True if page requires moderation
"""
return bool(page.get_moderator_queryset().count()) | 44,830 |
def _get_node_info(
node: NodeObject,
current_path: str,
node_type: str,
label: Optional[str] = None,
is_leaf: bool = True
) -> NodeInfo:
"""
Utility method for generating a NodeInfo from a NodeObject
:param node: NodeObject to convert into a NodeInfo.
... | 44,831 |
def do_begin(conn):
"""Emit our own BEGIN."""
conn.execute("BEGIN") | 44,832 |
def import_image(image_path, os_version):
"""Import image.
Input parameters:
:image_path: Image file path
:os_version: Operating system version. e.g. rhel7.2
"""
image_name = os.path.basename(image_path)
print("Checking if image %s exists or not, import it if not exists" %
... | 44,833 |
def get_peers():
"""Retrieve PeerIds and SSIDs for peers that are ready for OOB transfer"""
query = 'SELECT Ssid, PeerId from EphemeralState WHERE PeerState=1'
data = exec_query(query, db_path_peer)
return data | 44,834 |
def get_html_text(html):
"""
Return the raw text of an ad
"""
if html:
doc = BeautifulSoup(html, "html.parser")
return doc.get_text(" ")
return "" | 44,835 |
def test_default_scopes():
"""Test default_scopes."""
client = ClientFactory(default_scopes='readWrite readOnly')
assert client.default_scopes == ['readWrite', 'readOnly']
client.default_scopes = ['read', 'write']
assert client.default_scopes == ['read', 'write'] | 44,836 |
def valid_parentheses(string):
"""
Takes a string of parentheses, and determines if the order of the parentheses is valid.
:param string: a string of parentheses and characters.
:return: true if the string is valid, and false if it's invalid.
"""
stack = []
for x in string:
if x == "... | 44,837 |
def find_microbit():
"""
Returns a path on the filesystem that represents the plugged in BBC
micro:bit that is to be flashed. If no micro:bit is found, it returns
None.
Works on Linux, OSX and Windows. Will raise a NotImplementedError
exception if run on any other operating system.
"""
... | 44,838 |
def in_2core_graph_slow(cats: ArrayLike) -> BoolArray:
"""
Parameters
----------
cats: {DataFrame, ndarray}
Array containing the category codes of pandas categoricals
(nobs, ncats)
Returns
-------
retain : ndarray
Boolean array that marks non-singleton entries as Tru... | 44,839 |
def has_form_encoded_header(header_lines):
"""Return if list includes form encoded header"""
for line in header_lines:
if ":" in line:
(header, value) = line.split(":", 1)
if header.lower() == "content-type" \
and "x-www-form-urlencoded" in value:
... | 44,840 |
def get_best_checkpoint_path(path: Path) -> Path:
"""
Given a path and checkpoint, formats a path based on the checkpoint file name format.
:param path to checkpoint folder
"""
return path / LAST_CHECKPOINT_FILE_NAME_WITH_SUFFIX | 44,841 |
def storage_charge_rule(model, technology, timepoint):
"""
Storage cannot charge at a higher rate than implied by its total installed power capacity.
Charge and discharge rate limits are currently the same.
"""
return model.Charge[technology, timepoint] + model.Provide_Power[technology, timepoint] <... | 44,842 |
def test_conditional_to_hold(client, jwt, app):
"""
Setup:
- Initialize NameRequestService
- Create a new Request model instance
Test:
- Call apply_state_change on the NameRequestService instance
- Make sure to pass in the Request model instance to apply_state_change
- Make sure to pass ... | 44,843 |
def test_GET_articles_filter_by_tag(testapp: TestApp, democontent: None) -> None:
"""Test GET /api/articles, filter by author."""
res = testapp.get("/api/articles?tag=dogs", status=200)
assert res.json["articlesCount"] == 1
assert res.json["articles"][0]["slug"] == "foo" | 44,844 |
def blck_void(preprocessor: Preprocessor, args: str, contents: str) -> str:
"""The void block, processes commands inside it but prints nothing"""
if args.strip() != "":
preprocessor.send_warning("extra-arguments", "the void block takes no arguments")
preprocessor.context.update(preprocessor.current_position.end, "... | 44,845 |
def resize_image(image: np.ndarray,
width: typing.Optional[int] = None,
height: typing.Optional[int] = None,
interpolation=cv2.INTER_AREA):
"""
Resize image using given width or/and height value(s).
If both values are passed, aspect ratio is not preserved.
... | 44,846 |
def attr(*args, **kwargs):
"""Decorator that adds attributes to classes or functions
for use with unit tests runner.
"""
def wrapped(element):
for name in args:
setattr(element, name, True)
for name, value in kwargs.items():
setattr(element, name, value)
r... | 44,847 |
def convert_units(table_name, value, value_unit, targets):
"""
Converts a given value in a unit to a set of target units.
@param table_name Name of table units are contained in
@param value Value to convert
@param value_unit Unit value is currently in
@param targets List of units to convert to
... | 44,848 |
def find_vital_library_path(use_cache=True):
"""
Discover the path to a VITAL C interface library based on the directory
structure this file is in, and then to system directories in the
LD_LIBRARY_PATH.
:param use_cache: Store and use the cached path, preventing redundant
searching (default... | 44,849 |
def test_Is_Proper_Disk__Illegal_State(score, max_score):
"""Function is_proper_disk: illegal state."""
max_score.value += 1
try:
assert not Disk.is_proper_disk(4, Disk.init_disk(("ABC",), 4))
score.value += 1
except:
pass | 44,850 |
def hex2binary(hex_num):
""" converts from hexadecimal to binary """
hex1 = h[hex_num[0]]
hex2 = h[hex_num[1]]
return str(hex1) + str(hex2) | 44,851 |
def iter_sdf_records(fileobj, errors="strict", location=None):
"""Iterate over records in an SD file, returning records as blocks of text
fileobj - input stream. If fileobj.name exists then use it in error messages
errors - one of "strict" (default), "log", or "ignore". Other values are experimental
lo... | 44,852 |
def cxcywhn_after_pad(boxes, w0, h0, pad_w, pad_h):
"""cxcywhn -> cxcywhn. pad后的调整"""
w, h = w0 + pad_w * 2, h0 + pad_h * 2
boxes[:, 0] = (boxes[:, 0] * w0 + pad_w) / w # cx
boxes[:, 1] = (boxes[:, 1] * h0 + pad_h) / h # cy
boxes[:, 2] = boxes[:, 2] * w0 / w # w
boxes[:, 3] = boxes[:, 3] * h0... | 44,853 |
def swap(lst: LinkedList, i: int, j: int) -> None:
"""Swap the values stored at indexes <i> and <j> in the
given linked list.
Precondition: i and j are >= 0.
Raise an IndexError if i or j (or both) are too large
(out of bounds for this list).
NOTE: You don't need to create new nodes or change
... | 44,854 |
def p_for_simple(p):
"""
for_simple : var_cte TIMES
"""
p[0] = [p[1], p[2]]
# 1
quad_stack.for_simple(
expresion_to_symbols(p[1], global_func_table, current_state),
current_state.get_curr_state_table(),
global_func_table,
) | 44,855 |
def nn(value: int) -> int:
"""Casts value to closest non negative value"""
return 0 if value < 0 else value | 44,856 |
def resolve_vcf_counts_data(vcf_data, maf_data, matched_normal_sample_id, tumor_sample_data_col):
""" Resolves VCF allele counts data. """
vcf_alleles = [vcf_data["REF"]]
vcf_alleles.extend(vcf_data["ALT"].split(","))
tumor_sample_format_data = vcf_data["MAPPED_TUMOR_FORMAT_DATA"]
normal_sample_for... | 44,857 |
def repark(
api_id: int = typer.Argument(..., envvar="API_ID"),
api_hash: str = typer.Argument(..., envvar="API_HASH"),
):
"""
Update information about parked accounts.
"""
api = telegram.API(api_id, api_hash)
telegram.repark(db, api)
track() | 44,858 |
def example_profile_metadata_target():
"""Generates an example profile metadata document.
>>> root = example_profile_metadata_target()
>>> print_tree(root)
<?xml version='1.0' encoding='UTF-8'?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
<classAccesses>
<apexClass>ARTra... | 44,859 |
def log_config_change(setting_name, value):
"""Helper to log configuration changes.
Args:
setting_name: The setting being changed.
value: The setting's new value.
"""
logger.info("app configuration", extra={"setting": setting_name, "value": value,}) | 44,860 |
def separate(expr, deep=False):
"""Rewrite or separate a power of product to a product of powers
but without any expanding, ie. rewriting products to summations.
>>> from sympy import *
>>> x, y, z = symbols('x', 'y', 'z')
>>> separate((x*y)**2)
x**2*y**2
>>> separate((x... | 44,861 |
def get_sub_dirs(path: str):
"""Get sub-directories contained in a specified directory
Args:
path (str): path to directory
Returns:
str: lists of absolute paths
str: list of dir names
"""
try:
dirs = os.walk(path).next()[1]
except AttributeError:
try:
... | 44,862 |
def execute_queue(queueN):
"""send items in queue to be executed on different threads in parallel"""
spawn_threads(len(queueN))
pop_queue(queueN)
queue.join() | 44,863 |
def app_base(request):
"""
This should render the required HTML to start the Angular application. It is the only entry point for
the pyramid UI via Angular
:param request: A pyramid request object, default for a view
:return: A dictionary of variables to be rendered into the template
"""
de... | 44,864 |
def check_lists(document: Document, args: Args) -> List[Issue]:
"""Check that markdown lists items:
- Are preceded by a blank line.
- Are not left empty.
- End with a period if they're a list of sentences.
- End without a period if they're a list of items."""
issues = []
markdown_list_re = ... | 44,865 |
def transform_one(mt, vardp_outlier=100_000) -> Table:
"""transforms a gvcf into a form suitable for combining
The input to this should be some result of either :func:`.import_vcf` or
:func:`.import_vcfs` with `array_elements_required=False`.
There is a strong assumption that this function will be cal... | 44,866 |
def volume_rebalance(volume: str) -> Result:
"""
# This function doesn't do anything yet. It is a place holder because
# volume_rebalance is a long running command and I haven't decided how to
# poll for completion yet
# Usage: volume rebalance <VOLNAME> fix-layout start | start
# [force]|stop|... | 44,867 |
def get_droplet_ip():
"""get droplet ip from cache."""
cached_droplet_info_file = 'droplet_info.json'
with open(cached_droplet_info_file, 'r') as info_f:
droplet_info = json.load(info_f)
return droplet_info['networks']['v4'][0]['ip_address'] | 44,868 |
def position_not_change(poco, select_str, optional, dur_time, verify_count):
"""
determine the position of the element has not changed
"""
g_context.element.position_not_change(
poco, select_str, optional, dur_time, verify_count
) | 44,869 |
def country_converter(text_input, abbreviations_okay=True):
"""
Function that detects a country name in a given word.
:param text_input: Any string.
:param abbreviations_okay: means it's okay to check the list for abbreviations, like MX or GB.
:return:
"""
# Set default values
country_... | 44,870 |
def lat_long_to_idx(gt, lon, lat):
"""
Take a geotransform and calculate the array indexes for the given lat,long.
:param gt: GDAL geotransform (e.g. gdal.Open(x).GetGeoTransform()).
:type gt: GDAL Geotransform tuple.
:param lon: Longitude.
:type lon: float
:param la... | 44,871 |
def bugs_mapper(bugs, package):
"""
Update package bug tracker and support email and return package.
https://docs.npmjs.com/files/package.json#bugs
The url to your project's issue tracker and / or the email address to
which issues should be reported.
{ "url" : "https://github.com/owner/project/i... | 44,872 |
def BSMlambda(delta: float, S: float, V: float) -> float:
"""Not really a greek, but rather an expression of leverage.
Arguments
---------
delta : float
BSM delta of the option
V : float
Spot price of the option
S : float
Spot price of the underlying
Returns... | 44,873 |
def test_verbose_with_oob():
"""Check oob scoring for subsample does not cause error"""
old_stdout = sys.stdout
sys.stdout = StringIO()
est = SymbolicRegressor(max_samples=0.9, random_state=0, verbose=1)
est.fit(boston.data, boston.target)
verbose_output = sys.stdout
sys.stdout = old_stdout... | 44,874 |
def uid_to_name(uid):
"""
Find the username associated with a user ID.
:param uid: The user ID (an integer).
:returns: The username (a string) or :data:`None` if :func:`pwd.getpwuid()`
fails to locate a user for the given ID.
"""
try:
return pwd.getpwuid(uid).pw_name
e... | 44,875 |
def plot_density(read_depth_object,
mRNAobject,
fileout,
sjthread=1,
width=8.0,
height=12.0,
colors=None,
pasite=None,
wt_pasite=None,
pasite2=None,
t... | 44,876 |
def fit_poly(data, error_func, degree = 3):
""" Fit a polynomial to given data, using supplied error function.
Parameters
----------
data: 2D array where each row is a point (X0, Y)
error_func: function that computes the error between a polynomial and observed data
degree: polynomial degree
... | 44,877 |
def find_skyrmion_center_2d(fun, point_up=False):
"""
Find the centre the skyrmion, suppose only one skyrmion
and only works for 2d mesh.
`fun` accept a dolfin function.
`point_up` : the core of skyrmion, points up or points down.
"""
V = fun.function_space()
mesh = V.mesh()
c... | 44,878 |
def test(num_games, opponent, silent):
""" Test running a number of games """
def autoplayer_creator(state):
""" Create a normal autoplayer instance """
return AutoPlayer(state)
def minimax_creator(state):
""" Create a minimax autoplayer instance """
return AutoPlayer_MiniM... | 44,879 |
def pseudo_beaker(UserId: str, SessionId: str, replay=True, scope=True, browser=None, OrgId: str=None, is_staging: bool=True) -> dict:
"""
Mimic the Beaker admin tool in opening up one or both of session replay and
Scope tools for a given User Id and Session Id.
Option to specify a browser (e.g. "safar... | 44,880 |
def save_dataset(data, crypto_name, yymmdd):
"""
:param data: 保存対象データ
:param crypto_name: 仮想通貨名
:param yymmdd: データ日付
"""
file_name = crypto_name + "_" + yymmdd # ファイル名
try:
os.mkdir(os.path.dirname(__file__) + "/../data")
except FileExistsError:
pass
finally:
... | 44,881 |
def table_parse(table):
"""
"""
data = []
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele])
return data | 44,882 |
def scan_mv_preprocessing_fill_pivot_nan(df):
"""
Value imputation.
Impute missing data in pivot table.
Parameters
----------
df : dataframe
Pivot table data with potentially missing values.
Returns
-------
df : dataframe
Pivot table data with no missing values.
... | 44,883 |
def image_show(request,item_container):
""" zeigt die Beschreibung der Datei an """
app_name = 'image'
vars = get_item_vars_show(request, item_container, app_name)
file_path = DOWNLOAD_PATH + item_container.container.path
file_name = file_path + item_container.item.name
width, height = get_image_size(file_n... | 44,884 |
def train_and_eval():
"""Train and evaluate StackOver NWP task."""
logging.info('Show FLAGS for debugging:')
for f in HPARAM_FLAGS:
logging.info('%s=%s', f, FLAGS[f].value)
hparam_dict = collections.OrderedDict([
(name, FLAGS[name].value) for name in HPARAM_FLAGS
])
train_dataset_computation, tr... | 44,885 |
def with_slices(it: Iterator[np.ndarray]) -> Iterator[Tuple[FixedSlice, np.ndarray]]:
"""Add slice into vstacked array to each sub array in `it`."""
start_idx = 0
for d in it:
end_idx = start_idx + d.shape[0]
yield FixedSlice(start_idx, end_idx), d
start_idx = end_idx | 44,886 |
def common_kwargs(cfg, bin_count, pointing):
"""Creates a prepfold-friendly dictionary of common arguments to pass to prepfold"""
name = generate_prep_name(cfg, bin_count, pointing)
prep_kwargs = {}
if cfg["run_ops"]["mask"]:
prep_kwargs["-mask"] = cfg["run_ops"]["mask"]
prep_kwargs["-o"] = ... | 44,887 |
def main():
#sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
"""
image2reward
"""
# initialization of image and rewardMatrix
image_file = '../img/atacama.png'
img = cv2.imread(image_file)
rewardMatrix = np.zeros((img.shape[0], img.shape[1]))
# print(rewardMatrix.... | 44,888 |
def quatMultiply(q1,q2):
"""Returns a quaternion that is a composition of two quaternions
Parameters
----------
q1: 1 x 4 numpy array
representing a quaternion
q2: 1 x 4 numpy array
representing a quatnernion
Returns
-------
qM: 1 x 4 numpy array
rep... | 44,889 |
def gen_motion_feedback_file(pname, sampling_rate): # create NOHOLD pdl file for obtaining data from COMAU winC4G as a text file
"""
PREREQUISITE:
File generated through this function must accompany any motion program for COMAU.
Make sure to run this program before pressing start in the teaching... | 44,890 |
def expandingPrediction(input_list, multiple=5):
"""
:param input_list:
:param multiple:
:return:
"""
expanded_list = []
for prediction in input_list:
for i in range(multiple):
expanded_list.append(prediction)
return expanded_list | 44,891 |
def pages_siblings_menu(context, page, url='/'):
"""Get the parent page of the given page and render a nested list of its
child pages. Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_sett... | 44,892 |
def aes(img, mask=None, canny_edges=None, canny_sigma=2):
"""Calculate the Average Edge Strength
Reference:
Aksoy, M., Forman, C., Straka, M., Çukur, T., Hornegger, J., & Bammer, R. (2012).
Hybrid prospective and retrospective head motion correction to mitigate cross-calibration errors.
Magnetic ... | 44,893 |
def projection(basis, vectors):
"""
The vectors live in a k dimensional space S and the columns of the basis are vectors of the same
space spanning a subspace of S. Gives a representation of the projection of vector into the space
spanned by basis in term of the basis.
:param basis: an n-by-k array... | 44,894 |
def _build_execution_context(worker_index, ports):
"""
Create execution context for the model.
:param worker_index: The index of this worker in a distributed setting.
:param ports: A list of port numbers that will be used in setting up the servers.
:return: The generated execution context.
"""
... | 44,895 |
def grab(sequence, random = numpy.random):
"""
Return a randomly-selected element from the sequence.
"""
return sequence[random.randint(len(sequence))] | 44,896 |
def plt_time_mlty(info, out_dir, save_plt=False, rmv_flgs=False, hdrs=['I_CaII', 'I_Ha', 'I_NaI', 'I_HeI']):
"""
Saves timeseries plots of the indices identified in the rdb file by
starting with 'I_' in a 'multi-plot' format.
"""
if not out_dir: return
print()
print("Executing plt_time_mlt... | 44,897 |
def csl_url_args_retriever():
"""Returns the style and locale passed as URL args for CSL export."""
style = resource_requestctx.args.get("style")
locale = resource_requestctx.args.get("locale")
return style, locale | 44,898 |
def _set_from_xml(container, root):
""" Recursive helper for :meth:`set_from_xml`. """
members = root.find('members')
for member in members.findall('member'):
name = member.attrib['name']
obj = getattr(container, name)
if isinstance(obj, Container):
_set_from_xml(obj, mem... | 44,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.