content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def request_user_input(prompt='> '):
"""Request input from the user and return what has been entered."""
return raw_input(prompt) | 5,347,200 |
def get_clinic_qs():
""" Returns a list of clinic uuid values for clinics whose patients
will receive follow up reminder messages
"""
q = Q()
for clinic in MESSAGE_CLINICS:
q = q | Q(name__iexact=clinic)
return list(Clinic.objects.filter(q).values_list('uuid', flat=True)) | 5,347,201 |
def NPnm(n, m, x):
"""Eq:II.77 """
return sqrt( (2*n+1)/2 * abs(nmFactorial(n,m)) ) * lpmv(m, n, x) | 5,347,202 |
def all_columns_empty():
"""All columns are empty ... test will demoonstrate this edge case can be handled"""
return [[] for i in range(0, 100)] | 5,347,203 |
def ping(host, destination, repeat_count, vrf_name):
"""Execute Ping RPC over NETCONF."""
# create NETCONF provider
provider = NetconfServiceProvider(address=host,
port=830,
username='admin',
p... | 5,347,204 |
def compute_shape_index(mesh) -> np.ndarray:
"""
Computes shape index for the patches. Shape index characterizes the shape
around a point on the surface, computed using the local curvature around each
point. These values are derived using PyMesh's available geometric
processing functionality.
P... | 5,347,205 |
def edit_frame(frame: ndarray, y: int) -> Tuple[ndarray, ndarray]:
"""
Parameters
----------
frame : (is row-major)
y
Returns
-------
(frame, cut)
"""
np.random.uniform(-1, 1, size=20000000) # 20000000@6cores
cut = cv.cvtColor(frame[[y], :], cv.COLOR_BGR2GRAY)[0, :]
# C... | 5,347,206 |
def get_location(uniprot_id: str) -> Location: # pragma: no cover
"""Queries the UniProt database for a subcellular location with the id `uniprot_id`
and returns a `Location` object"""
g: LocationRDF = get_location_graph(uniprot_id)
return Location.from_location_rdf(g) | 5,347,207 |
def clean(params):
"""
Clean current folder
remove saved model and training log
"""
if os.path.isfile(params.vocab_file):
os.remove(params.vocab_file)
if os.path.isfile(params.map_file):
os.remove(params.map_file)
if os.path.isdir(params.ckpt_path):
shutil.rmtree(pa... | 5,347,208 |
def analyzeSentiment(folderNum):
"""Get the review and perform sentiment analysis."""
while True:
carMake, carModel, reviewPath = getReview()
if type(carMake) != Exception and carMake is not None:
if folderNum == 0:
carModel = '-'.join(carModel)
else:
... | 5,347,209 |
def test_paper_size(pdf, option_type, config):
"""
Проверка размера страницы.
"""
for pg in pdf:
assert point_to_mm(pg.rect.width) == dict_get(
config, [option_type, "paper_size", "width"]
)
assert point_to_mm(pg.rect.height) == dict_get(
config, [option_t... | 5,347,210 |
def _gaussian2d_rot_no_bg(p,x,y):
"""
Required Arguments:
p -- (m) [A,x0,y0,FWHMx,FWHMy,theta]
x -- (n x o) ndarray of coordinate positions for dimension 1
y -- (n x o) ndarray of coordinate positions for dimension 2
Outputs:
f -- (n x o) ndarray of function values at positions (x,y)
""... | 5,347,211 |
def queue_get_all(q):
"""
Used by report builder to extract all items from a
:param q: queue to get all items from
:return: hash of merged data from the queue by pid
"""
items = {}
maxItemsToRetreive = 10000
for numOfItemsRetrieved in range(0, maxItemsToRetreive):
try:
... | 5,347,212 |
def sample_account(self, profile, company, **params):
"""Create and return a sample customer"""
defaults = {
"balance": 0,
"account_name": "string",
"account_color": "string"
}
defaults.update(params)
return Account.objects.create(
profile=profile,
company=c... | 5,347,213 |
def extract_acqtime_and_physio_by_slice(log_fname, nSlices, nAcqs, acqTime_firstImg, TR=1000):
"""
:param log_fname:
:param nSlices:
:param nAcqs:
:return: repsAcqTime: ((SC+all slices) x Nacq x (PulseOx, Resp)
timePhysio: N_pulseOx_points x ((PulseOx, Resp)
value... | 5,347,214 |
def get_funghi_type_dict(funghi_dict):
"""
Parameters
----------
funghi_dict: dict {str: list of strs}
is the name: html lines dict created by get_funghi_book_entry_dict_from_html()
Return
------------
dict {str: FunghiType}
each entry contains a mushroom name and the corr... | 5,347,215 |
def init(item):
"""
Initializes any data on the parent item if necessary
"""
for component in item.components:
if component.defines('init'):
component.init(item) | 5,347,216 |
def default_error_mesg_fmt(exc, no_color=False):
"""Generate a default error message for custom exceptions.
Args:
exc (Exception): the raised exception.
no_color (bool): disable colors.
Returns:
str: colorized error message.
"""
return color_error_mesg('{err_name}: {err_mes... | 5,347,217 |
def fit_model(model, generator, n_epochs, batches_per_epoch):
"""Fit model with data generator
model : tf.keras.Model
generator : yield (batch_x, batch_y)
"""
model.fit(generator, epochs=n_epochs, steps_per_epoch=batches_per_epoch) | 5,347,218 |
def test_get_package_energy_with_only_pkg_rapl_api_return_correct_value(fs_pkg_one_socket):
"""
Create a RaplDevice instance on a machine with package rapl api with on one socket
configure it to monitor package domain
use the `get_energy` method and check if:
- the returned list contains one element... | 5,347,219 |
def check_values_on_diagonal(matrix):
"""
Checks if a matrix made out of dictionary of dictionaries has values on diagonal
:param matrix: dictionary of dictionaries
:return: boolean
"""
for line in matrix.keys():
if line not in matrix[line].keys():
return False
return Tru... | 5,347,220 |
def volat(path):
"""volat
Data loads lazily. Type data(volat) into the console.
A data.frame with 558 rows and 17 variables:
- date. 1947.01 to 1993.06
- sp500. S&P 500 index
- divyld. div. yield annualized rate
- i3. 3 mo. T-bill annualized rate
- ip. index of industrial production
- pc... | 5,347,221 |
def read_quantity(string):
"""
convert a string to a quantity or vectorquantity
the string must be formatted as '[1, 2, 3] unit' for a vectorquantity,
or '1 unit' for a quantity.
"""
if "]" in string:
# It's a list, so convert it to a VectorQuantity.
# The unit part comes after... | 5,347,222 |
def loop():
"""
The main loop for monitoring and alerting on services
"""
# Setup major objects
config = get_config('monitor')
logger = get_logger(level=config.grab('level', section='logging'),
location=config.grab('location', section='logging'),
m... | 5,347,223 |
async def stop_service(name: str) -> None:
""" stop service """
task = TASKS.get(name)
if task is None:
raise Exception(f"No such task {name}")
return task.cancel() | 5,347,224 |
def rand_bbox(img_shape, lam, margin=0., count=None):
""" Standard CutMix bounding-box
Generates a random square bbox based on lambda value. This impl includes
support for enforcing a border margin as percent of bbox dimensions.
Args:
img_shape (tuple): Image shape as tuple
lam (float): ... | 5,347,225 |
def main():
"""Main."""
parser = argparse.ArgumentParser(description='Get Redis master IP')
parser.add_argument('--cluster', '-c', help='cluster name', required=True)
parser.add_argument('--subcluster', '-s', help='subcluster name', default='redisdb')
parser.add_argument('--db', '-d', help='redis db... | 5,347,226 |
def get_current_dir():
"""
Get the directory of the executed Pyhton file (i.e. this file)
"""
# Resolve to get rid of any symlinks
current_path = Path(__file__).resolve()
current_dir = current_path.parent
return current_dir | 5,347,227 |
def concat_output_files(
input_directory=None,
output_directory=None,
reference_sample=None,
project_id=None,
):
"""This function will concatenate all chromosome output files
into a single file for viewing on P-distance Graphing Tool.
It will also remove the reference sample data as it is o... | 5,347,228 |
def build_gun_dictionary(filename):
"""Build a dictionary of gun parameters from an external CSV file:
- Key: the gun designation (e.g. '13.5 in V' or '12 in XI')
- Value: a list of parameters, in the order:
* caliber (in inches)
* maxrange (maximum range in yards)
... | 5,347,229 |
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
"""
Generate a simple plot of the test and training learning curve.
Parameters
----------
estimator : object type that implements the "fit" and "predict" metho... | 5,347,230 |
def fetch_events_AHEAD(base_url='http://www.ahead-penn.org'):
"""
Penn Events for Penn AHEAD
"""
page_soup = BeautifulSoup(requests.get(
urljoin(base_url, '/events')).content, 'html.parser')
events = []
event_table = page_soup.find('div', attrs={'id': 'main-content'})
all_events = e... | 5,347,231 |
def assert_records_equal_nonvolatile(first, second, volatile_fields, indent=0):
"""Compare two test_record tuples, ignoring any volatile fields.
'Volatile' fields include any fields that are expected to differ between
successive runs of the same test, mainly timestamps. All other fields
are recursively compar... | 5,347,232 |
def forkpty(*args, **kwargs): # real signature unknown
"""
Fork a new process with a new pseudo-terminal as controlling tty.
Returns a tuple of (pid, master_fd).
Like fork(), return pid of 0 to the child process,
and pid of child to the parent process.
To both, return fd of newly opened pse... | 5,347,233 |
def column_to_index(ref):
"""
カラムを示すアルファベットを0ベース序数に変換する。
Params:
column(str): A, B, C, ... Z, AA, AB, ...
Returns:
int: 0ベース座標
"""
column = 0
for i, ch in enumerate(reversed(ref)):
d = string.ascii_uppercase.index(ch) + 1
column += d * pow(len(string.ascii_upp... | 5,347,234 |
def cols_to_tanh(df, columns):
"""Transform column data with hyperbolic tangent and return new columns of prefixed data.
Args:
df: Pandas DataFrame.
columns: List of columns to transform.
Returns:
Original DataFrame with additional prefixed columns.
"""
for col in columns:... | 5,347,235 |
def draw_png_heatmap_graph(obs, preds_dict, gt, mixes, network_padding_logits, trackwise_padding, plt_size, draw_prediction_track, plot_directory, log_file_name,
multi_sample, global_step, graph_number, fig_dir, csv_name, rel_destination, parameters, padding_mask='None', distance=0):
"""... | 5,347,236 |
def main(mainscreen):
"""Sets up application settings and initializes windows objects"""
if (len(sys.argv) < 2):
exit("No input folder specified")
logger = utils.setup_logger('simple',
'simple.log',
extra={'filename': __file__})... | 5,347,237 |
def stdev_time(arr1d, stdev):
"""
detects breakpoints through multiple standard deviations and divides breakpoints into timely separated sections
(wanted_parts)
- if sigma = 1 -> 68.3%
- if sigma = 2 -> 95.5%
- if sigma = 2.5 -> 99.0%
- if sigma = 3 -> 99.7%... | 5,347,238 |
def test_create_build(mocker, expected_class, build_object_type):
"""
Given:
- server_type of the server we run the build on: XSIAM or XSOAR.
When:
- Running 'configure_an_test_integration_instances' script and creating Build object
Then:
- Assert there the rigth Build object cre... | 5,347,239 |
def main(_, **settings):
"""
This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings, route_prefix="/api")
# Initialise the broadcast view before c2cwsgiutils is initialised. This allows to test the
# reconfiguration on the fly of the broadcast framework
... | 5,347,240 |
def get_available_modules():
"""Return list of modules shipped with OnRamp.
Returns:
List of module shipped with OnRamp
"""
def verify_module_path(x):
return os.path.isdir(os.path.join(_shipped_mod_dir, x))
return [{
'mod_id': None,
'mod_name': name,
'in... | 5,347,241 |
def GetVarLogMessages(max_length=256 * 1024,
path='/var/log/messages',
dut=None):
"""Returns the last n bytes of /var/log/messages.
Args:
max_length: Maximum characters of messages.
path: path to /var/log/messages.
dut: a cros.factory.device.device_types.Devi... | 5,347,242 |
def _write_file(response, writer, size_limit=None):
"""Write download results to disk.
"""
size = 0
with writer.open_file('wb') as fp:
for chunk in response.iter_content(chunk_size=4096):
if chunk: # filter out keep-alive chunks
fp.write(chunk)
size +... | 5,347,243 |
def find_index(predicate, List):
"""
(a → Boolean) → [a] → [Number]
Return the index of first element that satisfy the
predicate
"""
for i, x in enumerate(List):
if predicate(x):
return i | 5,347,244 |
def base_user():
"""Base user"""
User.query.delete()
user = User(
username="testuser",
name="testname",
email="test@user.com",
password="1234",
birth_date="2000-01-01",
)
user.save()
yield user | 5,347,245 |
def logger(
wrapped: Callable[..., str], instance: Any, args: Any, kwargs: Dict[str, Any]
) -> str:
"""Handle logging for :class:`anndata.AnnData` writing functions of :class:`cellrank.estimators.BaseEstimator`."""
log, time = kwargs.pop("log", True), kwargs.pop("time", None)
msg = wrapped(*args, **kwar... | 5,347,246 |
def search_front():
"""
Search engine v0.1
- arguments:
- q: query to search (required)
"""
q = request.args.get('q', None)
if not q:
return flask.jsonify({'status': 'error', 'message': 'Missing query'}), 400
res = dict()
cursor = db.run(r.table(PRODUCTS_TABLE).pluck('sho... | 5,347,247 |
def assert_dir_structure(data_dir, out_dir):
""" Asserts that the data_dir exists and the out_dir does not """
if not os.path.exists(data_dir):
raise OSError("Invalid data directory '%s'. Does not exist." % data_dir)
if os.path.exists(out_dir):
raise OSError("Output directory at '%s' already... | 5,347,248 |
def insert_rare_words(sentence: str) -> str:
"""
attack sentence by inserting a trigger token in the source sentence.
"""
words = sentence.split()
insert_pos = randint(0, len(words))
insert_token_idx = randint(0, len(WORDS)-1)
words.insert(insert_pos, WORDS[insert_token_idx])
return " ".... | 5,347,249 |
def _can_be_quoted(loan_amount, lent_amounts):
"""
Checks if the borrower can obtain a quote. To this aim, the loan amount should be less than or
equal to the total amounts given by lenders.
:param loan_amount: the requested loan amount
:param lent_amounts: the sum of the amounts given by lenders
... | 5,347,250 |
def load_specs_from_docstring(docstring):
"""Get dict APISpec from any given docstring."""
# character sequence used by APISpec to separate
# yaml specs from the rest of the method docstring
yaml_sep = "---"
if not docstring:
return {}
specs = yaml_utils.load_yaml_from_docstring(docst... | 5,347,251 |
def get_bt_mac_lsb_offset(any_path,config_file):
"""
Obains the offset of the BT_MAC LSB from the BASE_MAC LSB by sdkconfig inspection.
"""
mac_sdkconfig_string='CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS'
sdkconfig=os.path.join(any_path,config_file)
config_lines=open(sdkconfig).readlines()
for... | 5,347,252 |
def get_transform(V1, V2, pair_ix, transform=None, use_ransac=True):
"""
Estimate parameters of an `~skimage.transform` tranformation given
a list of coordinate matches.
Parameters
----------
V1, V2 : [N,2] arrays
Coordinate lists. The transform is applied to V1 to match V2.
... | 5,347,253 |
def no_trajectory_dct():
""" Dictionary expected answer """
return () | 5,347,254 |
def transform_fn(net, data, input_content_type, output_content_type):
"""
Transform a request using the Gluon model. Called once per request.
:param net: The Gluon model.
:param data: The request payload.
:param input_content_type: The request content type.
:param output_content_type: The (desi... | 5,347,255 |
def catergorizeItems(
actions: list[argparse.Action],
) -> Generator[c2gtypes.Item, None, None]:
"""Catergorise each action and generate json."""
for action in actions:
if isinstance(action, _MutuallyExclusiveGroup):
yield buildRadioGroup(action)
elif isinstance(action, (_StoreTrueAction, _StoreFalseAction)):... | 5,347,256 |
def print_pandas_dataset(d):
"""
Given a Pandas dataFrame show the dimensions sizes
:param d: Pandas dataFrame
:return: None
"""
print("rows = %d; columns=%d" % (d.shape[0], d.shape[1]))
print(d.head()) | 5,347,257 |
def superuser_required(method):
"""
Decorator to check whether user is super user or not
If user is not a super-user, it will raise PermissionDenied or
403 Forbidden.
"""
@wraps(method)
def _wrapped_view(request, *args, **kwargs):
if request.user.is_superuser is False:
ra... | 5,347,258 |
def _section_data_download(course, access):
""" Provide data for the corresponding dashboard section """
course_key = course.id
show_proctored_report_button = (
settings.FEATURES.get('ENABLE_SPECIAL_EXAMS', False) and
course.enable_proctored_exams
)
section_key = 'data_download_2' i... | 5,347,259 |
def reshape_kb_mask_to_keys_size(kb_mask, kb_keys, kb_total):
"""
TODO document TODO move to helpers
"""
if not isinstance(kb_keys, tuple):
kb_keys = (kb_keys,)
keys_dim = product([keys.shape[1] for keys in kb_keys])
kb_pad_len = kb_total - keys_dim
assert kb_pad_len >= 0, f"kb... | 5,347,260 |
def tcache(parser, token):
"""
This will cache the contents of a template fragment for a given amount
of time with support tags.
Usage::
{% tcache [expire_time] [fragment_name] [tags='tag1,tag2'] %}
.. some expensive processing ..
{% endtcache %}
This tag also supports ... | 5,347,261 |
def bpg_compress(input_image_p, q, tmp_dir=None, chroma_fmt='444'):
""" Int -> image_out_path :: str """
assert 'png' in input_image_p
if tmp_dir:
input_image_name = os.path.basename(input_image_p)
output_image_bpg_p = os.path.join(tmp_dir, input_image_name).replace('.png', '_tmp_bpg.bpg')
else:
output_image_... | 5,347,262 |
def location_edit(type_, id_, location_name, location_type, date, user,
description=None, latitude=None, longitude=None):
"""
Update a location.
:param type_: Type of TLO.
:type type_: str
:param id_: The ObjectId of the TLO.
:type id_: str
:param location_name: The name o... | 5,347,263 |
def G2(species_index, eta, Rs):
"""G2 function generator.
This is a radial function between an atom and atoms with some chemical
symbol. It is defined in cite:khorshidi-2016-amp, eq. 6. This version is
scaled a little differently than the one Behler uses.
Parameters
----------
species_index... | 5,347,264 |
def get_portfolio_output(id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetPortfolioResult]:
"""
Resource Type definition for AWS::ServiceCatalog::Portfolio
"""
... | 5,347,265 |
async def async_setup_platform(hass, config, async_add_entities, _discovery_info=None):
"""Set up an Unifi Protect Switch."""
data = hass.data[UPV_DATA]
if not data:
return
ir_on = config.get(CONF_IR_ON)
if ir_on == "always_on":
ir_on = "on"
ir_off = config.get(CONF_IR_OFF)
... | 5,347,266 |
def convert_leg_pose_to_motor_angles(robot_class, leg_poses):
"""Convert swing-extend coordinate space to motor angles for a robot type.
Args:
robot_class: This returns the class (not the instance) for the robot.
Currently it supports minitaur, laikago and mini-cheetah.
leg_poses: A list of leg poses... | 5,347,267 |
def download_from_s3(s3_url: str, cache_dir: str = None, access_key: str = None,
secret_access_key: str = None, region_name: str = None):
"""
Download a "folder" from s3 to local. Skip already existing files. Useful for downloading all files of one model
The default and recommended auth... | 5,347,268 |
def get_all_records(session):
"""
return all records
"""
result = session.query(Skeleton).all()
skeletons = convert_results(result)
return skeletons | 5,347,269 |
def pwm_to_boltzmann_weights(prob_weight_matrix, temp):
"""Convert pwm to boltzmann weights for categorical distribution sampling."""
weights = np.array(prob_weight_matrix)
cols_logsumexp = []
for i in range(weights.shape[1]):
cols_logsumexp.append(scipy.special.logsumexp(weights.T[i] / temp))
... | 5,347,270 |
def mutation_delete_music_composition(identifier: str):
"""Returns a mutation for deleting a MusicComposition.
Args:
identifier: The identifier of the MusicComposition.
Returns:
The string for the mutation for deleting the music composition object based on the identifier.
"""
retur... | 5,347,271 |
def coords_from_gaia(gaia_id):
"""Returns table of Gaia DR2 data given a source_id."""
from astroquery.gaia import Gaia
import warnings
warnings.filterwarnings('ignore', module='astropy.io.votable.tree')
adql = 'SELECT gaia.source_id, ra, dec FROM gaiadr2.gaia_source AS gaia WHERE gaia.source_id={0}... | 5,347,272 |
def edgeplot(P,T,E,sz = 1):
""" Plots mesh with edges outlined.
Parameters
----------
P : (n,3) float array
A point cloud.
T : (m,3) int array
List of vertex indices for each triangle in the mesh.
E : (k,1) int array
List of edge point ind... | 5,347,273 |
def partition(smilist,ratio=0.7):
"""
A function to create test/ train split list
:param smilist: smiles (list)
:param ratio: test set split fraction (float)
Return type: traininglist, testlist (list)
"""
from random import shuffle, random
import numpy as np
shuffle(smilist, random)... | 5,347,274 |
def align(reference, query):
"""
do a pairwise alignment of the query to the reference, outputting up to 10000 of the highest-scoring alignments.
:param reference: a STRING of the reference sequence
:param query: a STRING of the query sequence
:return: a list of up to 10000 Alignment objects
"""... | 5,347,275 |
def cleanup_drained_instance(key):
"""Deletes the given drained Instance.
Args:
key: ndb.Key for a models.Instance entity.
"""
instance = key.get()
if not instance:
return
if instance.deleted:
return
if not instance.url:
logging.warning('Instance URL unspecified: %s', key)
return
... | 5,347,276 |
def output_name(ncfile):
"""output_name.
Args:
ncfile:
"""
ncfile_has_datetime = re.search('[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}', ncfile)
if ncfile_has_datetime:
forecast_time = ncfile_has_datetime.group()
else:
raise Exception("ncfile doesn't have datetime data.")
... | 5,347,277 |
def _replacement_func_decorator(
fn=None,
name=None,
help="",
args=None):
"""
Replaces xlo.func in jupyter but removes arguments which do not make sense
when called from jupyter
"""
def decorate(fn):
spec = _FuncDescription(fn, name or fn._... | 5,347,278 |
def stress_x_component(coordinates, prisms, pressure, poisson, young):
"""
x-component of the stress field.
Parameters
----------
coordinates : 2d-array
2d numpy array containing ``y``, ``x`` and ``z`` Cartesian cordinates
of the computation points. All coordinates should be in mete... | 5,347,279 |
def process_time_data(flag, last_time, model_params_dict_raw, time_data_raw):
"""
This is a helper function that takes the raw time data from the model
file and replaces it with the correct value in the params file.
:param flag:
:param last_time:
:param model_params_dict_raw:
:param time_da... | 5,347,280 |
def i_obtain_a_group1_http_error(step, error_code):
""" Assertions to check if HTTP response status has got the expected error code """
assert_equals(str(world.response.status_code), error_code, 'RESPONSE BODY: {}'.format(world.response.content)) | 5,347,281 |
def test_profile_mixed_error(recwarn):
"""Warn if both affine and transform are passed"""
warnings.simplefilter('always')
profile = Profile(affine='foo', transform='bar')
assert len(recwarn) == 1
assert recwarn.pop(DeprecationWarning)
assert 'affine' not in profile
assert profile['transform'... | 5,347,282 |
def create_pos_data(data, parser):
"""
creating the positive fh numeric dataset. performing another cleaning.
:param data: suspected fh examples
:param parser: parser used for the word tokenization
:return: all positive examples (after the cleaning), will be used
for creating the negat... | 5,347,283 |
def call(subcommand, args): # pylint: disable=unused-argument
"""Call a subcommand passing the args."""
KytosConfig.check_versions()
func = getattr(WebAPI, subcommand)
func(args) | 5,347,284 |
async def absent(hub, ctx, name, resource_uri, connection_auth=None, **kwargs):
"""
.. versionadded:: 2.0.0
Ensure a diagnostic setting does not exist for the specified resource uri.
:param name: The name of the diagnostic setting.
:param resource_uri: The identifier of the resource.
:param ... | 5,347,285 |
def test_synonym_mapping(model, threshold):
"""Test that synonym mapping is working. Could use some more tests for this function."""
set1 = set(['A', 'B', 'C'])
set2 = set(['A', 'D', 'E'])
mapping = ehnfer.commands.synonym_mapping(set1, set2, model, threshold)
# See function doc for why this is s... | 5,347,286 |
def print_mission_breakdown(results,filename='mission_breakdown.dat', units="imperial"):
"""This creates a file showing mission information.
Assumptions:
None
Source:
N/A
Inputs:
results.segments.*.conditions.
frames.
inertial.position_vector [m]
inertial.time ... | 5,347,287 |
def save_sentence_json(framenet_path, save_root, num_samples=100_000):
"""Save sentence data as individual files as json
Every sample has two documents, a sentence from
Framenet as well as the frame definition. This
can be used for text summarization Seq2Seq models.
Note:
As a proof ... | 5,347,288 |
def create_account(input_params:dict):
"""
Creates account in ldap db.
"""
ldap_connection = None
try:
ldap_connection = connect_to_ldap_server(input_params['--ldapuser'],
input_params['--ldappasswd'])
add_keys_to_dictionary(input_params)
if not is_account_presen... | 5,347,289 |
def get_ngrok() -> str or None:
"""Sends a `GET` request to api/tunnels to get the `ngrok` public url.
See Also:
Checks for output from get_port function. If nothing, then `ngrok` isn't running.
However as a sanity check, the script uses port number stored in env var to make a `GET` request.
... | 5,347,290 |
def contacts_per_person_symptomatic_60x80():
"""
Real Name: b'contacts per person symptomatic 60x80'
Original Eqn: b'contacts per person normal 60x80*(symptomatic contact fraction 80+symptomatic contact fraction 60\\\\ )/2'
Units: b'contact/Day'
Limits: (None, None)
Type: component
b''
... | 5,347,291 |
def get_pull_through_cache_rule_output(ecr_repository_prefix: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetPullThroughCacheRuleResult]:
"""
The AWS::ECR::PullThroughCacheRule resource configures the upstream registry ... | 5,347,292 |
def get_input_fn_common(pattern, batch_size, mode, hparams: SmartComposeArg):
""" Returns the common input function used in Smart Compose training and evaluation"""
return _get_input_fn_common(pattern, batch_size, mode,
**_get_func_param_from_hparams(_get_input_fn_common, hparams... | 5,347,293 |
def text_to_int(sentence, map_dict, max_length=20, is_target=False):
"""
对文本句子进行数字编码
@param sentence: 一个完整的句子,str类型
@param map_dict: 单词到数字的映射,dict
@param max_length: 句子的最大长度
@param is_target: 是否为目标语句。在这里要区分目标句子与源句子,因为对于目标句子(即翻译后的句子)我们需要在句子最后增加<EOS>
"""
# 用<PAD>填充整个序列
text_to_idx = ... | 5,347,294 |
def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):
"""
:param m:
:param d:
:param data_portal:
:param scenario_directory:
:param subproblem:
:param stage:
:return:
"""
generic_load_model_data(
m=m,
d=d,
data_portal=data_portal,... | 5,347,295 |
def map_to_udm_users(users_df: DataFrame) -> DataFrame:
"""
Maps a DataFrame containing Canvas users into the Ed-Fi LMS Unified Data
Model (UDM) format.
Parameters
----------
users_df: DataFrame
Pandas DataFrame containing all Canvas users
Returns
-------
DataFrame
... | 5,347,296 |
def custom_shibboleth_institution_login(
selenium, config, user_handle, user_pwd, user_name
):
"""Custom Login on Shibboleth institution page."""
wait = WebDriverWait(selenium, config.MAX_WAIT_TIME)
input_user_id = wait.until(
EC.element_to_be_clickable((By.XPATH, "//input[@id='userid']"))
)... | 5,347,297 |
def beamcenter_mask():
"""Returns beamcenter mask as an array. Given the PSF and the dimensions of
the beamstop, the minimum intensity around beamcenter occurs at a radius of
3 pixels, hence a 7x7 mask."""
from numpy import array
return array([[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
... | 5,347,298 |
def physical_conversion_actionAngle(quantity,pop=False):
"""Decorator to convert to physical coordinates for the actionAngle methods:
quantity= call, actionsFreqs, or actionsFreqsAngles (or EccZmaxRperiRap for actionAngleStaeckel)"""
def wrapper(method):
@wraps(method)
def wrapped(*args,**k... | 5,347,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.