content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def __process_opss_args(optional_arg_map):
"""
Determine if the user is using opss wallet and if so, get the passphrase.
:param optional_arg_map: the optional arguments map
:raises CLAException: if getting the passphrase from the user fails
"""
_method_name = '__process_opss_args'
if Comman... | 29,500 |
def processing(log: EventLog, causal: Tuple[str, str], follows: Tuple[str, str]):
"""
Applying the Alpha Miner with the new relations
Parameters
-------------
log
Filtered log
causal
Pairs that have a causal relation (->)
follows
Pairs that have a follow relation (>)... | 29,501 |
def word_tokenize(string: str, language: str = "english") -> List[str]:
"""tokenizes a given string into a list of substrings.
:param string: String to tokenize.
:param language: Language. Either one of ``english'' or ``german''.
"""
if language not in ["english", "german"]:
raise ValueErro... | 29,502 |
def get_project_id(file_name):
""" Extracts project ID from intput BAM filename.
:param file_name: string e.g. "/PITT_0452_AHG2THBBXY_A1___P10344_C___13_cf_IGO_10344_C_20___hg19___MD.bam"
:return: string e.g. "P10344_C"
"""
regex = "(?<=___)P[0-9]{5}[_A-Z,a-z]*(?=___)" # Valid proje... | 29,503 |
def forecasting_barplot(
dict_algo,
metric='rmsle',
plot_name='forecasting',
x_labels=['ALDI', 'ALDI++'],
figsize=(16,32),
ylim=(2,3),
fontsize=40
):
"""Plot the chosen forecasting RMSE based on different discord detectors"""
fig, ax = plt.subplots(figsize=figsize)
sns.barp... | 29,504 |
def modify_scaffolds_with_coords(scaffolds, coords):
""" Gets scaffolds and fills in the right data.
Inputs:
* scaffolds: dict. as returned by `build_scaffolds_from_scn_angles`
* coords: (L, 14, 3). sidechainnet tensor. same device as scaffolds
Outputs: corrected scaffolds
... | 29,505 |
def multinomial(**kwargs):
"""
Load multinomial toxicity model.
Parameters
----------
validate: bool, optional (default=True)
if True, malaya will check model availability and download if not available.
Returns
-------
BAYES : malaya._models._sklearn_model.MULTILABEL_BAYES clas... | 29,506 |
def create_bucket(bucket_name, region="us-west-2"):
"""Create an S3 bucket in a specified region
:param bucket_name: Bucket to create
:param region: String region to create bucket in, e.g., 'us-west-2'
:return: True if bucket created, else False
"""
# Create bucket
try:
# get list of existing buckets
s3_cli... | 29,507 |
def print_tf_graph(graph):
"""Prints tensorflow graph in dictionary form."""
for node in graph:
for child in graph[node]:
print("%s -> %s" % (node.name, child.name)) | 29,508 |
def create_client():
"""Return a client socket that may be connected to a remote address."""
return _new_sock() | 29,509 |
def test_pyramid_app_with_additional_fixtures(
pyramid_app_with_additional_fixtures: TestApp, request: FixtureRequest
) -> None:
"""
Test that pyramid_app factory works with additional_fixtures.
It checks if additional_fixtures are loaded for the test.
"""
assert set(request.fixturenames) == se... | 29,510 |
def derivative_surface(obj):
""" Computes the hodograph (first derivative) surface of the input surface.
This function constructs the hodograph (first derivative) surface from the input surface by computing the degrees,
knot vectors and the control points of the derivative surface.
The return value of... | 29,511 |
def configure(config):
"""
| [bing ] | example | purpose |
| -------- | ------- | ------- |
| api_key | VBsdaiY23sdcxuNG1gP+YBsCwJxzjfHgdsXJG5 | Bing Primary Account Key |
"""
chunk = ''
if config.option('Configuring bing search module', False):
config.interactive_add('bing', 'api_k... | 29,512 |
def CVRMSE(ip1,ip2):
""" The normalized RMSE (= Root Mean Square Error) is defined as CVRMSE(X,Y) = sqrt[ sum_i(Yi-Xi)^2 / N ] / mean(Yi) ) """
stats = ip1.getStatistics()
return RMSE(ip1,ip2) / stats.mean | 29,513 |
def get_verified_aid_pairs(ibs):
"""
Example:
>>> # DISABLE_DOCTEST
>>> from wbia_cnn._plugin import * # NOQA
>>> import wbia
>>> ibs = wbia.opendb('NNP_Master3', allow_newdir=True)
>>> verified_aid1_list, verified_aid2_list = get_verified_aid_pairs(ibs)
"""
# Gr... | 29,514 |
def post_scan_handler(active_scans, results):
"""
Process the scanned files and yield the modified results.
Parameters:
- `active_scans`: a list of scanners names requested in the current run.
- `results`: an iterable of scan results for each file or directory.
"""
pass | 29,515 |
def audio_sort_key(ex):
"""Sort using duration time of the sound spectrogram."""
return ex.src.size(1) | 29,516 |
def decorateEosWorkFlowWithPrintOutputsEveryNSteps(inpObj,printInterval=5):
""" For backwards compatability only, just calls wflowCoord.decorateWorkFlowWithPrintOutputsEveryNSteps
"""
wflowCoord.decorateWorkFlowWithPrintOutputsEveryNSteps(inpObj,printInterval=5) | 29,517 |
def print_dot(graph, options):
"""Print a dependency graph to standard output as a dot input file.
graph: a tl.eggdeps.graph.Graph instance
options: an object that provides formatting options as attributes
cluster: bool, cluster direct dependencies of each root distribution?
version_numb... | 29,518 |
def data_restore(directory, model):
"""Reverse the effect of `_dump_weights` by loading individual tensors
into the model."""
log.info("Replacing model state with data from", directory)
leaves = [module for module in model.modules()
if len(list(module.children())) == 0]
for i, module ... | 29,519 |
def saveplot(name, dpi=None, figure=None):
"""
Saves current figure as a png in the home directory
:param name: filename, including or expluding directory and or extension
:param dpi: image resolution, higher means larger image size, default=matplotlib default
:param figure: figure number, default =... | 29,520 |
def _filename_to_title(filename, split_char="_"):
"""Convert a file path into a more readable title."""
filename = Path(filename).with_suffix("").name
filename_parts = filename.split(split_char)
try:
# If first part of the filename is a number for ordering, remove it
int(filename_parts[0... | 29,521 |
def basis_function_contributions(universe, mo, mocoefs='coef',
tol=0.01, ao=None, frame=0):
"""
Provided a universe with momatrix and basis_set_order attributes,
return the major basis function contributions of a particular
molecular orbital.
.. code-block:: python
... | 29,522 |
def main(args):
"""
Deploys a ModeredditCore on the arguments that have been given through the
command line interface.
Raises:
InvalidColumnException: When a column provided in the options is invalid
PathNotValidException: When path provided does not exist or not valid
"""
modere... | 29,523 |
def test_get_confusion_matrix():
"""
Tests :func:`fatf.utils.metrics.tools.get_confusion_matrix` function.
"""
# [[1, 1, 1],
# [1, 2, 1],
# [1, 1, 1]]
ground_truth = np.array(['a', 'b', 'b', 'b', 'a', 'a', 'b', 'c', 'c', 'c'])
predictions = np.array(['b', 'a', 'b', 'c', 'a', 'c', 'b', ... | 29,524 |
def test_salesforce_switch_from_query_to_subscription(sdc_builder, sdc_executor, salesforce, subscription_type, api):
"""Start pipeline, write data using Salesforce client, read existing data via query,
check if Salesforce origin reads data via wiretap, write more data, check that Salesforce
origin reads it... | 29,525 |
def bspline_basis(d, knots, n, x, close=True):
"""The `n`-th B-spline at `x` of degree `d` with knots.
B-Splines are piecewise polynomials of degree `d` [1]_. They are defined on
a set of knots, which is a sequence of integers or floats.
The 0th degree splines have a value of one on a single interval... | 29,526 |
def is_versioned(obj):
"""
Check if a given object is versioned by inspecting some of its attributes.
"""
# before any heuristic, newer versions of RGW will tell if an obj is
# versioned so try that first
if hasattr(obj, 'versioned'):
return obj.versioned
if not hasattr(obj, 'Versio... | 29,527 |
def main():
"""Entry point for deployment"""
main_args = _parse_args()
# Load repo default config
default_demo_ini = f"{REPO_DIR}/demo-config.ini"
ini_dict= _load_configuration(default_demo_ini)
# Load developer overrides
override_dev_ini = f"{REPO_DIR}/.dev-config.ini"
override_ini_dict... | 29,528 |
def default_error_reporter(title, message):
"""By default, error messages are just logged"""
log.error("error: %s" % title)
log.error("details:\n%s" % message) | 29,529 |
def preprocess_and_suggest_hyperparams(
task,
X,
y,
estimator_or_predictor,
location=None,
):
"""Preprocess the data and suggest hyperparameters.
Example:
```python
hyperparams, estimator_class, X, y, feature_transformer, label_transformer = \
preprocess_and_su... | 29,530 |
def passphrase_from_private_key(private_key):
"""Return passphrase from provided private key."""
return mnemonic.from_private_key(private_key) | 29,531 |
def merge_on_empty_fields(base, tomerge):
"""Utility to quickly fill empty or falsy field of $base with fields
of $tomerge
"""
has_merged_anything = False
for key in tomerge:
if not base.get(key):
base[key] = tomerge.get(key)
has_merged_anything = True
return has... | 29,532 |
def clear_rows(grid, locked):
"""Deletes the row, if that row is filled."""
increment = 0
for i in range(len(grid) - 1, -1, -1):
row = grid[i]
if (0, 0, 0) not in row:
increment += 1
index = i
for j in range(len(row)):
try:
... | 29,533 |
def test_photoslibrary_folder_exception_1(photoslib):
""" test exceptions in folder() """
import photoscript
with pytest.raises(ValueError):
folder = photoslib.folder() | 29,534 |
def get_topo(topo_fname, remote_directory, force=None):
"""
Download a topo file from the web, provided the file does not
already exist locally.
remote_directory should be a URL. For GeoClaw data it may be a
subdirectory of http://kingkong.amath.washington.edu/topo/
See that website for a lis... | 29,535 |
def init():
"""
App initialisation.
"""
global APP
global config_parser
global oasis_lookup
global logger
global SERVICE_BASE_URL
# Enable utf8 encoding
reload(sys)
sys.setdefaultencoding('utf-8')
# Get the Flask app
APP = Flask(__name__)
# Create config_parser... | 29,536 |
def call(cmd_args, suppress_output=False):
""" Call an arbitary command and return the exit value, stdout, and stderr as a tuple
Command can be passed in as either a string or iterable
>>> result = call('hatchery', suppress_output=True)
>>> result.exitval
0
>>> result = call(['hatchery', 'notr... | 29,537 |
def provides(interface):
"""
A validator that raises a :exc:`TypeError` if the initializer is called
with an object that does not provide the requested *interface* (checks are
performed using ``interface.providedBy(value)`` (see `zope.interface
<http://docs.zope.org/zope.interface/>`_).
:param ... | 29,538 |
def v_t(r):
"""
Mean thermal velocity
"""
return (8/np.pi)**0.5*c(r) | 29,539 |
def _state_stateful_alarm_controller(
select_state: Callable[[str], OverkizStateType]
) -> str:
"""Return the state of the device."""
if state := cast(str, select_state(OverkizState.CORE_ACTIVE_ZONES)):
# The Stateful Alarm Controller has 3 zones with the following options:
# (A, B, C, A,B, ... | 29,540 |
def _connect_new_volume(module, array, answer=False):
"""Connect volume to host"""
api_version = array._list_available_rest_versions()
if AC_REQUIRED_API_VERSION in api_version and module.params['lun']:
try:
array.connect_host(module.params['host'],
module.... | 29,541 |
def discover_inductive(log_file, noise_thresholds):
"""
Discovers a petri net model from log using the Inductive Miner with specified noise threshold. The resulting model
is written into file
"""
log = xes_importer.apply(log_file)
for i in tqdm(range(len(noise_thresholds)), desc=" > Discovering ... | 29,542 |
def is_mongo_configured(accessor):
"""
works out if mongodb is configured to run with trackerdash
i.e. first time running
"""
return accessor.verify_essential_collections_present() | 29,543 |
def create_default_children_plugins(request, placeholder, lang, parent_plugin, children_conf):
"""
Create all default children plugins in the given ``placeholder``.
If a child have children, this function recurse.
Return all children and grandchildren (etc.) created
"""
from cms.api import add_p... | 29,544 |
def _split_value_equally(delta, count):
"""Splits an integer or rational into roughly equal parts."""
numer = sympy.numer(delta)
denom = sympy.denom(delta)
return [int(math.floor((numer + i) / count)) / denom for i in range(count)] | 29,545 |
def maybe_get_docstring(node: ast.AST):
"""Get docstring from a constant expression, or return None."""
if (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)
):
return node.value.value
elif (
isinstance(node... | 29,546 |
def part_work(NPCorpsList):
"""获取军团LP兑换物品及其信息
Args:
NPCorpList: NPC军团id列表
Returns:
NPCorpList: 可以兑换物品的NPC军团id列表
[123,124,125...244,245,246]
NPCorps: 可以兑换物品的NPC军团信息字典,key为id
[
'物品id': {
'i... | 29,547 |
def ShowSchedHistory(cmd_args=None, cmd_options=None):
""" Routine to print out thread scheduling history, optionally sorted by a
column.
Usage: showschedhistory [-S on-core|off-core|last-duration] [<thread-ptr> ...]
"""
sort_column = None
if '-S' in cmd_options:
sort_column = ... | 29,548 |
def read_metadata(image_dir_path):
"""Read image metadata from an image directory."""
return jsons.load_dataobject(
ImageMetadata, _get_metadata_path(image_dir_path)
) | 29,549 |
def subtract(list_1, list_2):
"""Subtracts list_2 from list_1 even if they are different lengths.
Length of the returned list will be the length of the shortest list supplied.
Index 0 is treated as the oldest, and the older list items are truncated.
Args:
list_1 (list of float): List to be su... | 29,550 |
def get_available_time_slots() -> list:
"""
An application is ready for scheduling when all the payment rules are satisfied plus:
- the application has been paid
- the window to schedule the review has not elapsed
"""
return [
{"try": middleware.create_correlation_id, "fail": []}... | 29,551 |
def test_stupid_shaped_hole(sink_grid4):
"""Tests inclined fill into a surface with a deliberately awkward shape."""
fr = FlowAccumulator(sink_grid4, flow_director="D8")
hf = SinkFiller(sink_grid4, apply_slope=True)
hf.fill_pits()
hole1 = np.array(
[
4.00007692,
4.000... | 29,552 |
def configure_bgp_neighbor(
device,
bgp_as,
neighbor_as,
neighbor_address,
source_interface=None,
ebgp=None,
):
""" Configures bgp neighbor on bgp router
Args:
device('obj'): device to configure on
bgp_as('str'): bgp_as to configure
neighbor_as('s... | 29,553 |
def library_detail(request, lib_id):
"""
Display information about all the flowcells a library has been run on.
"""
lib = get_object_or_404(Library, id=lib_id)
flowcell_list = []
flowcell_run_results = {} # aka flowcells we're looking at
for lane in lib.lane_set.all():
fc = lane.fl... | 29,554 |
def _unlink_device(device, nbd):
"""Unlink image from device using loopback or nbd"""
if nbd:
utils.execute('qemu-nbd', '-d', device, run_as_root=True)
_free_device(device)
else:
utils.execute('losetup', '--detach', device, run_as_root=True) | 29,555 |
def test_subst_multi_0_2_0_default_val_unknown_val():
""" Test that substitutions are correct """
# 0 albums, 2 keywords, 0 persons, default vals provided, unknown val in template
import osxphotos
photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB_15_7)
# one album, one keyword, two persons
photo =... | 29,556 |
def parse_directory(path, rgb_prefix='img_', flow_x_prefix='flow_x_', flow_y_prefix='flow_y_'):
"""
Parse directories holding extracted frames from standard benchmarks
"""
print('parse frames under folder {}'.format(path))
frame_folders = glob.glob(os.path.join(path, '*'))
def count_files(direc... | 29,557 |
def InjectIntoProcess(pid, env, capturefile, opts, waitForExit): # real signature unknown; restored from __doc__
"""
InjectIntoProcess(pid, env, capturefile, opts, waitForExit)
Where supported by operating system and permissions, inject into a running process.
:param int pid: The Process ID (P... | 29,558 |
def traverse_bw(output: List[Variable]) -> Generator[Variable, None, None]:
"""Returns a generator implementing a :term:`backward traversal` of `var`'s transitive dependencies.
This generator guarantees that a variable is yielded after all its usages.
Note:
If `var` is in the boundary, the generator... | 29,559 |
def create_effect(
effect_id: CardEffect.EffectId = CardEffect.EffectId.DMG,
target: CardLevelEffects.Target = CardLevelEffects.Target.OPPONENT,
power: int = 10,
range_: float = 5
) -> Effect:
"""
Creates effect with given data, or creates default effect dealing dmg to opponent i... | 29,560 |
def solver_log(logger, level=logging.ERROR):
"""Context manager to send solver output to a logger. This uses a separate
thread to log solver output while the solver is running"""
# wait 3 seconds to join thread. Should be plenty of time. In case
# something goes horribly wrong though don't want to ha... | 29,561 |
def part_two(stream: Stream, violation: int) -> int:
"""Find the sum of min & max in the sequence that sums to `violation`."""
for start in range(len(stream) - 1):
for end in range(start + 2, len(stream) + 1):
seq = stream[start:end]
seq_sum = sum(seq)
if seq_sum == v... | 29,562 |
def getDoubleArray(plug):
"""
Gets the float array from the supplied plug.
:type plug: om.MPlug
:rtype: om.MDoubleArray
"""
return om.MFnDoubleArrayData(plug.asMObject()).array() | 29,563 |
def test_main_stdlib_module():
"""This test makes sure that the module is really searched within the
sunpy package.
"""
with pytest.raises(ValueError):
sunpy.self_test(package='random') | 29,564 |
def main():
"""This script reads a CSV file with self-created publisher IDs and looks up the name of the publisher in a separate CSV to identify the "real" identifier."""
parser = OptionParser(usage="usage: %prog [options]")
parser.add_option('-i', '--input-file', action='store', help='The name of the file with ... | 29,565 |
def get_fb(file_name):
"""#{{{
load feature file and transform to dict
return:
dict
key_list_feat
"""
ff = open(file_name, 'r')
fb = []
delta = []
fb_matrix = numpy.zeros([1, 24])
delta_matrix = numpy.zeros([1, 24])
fbanks = {}
deltas = {}
fb_keylist = [... | 29,566 |
def make_train_input_fn(
feature_spec, labels, file_pattern, batch_size, shuffle=True):
"""Makes an input_fn for training."""
return _make_train_or_eval_input_fn(
feature_spec,
labels,
file_pattern,
batch_size,
tf.estimator.ModeKeys.TRAIN,
shuffle) | 29,567 |
def _find(xs, predicate):
"""Locate an item in a list based on a predicate function.
Args:
xs (list) : List of data
predicate (function) : Function taking a data item and returning bool
Returns:
(object|None) : The first list item that predicate returns True for or None
"""
... | 29,568 |
def remove_dataparallel_prefix(state_dict):
"""Removes dataparallel prefix of layer names in a checkpoint state dictionary."""
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[7:] if k[:7] == "module." else k
new_state_dict[name] = v
return new_state_dict | 29,569 |
def user_upload_widget(node, on_complete=''):
"""Returns a Valum Uploader widget that uploads files based on the user's
home directory.
:param node: storage type (public or private) and path indicator, e.g.
"public:foo/bar" to have the uploaded file go in
MEDIA_ROOT/$USERNAME/foo/bar.
... | 29,570 |
def run_lsa(model, lsa_options):
"""Implements local sensitivity analysis using LSI, RSI, and parameter subset reduction.
Parameters
----------
model : Model
Object of class Model holding run information.
options : Options
Object of class Options holding run settings.
... | 29,571 |
def main():
"""
For entry point
"""
parser = argparse.ArgumentParser("Convert temperature in fahrenheit to kelvin or celsius")
parser.add_argument("temperature", help="Temperature in fahrenheit")
parser.add_argument("-c", "--celsius", action="store_true", help="Convert to celsius scale")
ar... | 29,572 |
def condense_simple_conv3x3(in_channels,
out_channels,
groups):
"""
3x3 version of the CondenseNet specific simple convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Num... | 29,573 |
def read_data_from(file_: str) -> list:
"""Read bitmasks and values from file."""
return open(file_, "r").read().splitlines() | 29,574 |
def version_for(plugin):
# (Plugin) -> Optional[str]
"""Determine the version of a plugin by its module.
:param plugin:
The loaded plugin
:type plugin:
Plugin
:returns:
version string for the module
:rtype:
str
"""
module_name = plugin.plugin.__module__
... | 29,575 |
def delete_tasks_repeat(start, end, user=None, for_reminder=False, filters=None):
"""Delete all schedule within the Date range and specified filters"""
self = frappe.get_doc("Tasks", user)
rescheduled = []
reschedule_errors = []
schedules = frappe.get_list("Tasks",
fields=["name", "task_date", "repeat_on"]... | 29,576 |
def choose_organization():
"""Allow user to input organization id.
Returns:
str: Access target id
"""
target_id = None
while not target_id:
orgs = None
return_code, out, err = utils.run_command([
'gcloud', 'organizations', 'list', '--format=json'])
if ret... | 29,577 |
def start_server(function):
"""
Decorator.
Tries to call function, if it fails, try to (re)start inotify server.
Raise QueryFailed if something went wrong
"""
def decorated_function(self, *args):
result = None
try:
return function(self, *args)
except (OSError,... | 29,578 |
def get_subscriber_groups(publication_id, subscription_id='', full_uri=False):
"""This function identifies the subscriber groups for one or more subscriptions within a publication.
.. versionchanged:: 3.1.0
Refactored the function to be more efficient.
:param publication_id: The ID of the publicati... | 29,579 |
def get_salutation_from_title(title):
"""
Described here: https://github.com/VNG-Realisatie/Haal-Centraal-BRP-bevragen/blob/v1.0.0/features/aanhef.feature#L4-L38
"""
if title in [BARON, HERTOG, JONKHEER, MARKIES, RIDDER]:
return HOOGWELGEBOREN_HEER
if title in [BARONES, HERTOGIN, JONKVROUW,... | 29,580 |
def hourOfDayNy(dateTime):
"""
Returns an int value of the hour of the day for a DBDateTime in the New York time zone.
The hour is on a 24 hour clock (0 - 23).
:param dateTime: (io.deephaven.db.tables.utils.DBDateTime) - The DBDateTime for which to find the hour of the day.
:return: (int) A Qu... | 29,581 |
def _extract_action_num_and_node_id(m):
"""Helper method: Extract *action_num* and *node_id* from the given regex
match. Convert *action_num* to a 0-indexed integer."""
return dict(
action_num=(int(m.group('action_num')) - 1),
node_id=m.group('node_id'),
) | 29,582 |
def get_uid_cidx(img_name):
"""
:param img_name: format output_path / f'{uid} cam{cidx} rgb.png'
"""
img_name = img_name.split("/")[-1]
assert img_name[-8:] == " rgb.png"
img_name = img_name[:-8]
import re
m = re.search(r'\d+$', img_name)
assert not m is None
cidx = int(m.group(... | 29,583 |
def main():
"""
Configures the parser by parsing command line arguments and calling the core code.
It might also profile the run if the user chose to do so.
"""
args = configure()
# Prepare output directories
outdir, _ = make_dirs(args)
logging.info('Writing files to: %s', outdir)
... | 29,584 |
def parse_color(hex_color):
"""Parse color values"""
cval = int(hex_color, 16)
x = lambda b: ((cval >> b) & 0xff) / 255.0
return {k: x(v) for k, v in dict(r=16, g=8, b=0).iteritems()} | 29,585 |
def ls(
verbose: int,
username: str,
password: str,
label: Optional[str]
) -> None:
"""List ssh key authorized to the specified user account."""
obj = setup_shared_cmd_options(verbose, username, password)
client_builder = obj.client_builder
client = client_builder.build_c... | 29,586 |
def apply_4x4(RT, XYZ):
"""
RT: B x 4 x 4
XYZ: B x N x 3
"""
#RT = RT.to(XYZ.device)
B, N, _ = list(XYZ.shape)
ones = np.ones([B, N, 1])
XYZ1 = np.concatenate([XYZ, ones], 2)
XYZ1_t = np.transpose(XYZ1, 1, 2)
# this is B x 4 x N
XYZ2_t = np.matmul(RT, XYZ1_t)
XYZ2 = np.tr... | 29,587 |
def smoothmax(value1, value2, hardness):
"""
A smooth maximum between two functions. Also referred to as the logsumexp() function.
Useful because it's differentiable and preserves convexity!
Great writeup by John D Cook here:
https://www.johndcook.com/soft_maximum.pdf
:param value1: Value of... | 29,588 |
def base_app(instance_path):
"""Flask application fixture."""
app_ = Flask('testapp', instance_path=instance_path)
app_.config.update(
SECRET_KEY='SECRET_KEY',
SQLALCHEMY_DATABASE_URI=os.environ.get(
'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),
SQLALCHEMY_TRACK_MODIFI... | 29,589 |
def udf_con(udf_backend):
"""
Instance of Client, already connected to the db (if applies).
"""
return udf_backend.connection | 29,590 |
def InMenu(gumpid: int, text: str):
"""
Returns True if the menu title or entry titles contains the given text.
:param gumpid: ItemID / Graphic such as 0x3db.
:param text: String value - See description for usage.
"""
pass | 29,591 |
def resolve_config(*, config: Union[Path, str]) -> Optional[Path]:
"""Resolves a config to an absolute Path."""
path = config if isinstance(config, Path) else Path(config)
# Is it absolute, or relative to the CWD?
if path.exists():
return path
# Is it relative to a configuration directory?... | 29,592 |
def test_persistent_cache_linux(mock_extensions):
"""The credential should use an unencrypted cache when encryption is unavailable and the user explicitly opts in.
This test was written when Linux was the only platform on which encryption may not be available.
"""
required_arguments = ("tenant-id", "c... | 29,593 |
def get_default_config() -> DefaultConfig:
"""
Get the default config.
Returns:
A dict with the default config.
"""
images = assets.get_images()
return {
"static_url": "/static",
"favicon_ico": images.favicon_ico.name,
"favicon_png": images.favicon_png.name,
... | 29,594 |
def normalize_elt(elt, alphanum=True):
"""
Normalize string by removing newlines, punctuation, spaces,
and optionally filtering for alphanumeric chars
Args:
elt (string):
string to normalize
alphanum (bool, optional, default True):
if True, only return elt if it ... | 29,595 |
def check_importability(code: str, func_name: str) -> Tuple[bool, Optional[Exception]]:
"""Very simple check just to see whether the code is at least importable"""
try:
import_func_from_code(
code,
func_name,
raise_if_not_found=False,
register_module=False... | 29,596 |
def compute_q(u, v, omega, k_hat, m_hat, N=100, map_est=False):
"""
Inputs:
u, v - (B,L*2)
omega - (L,n)
k_hat, m_hat - (B,J)
"""
B, L = u.size()[0], int(u.size()[1]/2)
unique_omega, inverse_idx = torch.unique(omega, dim=0, return_inverse=True) # (J,n), (L)
c, s = utils.circular_mome... | 29,597 |
def stationarity(sequence):
"""
Compute the stationarity of a sequence.
A stationary transition is one whose source and destination symbols
are the same. The stationarity measures the percentage of transitions
to the same location.
Parameters
----------
sequence : list
A... | 29,598 |
def build_nmt_model(Vs, Vt, demb=128, h=128, drop_p=0.5, tied=True, mask=True, attn=True, l2_ratio=1e-4,
training=None, rnn_fn='lstm'):
"""
Builds the target machine translation model.
:param demb: Embedding dimension.
:param h: Number of hidden units.
:param drop_p: Dropout per... | 29,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.