content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mol2_to_dataframe(mol2_file, parse_multi_model=False, parse_coord=False,
columns=('serial', 'name', 'x', 'y', 'z', 'resSeq', 'resName', 'attype', 'charge', 'model')):
"""
Parse a Tripos MOL2 file format to a Pandas DataFrame
Uses the same column headers as the main TopologyDataFra... | 68,800 |
def extractLogData(fname):
"""
Given a filename of a job file "path/job.NUMBER.out"
extract the statistics of the job duration, etc.
@param fname: Filename to extract
@return: a dictionary with keys:
- glidein_duration - integer, how long did the glidein run
- validation_duration - ... | 68,801 |
def dao_reduce_sms_provider_priority(identifier, *, time_threshold):
"""
Will reduce a chosen sms provider's priority, and increase the other provider's priority by 10 points each.
If either provider has been updated in the last `time_threshold`, then it won't take any action.
"""
amount_to_reduce_b... | 68,802 |
def set_file_input_files(
files: list[str],
nodeId: Optional[NodeId] = None,
backendNodeId: Optional[BackendNodeId] = None,
objectId: Optional[runtime.RemoteObjectId] = None,
) -> dict:
"""Sets files for the given file input element.
Parameters
----------
files: list[str]
Ar... | 68,803 |
def test_manage_event_pir_init(event_manager):
"""Verify that a new PIR event can be managed."""
event_manager.update(PIR_INIT)
assert event_manager.values()
event = event_manager["tns1:Device/tnsaxis:Sensor/PIR_0"]
assert event.topic == "tns1:Device/tnsaxis:Sensor/PIR"
assert event.source == "... | 68,804 |
def islist(item):
"""Check if an is item is a list - not just a sequence.
Args:
item (mixed): The item to check as a list.
Returns:
result (bool): True if the item is a list, False if not.
"""
return isinstance(item, list) | 68,805 |
def group_parameters(model_params_dict_expanded):
"""Groups the parameters to be estimates
in flat dictionary structure"""
model_params_dict_flat = dict()
model_params_dict_flat["gamma_0s"] = list(
model_params_dict_expanded["const_wage_eq"].values()
)
model_params_dict_flat["gamma_1s... | 68,806 |
def read_static_info(static_tracks_file):
"""
This method reads the static info file from highD data.
:param static_tracks_file: the input path for the static csv file.
:return: the static dictionary - the key is the track_id and the value is the corresponding data for this track
"""
return pan... | 68,807 |
def nullify(grammar, state, visiting):
"""Return a list of results: each is the parsed part of reduced(state)
if state can derive the empty string."""
parsed, chain = state = reduced(state)
if not chain: return [parsed]
(tag, x), tail = chain[0], chain[1:]
if tag == 'push':
if x in visit... | 68,808 |
def list_ground_truth_data(ctx, app_id: str, page: int, size: int):
"""
List all ground truth data for an application
"""
client = ctx.obj['client']
print(f"Fetching ground truth data per application {app_id}")
print(client.list_ground_truth_data(app_id, page, size)) | 68,809 |
def positional_encoding(tensor, start_index, omega):
"""
tensor: a reference tensor we use to get shape. actually only T and C are needed. Shape(B, T, C)
start_index: int, we can actually use start and length to specify them.
omega (B,): speaker position rates
return (B, T, C), position embedding
... | 68,810 |
def task_csubscription_dep():
"""Build csubscription .d files"""
yield from _build.get_task_deps() | 68,811 |
def initAfterReload():
"""
Initialize BUG and fires PythonReloaded event after reloading Python modules while game is still running.
The first time this module is loaded after the game launches, the global context is not yet ready,
and thus BUG cannot be initialized. When the Python modules are reloaded after bei... | 68,812 |
def draw_smopy_basemap(G, figsize=(8, 6), zoom=10, ax=None):
"""Draw a basemap with the extent given by graph G"""
pos_wgs = nx_coordinate_layout(G)
lon = [coords[0] for coords in pos_wgs.values()]
lat = [coords[1] for coords in pos_wgs.values()]
lon_min = min(lon)
lon_max = max(lon)
lat_m... | 68,813 |
def get_conversation_by_name(conversation_name: str) -> dict:
"""
Get a slack conversation by its name. Order of operation is:
1. Check the COMMON_CHANNEL parameter for the conversation
2. Check the integration context for the conversation
3. If DISABLE_CACHING is false, then we will paginate the ap... | 68,814 |
def test_palabra_concreta():
"""Comprueba que la extracción de una palabra concreta se hace correctamente"""
respuesta = "Si que me parece muy muy bien"
resp = Respuesta(respuesta)
assert_that(resp.get_palabra_concreta('parece')).is_equal_to(1) | 68,815 |
def get_file_extension(fname):
""" Returns the extension from a filepath string ignoring the '.' character """
return os.path.splitext(fname)[-1][1:] | 68,816 |
def test_toggle_button(run_gui, button_definition):
"""The button should toggle on/off when clicked."""
defn = replace(
button_definition,
hover_color=None,
on_press=change_text_callback("On"),
on_release=change_text_callback("Off"),
)
layer = ToggleButton(defn)
asse... | 68,817 |
def cloud_remove(img, bandnumber):
"""
img: image
bandnumber: bandnumber
"""
if bandnumber < 1 | bandnumber > 11:
print 'ValueError: bandnumber should be 1~11.'
return 0
# TODO D中元素表示各通道截至频率,需要修改一下
D = [0.4, 0.4, 0.4, 0.4, 0.4, 0.4,\
0.4, 0.4, 0.4, 0.4, 0.4]
img1 ... | 68,818 |
def _apply_laplacian(nx, ny, alpha, image):
""" Apply isotropic Laplacian to an image.
Parameters
----------
nx, ny: int
Dimensions of 2D image
alpha: float
Diffusion parameter
image: ndarray, ndim=1
Image as a 1D vector
Returns
-------
output: ndarray, ndim... | 68,819 |
def get_tree():
"""You probably want to use ET.fromstring"""
root = ET.fromstring(xmlstring)
return ET.ElementTree(root) | 68,820 |
def standard_rated_expenses_emiratewise(data, filters):
"""Append emiratewise standard rated expenses and vat."""
total_emiratewise = get_total_emiratewise(filters)
emirates = get_emirates()
amounts_by_emirate = {}
for emirate, amount, vat in total_emiratewise:
amounts_by_emirate[emirate] = {
"legend": emirat... | 68,821 |
def MPIBroadcast(inputs, root, mpi_ranks=None, **kwargs):
"""Broadcast a tensor to all nodes in the ``MPIGroup``.
Parameters
----------
inputs : Tensor
The tensor to broadcast.
root : int
The world rank of root node.
mpi_ranks: sequence of int, optional
The world rank of... | 68,822 |
def calc_namp(tors_names, nsamp_par, cnf_save_fs, cnf_run_fs):
""" Determine the number of samples to od
"""
tors_ranges = tuple((0, 2*numpy.pi) for tors in tors_names)
tors_range_dct = dict(zip(tors_names, tors_ranges))
nsamp = util.nsamp_init(nsamp_par, len(tors_names))
ioprinter.debug_me... | 68,823 |
def PyErr_NoMemory(space):
"""This is a shorthand for PyErr_SetNone(PyExc_MemoryError); it returns NULL
so an object allocation function can write return PyErr_NoMemory(); when it
runs out of memory.
Return value: always NULL."""
PyErr_SetNone(space, space.w_MemoryError) | 68,824 |
def delete_account_password_policy():
"""
Deletes the password policy for the AWS account. There are no parameters.
See also: AWS API Documentation
Exceptions
Examples
The following command removes the password policy from the current AWS account:
Expected Output:
:example: res... | 68,825 |
def _add_loss_summaries(total_loss):
"""Add summaries for losses.
Generates moving average for all losses and associated summaries for
visualizing the performance of the network.
Args:
total_loss: Total loss from loss().
Returns:
loss_averages_op: op for generating moving averages of l... | 68,826 |
def mk_newnode(abspath, check_exsistence=False):
"""
make new file node for abspath
:param abspath:
plz use absolute path. Not relative path
:param check_exsistence:
if True, will check if the abspath existence (
raise IOError if abspath exists)
:raise Exception:
IOE... | 68,827 |
def check_extension(fname, extension = ".csv"):
"""
Checks whether the fname includes an extension.
Adds an extension if none exists.
fname - the name of the file to check.
extension - the extension to append if necessary.
>> Default: ".csv".
"""
root, ending = os.path.splitext(fname)... | 68,828 |
def lock2key(lock):
"""
Generates response to $Lock challenge from Direct Connect Servers
Borrowed from free sourcecode online.
"""
lock = array.array('B', lock)
ll = len(lock)
key = list('0'*ll)
for n in xrange(1,ll):
key[n] = lock[n]^lock[n-1]
key[0] = lock[0] ^ l... | 68,829 |
def get_channel_count(ods, hw_sys, check_loc=None, test_checker=None, channels_name='channel'):
"""
Utility function for CX hardware overlays.
Gets a channel count for some hardware systems.
Provide check_loc to make sure some data exist.
:param ods: OMAS ODS instance
:param hw_sys: string
... | 68,830 |
def get_bundle_files_cached(bundle_uuid, bundle_version=None, draft_name=None):
"""
Get the list of files in the bundle, optionally with a version and/or draft
specified.
"""
if draft_name:
return get_bundle_draft_files_cached(bundle_uuid, draft_name)
else:
if bundle_version is N... | 68,831 |
def get_token_header(user_id: UUID) -> Dict[str, str]:
"""Get an authentication token header."""
token = encode_token(user_id, FAKE_KEY)
return {"Authorization": f"Bearer {token}"} | 68,832 |
def _add_prefix(key_type: Union[PublicKeyTypeAgreement, PublicKeyTypeAuthentication], data: bytes) -> bytes:
"""
Adds prefix to a data
:param key_type: type of key
:param data: data to be prefixed
:return: prefixed data
"""
prefix = varint.encode(key_type.value)
return b''.join([prefix... | 68,833 |
def tshirt_code(tshirt_string):
""" convert tshirt size strings into a code for us"""
if not tshirt_string:
return ""
tshirt_code = ""
if tshirt_string[0] == "f":
tshirt_code += "0"
tshirt_string = tshirt_string[1:]
else:
tshirt_code += "1"
size_code = {"s": "1"... | 68,834 |
def get_scanloc_msg(picks_file,origins_file,origins_loc={"LOCSAT":"iasp91"},
db="sysop:sysopp@10.100.100.13/seiscomp3"):
"""
Parameters:
picks_file: str
Path of the xml picks file
origins_file: str
Path of the xml origins file
origins_loc: dict (default:{"LOCSAT":... | 68,835 |
def dates_to_epoch(d):
"""Recursively converts all dict values that are struct_times to Unix timestamps."""
for key, value in d.iteritems():
if hasattr(value, 'iteritems'):
d[key] = dates_to_epoch(value)
elif type(value) is time.struct_time:
d[key] = int(calendar.timegm(v... | 68,836 |
def perfect_numbers(n1, n2, method = 'fast'):
""" prints all the perfect numbers in [n1,n2] (n1 < n2) in
increasing fashion, using either a fast or a slow method
(default method is 'fast')
"""
if method == 'fast':
fun = is_perfect_fast
else:
fun = is_perfect_slow
for... | 68,837 |
def main():
"""
This function is called directly from command line and run the above code
"""
ap = argparse.ArgumentParser(description='Calculate the TOPSIS')
ap.add_argument('-f', '--Filepath', type=str, required=True, default = None, help='filepath of CSV file', dest='filepath')
ap.add_argumen... | 68,838 |
def get_lineage(dag_id: str, execution_date: str):
""" Get Lineage details for a DagRun """
# Convert string datetime into actual datetime
try:
execution_dt = timezone.parse(execution_date)
except ValueError:
error_message = (
'Given execution date, {}, could not be identifie... | 68,839 |
def get_release_versions(script_bool):
"""Prompt the user for the current and next release versions."""
version = vinfo['version']
if version.endswith('.dev'):
logger.info('Current development version: {0}'.format(version))
relver = version[:-4]
if not script_bool:
overri... | 68,840 |
async def send_task(writer, que):
"""Receive data from queue and send this to writer utility
Args:
writer (StreamWriter): Writer stream to write the state information
que (Queue): Send queue
Raises:
ConnectionResetError - when client gets disconnected
"""
_data = None
t... | 68,841 |
def build_log_config(level: str) -> Dict[str, Any]:
"""Build a log config from a level."""
return {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"basic": {"format": "%(asctime)s %(name)s %(levelname)s %(message)s"}
},
"handlers": {
... | 68,842 |
def sum2(n):
"""
sum of n numbers - recursion
n - unsigned
"""
if n == 0:
return 0
if n == 1:
return 1
else:
return n + sum2(n-1) | 68,843 |
def i2n(i):
"""ip to number """
ip = [int(x) for x in i.split('.')]
return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] | 68,844 |
def compute_dist_with_visibility(array1, array2, vis1, vis2, dist_type='cosine', avg_by_vis_num=True):
"""Compute the euclidean or cosine distance of all pairs, considering part visibility.
In this version, if a query image does not has some part, don't calculate distance for this part.
If a query has one p... | 68,845 |
def count_increases(report):
"""Meh
>>> count_increases([199, 200, 208, 210, 200, 207, 240, 269, 260, 263])
7
"""
return sum((1 if report[n] < report[n + 1] else 0 for n in range(len(report) - 1))) | 68,846 |
def all_qos_for_topic(topic: str):
"""Build a list of (topic, QoS) pairs that covers all quality of service levels."""
return [(topic, QOS_0), (topic, QOS_1), (topic, QOS_2)] | 68,847 |
def unumpy_to_numpy_matrix(arr):
"""
If arr in a unumpy.matrix, it is converted to a numpy.matrix.
Otherwise, it is returned unchanged.
"""
if isinstance(arr, matrix):
return arr.view(numpy.matrix)
else:
return arr | 68,848 |
def abtest_power(
group_sizes,
baseline,
alt_lift,
alpha=0.05,
null_lift=0.0,
power=score_power,
lift="relative",
):
"""Power associated with an A/B Test
Parameters
----------
group_sizes : array_like
Number of experimental units in each group.
baseline : float... | 68,849 |
def pull_docker_image(docker_client, image_location, username, password):
"""
Pulls the docker image from the ACR
:param docker_client:
:type docker_client: docker.DockerClient
:param image_location:
:type image_location: str
:param username:
:type username: str
:param passw... | 68,850 |
def get_image_creation_timestamp(client: Client, image: str, digest: str,) -> datetime:
"""
Return an image's creation timestamp.
Args:
client (Client): A client instance authenticated with a Bearer token and pointed
at version 2 of the Docker registry API.
image (str): The full... | 68,851 |
def _deconv_rl_gpu_fft(data_g, h_g, Niter=10):
"""
using fft_convolve
"""
if data_g.shape!=h_g.shape:
raise ValueError("data and h have to be same shape")
# set up some gpu buffers
u_g = OCLArray.empty(data_g.shape, np.complex64)
u_g.copy_buffer(data_g)
tmp_g = OCLArray.empt... | 68,852 |
def pretty_entry(team):
"""Formats a single team entry in a PrettyTable"""
fields = ["Property", "Value"]
table = PrettyTable(field_names=fields)
table.align = "l"
table.title = team.name + " - " + team.player_first_name + " " + team.player_last_name
for attr, value in team.__dict__.items():
... | 68,853 |
def process_spike(percent_diff):
"""
Handles a spike on the last ping that happened
Will flash with blue for 1 second
"""
global prev_state
colorWipe(strip, Color(0, 0, 255))
time.sleep(1)
cur_state = prev_state
prev_state = 10
set_internet_state(cur_state) | 68,854 |
async def test_form_image_timeout(hass, user_flow, mock_create_stream):
"""Test we handle invalid image timeout."""
respx.get("http://127.0.0.1/testurl/1").side_effect = [
httpx.TimeoutException,
]
with mock_create_stream:
result2 = await hass.config_entries.flow.async_configure(
... | 68,855 |
def has_conflicts(path):
"""Does repository at path have any conflicts?"""
global svn
changed = svn.status(path, ignore_externals=True)
for f in changed:
if f.text_status == pysvn.wc_status_kind.conflicted:
return True
return False | 68,856 |
def first_n_false_reducer(data_list, n=0, **kwargs):
"""Reduce a list of boolean values to a single boolean value.
Parameters
----------
data_list : list
A list of dicts containing a "result" key which should correspond with a
boolean value.
n: int
The first n results in `d... | 68,857 |
def echo_msmt_induced_dephasing(qubits: list, angles: list, platf_cfg: str,
wait_time: float=0):
"""
Ramsey sequence that varies azimuthal phase instead of time. Works for
a single qubit or multiple qubits. The coherence of the LSQ is measured,
while the whole list of qub... | 68,858 |
def compute_huber_loss(predictions, labels, reduction='mean', delta=None):
"""Compute the Huber loss.
Args:
predictions (tensor): a batch of point predictions.
labels (tensor): the labels, an array of shape [batch_size].
reduction (str): the method to aggregate the results across the ba... | 68,859 |
def handle_release(key: keyboard.Key):
"""The method required by the keyboard package but not used in this skill."""
pass | 68,860 |
def run_periodic_scheduler(model, log_name, handler, time_field="time", recurrence_field="recurrence"):
"""Check a model with a recurring schedule for instances that should be run in the next time period.
model: the Django model to check,
log_name: short description to include in log strings,
... | 68,861 |
def pp(xs):
"""
prints elements of a generator
one on each line
"""
for x in xs: print(x) | 68,862 |
def report_template(name, raise_error=True):
"""Evaluation report template found in ../templates/
"""
import inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
this_dir = os.path.dirname(os.path.abspath(filename))
template_file = os.path.join(this_dir, 'templates/', name)
... | 68,863 |
def get_hosted_zones():
""" list domains """
client = boto3.client("route53", region_name="us-east-1")
response = client.list_hosted_zones()
LOGGER.debug(response)
zones = response["HostedZones"]
store("zones", zones)
return zones | 68,864 |
def test_auth_login_without_username_returning_400_status_code(client):
"""
GIVEN a Flask application
WHEN the '/auth/login' URL is requested (POST) without username
THEN check the response HTTP 400 response
"""
data = {'password': "123"}
response = client.post('/auth/login',
... | 68,865 |
async def test_monthly(hass: HomeAssistant) -> None:
"""Monthly collection."""
config_entry: MockConfigEntry = MockConfigEntry(
domain=const.DOMAIN,
data={
"frequency": "monthly",
"weekday_order_number": ["2"],
"collection_days": ["fri"],
},
t... | 68,866 |
def test_grade_correct():
"""
Test grader_scripts.3.grade script.
"""
answer: dict = {
"xqueue_body": {
"student_response": """from onvif import ONVIFCamera
cam = ONVIFCamera("172.18.191.143", "80", "admin", "Supervisor")
media_service = cam.create_media_service()
profiles = media_se... | 68,867 |
def serialize(hashObject):
"""
Serializes the internal state of the hash object passed in. Calling
restore() on the serialized value afterward will return an equivalent
hash object to the one passed.
:param hashObject: The hash object to serialize.
:type hashObject: _hashlib.HASH
:returns: ... | 68,868 |
def create_app(context=None, server=None, uri=None, **kwargs):
"""
the script API execution entry point
:return: result
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app ... | 68,869 |
def generate_keys():
""" Generate a new private and public key. """
if os.path.exists(PATH_TO_PRIVATE_KEY):
raise Exception("Private key file already exists.")
bpw = get_bytes_password_new()
private_key = rsa.generate_private_key(public_exponent=PUBLIC_EXPONENT,
... | 68,870 |
def example_gdal_path(data_folder):
"""Return the pathname of a sample geotiff file
Use this fixture by specifiying an argument named 'example_gdal_path' in your
test method.
"""
return str(os.path.join(data_folder, 'sample_tile_151_-29.tif')) | 68,871 |
def test_empty_th():
"""test if input empty"""
assert th(0, '', '', '') is None | 68,872 |
def overall_accuracy(input, target):
"""Overall accuracy for batches"""
if input.is_cuda:
s = torch.FloatTensor(1).cuda().zero_()
else:
s = torch.FloatTensor(1).zero_()
for i, c in enumerate(zip(input, target)):
s = s + OverallAccuracy().forward(c[0], c[1])
return s / (i + ... | 68,873 |
def _dataset_object_metadata(dataset_object):
"""Return mapping of dataset metadata key to value.
Args:
dataset_object: ArcPy geoprocessing describe data object for dataset.
Returns:
dict.
"""
meta = {"object": dataset_object}
meta["name"] = getattr(meta["object"], "name", None... | 68,874 |
def solve_set_based(discretization,
rect_size,
obs_cpd=1):
"""
"""
disc = discretization.copy()
Q_ref = disc.get_output().get_reference_value()
simpleFunP.regular_partition_uniform_distribution_rectangle_size(
data_set=disc, Q_ref=Q_ref, rect_size=... | 68,875 |
def main():
"""Do Something"""
for (spreadkey, sheetlabel, tablename, cols) in JOB_LISTING:
do(spreadkey, sheetlabel, tablename, cols) | 68,876 |
def effective_sample_size(
weights: Iterable[float],
total_weight: Optional[float] = None,
) -> float:
"""Computes the "effective sample size" of the given weights
This value represents how "healthy" the underlying samples are. The lower
this value, the fewer "real samples" are represented. As in, ... | 68,877 |
def validate_fixity_algo(algo):
"""Validate accepted digest algorithms."""
assert algo in ["md5", "sha1", "sha256", "sha512", "blake2b-512"] | 68,878 |
def split_pair_occurrence(input_str):
"""
Q9HD36.A79T (x11) → (Q9HD36.A79T, 11)
"""
if '(x' not in input_str:
return input_str, 1
pair, occurrence = [item.strip() for item in input_str.split()]
occurrence = int(occurrence[2:-1])
return pair, occurrence | 68,879 |
def index(request):
"""Blog home page view"""
blog_settings = BlogSettings.load()
post_list = Post.get_displayable().all()
page = request.GET.get("page")
ret_dict = {
'blog_settings': blog_settings,
'posts': __get_post_page(post_list, page=page,
blo... | 68,880 |
def find_joins(df, ids, downstream_col="downstream", upstream_col="upstream", expand=0):
"""Find the joins for a given segment id in a joins table.
Parameters
----------
df : DataFrame
data frame containing the joins
ids : list-like
ids to lookup in upstream or downstream columns
... | 68,881 |
def repo():
"""Imports TFRT."""
# Attention: tools parse and update these lines.
TFRT_COMMIT = "ad09d3736c5120de1e7dba6edd0ff5eeae6b8102"
TFRT_SHA256 = "4e08e144f1e21e8597d22b9dc4c3df363e6e96be673813cb0055400bc3757020"
tf_http_archive(
name = "tf_runtime",
sha256 = TFRT_SHA256,
... | 68,882 |
def prof_area_matrix(len_profareas: pd.DataFrame, row: set):
"""
Создаём метод, который заполняет матрицу сопоставлений сфер в одной вакансии
Аргументы:
len_profareas - матрица, которую заполняет метод
row - строка в столбце со всеми сферами в исхдном датафрейме
"""
for el_1 in row:
... | 68,883 |
def velocity(sigma, xs, ys, X, Y):
"""
Generalizing the one source case:
xs, ys --> (1,)
X, Y --> (nx, ny)
sigma --> (1,)
To the several sources one:
xs, ys --> (ns, 1, 1)
X, Y --> (ns, nx, ny)
sigma --> (ns, 1, 1)
"""
sigma = np.atleast_1d(sigma)... | 68,884 |
def rate_limit(limit, period):
"""This decorator implements rate limiting."""
def decorator(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
if current_app.config['USE_RATE_LIMITS']:
# generate a unique key to represent the decorated function and
... | 68,885 |
def access_code_get_detail(transaction):
"""
GET /access-codes/1
:param transaction:
:return:
"""
with stash['app'].app_context():
access_code = AccessCodeFactory()
db.session.add(access_code)
db.session.commit() | 68,886 |
def test_cli_09_launch_bottleneck_1truck(runner, bottleneck_1truck):
"""Run: ensemble launch -s path/bottleneck_1truck.xml"""
result = runner.invoke(cli.main, ["launch", "-s", bottleneck_1truck])
f"Input File: {bottleneck_1truck} Found\n" in result.output | 68,887 |
def CheckAppId(request_trusted, request_app_id, app_id):
"""Check that this is the stub for app_id.
Args:
request_trusted: If the request is trusted.
request_app_id: The application ID of the app making the request.
app_id: An application ID.
Raises:
apiproxy_errors.ApplicationError: if this is ... | 68,888 |
def write_text(config: Config, frames: DFs, output: OutputOption,
method: str) -> None:
"""Write a group of of memory usage data frames as human-readable text."""
with open_output(config, output) as out:
sep = ''
for df in frames.values():
print(end=sep, file=out)
... | 68,889 |
def get_sketch_details(sketch_id: Optional[int] = 0) -> Text:
"""Return back details about an existing sketch.
Args:
sketch_id (int): the sketch ID to check.
Returns:
string containing information about the sketch.
"""
sketch = None
state_obj = state.state()
if not sketch_id:
sketch = state... | 68,890 |
def finder_for_path(path):
"""
Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path.
"""
result = None
# calls any path hooks, gets importer into cache
pkgutil.get_importer(path)
load... | 68,891 |
def dataProcessing(data_x, data_y, batch_size, training_ratio, validation_ratio,
FM_indices, bool_norm=False):
"""
Data preprocessing.
Parameters:
----------
data_x: 2D Array (nDOF x SampleNum).
The deformation data (x SampleNum) of all DOFs.
d... | 68,892 |
def ten_interp(x, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9):
"""``Approximation degree = 10``
"""
return (
a0
+ a1 * x
+ a2 * (x ** 2)
+ a3 * (x ** 3)
+ a4 * (x ** 4)
+ a5 * (x ** 5)
+ a6 * (x ** 6)
+ a7 * (x ** 7)... | 68,893 |
def force_implementation(modname):
"""Forces anyjson to use a specific json module if it's available"""
global implementation
for name, spec in [(e[0], e) for e in _modules]:
if name == modname:
implementation = _JsonImplementation(spec)
return
raise ImportError("No modul... | 68,894 |
def mock_interface_settings_match(mock_interface_settings):
"""
Fixture that yields mock USB interface settings that is the correct USB class, subclass, and protocol.
"""
mock_interface_settings.getClass.return_value = libusb.USB_DEVICE_CLASS
mock_interface_settings.getSubClass.return_value = libusb... | 68,895 |
def multinomial_naive_bayes_inference(X, W, b):
"""Multinomial naive Bayes classifier inference.
Parameters
----------
X : ndarray, shape (m, n)
input features (one row per feature vector).
W : ndarray, shape (n, k)
weight vectors, each row representing a different class.
b : ... | 68,896 |
def parse_bibtex_entry(entry, pub_dir='publication', featured=False, overwrite=False, normalize=False):
"""Parse a bibtex entry and generate corresponding publication bundle"""
verbose = False
print(f"Parsing entry {entry['ID']}") if verbose else None
bundle_path = f"content/{pub_dir}/{slugify(entry['I... | 68,897 |
def sort_dist_matrix(mat, row_col_names):
"""
sort the distance matrix by seg_id_nat
:return:
"""
df = pd.DataFrame(mat, columns=row_col_names, index=row_col_names)
df = df.sort_index(axis=0)
df = df.sort_index(axis=1)
sensor_id_to_ind = {}
for i, sensor_id in enumerate(df.c... | 68,898 |
def is_complete(step, lst):
"""
Check required field of question for complete state
Required: question is always require user response to be complete
Conditional: Optional question needed depends on reveal_response value of conditional_target.
"""
if not lst:
return False, []
questio... | 68,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.