content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mat_list_to_rf_array(mats_list: list) -> (np.ndarray, dict):
"""Make an RF array from a list of mats"""
rf_array = np.array(
[open_rf(x) for x in mats_list]
)
parameters = open_parameters(mats_list[0])
return rf_array, parameters | 5,318,300 |
def writediffproperties(ctxs, diff):
"""write metadata to diff so patches could be applied losslessly
``ctxs`` is the list of commits that created the diff, in ascending order.
The list is generally a single commit, but may be several when using
``phabsend --fold``.
"""
# creatediff returns wit... | 5,318,301 |
def issue_shutdown_log_entry(func_name: str,
req_time: ReqTime,
log_ver: Optional[LogVer] = None) -> None:
"""Log the shutdown progress message.
Args:
func_name: name of function for log message
req_time: number of requests and time
... | 5,318,302 |
def _AddClearExtensionMethod(cls):
"""Helper for _AddMessageMethods()."""
def ClearExtension(self, extension_handle):
self.Extensions._ClearExtension(extension_handle)
cls.ClearExtension = ClearExtension | 5,318,303 |
def show_options(last_row):
"""
Show the options. The user can choose what to do.
last_row: the last row in the worksheet (list).
"""
while True:
choose = input('What to do? (Q)uit/(L)ist/(N)ew [N]: ')
if choose is '' or choose.lower()[0] is 'n':
return True
eli... | 5,318,304 |
def is_pilot_snipe(sortie):
"""
A pilot snipe is when a plane goes down because the pilot gets killed, and not because the aircraft is crtically
damaged. Currently, in the logs, a pilot snipe looks rather similar to a normal death. Even in a pilot snipe,
the logs think the aircraft gets shotdown before ... | 5,318,305 |
def test_generate_oob_info():
"""
test generate_oob_info
basic tests - just check structure
"""
n_obs_class = 100
X_trained = np.concatenate(
(np.random.normal(loc = (1,2), scale = .6, size = (n_obs_class,2)),
np.random.normal(loc = (-1.2, -.5), scale = .6, size = (n_obs_class,2... | 5,318,306 |
def rouge_log(results_dict, dir_to_write):
"""Log ROUGE results to screen and write to file.
Args:
results_dict: the dictionary returned by pyrouge
dir_to_write: the directory where we will write the results to"""
log_str = ""
for x in ["1", "2", "l"]:
log_str += "\nROUGE-%s:\n" % x... | 5,318,307 |
def stim_swap(idx, i):
"""
Stim swap takes 'idx' which is the stim index % 8 and 'i' which is the actual stim idx
and then deletes the one at 'idx' and replaces it with the stim at i so that
neuroGPU reads stims like 13 as stim_raw5 (13 % 8)
"""
old_stim = '../Data/Stim_raw' + str(idx) + '.csv'... | 5,318,308 |
def merge_meta(meta: dict) -> dict:
"""
merge data for api: get meta config.
"""
modules = meta.pop(CONFIG_MODULE)
_meta = {meta.pop(CONFIG_NAME): meta}
for meta_name, detail in modules.items():
if SOURCE_META in detail.keys():
# meta config
file_path = os.getcwd(... | 5,318,309 |
def load_messages(language):
"""Load translation messages for given language from all `setup_wizard_requires`
javascript files"""
frappe.clear_cache()
set_default_language(get_language_code(language))
frappe.db.commit()
m = get_dict("page", "setup-wizard")
for path in frappe.get_hooks("setup_wizard_requires"):
... | 5,318,310 |
def change_lang(request):
"""
Change current documentation language.
"""
lang = request.GET.get('lang_code', 'en')
response = redirect('/')
portal_helper.set_preferred_language(request, response, lang)
return response | 5,318,311 |
def test_markup_dunder_methods(sn):
"""Verifies __str__ and __repr__ do not cause errors."""
script = get_script("markup_template_anchor.sql")
markup = script.doc()
assert str(markup)
assert repr(markup) | 5,318,312 |
def cleanHtml(sentence):
"""
remove all Html canvas from the sentence
:param sentence {str} sentence
:return:
{str}: sentence without html canvas
"""
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, ' ', str(sentence))
return cleantext | 5,318,313 |
def simple_decoder_fn_train(encoder_state, name=None):
""" Simple decoder function for a sequence-to-sequence model used in the
`dynamic_rnn_decoder`.
The `simple_decoder_fn_train` is a simple training function for a
sequence-to-sequence model. It should be used when `dynamic_rnn_decoder` is
in the training ... | 5,318,314 |
def test_id_case_sensitivitiy():
"""Test that uids are case insensitive."""
with pytest.raises(ValueError):
IngredientRun(uids={'my_id': 'sample1', 'My_ID': 'sample2'})
ingredient = IngredientRun(uids={'my_id': 'sample1'})
assert ingredient.uids['my_id'] == 'sample1'
assert ingredient.uids[... | 5,318,315 |
def handle_command_line():
"""Parse the command line."""
commands = scan_for_commands()
parser = argparse.ArgumentParser(
description="A set of utilities to ease the installation of Modoboa.",
epilog="""Available commands:
%s
""" % "\n".join(["\t%s" % c for c in sorted(commands)]))
parse... | 5,318,316 |
def explain_point_local(data_row, neighbors, oversampled_data, model_features, categorical_features, numeric_features, budget=999, show_pos_neg = False):
"""
Provides explanations on each point in the selected subset for local explanations.
Parameters:
-----------------
data_row: integer, the i... | 5,318,317 |
def pots_scan(n_src, ele_lims, true_csd_xlims,
total_ele, ele_pos, R_init=0.23):
"""
Investigates kCSD reconstructions for unitary potential on different
electrodes
Parameters
----------
n_src: int
Number of basis sources.
ele_lims: list
Boundaries for electrod... | 5,318,318 |
def add_nav_entry(mkdocs_settings, nav_entry: NavEntry) -> Any:
"""
Add an additional entry to the Nav in mkdocs.yml
Args:
mkdocs_settings (): The mkdocs settings to update.
nav_entry (NavEntry): The NavEntry to add
Returns:
The updated mkdocs_settings
"""
mkdocs_settin... | 5,318,319 |
def main():
"""
Build html from specified files, using pweave.
"""
# Get the pweave files from the source directoy :
files = [f for f in os.listdir("src/") if f[-4:] == ".pmd"]
for f in files:
pweave.publish(
os.path.join("src", f),
output = os.path.joi... | 5,318,320 |
def is_guid(value):
"""
проверяет на наличие только [a-zA-z/-]
"""
if re.match("^[A-Za-z0-9_-]*$", value):
return value
return None | 5,318,321 |
def load_scikit_learn_model(model_uri):
"""
Load a scikit-learn model from a local file.
:param model_uri: The location, in URI format, of the aiflow model, for example:
- ``/Users/aiflow/path/to/local/model``
- ``relative/path/to/local/model``
... | 5,318,322 |
def epimorphism_in_laurent(tri, angle, cycles, ZH):
"""
The argument cycles specifies a group epimorphism from the
manifold to the filled manifold. This function returns the image
of the generators of the group ring under the induced epimorphism.
"""
n = tri.countTetrahedra()
S,U,V = faces_... | 5,318,323 |
def merge_config(a, b):
"""Merges config b in a."""
for key, b_value in b.items():
if not isinstance(b_value, dict):
a[key] = b_value
else:
a_value = a.get(key)
if a_value is not None and isinstance(a_value, dict):
merge_config(a_value, b_value... | 5,318,324 |
def tsi_moving_average(df, periods=7):
"""Function calculating Moving Average (MA) for TSI
Args:
df (pandas.DataFrame): Quotes with TSI values
periods (int, optional): The number of periods from which MA is calculated. Defaults to 7.
Returns:
pandas.DataFrame: Quotes extended by th... | 5,318,325 |
def test_redirect(strategy, https_server, https_client, tctx, monkeypatch):
"""Test redirects between http:// and https:// in regular proxy mode."""
server = Placeholder(Server)
flow = Placeholder(HTTPFlow)
tctx.options.connection_strategy = strategy
p = Playbook(http.HttpLayer(tctx, HTTPMode.regula... | 5,318,326 |
def fit_index(dataset, list_variables):
""" Mapping between index and category, for categorical variables
For each (categorical) variable, create 2 dictionaries:
- index_to_categorical: from the index to the category
- categorical_to_index: from the category to the index
Parameters
---... | 5,318,327 |
def test_single_condition_not_equal_datetime(df, right):
"""Test output for a single condition. "!="."""
assume(not df.empty)
assume(not right.empty)
# simulate output as it would be in SQL
left_on, right_on = ["E", "Dates"]
expected = (
df.assign(t=1)
.merge(right.assign(t=1), o... | 5,318,328 |
def decisionRule():
"""Decide whether to buy, sell, or hold."""
pass | 5,318,329 |
def test_language_max_length003_1426_language_max_length003_1426_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=maxLength and value=6 and
document value=en-xx
"""
assert_bindings(
schema="msData/datatypes/Facets/language/language_maxLength003.xsd",
in... | 5,318,330 |
def theoretical_motion(input, g):
"""
Compute the theoretical projectile motion.
Args:
input: ndarray with shape (num_samples, 3) for t, v0_x, v0_z
g: gravity acceleration
Returns:
theoretical motion of x, z.
"""
t, v0_x, v0_z = np.split(input, 3, axis=-1)
x = v0_x ... | 5,318,331 |
def list_analyses() -> List[str]:
"""Get a list of all supported analyses."""
response = requests.get(_url("/info/analyses"))
assays = response.json()
return assays | 5,318,332 |
def applyAlign(mrt,al):
"""
Takes meaning representation triples (mrt) and combines with alignments
"""
for alignment in al.split():
# Alignment: x9:arg0:sell:x11-39
fromNode,rest = alignment.split(":",1)
rest,toAlign = rest.rsplit("-",1)
edgeLabel,toNode ... | 5,318,333 |
def get_unverified_jwt_claims(encoded_token):
"""
Returns the Headers of an encoded JWT without verifying the actual signature of JWT.
Note: The signature is not verified so the header parameters
should not be fully trusted until signature verification is complete
:param encoded_token: The encode... | 5,318,334 |
def dos_orbitals(
folder,
orbitals,
output='dos_orbitals.png',
fill=True,
alpha=0.3,
linewidth=1.5,
sigma=0.05,
energyaxis='x',
color_list=None,
legend=True,
total=True,
figsize=(4, 3),
erange=[-6, 6],
spin='up',
soc_axis=None,
combination_method='add',
... | 5,318,335 |
def get_free_energy_single(
free_energy: Union[str, FreeEnergyBase] = "ginzburg-landau"
) -> FreeEnergyBase:
"""get free energy for systems with a single effective component
Args:
free_energy (str or FreeEnergyBase):
Defines the expression to used for the local part of the free energy
... | 5,318,336 |
def unbuffered_input():
"""Read a single character from stdin, without waiting for the enter key."""
# Adapted from http://code.activestate.com/recipes/134892/
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setcbreak(fd)
ch = sys.stdin.read(1)
finally:
... | 5,318,337 |
def convert_bin_to_text(bin_str: str) -> str:
"""Convert a string of binary to text.
Parameters:
-----------
bin_str:
string: A string of binary, terminating with 00000000.
Returns:
--------
text:
string: A plaintext representation of the binary string.
"""
# get nu... | 5,318,338 |
def _retrieve_transaction_type(t_type: str, connection) -> RowProxy:
""" Retrieves Transaction Type
Args:
ttype (str): The transaction type that represents the trasaction being recorded 'archive' or 'compress'.
Returns:
RowProxy: The transaction_type
"""
transaction = sele... | 5,318,339 |
def myDijkstra(graph, source, start, end):
"""
Implements Dijkstra's single source shortest path algorithm
for a directed graph
Parameters:
graph: the graph we are working on
source (int): the vertex choose as source
start (strin... | 5,318,340 |
def scale_on_x_list(x_list, scaler):
"""Scale list of ndarray.
"""
return [scaler.transform(e) for e in x_list] | 5,318,341 |
def get_centernet(backbone,
backbone_out_channels,
classes,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create CenterNet mode... | 5,318,342 |
def calc_distance(origin, destination):
"""
title::
calc_distance
description::
Great-circle distance between two points on a sphere from their longitudes
and latitudes.
author::
Stackoverflow User: user2514381
https://stackoverflow.com/questions/1727312... | 5,318,343 |
def tokenize(string,tokenizer = tokenizers.keras):
"""
Tokenizes a string using the selected tokenizer.
:param string: the string to tokenize
:param tokenizer: which tokenizer to use (nltk or keras)
:return: the list of tokens
"""
if tokenizer == tokenizers.nltk:
return nltk.word_to... | 5,318,344 |
def move_point(pt: XY, distance: float, degrees: float) -> XY:
"""
Create a new point that is the original point moved by distance (m) in direction degrees.
"""
x = pt.x + distance * math.cos(math.radians(degrees))
y = pt.y + distance * math.sin(math.radians(degrees))
return XY(x, y) | 5,318,345 |
def _generate_follow_up(the_date, vms, template='delete_followup.html'):
"""Create the HTML email body stating what VMs were randomly deleted.
:Returns: String
:param the_date: The specific time when vLab randomly deleted a user's VM(s).
:type the_date: Integer
:param vms: The names of the VM(s) ... | 5,318,346 |
def move_to_end_of_word(tab: apitypes.Tab, count: int = 1) -> None:
"""Move the cursor or selection to the end of the word.
Args:
count: How many words to move.
"""
tab.caret.move_to_end_of_word(count) | 5,318,347 |
def find_empty_node(grid):
"""There should be one and only one empty node. Find it
and return its location as a tuple."""
for x in range(len(grid)):
row = grid[x]
for y in range(len(row)):
if row[y][USED] == 0:
return (x, y)
# else:
# p... | 5,318,348 |
def md5(ori_str):
""" MD5加密算法
:param ori_str: 原始字符串
:return: 加密后的字符串
"""
md5_obj = hashlib.md5()
md5_obj.update(ori_str.encode("utf8"))
return md5_obj.hexdigest() | 5,318,349 |
def getuser() -> str:
"""
Get the username of the current user.
Will leverage the ``getpass`` package.
Returns:
str: The username of the current user
"""
import getpass
return getpass.getuser() | 5,318,350 |
def order_depth(type_id: int, region_id: int = 10000002, system_id: int = None, order_type: str = 'sell'):
"""
Pulls the orders for a specified typeid in a region
Args:
type_id: typeid to pull the market orders for
region_id: the region the orders should be pulled from. the default region_i... | 5,318,351 |
def get_normal_amps():
"""This parameter will deliver the normal ampere rating for the active PDElement."""
return dsslib.CktElementF(ctypes.c_int32(0), ctypes.c_double(0)) | 5,318,352 |
def cal_pipe_equivalent_length(tot_bui_height_m, panel_prop, total_area_module):
"""
To calculate the equivalent length of pipings in buildings
:param tot_bui_height_m: total heights of buildings
:type tot_bui_height_m: float
:param panel_prop: properties of the solar panels
:type panel_prop: di... | 5,318,353 |
def embedding_to_padding(maxlen, sequence_length):
""" Calculates the padding mask based on `sequence_length`.
Args:
maxlen: The maximum sequence length.
sequence_length: Length of each sequence in `emb`,
a Tensor with shape [batch_size, ]
Returns: A float Tensor with shape [bat... | 5,318,354 |
def csv_fat_cross_time(arrival_enum: ArrivalEnum,
list_number_servers: List[int],
perform_param: PerformParameter, opt_method: OptMethod,
mc_dist: MonteCarloDist, target_util: float) -> dict:
"""Chooses parameters by Monte Carlo type random choice... | 5,318,355 |
def cmd(msg: str = "") -> None:
"""
コマンド
"""
result = generator(msg)
pyperclip.copy(result)
click.echo(result) | 5,318,356 |
def service_status() -> Response:
"""
Service status endpoint.
Returns ``200 OK`` if the service is up and ready to handle requests.
"""
data, code, headers = controllers.service_status(request.params)
response: Response = jsonify(data)
response.status_code = code
response.headers.exten... | 5,318,357 |
def test_config_via_env_var(cli, ckan_config):
"""CliRunner uses test config automatically, so we have to explicitly
set CLI `-c` option to `None` when using env `CKAN_INI`.
"""
result = cli.invoke(ckan, [u'-c', None, u'-h'],
env={u'CKAN_INI': ckan_config[u'__file__']})
asse... | 5,318,358 |
def nfvi_guest_initialize(config, pool):
"""
Initialize the NFVI Guest package
"""
global _guest_plugin
_guest_plugin = NFVIGuestPlugin(config['namespace'], pool)
_guest_plugin.initialize(config['config_file']) | 5,318,359 |
def init_instance_matlab():
"""
This function must be called at least once before using any Matlab function
:return:
"""
if not os.path.exists(matlab_wrapper_temp_folder):
os.makedirs(matlab_wrapper_temp_folder)
global matlab_eng, matlab_io_out, matlab_io_err
# configure Matlab in... | 5,318,360 |
def handler500(request, exception=None, template_name='templates/500.html'):
"""500 Error Page Controller"""
controller = Controller()
helpers = Helpers()
logger = helpers.get_logger(__name__)
if exception is not None:
logger.error("Server Error: %(exception)s" % {
"exception":... | 5,318,361 |
def gromov_wasserstein2(C1, C2, p, q, loss_fun, epsilon,
max_iter=1000, tol=1e-9, verbose=False, log=False):
"""
Returns the gromov-wasserstein discrepancy between the two measured similarity matrices
(C1,p) and (C2,q)
The function solves the following optimization probl... | 5,318,362 |
def parseOptions(json_options):
"""Parse the raw son options.
Parses the parameter values into ranges and adds missing information
that can be inferred from other values.
Returns parsed options as dictionary"""
parsed = dict(json_options)
if "algorithms" in json_options:
algori... | 5,318,363 |
def numeric_type(num):
""" Verify that a value is given as a numeric data type.
Return the number if the type is sensible or raise ValueError
if not.
"""
if num is None:
num = 0
elif not (isinstance(num, int) or \
isinstance(num, long) or \
isinstance... | 5,318,364 |
def compute_rhs(state, t, dstate):
"""Compute deltas for b, u, U and update p.
The deltas for b, u, U are saved in dstate, while the updated p is
saved in state. The time t has currently no influence. The
contravariant velocity U is handled like a prognostic variable,
because its delta is a by-pr... | 5,318,365 |
async def load(payload: None, context: EventContext, *,
item_id: str, update_status: bool = False) -> Union[Something, SomethingNotFound]:
"""
Loads json file from redis as `Something` instance
:param payload: unused
:param context: EventContext
:param item_id: str, item id to load
... | 5,318,366 |
def log_exception(method: str, exception: Exception):
"""
Logs the given exception to the log.
:params method: The method name where the exception is raised.
:params exception: The exception to be logged.
"""
logging.error(
"Exception raised from %s: %s",
method,
excepti... | 5,318,367 |
def format_parameters(section):
"""Format the "Parameters" section."""
def format_item(item):
item = map(lambda x: x.strip(), item)
return ' - **{0}**: *{1}*\n {2}'.format(*item)
return '**Parameters**\n\n{0}'.format('\n\n'.join(
map(format_item, section))) | 5,318,368 |
def get_kinds(cell, mf, kpts, tol=1e-6):
"""Given a list of kpts, return inds such that mf.kpts[inds] is a list of kpts equivalent to the input list"""
kdiffs = mf.kpts[np.newaxis] - kpts[:, np.newaxis]
frac_kdiffs = np.dot(kdiffs, cell.lattice_vectors().T) / (2 * np.pi)
kdiffs = np.mod(frac_kdiffs ... | 5,318,369 |
def set_config_ip_delimiter_semicolon():
"""set config"""
# change config
system_importer_file_csv_config_model = (
SystemImporterFileCsvConfigModel.objects.get(
system_importer_file_csv_config_name='SystemImporterFileCsvConfig'
)
)
system_importer_file_csv_config_model.... | 5,318,370 |
def mock_config_file_for_lock() -> Iterator[Tuple[Configuration, str]]:
"""A pytest fixture that creates a temporary directory and a config file for testing locking"""
overrides = {
"lock": {
"timeout": 5
}
}
config_instance, working_dir = _create_temp_work_dir(override_dict=... | 5,318,371 |
def test_w_shortchut(vim_bot):
"""Test w command (Cursor moves to the next word)."""
main, editor_stack, editor, vim, qtbot = vim_bot
editor.stdkey_backspace()
editor.moveCursor(QTextCursor.PreviousWord, QTextCursor.KeepAnchor)
qtbot.keyPress(editor, Qt.Key_Left)
cmd_line = vim.get_focus_widget(... | 5,318,372 |
def restore_checkpoints(
models: List[tf.keras.Model], ckpt_dir: str) -> tf.keras.Model:
"""Restores weights from the checkpoint."""
attr_names = list(ATTRIBUTES.keys())
for i in range(2):
attr_name = attr_names[i]
print("Restoring weights for attribute %s" % attr_name)
ckpt_path... | 5,318,373 |
def get_schema_piece(content_piece, uniprot_to_dcid):
"""Generate each
Args:
content_piece example:
AAC ABCD_AU181
BIT Nanobody
AID anti-SARS-CoV-2 Nb
TTY Protein
TGP UniProt:P0DTC2
TDE S, Spike protein, Spike glycoprotein
TPE Receptor-bindi... | 5,318,374 |
def editViewData(uniqueValue):
"""Edit the source service data for the current unique value"""
# Create a copy from the source service data
uniqueValueData = copy.deepcopy(_sourceServiceData)
# Change service data to use current unique value information (assumes a string value )
uniqueValueData["l... | 5,318,375 |
def _add_dll_dir():
"""
On windows for Python 3.8 or later, we have to add the bin directory to the search path for DLLs
Because python will no longer use the PATH environment variable to find dlls.
We assume here that this file is in $(RELEASE_DIR)\lib\python\htcondor and that the
bin directory is ... | 5,318,376 |
def _borg_pod_set_with_safe_self_access(wrapped_method):
"""
Wrapper for __setattr__ methods in @assimilate decorated classes to apply self.queen injection wrapper on any
relevant instance methods set during runtime.
:param Function wrapped_method: A @assimilate decorated class's __setattr__ method... | 5,318,377 |
def prepend(catch: Union[type, tuple[type]], *values: Iterable[Union[Any, Iterable[Any]]]):
"""
Return a context manager that catches exception(s), prepends value(s) to the exception's
message (first argument) and reraises the exception.
Parameters:
• catch: exception class or classes to catch
... | 5,318,378 |
def test_return_category_list():
"""Test that categories can be returned"""
result = False
category_obj = prism.Categories(api_client=_api())
categories = category_obj.get_categories()
if categories:
result = True
assert not result | 5,318,379 |
def stop():
"""Stops the application"""
session = session_manager.get_session()
if session['user'].is_admin:
# http_view.controller.stop(from_bottle=True)
sys.stderr.close() | 5,318,380 |
def test_start_with_description_as_multiple_params(cli, entries_file):
"""
Description can either be entered as a single quoted param or as multiple params, in which case it will be joined
with space characters.
"""
expected = """20/01/2014
alias_1 09:00-? Play ping-pong
"""
with freeze_time('... | 5,318,381 |
def sha256(message):
"""
Returns the hexadecimal representation of the SHA256 hash digest.
"""
return hashlib.sha256(to_bytes(message)).hexdigest() | 5,318,382 |
def _grouprule_aggs_filter(having, columns):
"""
Given (having) conditions, return what to filter on as a string, to be used
after groupbys as grouped.query(string returned by this function).
:param having:
:type having: list
:param columns: Columns on which the group by is made.
:type colu... | 5,318,383 |
def clean(c, docs=False, bytecode=False, extra=""):
"""Clean up stuff from previous builds"""
print(" Cleaning ".center(80, "="))
patterns = ["dist", "build", "cellpy.egg-info"]
if docs:
print(" - cleaning doc builds")
patterns.append("docs/_build")
if bytecode:
print(" - cle... | 5,318,384 |
def test_search_by_string_ss_fallback_success(
address_string_request, smarty_streets_response, google_geocode_response_no_zip9
):
"""Search by string; Google doesn't return zip9; no address match; smartystreets fallback finds zip9; find match"""
precinct = baker.make("app.Precinct")
ztp = baker.make("... | 5,318,385 |
def _trim(s):
""" Trim long string to LOG_ENTRY_MAX_STRING(+3) length """
return s if not isinstance(s, str) or len(s) < LOG_ENTRY_MAX_STRING else s[:LOG_ENTRY_MAX_STRING] + '...' | 5,318,386 |
def get_id_or_name(value, model):
"""Returns the id or name of a model instance from value. If a number or a
string is supplied, a check will be made to make sure it exists in the
data store.
"""
if not issubclass(model, db.Model):
raise TypeError('Invalid type (model); expected subclass of ... | 5,318,387 |
def validate_query_handler(query_string):
"""Verify the input query is some level of valid, right now it does not
check the value sent, just the key.
Currently only support one key, value pair -- but does verify this is
supplied."""
# likely throws an exception on parse error.
query_dict = p... | 5,318,388 |
def makevalue(t, value):
"""Get value of ctypes-compatible value in XDWAPI-compatible type."""
t = XDW_ATTRIBUTE_TYPE.normalize(t)
if t == XDW_ATYPE_INT:
return int(value)
elif t == XDW_ATYPE_STRING:
return str(value)
elif t == XDW_ATYPE_DATE:
return datetime.date.fromtimesta... | 5,318,389 |
def parse_directive_definition(
directive_definition_node: "DirectiveDefinitionNode",
schema: "GraphQLSchema",
) -> Optional["GraphQLDirective"]:
"""
Computes an AST directive definition node into a GraphQLDirective instance.
:param directive_definition_node: AST directive definition node to treat
... | 5,318,390 |
def light_type_property_test(light_type, light_properties, light_component_id_pair, light_entity_name, light_entity):
"""
Updates the current light type and modifies its properties, then verifies they are accurate to what was set.
:param light_type: The type of light to update, must match a value in LIGHT_T... | 5,318,391 |
def _find_literal(s, start, level, parts, exprs):
"""Roughly Python/ast.c:fstring_find_literal"""
i = start
parse_expr = True
while i < len(s):
ch = s[i]
if ch in ("{", "}"):
if level == 0:
if i + 1 < len(s) and s[i + 1] == ch:
i += 2
... | 5,318,392 |
def setfirstaxislabel(td, axis, title=True):
"""
set up the label on an axis; despite the name, you can use
this for the second axis, too, just set title=False if you
set the title with the first axis
input: trackdata object; axis object; flag to set title
output: none (formats axis)
"... | 5,318,393 |
def evaluate(ref_intervals, ref_labels, est_intervals, est_labels, **kwargs):
"""Compute all metrics for the given reference and estimated annotations.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels)... | 5,318,394 |
def parse_arguments():
"""Arguments parsing."""
parser = argparse.ArgumentParser("my_agent", description="Launch my agent.")
parser.add_argument("--name", default="my_agent", help="Name of the agent")
parser.add_argument(
"--oef-addr", default="127.0.0.1", help="TCP/IP address of the OEF Agent"
... | 5,318,395 |
def custom_base85_encode(fi):
"""
Encode selected region with custom base85 table
"""
standard_table = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"
offset = fi.getSelectionOffset()
length = fi.getSelectionLength()
if length > 0:
... | 5,318,396 |
def amex(value):
"""
Return whether or not given value is a valid American Express card number.
Examples::
>>> amex('378282246310005')
True
>>> amex('4242424242424242')
ValidationFailure(func=amex, args={'value': '4242424242424242'})
.. versionadded:: 0.15.0
:par... | 5,318,397 |
def to_day_of_year(self):
"""Check toDayOfYear() function with DateTime64 extended range date time."""
to_day_of(py_func="tm_yday", ch_func="toDayOfYear") | 5,318,398 |
def rel_multihead_attn(q, k, v, pos_enc, seg_mat, attn_mask, d_model, n_head,
d_head, dropout, dropatt, is_training, initializer,
attn_bias=None, func_mask=None, scope="rel_attn",
reuse=None, rel_attn_type="factorized",
name='rel_attn'):
"""Multi-head attention with rel... | 5,318,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.