content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def has_level_or_node(level: int, *auth_nodes: str) -> Rule:
"""
:param level: 需要群组权限等级
:param auth_nodes: 需要的权限节点
:return: 群组权限等级大于要求等级或者具备权限节点, 权限节点为deny则拒绝
"""
async def _has_level_or_node(bot: Bot, event: Event, state: T_State) -> bool:
auth_node = '.'.join(auth_nodes)
detail... | 3,300 |
def solve_problem(problem, max_iter_num=MAX_ITER_NUM, max_iter_num_without_adding=MAX_ITER_NUM_WITHOUT_ADDITIONS, iter_num_to_revert_removal=ITER_NUM_TO_REVERT_REMOVAL, remove_prob=ITEM_REMOVAL_PROBABILITY, consec_remove_prob=CONSECUTIVE_ITEM_REMOVAL_PROBABILITY, ignore_removed_item_prob=IGNORE_REMOVED_ITEM_PROBABILITY... | 3,301 |
def test_task_types() -> None:
"""
mypy should find type errors related to redun task calls.
"""
workflow_file = get_test_file("test_data/typing/workflow_fail.py.txt")
stdout, stderr, ret_code = api.run(
[
"--show-traceback",
workflow_file,
"redun",
... | 3,302 |
def write_config(config):
"""Writes contents of configparser to properties.conf"""
with open(__file__.replace('core.py', 'properties.conf'), 'w') as configfile:
config.write(configfile) | 3,303 |
def _pil_apply_edit_steps_mask(image, mask, edit_steps, inplace=False):
"""
Apply edit steps from unmasking method on a PIL image.
Args:
image (PIL.Image): The input image.
mask (Union[int, tuple[int, int, int], PIL.Image]): The mask to apply on the image, could be a single grey
... | 3,304 |
def do_let_form(expressions, env):
"""Evaluate a let form."""
check_form(expressions, 2)
let_env = make_let_frame(expressions.first, env)
return eval_all(expressions.second, let_env) | 3,305 |
def bubble(n_categories=5,n=10,prefix='category',mode=None):
"""
Returns a DataFrame with the required format for
a bubble plot
Parameters:
-----------
n_categories : int
Number of categories
n : int
Number of points for each category
prefix : string
Name for each category
mode : string
Form... | 3,306 |
def get_coherence(model, token_lists, measure='c_v'):
"""
Get model coherence from gensim.models.coherencemodel
:param model: Topic_Model object
:param token_lists: token lists of docs
:param topics: topics as top words
:param measure: coherence metrics
:return: coherence score
"... | 3,307 |
def run_vscode_command(
command_id: str,
*args: str,
wait_for_finish: bool = False,
return_command_output: bool = False,
):
"""Runs a VSCode command, using command server if available
Args:
command_id (str): The ID of the VSCode command to run
wait_for_finish (bool, optional): W... | 3,308 |
def clc_prepare(reference, outdir, source):
"""
create a CLC subset resampled to a reference image.
Parameters
----------
reference: str
the reference file with the target CRS and extent
outdir: str
the directory to write the new file to;
new files are named clc{inde... | 3,309 |
def find_calibrations_for_sensor(
sensor_id: str,
folder: Optional[path_t] = None,
recursive: bool = True,
filter_cal_type: Optional[str] = None,
custom_validator: Optional[Callable[["CalibrationInfo"], bool]] = None,
ignore_file_not_found: Optional[bool] = False,
) -> List[Path]:
"""Find po... | 3,310 |
def reward_displacement(navenv):
""" Reward = distance to previous position"""
r = dist(navenv.current_pos, navenv.old_pos)
return r | 3,311 |
def MakeLinuxFirmware(save=True, **kwargs):
"""Create and return a LinuxFirmware for test."""
defaults = {
'manufacturer': 'Lonovo',
'serial': 'blah',
'password': '123456789',
'machine_uuid': str(uuid.uuid4()).upper(),
'owner': 'someone',
'asset_tags': ['12345'],
'hostname'... | 3,312 |
def get_unity_filesystem_parameters():
"""This method provide parameters required for the ansible filesystem
module on Unity"""
return dict(
filesystem_name=dict(required=False, type='str'),
filesystem_id=dict(required=False, type='str'),
nas_server_name=dict(required=False, type=... | 3,313 |
def get_time_difference(row, start_col, end_col, start_format, end_format, unit='days'):
"""
Returns a Series object of days
Unit can be D for Days, or Y for Years
"""
start_date = row[start_col]
end_date = row[end_col]
if pd.isnull(start_date) or pd.isnull(end_date):
return np.nan
else:
... | 3,314 |
def main(config):
"""Initialize model, data loaders and trainer based on config file and run training."""
model = config.init_model()
data_loaders = config.init_data_loaders(model)
trainer = config.init_trainer(model, data_loaders["train"], data_loaders["dev"])
trainer.train() | 3,315 |
def get_account(account_name, password):
"""Displays account data from the wallet.
--- Definitions ---
{"name": "account_name", "prompt": "Alias of account", "default": "Myaccount"}
{"name": "password", "prompt": "Password to decrypt private key", "default": "Mypassword"}
"""
db = get_wallet_d... | 3,316 |
def invert(img):
"""
Function to invert colors of an image
"""
r, g, b, a = colorsys_getRGBA(img) # Get r, g, b, a
r, g, b = 255 - r, 255 - g, 255 - b # Invert all colors
img_arr = np.dstack((r, g, b, a))
return img_arr | 3,317 |
def spearman_kendall_test(df, item, alpha=0.05, increasing=True,
rank_in='Rank',
category_in='category',
dataset_in='dataset',
userid_in='userid'
):
"""
Do spearman's and kendall's t... | 3,318 |
def test_restore_from_minimized(session):
"""
12. If the visibility state of the top-level browsing context's
active document is hidden, restore the window.
[...]
To restore the window, given an operating system level window with
an associated top-level browsing context, run implementation-spe... | 3,319 |
def circle(*args, **kwargs):
"""
The circle command creates a circle or partial circle (arc).
Returns: `string[]` Object name and node name
"""
pass | 3,320 |
def array2string(array, _depth=0):
"""
Recursively create a initializer list style string from an iterable with
multiple dimensions.
Args:
array (iterable): input iterable which is expected to have elements that
can be converted to strings with `str()`.
_depth ... | 3,321 |
def do_appl_error(row_id, text):
"""If the line is a APPL-ERROR then add it to the list."""
if text.find('APPL-ERROR') != -1:
add_appl_error = ApplError(row_id)
appl_list.append(add_appl_error) | 3,322 |
def rail_help_wrapper(prog):
""" So formatter_class's max_help_position can be changed. """
return RailHelpFormatter(prog, max_help_position=40) | 3,323 |
def evaluate(args):
"""Function to predict for a single image or folder of images"""
val_dataset = WoodScapeRawDataset(data_path=args.dataset_dir,
path_file=args.val_file,
is_train=False,
config=arg... | 3,324 |
def main(path_config_yaml):
"""
フォルダを指定して全体の処理をやる
"""
with open(path_config_yaml, 'r') as fy:
config = yaml.load(fy, Loader=yaml.FullLoader)
out_dir = expanduser(config['out_dir'])
full_align_round_seg_files = natsorted(glob(f'{out_dir}/full_align_round_seg/*.lab'))
full_score_round... | 3,325 |
def project_dashboard(request):
"""
The function calling Project Dashboard page.
:param request:
:return:
"""
global all_vuln, \
total_web, \
all_high, \
total_network, \
all_medium, \
all_low, \
all_web_high, \
all_web_medium, \
al... | 3,326 |
def getSelfRole(store):
"""
Retrieve the Role which corresponds to the user to whom the given store
belongs.
"""
return getAccountRole(store, userbase.getAccountNames(store)) | 3,327 |
def warnings_to_stdout():
""" Redirect all warnings to stdout.
"""
showwarning_orig = warnings.showwarning
def showwarning(msg, cat, fname, lno, file=None, line=0):
showwarning_orig(msg, cat, os.path.basename(fname), line, sys.stdout)
warnings.showwarning = showwarning
# warni... | 3,328 |
def forwardCOMDQ(robot, m = 0, symbolic = False):
"""
Using Dual Quaternions, this function computes forward kinematics to m - th center of mass, given joints positions in radians. Robot's kinematic parameters have to be set before using this function
robot: object (robot.jointsPositions, robot.lin... | 3,329 |
def gen_mode():
"""获取玩家想要考试的模式"""
while True:
mode = input("如何考试?\n输入1顺序考试\n输入2乱序考试\n>>")
if mode in ("1", "2"):
return mode
else:
print()
print("非法输入,请输入\"1\"或\"2\"")
print("你不需要输入双引号")
print("--------------------------------") | 3,330 |
def find_movers(threshold, timeframe: Timeframe, increasing=True, decreasing=False, max_price=None):
"""
Return a dataframe with row index set to ASX ticker symbols and the only column set to
the sum over all desired dates for percentage change in the stock price. A negative sum
implies a decrease, pos... | 3,331 |
def create_pl_pruning_callback(*args, **kwargs):
"""Create PyTorchLightning Pruning Callback. Optuna Only."""
from bigdl.nano.deps.automl.hpo_api import create_optuna_pl_pruning_callback
return create_optuna_pl_pruning_callback(*args, **kwargs) | 3,332 |
def get_all_token_volume_by_direction(chain:str, direction:str):
"""
chain: Allowed: ethereum ┃ avalanche ┃ bsc ┃ polygon ┃ arbitrum ┃ fantom ┃ harmony ┃ boba ┃ optimism ┃ moonriver ┃ aurora
direction: Allowed: in ┃ out
"""
chain = chain.lower()
direction = direction.lower()
chains = ["e... | 3,333 |
def _interactively_fix_missing_variables(project, result):
"""Return True if we need to re-prepare."""
if project.problems:
return False
if not console_utils.stdin_is_interactive():
return False
# We don't ask the user to manually enter CONDA_PREFIX
# (CondaEnvRequirement) because ... | 3,334 |
def build_node_descr(levels, switch=False):
"""
Produces a node description of the above binary trees
"""
num_parents = sum([2**i for i in range(levels-1)])
parents, children = tee(character_iterator(switch))
next(children)
node_descr = []
for parent_ident in islice(parents, num_parents)... | 3,335 |
def save_json_in_s3(json_data: dict, key: str, bucket=DEFAULT_S3_BUCKET):
"""
Saves the given JSON data as bytes using the given key.
"""
s3.put_object(
Bucket=bucket,
Key=key,
# convert JSON dict to a byte string:
Body=json.dumps(json_data).encode()
) | 3,336 |
def random_sources(xSize, ySize, zSize, number):
""" returns a list of random positions in the grid where the sources of nutrients (blood vessels) will be """
src = []
for _ in range(number):
x = random.randint(0, xSize-1)
y = random.randint(0, ySize-1)
z = random.randint(0, zSize-1)... | 3,337 |
def sqeuclidean(
x_mat: 'Tensor', y_mat: 'Tensor', device: str = 'cpu'
) -> 'numpy.ndarray':
"""Squared euclidean distance between each row in x_mat and each row in y_mat.
:param x_mat: tensorflow array with ndim=2
:param y_mat: tensorflow array with ndim=2
:param device: the computational device... | 3,338 |
def get(*, db_session, tag_id: int) -> Optional[Tag]:
"""Gets a tag by its id."""
return db_session.query(Tag).filter(Tag.id == tag_id).one_or_none() | 3,339 |
def plot_lines(axes, xdata, ydata, yerrors=None, cdata=None, cmap=None, line_spec='-o', *args, **kwargs):
"""
Plot lines on given matplotlib axes subplot
Uses matplotlib.plot or matplotlib.errorbar if yerrors is not None
:param axes: matplotlib figure or subplot axes, None uses current axes
:param x... | 3,340 |
def conv_binary_prevent_overflow(array, structure):
"""
Make sure structure array has great enough positive bitdepth
to be convolved with binary primary array.
Parameters
----------
array : ndarray of bool or int, 2D
Primary integer array to convolve.
Must be a binary array of o... | 3,341 |
def filter_freq_and_csq(mt: hl.MatrixTable, data_type: str, max_freq: float, least_consequence: str):
"""
Filters MatrixTable to include variants that:
1. Have a global AF <= `max_freq`
2. Have a consequence at least as severe as `least_consequence` (based on ordering from CSQ_ORDER)
:param MatrixT... | 3,342 |
def get_regular_intervals(
pre_sfes: list,
post_sfes: list,
pre_keep_flag: bool,
post_keep_flag: bool,
) -> list:
"""
Calculates the intervals for the "regular" egg laying epoch. If pre_keep_flag,
the "regular" epoch is the pre-breakpoint region. If post_keep_flag, the
"regular" epoch is... | 3,343 |
def plot(data: np.ndarray):
"""
Convenience function for plotting radar data.
"""
fig = pl.figure(figsize=(10, 8))
wrl.vis.plot_ppi(data, fig=fig, proj="cg") | 3,344 |
async def async_setup(hass, config):
"""Platform setup, do nothing."""
if DOMAIN not in config:
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=dict(config[DOMAIN])
)
)
return True | 3,345 |
def get_new_bucket(target=None, name=None, headers=None):
"""
Get a bucket that exists and is empty.
Always recreates a bucket from scratch. This is useful to also
reset ACLs and such.
"""
if target is None:
target = targets.main.default
connection = target.connection
if name is... | 3,346 |
def update_markdown(path: Union[str, pathlib.Path]) -> None:
"""Update the given markdown file."""
with open(path) as file:
lines = [line.rstrip("\n") for line in file]
assert lines[0] == "---"
idx = min(i for i, line in enumerate(lines[1:], start=1) if line == "---")
# Load the data like ... | 3,347 |
def angle_rms(ang, axis=None, period=2*np.pi):
"""returns the rms of angles, uses the property that rms(x)**2 = mean(x)**2 + std(x)**2"""
#rms(x)**2 = mean(x)**2 + std(x)**2
#sqrt(E[X**2]) = E[X]**2 + sqrt(E[(X - E[X])**2])
m,s = angle_mean_std(ang,axis,period)
return np.hypot(m, s) | 3,348 |
def check_units(*units_by_pos, **units_by_name):
"""Create a decorator to check units of function arguments."""
def dec(func):
# Match the signature of the function to the arguments given to the decorator
sig = signature(func)
bound_units = sig.bind_partial(*units_by_pos, **units_by_name... | 3,349 |
def check_nifti_dim(fname, data, dim=4):
"""
Remove extra dimensions.
Parameters
----------
fname : str
The name of the file representing `data`
data : np.ndarray
The data which dimensionality needs to be checked
dim : int, optional
The amount of dimensions expected/... | 3,350 |
def bar_chart(x_data=None, y_data=None, title="Chart Title", x_label=None, y_label=None,
color="blue", figsize=(10,5)):
"""
This function requires two Pandas data series for x and y data.
Optionally: the x label, y label, color, title, and size may be set.
This function returns a bar ch... | 3,351 |
def get_qtobject_for_uipath(pathstr):
""" Returns the QtObject for a Maya UI path.
Ensure that the path starts from the Maya main window and that there are no \
empty elements in it as this will fail.
"""
split_pathstr = pathstr.split("|")
return _find_qobject(get_maya_main_window(), split_paths... | 3,352 |
def parse_study_with_run(soup):
"""Given a BeautifulSoup object representing a study, parse out relevant
information.
:param soup: a BeautifulSoup object representing a study
:type soup: bs4.BeautifulSoup
:return: a dictionary containing study information and run information
:rtype: dict
"... | 3,353 |
def create_embed(**kwargs) -> Embed:
"""Creates a discord embed object."""
embed_type = kwargs.get('type', Embed.Empty)
title = kwargs.get('title', Embed.Empty)
description = kwargs.get('description', Embed.Empty)
color = kwargs.get('color', get_default_color())
timestamp = kwargs.get('timestamp... | 3,354 |
def validate_commit(commit: Commit, out_errors: List[str] = None, ignore_validators: List[str] = None) -> bool:
"""Validates a commit against all validators
:param commit: The commit to validate
:param out_errors: if not None, will populate with the list of errors given by the validators
:param ignore_... | 3,355 |
def test_examples(example_file):
"""Loop through all example files, verify that the ast_parser can parse the file.
Examples located at: ``openqasm/examples``.
"""
with open(example_file) as f:
source = f.read()
openqasm3.parse(source) | 3,356 |
def _safe_types(
*, test_data: Any, cached_data: Any, key_rules: List[KeyRule],
) -> Dict:
"""Convert data and key_rules to safe data types for diffing.
Args:
test_data: data to compare
cached_data: data to compare
key_rules: list of key rules to apply
Returns:
Dict: sa... | 3,357 |
def _flatten_output(attr_dict, skip: list=[]):
"""
flaten output dict node
node_collection is a list to accumulate the nodes that not unfolded
:param skip: is a list of keys (format with parent_key.key) of Dict name that
will not collected into the json file.
For output nodes not being ex... | 3,358 |
def validate_threatbus_config(config: Settings):
"""
Validates the given Dynaconf object, potentially adding new entries for the default values.
Throws if the config is invalid.
"""
validators = [
Validator("logging.console", is_type_of=bool, required=True, default=True),
Validator("... | 3,359 |
def get_tpu_estimator(
working_dir,
model_fn,
iterations_per_loop=320,
keep_checkpoint_max=20,
use_tpu=False,
train_batch_size=64):
"""Obtain an TPU estimator from a directory.
Args:
working_dir: the directory for holding checkpoints.
model_fn: an estimator model function.
iter... | 3,360 |
def rho_err(coeffs, rho, z, density_func):
"""
Returns the difference between the estimated and actual data
"""
soln = density_func(z, coeffs)
return rho - soln | 3,361 |
def ui_form_stations():
"""
This function lists all stations
"""
# get _all_ the stations
stations = station_get(0)
# render stations in HTML template
return render_template("stations.html", result=stations) | 3,362 |
def create_digital_object(obj):
"""
Create a digitial object for a cilantro object in AtoM.
:param Object obj: THE cilantro object
:return: str The generated URI for the digital object
"""
url = f"{atom_uri}/api/digitalobjects"
headers = {'REST-API-Key': atom_api_key,
'Conten... | 3,363 |
def fitcreds():
"""
returns the ['credentials'] dictionary
:return: dictionary or None
"""
return fitcfg().get('credentials', None) | 3,364 |
def brace_expand(str):
"""Perform brace expansion, a lá bash."""
match = re.search('{(.+?)(,.*?)?}', str)
if match:
strings = brace_expand(replace_range(str,
match.start(),
match.end(),
... | 3,365 |
def create(number):
"""
create() : Add document to Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post'}
"""
try:
id = request.json['id']
todo_ref = user_ref.docume... | 3,366 |
def turn_on(entity_id):
"""
Turn on a switch
Parameters
----------
entity_id : str
"""
call_service('{"entity_id": "' + entity_id + '" }', "switch/turn_on") | 3,367 |
def sort_terms(node, parent_children, hierarchy):
"""Recursively create a list of nodes grouped by category."""
for c in parent_children.get(node, []):
hierarchy.append(c)
sort_terms(c, parent_children, hierarchy)
return hierarchy | 3,368 |
def main() -> None:
""" Make a jazz noise here """
args = get_args()
syllables = args.syllable
song = {
'Do': 'A deer, a female deer',
'Re': 'A drop of golden sun',
'Mi': 'A name I call myself',
'Fa': 'A long long way to run',
'Sol': 'A needl... | 3,369 |
def sumPm(mirror):
"""Returns sum of all mechanical power from active machines"""
sysPm = 0.0
# for each area
for area in mirror.Area:
# reset current sum
area.cv['Pm'] = 0.0
# sum each active machine Pm to area agent
for mach in area.Machines:
if mach.cv['S... | 3,370 |
async def create_tables(conn):
"""initialize db"""
await conn.execute("""
CREATE TABLE IF NOT EXISTS embyusers (
discordid BIGINT,
embyuser TEXT,
primary key (discordid, embyuser)
)
""") | 3,371 |
def cmd_publish(sensor,hours):
"""Publish a sensor"""
if sensor == '':
name = click.promt('Please enter a name for your sensor', type=str)
endpoint = click.promt('Measurement endpoint (e.g. http://10.5.20.6:3001/measurement)', type=str)
price = click.promt('Price per measurement in satoshi', type=int)
mtype... | 3,372 |
def chunk(rs, n, column=None):
"""Returns a list of rows in chunks
:param rs: a list of rows
:param n:
- int => returns 3 rows about the same size
- list of ints, [0.3, 0.4, 0.3] => returns 3 rows of 30%, 40$, 30%
- list of nums, [100, 500, 100] => returns 4 rows with break p... | 3,373 |
def get_file_detail(traffic_file):
"""
Args:
traffic_file: a name
Returns:
roadnet_file and flow_file name
"""
phase = None
roadnet_file = None
flow_file = None
for category in TRAFFIC_CATEGORY:
if traffic_file in list(TRAFFIC_CATEGORY[category].keys()):
... | 3,374 |
def setup_logging(default_path='logging.json',
default_level=logging.INFO,
env_key='LOG_CFG'):
"""Setup logging configuration """
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, '... | 3,375 |
async def root():
"""
:return: welcoming page returning Made by @woosal1337
"""
try:
return {f"Made by @woosal1337"}
except Exception as e:
return {f"{e} has happened!"} | 3,376 |
def test_tah_pocitace_skoro_plne_konec_2():
"""
Hra na skoro plné pole (2× volno na konci).
"""
pole = "xooxxooxoxoxoxooxx--"
result = tah_pocitace(pole)
assert len(result) == 20
assert result.count("x") == 9
assert result.count("o") == 10
assert result.count("-") == 1 | 3,377 |
def sequence_accuracy_score(y_true, y_pred):
"""
Return sequence accuracy score. Match is counted only when two sequences
are equal.
"""
total = len(y_true)
if not total:
return 0
matches = sum(1 for yseq_true, yseq_pred in zip(y_true, y_pred)
if yseq_true == yseq_... | 3,378 |
def scale_axes(fig: Figure,
vertices: List[np.ndarray],
scale: float = 1.3):
"""Scale the axes of the figure to fit the given set of vertices.
Args:
fig (Figure): Figure whose axes will get re-scaled.
vertices (List[np.ndarray]): Set of vertices to be contained.
... | 3,379 |
def load_content(sentence_file):
"""Load input file with sentences to build LSH.
Args:
sentence_file (str): Path to input with txt file with sentences to Build LSH.
Returns:
dict: Dict with strings and version of string in lower case and without comma.
"""
sentences = {}
with ... | 3,380 |
def _analyse_graph(graph):
""" Analyses a connected graph to find a set of distinct paths and a
topologically ordered sequence.
"""
# Make a copy without self-cycles to modify
g = graph.clean_copy()
g0 = g.copy()
# Start with the diameter of the graph
diameter = g.diameter()
if n... | 3,381 |
def rare_last_digit(first):
"""Given a leading digit, first, return all possible last digits of a rare number"""
if first == 2:
return (2,)
elif first == 4:
return (0,)
elif first == 6:
return (0,5)
elif first == 8:
return (2,3,7,8)
else:
raise ValueError... | 3,382 |
def decorrelation_witer(W):
"""
Iterative MDUM decorrelation that avoids matrix inversion.
"""
lim = 1.0
tol = 1.0e-05
W = W/(W**2).sum()
while lim > tol:
W1 = (3.0/2.0)*W - 0.5*dot(dot(W,W.T),W)
lim = npmax(npabs(npabs(diag(dot(W1,W.T))) - 1.0))
W = W1
return W | 3,383 |
def run_task(task, request):
""" Run/enqueue the given task for the given request
Note that the request should be validated before
this is called.
@param task: Name of the task. One of package_url,
package_dwc_archive or package_datastore
@param request: Dictionary containing ... | 3,384 |
def _open_public_images(username):
"""
:param username: username of a given person
:return:
"""
try:
new_url = "https://www.facebook.com/" + username + "/photos_all"
webbrowser.open_new_tab(new_url)
return 1
except Exception as e:
print(e)
return -1 | 3,385 |
def fermat_number(n: int) -> int:
"""
https://en.wikipedia.org/wiki/Fermat_number
https://oeis.org/A000215
>>> [fermat_number(i) for i in range(5)]
[3, 5, 17, 257, 65537]
"""
return 3 if n == 0 else (2 << ((2 << (n - 1)) - 1)) + 1 | 3,386 |
def get_id_ctx(node):
"""Gets the id and attribute of a node, or returns a default."""
nid = getattr(node, "id", None)
if nid is None:
return (None, None)
return (nid, node.ctx) | 3,387 |
def fitsfile_clumpy(filename,ext=None,header=True,**kwargs):
"""Read a (CLUMPY) fits file.
Parameters:
-----------
filename : str
Path to the CLUMPY .fits file to be read.
ext : {int,str}
The FITS extension to be read. Either as EXTVER, specifying
the HDU by an integer, o... | 3,388 |
def Node(object):
"""
"""
@property
def location(self):
"""
"""
@station.setter
def location(self, value):
"""
"""
@property
def name(self):
"""
"""
@name.setter
def name(self):
"""
"""
... | 3,389 |
def is_tkg_plus_enabled(config: Optional[dict] = None) -> bool:
"""
Check if TKG plus is enabled by the provider in the config.
:param dict config: configuration provided by the user.
:return: whether TKG+ is enabled or not.
:rtype: bool
"""
if not config:
try:
config =... | 3,390 |
def da_cma(max_evaluations = 50000, da_max_evals = None, cma_max_evals = None,
popsize=31, stop_fitness = -math.inf):
"""Sequence differential evolution -> CMA-ES."""
daEvals = np.random.uniform(0.1, 0.5)
if da_max_evals is None:
da_max_evals = int(daEvals*max_evaluations)
if cma_max... | 3,391 |
def j_hashset(s: Set = None) -> jpy.JType:
"""Creates a Java HashSet from a set."""
if s is None:
return None
r = jpy.get_type("java.util.HashSet")()
for v in s:
r.add(v)
return r | 3,392 |
def get_year(h5, songidx=0):
"""
Get release year from a HDF5 song file, by default the first song in it
"""
return h5.root.musicbrainz.songs.cols.year[songidx] | 3,393 |
def _create_simulation_parametrization():
"""Convert named scenarios to parametrization.
Each named scenario is duplicated with different seeds to capture the uncertainty in
the simulation..
"""
named_scenarios = get_named_scenarios()
scenarios = []
for name, specs in named_scenarios.item... | 3,394 |
def calc_buffer(P, T, buffer):
"""
Master function to calc any buffer given a name.
Parameters
----------
P: float
Pressure in GPa
T: float or numpy array
Temperature in degrees K
buffer: str
Name of buffer
Returns
-------
float or numpy array
logfO2
"""
if buffer == 'NNO':
return calc_NNO(P... | 3,395 |
def printImproperDihedral(dihedral, alchemical = False):
"""Generate improper dihedral line
Parameters
----------
dihedral : dihedral Object
dihedral Object
Returns
-------
dihedralLine : str
Improper dihedral line data
"""
V2 = dihedral.V2*0.5
V2_B = dihedral.... | 3,396 |
def test_cache_permission(mocker, monkeypatch, tmpdir):
"""Emit a warning once that this can't cache the latest PSL."""
warning = mocker.patch.object(logging.getLogger("tldextract.cache"), "warning")
def no_permission_makedirs(*args, **kwargs):
raise PermissionError(
"""[Errno 13] Perm... | 3,397 |
def inv_erf(z):
"""
Inverse error function.
:param z: function input
:type z: float
:return: result as float
"""
if z <= -1 or z >= 1:
return "None"
if z == 0:
return 0
result = ndtri((z + 1) / 2.0) / math.sqrt(2)
return result | 3,398 |
def config_info_line(name, help_text):
"""Helper function to print formatted help text for Bazel config options."""
print('\t--config=%-12s\t# %s' % (name, help_text)) | 3,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.