content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def transformer_decoder_layers(name,
n_layers,
decoder_input,
**kwargs):
"""A transformation block composed of transformer decoder layers."""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
hparams = kwargs["hparams"... | 5,314,500 |
def group_filenames(filenames):
"""Given a list of JWST filenames, group together files from the
same exposure. These files will share the same ``program_id``,
``observation``, ``visit``, ``visit_group``, ``parallel_seq_id``,
``activity``, ``exposure``, and ``suffix``. Only the ``detector``
will be ... | 5,314,501 |
def main():
"""Make a jazz noise here"""
args = get_args()
random.seed(args.seed)
# new_text = ''
# for char in args.text:
# new_text += choose(char)
# print(''.join([choose(char) for char in args.text]))
print(''.join(map(choose, args.text))) | 5,314,502 |
def check_can_unpublish_activity(user, activity_rights):
"""Checks whether the user can unpublish given activity.
Args:
user: UserActionsInfo. Object having user_id, role and actions for
given user.
activity_rights: ActivityRights or None. Rights object for the given
act... | 5,314,503 |
def gql_add_user_attendance(time: str, user_id: int = None, date: str = None, attendance_id: int = None,
is_clock_in: bool = True, comment: str = None):
"""
GQL mutation to insert/update attendance
:param time: time string in HH:MM:SS format
:param user_id: unique user id
... | 5,314,504 |
def _convert_json_to_binary(document, output_filename):
""" converting the split sections of json filenames to
binary for training and storing in output file """
with open(output_filename, 'ab') as out_file:
# extracting body and abstract out of document.
body = document['body']
... | 5,314,505 |
def make_pipeline(steps, params):
"""
Args:
steps (dict): (name, module_name, method_name) Tuples to specify steps of the pipeline to fit.
params (dict): string -> object. Parameters passed to the fit method of
each step, where each parameter name is ... | 5,314,506 |
def format_fields(field_data, include_empty=True):
"""Format field labels and values.
Parameters
----------
field_data : |list| of |tuple|
2-tuples of field labels and values.
include_empty : |bool|, optional
Whether fields whose values are |None| or an empty |str| should
be... | 5,314,507 |
def loadDecomposition(name):
"""Load a tree decomposition in the PACE-2016 format"""
B = 0 # number of bags
TW = 0
Bags = []
f = open(name, "r")
lines = f.readlines()
for l in lines:
s = l.split()
if len(s) < 1:
continue
if s[0] == "c":
cont... | 5,314,508 |
def testing_report():
""" Testing Site Daily Summary Report: RESTful CRUD Controller """
return crud_controller() | 5,314,509 |
def virtual_network_present(
name,
address_prefixes,
resource_group,
dns_servers=None,
tags=None,
connection_auth=None,
**kwargs
):
"""
.. versionadded:: 2019.2.0
Ensure a virtual network exists.
:param name:
Name of the virtual network.
:param resource_group:
... | 5,314,510 |
def parse_config_yaml(current_config, first_run=False):
"""This function parses the configuration values contained in the
configuration dictionary obtained by reading the YAML file."""
config_options = current_config
used_options = {}
if config_options is None:
return validate_config(
... | 5,314,511 |
def acf(x, length=20):
""" Compute autocorrelation. """
return np.array([1] + [np.corrcoef(x[:-i], x[i:])[0,1] for i in range(1, length)]) | 5,314,512 |
def normalizeInfinity(a):
"""
Normalize array a so that the maximum absolute value is 1.
Parameters
----------
a : ndarray of float
The array to be normalized.
Returns
-------
ndarray of float, same shape as a
The normalized array.
"""
return a / xplib.xp.ma... | 5,314,513 |
def getConfigPath():
"""
Returns the config location (either default or user defined)
"""
global args, ConfigPathDefault
if args.config_location:
return args.config_location
return ConfigPathDefault | 5,314,514 |
def only_bf(txt):
""" Strip a string from all characters, except brainfuck chars """
return re.sub(r"[^\.,<>\+-\]\[]", "", txt) | 5,314,515 |
def test_bad_value_cases(task, bad_value_cases):
""" Test configs with invalid values.
Args:
task (dict): A task config dict. task['config'] will be overwritten.
bad_value_cases (list(tuple)): List of tuples of the form ('config_name', config), where config
contains a key:value pair... | 5,314,516 |
def run_hidef_cmd(cmd):
"""
Runs hidef command as a command line process
:param cmd_to_run: command to run as list
:type cmd_to_run: list
:return: (return code, standard out, standard error)
:rtype: tuple
"""
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
... | 5,314,517 |
def create_ice_connection(user_token):
"""Creates an instance of the ICE API using common settings."""
# Use getattr to load settings without raising AttributeError
key_id = getattr(settings, "ICE_KEY_ID", None)
url = getattr(settings, "ICE_URL", None)
verify = getattr(settings, "ICE_VERIFY_CERT", F... | 5,314,518 |
def make_uris(sids, start, end):
"""Make the URIs for all stations
Args:
sids (list): List of IACO station identifiers (str)
start (str): Starting date in YYYY-mm-dd
end (str): ending date in YYYY-mm-dd
Returns:
a list of URIs, one for each dataset
"""
service = BAS... | 5,314,519 |
def is_valid_slack_app(qs):
"""
Checks to see if the request is being made by a valid Slack app.
"""
data = parse_qs(qs)
return safe_list_get(data["api_app_id"], 0) == os.environ.get("SLACK_APP_ID") | 5,314,520 |
def sr_inverse_org(J, k=1.0):
"""Return SR-inverse of given J
Definition of SR-inverse is following.
:math:`J^* = J^T(JJ^T + kI_m)^{-1}`
Parameters
----------
J : numpy.ndarray
jacobian
k : float
coefficients
Returns
-------
sr_inverse : numpy.ndarray
... | 5,314,521 |
def get_vectors(mols):
"""
Get the vectors for a given molecule
:param mols: the Django molecules to get them from
:param target: the Django target to record them from
:return: None
"""
vect_types = VectTypes()
for mol in mols:
if "." in mol.smiles:
print("SKIPPING - ... | 5,314,522 |
def get_embeddingset(veclist, textlist):
"""gets a whatlies.embeddingset from the encoding given by the language model
Args:
veclist (numpy.ndarray): ndarray of all encodings
textlist (list): vector of encoded texts
Returns:
whatlies.EmbeddingSet: whatlies EmbeddingSet for easier t... | 5,314,523 |
def render_quoted_form(compiler, form, level):
"""
Render a quoted form as a new hy Expression.
`level` is the level of quasiquoting of the current form. We can
unquote if level is 0.
Returns a two-tuple (`expression`, `splice`).
The `splice` return value is used to mark `unquote-splice`d for... | 5,314,524 |
def get_index_portfolio_deposit_file(date: str, ticker: str) -> list:
"""지수구성종목을 리스트로 반환
Args:
date (str): 조회 일자 (YYMMDD)
ticker (str): 인덱스 ticker
Returns:
list: ['005930', '000660', '051910', ...]
"""
df = 지수구성종목().fetch(date, ticker[1:], ticker[0])
if df.empty:
... | 5,314,525 |
def get_account_by_path(
path_string: str, dongle: Optional[Dongle] = None
) -> LedgerAccount:
"""Return an account for a specific `BIP-44`_ derivation path
:param path_string: (:code:`str`) - HID derivation path for the account to
sign with.
:param dongle: (:class:`ledgerblue.Dongle.Dongle`) -... | 5,314,526 |
def _search_path(file_path):
"""Completes the file path if given a filename and not a directory. If only given a file name and
not a directory, the system will search for it in the library folder. The library folder is defined
either in rosparam:`/baxter/playback_library_dir` or if doesn't exist. Defaults ... | 5,314,527 |
def down_capture_nb(returns, factor_returns, ann_factor):
"""2-dim version of `down_capture_1d_nb`."""
result = np.empty(returns.shape[1], dtype=np.float_)
for col in range(returns.shape[1]):
result[col] = down_capture_1d_nb(returns[:, col], factor_returns[:, col], ann_factor)
return result | 5,314,528 |
def validate_word(word, text):
"""Check if something is a valid "word" submission with previous existing text.
Return (valid, formatted_word, message), where valid is a boolean, formatted_word is
the word ready to be added to existing text (adding a space if applicable for example), and
message is an er... | 5,314,529 |
def process_content_updates(results):
"""Process Content Updates
Args:
results (Element): XML results from firewall
Returns:
max_app_version (str): A string containing the latest App-ID version
"""
app_version_list = []
version_list = results.findall('./result/content-updates/e... | 5,314,530 |
def load_synthetic(name):
"""
Loads expression data from pickle file with the given name (produced by save_synthetic function)
:param name: name of the pickle file in SYNTHETIC_DIR containing the expression data
:return: np.array of expression with Shape=(nb_samples, nb_genes) and list of gene symbols m... | 5,314,531 |
def sf_create_app(client, # pylint: disable=too-many-locals,too-many-arguments
app_name, app_type, app_version, parameters=None,
min_node_count=0, max_node_count=0, metrics=None,
timeout=60):
"""
Creates a Service Fabric application using the specified desc... | 5,314,532 |
def cell_count(ring):
"""
>>> cell_count(0) == contour_len(0)
True
>>> cell_count(1) == contour_len(0) + contour_len(1)
True
>>> cell_count(2) == contour_len(0) + contour_len(1) + contour_len(2)
True
>>> cell_count(2)
25
>>> cell_count(3)
49
"""
if ring == 0:
... | 5,314,533 |
def exponential_search(ordered_list, x):
"""
implementation of an exponential search algorithm
taken from: https://en.wikipedia.org/wiki/Exponential_search
"""
list_size = len(ordered_list)
bound = 1
while bound*2 < list_size and ordered_list[2*bound-1] < x:
bound = bound ... | 5,314,534 |
def verify(payload, signature, public_key):
"""
Verify payload using (base64 encoded) signature and verification key. public_key should be obtained from load_public_key
Uses RSA-PSS with SHA-512 and maximum salt length.
The corresponding openssl command to create signatures that this function can verify... | 5,314,535 |
def get_models_from_api_spec(
api_spec: dict, model_dir: str = "/mnt/model"
) -> CuratedModelResources:
"""
Only effective for predictor:model_path, predictor:models:paths or for predictor:models:dir when the dir is a local path.
It does not apply for when predictor:models:dir is set to an S3 model path... | 5,314,536 |
def prepare_segment(net, source, dev='cuda'):
"""
Prepares target image before foreground and background separation
Parameters:
net (pytorch_vision.model): Segmentation Model
source (cv2.Mat): Hand image
dev (str): Computation device, default GPU
Returns:
(cv2.Mat): Hand ... | 5,314,537 |
def extract_information_per_turker(filename):
"""
Extracts dictionary with turker's details
Returns:
user_information: dictionary with user details
"""
user_information = {}
with open(filename) as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
... | 5,314,538 |
def upload_str(name: str, content: str, bucket_name: str):
"""
:param name: Name of file including directories i.e. /my/path/file.txt
:param content: UTF-8 encoded file content
:param bucket_name: Name of GCS bucket, i.e. deepdriveio
:return: Url of the public file
"""
key = name
bucket... | 5,314,539 |
def getRenderTasks(*args, **kwargs):
"""
Command to return render tasks to render an image source.
Returns: `string[]` Render tasks (one per string) for argument render target.
"""
pass | 5,314,540 |
def main(orig_dir, new_dir, blocksize, comparison_operator):
""" main source of pain """
if not os.path.isdir(orig_dir):
raise comparisonException("Directory {d} does not exist".format(d=orig_dir))
if not os.path.isdir(new_dir):
raise comparisonException("Directory {d} does not exist".format... | 5,314,541 |
def test_delete_all_error_client():
"""
GIVEN stubbed s3 client that raises an error
WHEN delete_all is called
THEN StorageError is raised.
"""
bucket = "bucket1"
key = "key 1"
s3_instance = storage.s3.Storage(bucket)
stubber = stub.Stubber(s3_instance.client)
stubber.add_client_... | 5,314,542 |
def inverso(x):
"""
El inverso de un número.
.. math::
\\frac{1}{x}
Args:
x (float): Número a invertir.
Returns:
float: El inverso.
"""
return 1 / x | 5,314,543 |
def test_post_create_not_supported(sut: SystemUnderTest):
"""Perform tests for Assertion.REQ_POST_CREATE_NOT_SUPPORTED."""
response = sut.get_response('POST', sut.accounts_uri)
if response is None:
msg = ('Not response found for POST to Accounts URI; unable to test '
'this assertion')... | 5,314,544 |
def get_past_data(df: pd.DataFrame, dir_name: str):
"""
Get the NFTs events data as new dataframe. To use this function can get past data max 100.
Prameters
---------
df : pd.DataFrame
Dataframe of the collection data.
dir_name : str
The name of directory you want to save data.
... | 5,314,545 |
def _scale(scale:bool,X:Union[pd.Series,np.ndarray]):
"""
Normalization of the Time Serie
Parameters
----------
scale : bool
X : pd.Serie or Numpy Array
Returns
-------
global_mean : float, mean of the Time Serie
global_sdt : float, sdt of the Time Serie
X : numpy array, 1D Array
"""
if is... | 5,314,546 |
def update_user_count_eponymous(set_of_contributors, anonymous_coward_comments_counter):
"""
Eponymous user count update.
Input: - set_of_contributors: A python set of user ids.
- anonymous_coward_comments_counter: The number of comments posted by anonymous user(s).
Output: - user_count: ... | 5,314,547 |
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Translate DNA/RNA to proteins',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'positional', metavar='str', help='DNA/RNA sequence')
parser.add_argument... | 5,314,548 |
def delete_fleet(Name=None):
"""
Deletes a fleet.
See also: AWS API Documentation
:example: response = client.delete_fleet(
Name='string'
)
:type Name: string
:param Name: [REQUIRED]
The name of the fleet to be deleted.
:rtype: dict
... | 5,314,549 |
def translation(component, direction=1, kernel=interpolation.lanczos, padding=3):
"""Shift the morphology by a given amount
"""
dy, dx = component.shift
dy *= direction
dx *= direction
_kernel, _, _ = interpolation.get_separable_kernel(dy, dx, kernel=kernel)
component.morph[:] = interpolatio... | 5,314,550 |
def workflow(
user_id: Optional[int] = None,
screen_name: Optional[str] = None,
total_followers: int = 100000,
batch_size: int = 5000,
output_csv: Optional[str] = None
) -> pd.DataFrame:
"""
Pull a user's Twitter following and map each follower to a row
of their ident... | 5,314,551 |
def otf_plots(model_kwargs):
"""NOTE: the results are _very_ close on a qualitative scale, but they do not match exactly as
theory says they should (they're mathematically identical to one another)
"""
# generate a comparison
psfs = HanserPSF(**model_kwargs), SheppardPSF(**model_kwargs)
fig, a... | 5,314,552 |
def dcaFuse(X, Y, L):
"""
X (p*n)
Y (q*n)
L (n)
"""
# X = np.array([[1,2,3,4],
# [4,5,6,7],
# ])
# Y = np.array([[4,4,4,4],
# [1,1,1,1]]
# )
# L = np.array([0,1,2,2])
p, n = X.shape
q = Y... | 5,314,553 |
def cutting_plane(n, d, s):
"""
Create a new cutting plane with index `n`, normal `d`, and fractional displacement `s`.
"""
gcv().cutting_plane(n, d, s) | 5,314,554 |
def flowRate(t):
""" gives fixed flow rate as a function of time
notice that it depends on pump coastdown time constant, so
be sure to change that if needed. right now, it's set to 5s """
tau = 5.0
return 21.7 * np.exp(-t/tau) | 5,314,555 |
def obtain_root_b():
""" 获取指向 root 节点的边界的个数 // 所有边界的个数
统计, 位置2指向的位置1节点为root节点或者0,并且句法关系为0的个数 / 所有边个数
1. 找到 root 节点;
2. 找边界列表;统计边界个数;
3. 统计边界指向root节点的元素个数;
"""
train, dev, test = load_data(DATA_SETS)
sets = train + dev + test
total_b, root_b = 0., 0.
for ... | 5,314,556 |
def generator_from_atom_argument(arg: AtomSpec) -> IndexGenerator:
"""
Returns a generator function for selecting a subset of sites from a pymatgen :obj:`Structure` object.
Args:
arg (various): Argument used to construct the generator function.
Returns:
(func): Generator function that ... | 5,314,557 |
def _RunIgnoringErrors(cmd):
"""Runs the given command, ignores errors but warns user."""
try:
cros_build_lib.sudo_run(cmd, quiet=True)
except cros_build_lib.RunCommandError as e:
logging.error('Cleanup operation failed. Please run "%s" manually.',
' '.join(cmd))
logging.debug('Encou... | 5,314,558 |
def get_total_memory():
"""
get_total_memory()
Returns the total memory in GBs
"""
total_memory = shell_tools.run('sysctl -a | grep hw.memsize')['stdout']
return (int(total_memory.split('=')[-1]) / (1024 * 3)) | 5,314,559 |
def generate_arg_defaults():
"""Return a dict of programmatically determined argument defaults."""
return {'user': os.getlogin(),
'uid': os.getuid(),
'gid': os.getgid(),
'tag': 'latest',
'dockerfile': './docker/escadrille'} | 5,314,560 |
def _d_conv_mha(c: TransformerConfigs):
"""
Add the [option](https://docs.labml.ai/api/configs.html#labml.configs.option)
of [**Multi-DConv-Head Attention**](index.html) to
[configurable transformer](../configs.html#TransformerConfigs)
"""
from labml_nn.transformers.primer_ez import MultiDConv... | 5,314,561 |
def c_commands(context, commands):
"""
The c in c_commands refers to the c file.
This function filters a list of commands for the generated .c file.
WGL core functions are not dynamically loaded but need to be linked,
this functions filters out wgl core functions for the .c file.
:param contex... | 5,314,562 |
async def get_job_status(job_id: int, request: Request, response: Response):
"""Get the status of a previously-submitted job.
**Arguments:**
- **job_id**: Identifier of the submitted job, as returned by the "Submit Job" endpoint.
"""
loop = asyncio.get_running_loop()
try:
job_state, _ ... | 5,314,563 |
def replace_tool(string_file, old_tool_file, new_tool_file, old_tool_name='', new_tool_name='', N=0):
"""Swaps old_tool_file for new_tool_file in string_file. Also replaces the tools Name field.
Parameters
----------
string_file : str
Path to an Adams Drill string file. Accepts full path ... | 5,314,564 |
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understan... | 5,314,565 |
def choose_insertsize(readlen=150, step=20, cutoff=0.01):
"""
Calculate ratio of overlap for a range of insert sizes. Idea borrowed from
ALLPATHS code (`allpaths_cache/CacheToAllPathsInputs.pl`).
"""
print("Insert-size\tOverlap", file=sys.stderr)
for i in range(0, 3 * readlen, step):
p =... | 5,314,566 |
def read_bytes(urlpath, delimiter=None, not_zero=False, blocksize=2**27,
sample=True, compression=None, **kwargs):
""" Convert path to a list of delayed values
The path may be a filename like ``'2015-01-01.csv'`` or a globstring
like ``'2015-*-*.csv'``.
The path may be preceded by a pro... | 5,314,567 |
def handle_command(command, channel):
"""
Executes bot command if the command is known
"""
SENTENCES = 4
# Default response is help text for the user
default_response = "Something broke! Contact the devs!"
match = re.search(MENTION_REGEX2, command)
response = None
if match is Non... | 5,314,568 |
def _plot_residual(dset: "Dataset", figure_dir: "pathlib.PosixPath") -> None:
"""Plot residual plot
Args:
dset: A dataset containing the data.
figure_dir: Figure directory
"""
plot(
x_arrays=dset.time.gps.datetime,
y_arrays=dset.residual,
xlabel="Time [GPS]... | 5,314,569 |
def test_inside():
"""Test INSIDE layer."""
x = tf.convert_to_tensor(np.ones((1, 5, 5, 2)), dtype=tf.float32)
gamma_s = tf.Variable([[1]], dtype=tf.float32)
gamma_b = tf.Variable([[1]], dtype=tf.float32)
mu_a = tf.Variable([[-1, 1]], dtype=tf.float32)
sigma_a = tf.Variable([[0.1, 0.1]], dtype=... | 5,314,570 |
def scale_against_target(
reflection_table,
experiment,
target_reflection_table,
target_experiment,
params=None,
model="KB",
):
"""Determine scale factors for a single dataset, by scaling against a target
reflection table. Requires a single reflection table for the reflections to
sca... | 5,314,571 |
def dvilike_machine(transitions, actions, start = 'start', **state_vars):
"""No.
transitions: Dictionary mapping commands (strings) to dictionaries
mapping states (strings) to a state (a string).
actions: Dictionary mapping commands (strings) to dictionaries
mapping states to an action (a function... | 5,314,572 |
def billing_pattern(data, params, hitlist):
"""
In this model, outliers from the general billing pattern (see below) are flagged,
based on how far away from the nearest cluster they are.
The pattern is defined as the fraction of money billed for different procedures.
This multi-dimensional space is reduced to thre... | 5,314,573 |
def partition_annots_into_singleton_multiton(ibs, aid_list):
"""
aid_list = aid_list_
"""
aids_list = ibs.group_annots_by_name(aid_list)[0]
singletons = [aids for aids in aids_list if len(aids) == 1]
multitons = [aids for aids in aids_list if len(aids) > 1]
return singletons, multitons | 5,314,574 |
def teaser_block(parser, token):
"""
Template tag that takes a model instance and returns the given instance as
a template-formatted block. Inserts two objects into the context:
``instance`` - The model instance
``fields`` - A list of (name, label, value) tuples representing the
... | 5,314,575 |
def poem():
"""每日诗词"""
_svg = '<svg xmlns="http://www.w3.org/2000/svg" height="22.0" width="342.5"><g><text text-anchor="start" ' \
'letter-spacing="1.5" font-smoothing="antialiased" ' \
'font-family="KaiTi,Segoe UI,Lucida Grande,Helvetica,Arial,Microsoft YaHei,FreeSans,' \
'Ari... | 5,314,576 |
def galeshapley(suitor_pref_dict, reviewer_pref_dict, max_iteration):
""" The Gale-Shapley algorithm. This is known to provide a unique, stable
suitor-optimal matching. The algorithm is as follows:
(1) Assign all suitors and reviewers to be unmatched.
(2) Take any unmatched suitor, s, and their most p... | 5,314,577 |
def geom_bar(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None,
**other_args):
"""
Display a bar chart which makes the height of the bar proportional to the
number of observed variable values, mapped to x axis.
Parameters
----------
... | 5,314,578 |
def diff_string(old, new):
"""given a old and new int value, return a string representing the
difference
"""
diff = abs(old - new)
diff_str = "%s%s" % (CMPS[cmp(old, new)], diff and ('%.2f' % diff) or '')
return diff_str | 5,314,579 |
def _tile_grid_to_cesium1x_source_options(tile_grid: TileGrid, url: str):
"""
Convert TileGrid into options to be used with Cesium.UrlTemplateImageryProvider(options) of Cesium 1.45+.
See
* https://cesiumjs.org/Cesium/Build/Documentation/UrlTemplateImageryProvider.html?classFilter=UrlTemplateImageryPr... | 5,314,580 |
def update_code(code_id: int, code: schemas.CodeUpdate, db: Session = Depends(get_db)):
"""
Update Code
"""
db_code = crud.get_code(db=db, code_id=code_id)
if db_code is None:
raise HTTPException(status_code=404, detail="Code not found")
db_device = crud.get_device(db=db, device_id=code... | 5,314,581 |
def vgg19_lstar():
"""
Setup the VGG19 neural network, protect it using Gu and Rigazio's L* defense
mechanism and perform an inference on an example input.
"""
model = networks.VGG19()
dm = dms.GuRigazio(
keras_model = model.wrapped_model(),
noise_stddev = 4.71e-4,
how = ... | 5,314,582 |
def update_state(self, step: int):
"""Updates the system state.
Args:
step (int): Current simulation time step.
"""
self.current_step = step | 5,314,583 |
def find_setting(group, key, site=None):
"""Get a setting or longsetting by group and key, cache and return it."""
siteid = _safe_get_siteid(site)
setting = None
use_db, overrides = get_overrides(siteid)
ck = cache_key('Setting', siteid, group, key)
if use_db:
try:
setting... | 5,314,584 |
def enableSphinxStatus():
"""
enable verbosity for features handled by this utility class
When invoked, this utility class will attempt to prepare or invoke
requests in a verbose manner.
"""
os.environ['SPHINX_STATUS'] = '1' | 5,314,585 |
def list_tags_for_resource(ResourceArn=None, MaxResults=None, NextToken=None):
"""
Returns all the tags associated with a specified resources.
See also: AWS API Documentation
Exceptions
:example: response = client.list_tags_for_resource(
ResourceArn='string',
MaxResults=123... | 5,314,586 |
def isoslice(var,prop,isoval, grd, Cpos='rho', masking=True, vert=False):
"""
isoslice, lon, lat = isoslice(variable,property, isoval, grd)
optional switch:
- Cpos='rho', 'u' or 'v' specify the C-grid position where
the variable rely
- masking=True mask the output... | 5,314,587 |
def get_solution(x):
"""
Args:
x (numpy.ndarray) : binary string as numpy array.
Returns:
numpy.ndarray: graph solution as binary numpy array.
"""
return 1 - x | 5,314,588 |
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
controller = hass.data[DOMAIN][config_entry.entry_id]
diag: dict[str, Any] = {}
diag["entry"]: dict[str, Any] = {}
diag["entry"]["data"]... | 5,314,589 |
def get_link(update: Updater, context: CallbackContext):
"""List all available matches, and the ones the user is subscribed to.
Offer the registration"""
if not Users.doesUserExist(update.effective_user['id']):
context.bot.send_message(chat_id=update.effective_user['id'],
... | 5,314,590 |
def create_upload_file(tmp_path):
"""Create temporary text file for upload."""
file_path = Path(tmp_path, "test_upload_1.txt")
with open(file_path, "w") as f:
f.write("Hello World")
return file_path | 5,314,591 |
def makeFigure():
"""Get a list of the axis objects and create a figure"""
ax, f = getSetup((10, 8), (3, 4), multz={8: 1, 10: 1})
subplotLabel(ax)
Tcell_pathname = path_here + "/data/flow/2019-11-08 monomer IL-2 Fc signaling/CD4 T cells - IL2-060 mono, IL2-060 dimeric"
NK_CD8_pathname = path_here ... | 5,314,592 |
def KimKim2011(medium="Water", p_steam=120, deltaT_sub=5, Theta=90, CAH=10,
Theta_a=None, Theta_r=None, k_coat=15, delta_coat=0, h_i=None,
c=1, N_s=250, print_properties=False, **kwargs):
""" main function, calculates dropwise condensation heat flux as described in:
Kim, S., & ... | 5,314,593 |
def log_and_rethrow(
to_be_fixed_by: ResolvableBy,
log: Logger,
what_happened: str,
why_it_happened: str,
consequences: str,
countermeasures: str,
exception: BaseException,
wrap_in_vdk_error=False,
) -> None:
"""
Log message only if it has not been logged already. And throws it a... | 5,314,594 |
def cumall(series):
"""
Calculates cumulative all of values. Equivalent to
`series.expanding().apply(np.all).astype(bool)`.
Args:
series: column to compute cumulative all for.
"""
alls = series.expanding().apply(np.all).astype(bool)
return alls | 5,314,595 |
def manhattan_distance(a: Point, b: Point) -> int:
"""Return the Manhattan distance between two points."""
return abs(a[0] - b[0]) + abs(a[1] - b[1]) | 5,314,596 |
def gen_new_dns_json():
"""
Generate json file with IPs and their respective domains.
:return: Stats about domains
"""
json_dict = []
for ip in DATA.keys():
entry = {'ip': ip, 'domain': DATA.get(ip)}
json_dict.append(entry)
dist = {"domains": json_dict}
with open(f'{PATH}... | 5,314,597 |
def label_point(event):
"""
Label segment under cursor at key press event.
Supported labels:
[g]round
[v]egetation
[s]hadow
[n]ull
Quits on "q" keypress.
"""
if event.key == 'q':
# Default: all unlabelled points saved as ground
labelled_image[np.... | 5,314,598 |
def recorderLocations(year = 2014):
"""
This function returns all survey locations and recorder abbreviations for a given year. Only valid from 2009 onwards.
"""
if year > 2009:
stryear = str(year)
groups = loadTable('groups')
recorderids = loadTable('recorderinstall... | 5,314,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.