content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_role(session, project_name, project_model_nexus):
"""
Создание локальных ролей Nexus
:param session: an opened session of NexusSession
:param project_name: name of project
:param project_model_nexus: nexus part of project map dict
"""
roles_dict = Role(session).list()
privileg... | 29,100 |
def init():
"""
Function: init
Parameter: none
Functionality: Initializes the variables
"""
global grn_graph
parent_path = os.getcwd()
file_prefix = '400'
file_name = file_prefix + '.gml'
grn_file_path = os.path.join(parent_path, 'grn_endpoint', file_name)
grn_graph = nx.read... | 29,101 |
def test_remove_autosave_file(editor_bot, mocker, qtbot):
"""
Test that remove_autosave_file() removes the autosave file.
Also, test that it updates `name_mapping`.
"""
editor_stack, editor = editor_bot
autosave = editor_stack.autosave
editor.set_text('spam\n')
autosave.maybe_autosave(... | 29,102 |
def threshold_xr_via_auc(ds, df, res_factor=3, if_nodata='any'):
"""
Takes a xarray dataset/array of gdv likelihood values and thresholds them
according to a pandas dataframe (df) of field occurrence points. Scipy
roc curve and auc is generated to perform thresholding. Pandas dataframe
must include ... | 29,103 |
def check_travis_python_versions(python_versions_in_travis, all_results):
"""
Add list of python versions to the results
"""
all_results[module_dict_key]["python_versions"] = python_versions_in_travis | 29,104 |
def plot_pie_all(day):
"""
plots two a pie charts of the distribution of vehiles by terminal, parking and pass through
"""
plt.figure(figsize=(20,8))
labels = ['A','B','C','D','E','Pass Through','Parking']
inter_labels = ['A','B','C','D','E','pass','parking']
broad = [day['terminal_tot'].s... | 29,105 |
def kd_or_scan(func=None, array=None, extra_data=None):
"""Decorator to allow functions to be call with a scan number or kd object """
if func is None:
return partial(kd_or_scan, array=array, extra_data=extra_data)
@wraps(func)
def wrapper(scan, *args, **kwargs):
# If scan number given... | 29,106 |
def matching_intervals(original: DomainNode, approx: DomainNode, conf: float) -> bool:
""" Checks if 2 intervals match in respect to a confidence interval."""
# out_of_bounds = (not matching_bounds(original.domains[v], approx.domains[v], conf) for v in original.variables)
# return not any(out_of_bounds)
... | 29,107 |
def _make_label_sigmoid_cross_entropy_loss(logits, present_labels, split):
""" Helper function to create label loss
Parameters
----------
logits: tensor of shape [batch_size, num_verts, num_labels]
present_labels: tensor of shape [batch_size, num_verts, num_labels]; labels of labelled verts
spl... | 29,108 |
def train(model, optimizer, loss_fn, dataloader, metrics, params):
"""Train the model on `num_steps` batches
Args:
model: (torch.nn.Module) the neural network
optimizer: (torch.optim) optimizer for parameters of model
loss_fn: a function that takes batch_output and batch_labels and compu... | 29,109 |
def _merge_meta(base, child):
"""Merge the base and the child meta attributes.
List entries, such as ``indexes`` are concatenated.
``abstract`` value is set to ``True`` only if defined as such
in the child class.
Args:
base (dict):
``meta`` attribute from the base class.
... | 29,110 |
def _parse_quotes(quotes_dict: Dict[str, Dict[str, Dict[str, Any]]]) -> "RegionalQuotes":
"""
Parse quote data for a :class:`~.DetailedProduct`.
:param quotes_dict:
"""
quotes: RegionalQuotes = RegionalQuotes()
for gsp, payment_methods in quotes_dict.items():
quotes[gsp] = {}
for method, fuels in payment_... | 29,111 |
def train_validation(train_df, valid_df, epochs=100, batch_size=512, plot=False,
nn_args={}):
"""
Wrapper for training on the complete training data and evaluating the
performance on the hold-out set.
Parameter:
-------------------
train_df: df,
train df... | 29,112 |
def _log_to_temp_dir(mocker, tmp_path):
"""Stub the logging dir to tmp_path."""
log_dir = tmp_path / "logs"
mocker.patch.object(youtube_monitor_action.__main__, "LOGGING_DIR", log_dir)
yield | 29,113 |
def main():
"""
The programme will find the part in the given strand with the highest similarity with the strand inputted.
"""
l = input('Please give me a DNA sequence to search: ').upper()
s = input('What DNA sequence would you like to match? ').upper()
best, similarity = homology(l, s)
pri... | 29,114 |
def retrieve_email() -> str:
"""
Uses the Git command to retrieve the current configured user email address.
:return: The global configured user email.
"""
return subprocess.run(
["git", "config", "--get", "user.email"],
capture_output=True,
text=True,
).stdout.strip("\n... | 29,115 |
def bootstrap_compute(
hind,
verif,
hist=None,
alignment="same_verifs",
metric="pearson_r",
comparison="m2e",
dim="init",
reference=["uninitialized", "persistence"],
resample_dim="member",
sig=95,
iterations=500,
pers_sig=None,
compute=compute_hindcast,
resample_u... | 29,116 |
def main():
"""CLI Main"""
git_author_name = derive_git_author()
user = derive_user()
branch = None
try:
branch = derive_branch()
perform_precommit_sanity_checks(git_author_name, user, branch)
# This is purposefully broad: we want to catch any possible error here so
# that an... | 29,117 |
def description_for_number(numobj, lang, script=None, region=None):
"""Return a text description of a PhoneNumber object for the given language.
The description might consist of the name of the country where the phone
number is from and/or the name of the geographical area the phone number
is from. Th... | 29,118 |
def _construct_new_particles(samples, old_particles):
"""Construct new array of particles given the drawing results over the old
particles.
Args:
+ *samples* (np.ndarray):
NxM array that contains the drawing results, where N is number of
observations and M number of part... | 29,119 |
def test_branches(runner):
"""Test undo alias un"""
result = runner.invoke(cli, ["branches"])
assert result.exit_code == 0 | 29,120 |
def trunc(x, y, w, h):
"""Truncates x and y coordinates to live in the (0, 0) to (w, h)
Args:
x: the x-coordinate of a point
y: the y-coordinate of a point
w: the width of the truncation box
h: the height of the truncation box.
"""
return min(max(x, 0), w - 1), min... | 29,121 |
def GetPlayFabIDsFromNintendoSwitchDeviceIds(request, callback, customData = None, extraHeaders = None):
"""
Retrieves the unique PlayFab identifiers for the given set of Nintendo Switch Device identifiers.
https://docs.microsoft.com/rest/api/playfab/server/account-management/getplayfabidsfromnintendoswitch... | 29,122 |
def testInputLog(log_file):
""" Test the user input for issues in the DNS query logs """
# if the path is a file
if os.path.isfile(log_file):
pass
else:
print("WARNING: Bad Input - Use a DNS (text) log file which has one domain per row without any other data or punctuation.")
print("Exiting...")
sys.exit(0... | 29,123 |
def test_4_1_9_audit_rule_file_exists(host):
"""
CIS Ubuntu 20.04 v1.0.0 - Rule # 4.1.9
Tests if /etc/audit/rules.d/4.1.9.rules file exists
"""
host.file(RULE_FILE_419).exists | 29,124 |
def exact_match(true_labels, predicts):
""" exact_match
This is the most strict metric for the multi label setting. It's defined
as the percentage of samples that have all their labels correctly classified.
Parameters
----------
true_labels: numpy.ndarray of shape (n_samples, n_target... | 29,125 |
def dimred3(dat):
"""convenience function dimensionally reduce input data, each row being an
element in some vector space, to dimension 3 using PCA calcualted by the
SVD"""
return dimred(dat, 3) | 29,126 |
def stedflow():
"""
stedflow()
Defined at ../src/stedflow.f lines 67-133
"""
_min3p.f90wrap_stedflow() | 29,127 |
def render_orchestrator_registrations(
driver: Driver = None,
collab_id: str = None,
project_id: str = None
):
""" Renders out retrieved registration metadata in a custom form
Args:
driver (Driver): A connected Synergos driver to communicate with the
selected orchestrator.
... | 29,128 |
def check_nan(data, new_data):
"""checks if nan values are conserved
"""
old = np.isnan(data)
new = np.isnan(new_data)
if np.all(new == old):
return True
else:
return False | 29,129 |
def Var(poly, dist=None, **kws):
"""
Element by element 2nd order statistics.
Args:
poly (chaospy.poly.ndpoly, Dist):
Input to take variance on.
dist (Dist):
Defines the space the variance is taken on. It is ignored if
``poly`` is a distribution.
Ret... | 29,130 |
def view_n_image_rels(relationships, n, image_dir="data/VisualGenome/VG_100K/"):
"""Displays a relationship from `n` distinct images.
Args:
relationships: list of relationships from VG (e.g. relationships.json)
n: images to show
image_dir: directory where images live
"""
fr... | 29,131 |
def op_par_loop_parse(text):
"""Parsing for op_par_loop calls"""
loop_args = []
search = "op_par_loop"
i = text.find(search)
while i > -1:
arg_string = text[text.find('(', i) + 1:text.find(';', i + 11)]
# parse arguments in par loop
temp_args = []
num_args = 0
# parse each op_arg_dat
... | 29,132 |
def ex7a():
"""Do not accept non-numeric inputs"""
area_of_rectangle(input_numeric, 'feet') | 29,133 |
def bin_to_hex(bin_str: str) -> str:
"""Convert a binary string to a hex string.
The returned hex string will contain the prefix '0x' only
if given a binary string with the prefix '0b'.
Args:
bin_str (str): Binary string (e.g. '0b1001')
Returns:
str: Hexadecimal string zero... | 29,134 |
def exp_value_interpolate_bp(prod_inst, util_opti,
b_ssv_sd, k_ssv_sd, epsilon_ssv_sd,
b_ssv, k_ssv, epsilon_ssv,
b_ssv_zr, k_ssv_zr, epsilon_ssv_zr,
states_vfi_dim, shocks_vfi_dim):
"""interpolate va... | 29,135 |
def remove_non_protein(
molecule: oechem.OEGraphMol,
exceptions: Union[None, List[str]] = None,
remove_water: bool = False,
) -> oechem.OEGraphMol:
"""
Remove non-protein atoms from an OpenEye molecule.
Parameters
----------
molecule: oechem.OEGraphMol
An OpenEye molecule holding... | 29,136 |
def test_2():
"""Test empties."""
num_1 = ListNode()
num_2 = ListNode()
assert add_two_numbers(num_1, num_2) == ListNode() | 29,137 |
def configure_connection(instance, name='eventstreams', credentials=None):
"""Configures IBM Streams for a certain connection.
Creates an application configuration object containing the required properties with connection information.
Example for creating a configuration for a Streams instance with conn... | 29,138 |
def setup(app):
"""
Any time a python class is referenced, make it a pretty link that doesn't
include the full package path. This makes the base classes much prettier.
"""
app.add_role_to_domain("py", "class", truncate_class_role)
return {"parallel_read_safe": True} | 29,139 |
def test_except_project_name_handler(project_name, ctrl_init, svc_client_templates_creation, mocker):
"""Test template create project controller exception raised."""
from renku.service.controllers.templates_create_project import TemplatesCreateProjectCtrl
cache, user_data = ctrl_init
svc_client, header... | 29,140 |
def transects_to_gdf(transects):
"""
Saves the shore-normal transects as a gpd.GeoDataFrame
KV WRL 2018
Arguments:
-----------
transects: dict
contains the coordinates of the transects
Returns:
-----------
gdf_all: gpd.GeoDataFrame
... | 29,141 |
def deduce_final_configuration(fetched_config):
""" Fills some variables in configuration based on those already extracted.
Args:
fetched_config (dict): Configuration variables extracted from a living environment,
Returns:
dict: Final configuration from live environment.
"""
final_c... | 29,142 |
def total_benchmark_return_nb(benchmark_value: tp.Array2d) -> tp.Array1d:
"""Get total market return per column/group."""
out = np.empty(benchmark_value.shape[1], dtype=np.float_)
for col in range(benchmark_value.shape[1]):
out[col] = returns_nb.get_return_nb(benchmark_value[0, col], benchmark_value... | 29,143 |
def young_modulus(data):
"""
Given a stress-strain dataset, returns Young's Modulus.
"""
yielding = yield_stress(data)[0]
"""Finds the yield index"""
yield_index = 0
for index, point in enumerate(data):
if (point == yielding).all():
yield_index = index
... | 29,144 |
def generateODTableDf(database: pd.DataFrame, save: bool = True) -> pd.DataFrame:
"""生成各区间OD表相关的数据集
Args:
database (pd.DataFrame): 经初始化的原始数据集
save (bool, optional): 是否另外将其保存为csv文件. Defaults to True.
Returns:
pd.DataFrame: 各区间OD表相关的数据集
"""
table4OD: np.ndarray = fetchTable4O... | 29,145 |
def check_datatype(many: bool):
"""Checks if data/filter to be inserted is a dictionary"""
def wrapper(func):
def inner_wrapper(self, _filter={}, _data=None, **kwargs):
if _data is None: # statements without two args - find, insert etc
if many: # statements that expect a l... | 29,146 |
def login():
"""Login Page"""
if request.cookies.get('user_id') and request.cookies.get('username'):
session['user_id'] = request.cookies.get('user_id')
session['username'] = request.cookies.get('username')
update_last_login(session['user_id'])
return render_template('main/index.... | 29,147 |
def suite_test():
"""
suite_test()
Run all the tests in the test suite
"""
ret = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not ret.wasSuccessful()) | 29,148 |
def _get_index_train_test_path(split_num, train = True):
"""
Method to generate the path containing the training/test split for the given
split number (generally from 1 to 20).
@param split_num Split number for which the data has to be generated
@param train Is true if the ... | 29,149 |
def reboot_nodes(batch_client, config, all_start_task_failed, node_ids):
# type: (batch.BatchServiceClient, dict, bool, list) -> None
"""Reboot nodes in a pool
:param batch_client: The batch client to use.
:type batch_client: `azure.batch.batch_service_client.BatchServiceClient`
:param dict config: ... | 29,150 |
def configureDefaultOptions():
"""Select default options based on the file format and force field."""
implicitWater = False
if session['fileType'] == 'pdb' and session['waterModel'] == 'implicit':
implicitWater = True
isAmoeba = session['fileType'] == 'pdb' and 'amoeba' in session['forcefield']
... | 29,151 |
def my_filter(predicate, lst):
"""Return a new list of those items x in lst such that predicate(x)
is True, in their relative order in lst.
Precondition: lst is a list; predicate maps items to booleans.
Examples:
* my_filter(whatever, []) = []
* If you have
def pos(n):
re... | 29,152 |
def mock_socket() -> MagicMock:
"""A mock websocket."""
return MagicMock(spec=WebSocket) | 29,153 |
def check_function(
func: ast.FunctionDef, ignore_ambiguous_signatures: bool = True
) -> Iterator[Tuple[ast.AST, List[str], List[str]]]:
"""Check the documented and actual arguments for a function.
Parameters
----------
func : ast.FunctionDef
The function to check
ignore_ambiguous_signa... | 29,154 |
def extract_annotations_objtrk(out_path, in_image, project_id, track_prefix, **kwargs):
"""
out_path: str
in_image: BiaflowsCytomineInput
project_id: int
track_prefix: str
kwargs: dict
"""
image = in_image.object
path = os.path.join(out_path, in_image.filename)
data, dim_order, _... | 29,155 |
def gen_device(dtype, ip, mac, desc, cloud):
"""Convenience function that generates devices based on they type."""
devices = {
# sp1: [0],
sp2: [
0x2711, # SP2
0x2719,
0x7919,
0x271A,
0x791A, # Honeywell SP2
0x2720, # SP... | 29,156 |
def get_dbfs_file_output(limit_file_size: Optional[pulumi.Input[bool]] = None,
path: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetDbfsFileResult]:
"""
## Example Usage
```python
import pulumi
i... | 29,157 |
def berks(berks_bin, path, action='update'):
"""
Execute various berks commands
:rtype : tuple
:param berks_bin: path to berks bin
:param path: path to change directory to before running berks commands (berks is a dir context aware tool)
:param action: berks action to run, e.g. berks install
... | 29,158 |
def container_clone(request, pk):
"""
Make a clone of the container.
Todo: show params on OPTIONS call.
Todo: permissions
:param pk pk of the container that needs to be cloned
:param name
:param description
"""
params = {}
data = request.data
if not data.get('name'):
... | 29,159 |
async def test_form_user_discovery_manual_and_auto_password_fetch(hass):
"""Test discovery skipped and we can auto fetch the password."""
await setup.async_setup_component(hass, "persistent_notification", {})
mocked_roomba = _create_mocked_roomba(
roomba_connected=True,
master_state={"state... | 29,160 |
def parse_multi_id_graph(graph, ids):
"""
Parse a graph with 1 to 3 ids and return
individual graphs with their own braced IDs.
"""
new_graphs = ''
LEVEL_STATE.next_token = ids[0]
pid1 = LEVEL_STATE.next_id()
split1 = graph.partition('({})'.format(ids[1]))
text1 = combine_bolds(split... | 29,161 |
def filter_multimappers(align_file, data):
"""
It does not seem like bowtie2 has a corollary to the -m 1 flag in bowtie,
there are some options that are close but don't do the same thing. Bowtie2
sets the XS flag for reads mapping in more than one place, so we can just
filter on that. This will not ... | 29,162 |
def try_run(obj, names):
"""Given a list of possible method names, try to run them with the
provided object. Keep going until something works. Used to run
setup/teardown methods for module, package, and function tests.
"""
for name in names:
func = getattr(obj, name, None)
if func is... | 29,163 |
def download_file(url, path=None, clobber=False):
"""
thanks to: https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py
path : str
local path to download to.
"""
if path is None:
local_filename = os.path.join(directory, url.split("/")[-1])... | 29,164 |
def write_word_concept_transducer_same_prob(data):
"""
Write the word to concept transducer as a .txt file of transitions, to be later compiled.
This function will make it so that <unk> words will have an equal probability of being mapped to all the different
concepts.
:param data: Data class contai... | 29,165 |
def param_to_secopt(param):
"""Convert a parameter name to INI section and option.
Split on the first dot. If not dot exists, return name
as option, and None for section."""
sep = '.'
sep_loc = param.find(sep)
if sep_loc == -1:
# no dot in name, skip it
section = None
opt... | 29,166 |
async def on_reaction_remove(reaction, user):
"""
This is called when a message has a reaction removed from it.
The message is stored in ``reaction.message``.
For older messages, it's possible that this event
might not get triggered.
Args:
reaction:
A Reaction object of th... | 29,167 |
def load_contracts(
web3: web3.Web3, contracts_file: str, contracts_names: List[str]
) -> Dict[str, web3.contract.Contract]:
"""
Given a list of contract names, returns a dict of contract names and contracts.
"""
res = {}
with open(contracts_file) as infile:
source_json = json.load(infil... | 29,168 |
async def test_query_no_db(hass: HomeAssistant) -> None:
"""Test the SQL sensor."""
config = {
"sensor": {
"platform": "sql",
"queries": [
{
"name": "count_tables",
"query": "SELECT 5 as value",
"column":... | 29,169 |
def main():
"""Called after using python mosaic.py"""
parser = argparse.ArgumentParser(description="Generate a mosaic from spotify playlist.")
parser.add_argument("spotifyid", help="Spotify API Client ID")
parser.add_argument("spotifysecret", help="Spotify API Client Secret")
parser.add_argument("p... | 29,170 |
def removecandidate(_id=''):
"""
Remove a candidate from the candidate list
Use with the lexcion's identifiers
/removecandidate?identifier=katt..nn.1
"""
lexicon = request.args.get('lexicon', C.config['default'])
lexconf = lexconfig.get_lexiconconf(lexicon)
try:
identifier = ... | 29,171 |
def outlier_dates_correction(series, coef=2.0):
"""Corrects the dates that are outliers.
It receives all the dates in which samples were collected,
for example for a patient and tries to (i) identify
outliers and (ii) correct them with the best possible
date.
.. note: Using mean/std for outlie... | 29,172 |
def svn_log_entry_dup(*args):
"""svn_log_entry_dup(svn_log_entry_t log_entry, apr_pool_t pool) -> svn_log_entry_t"""
return _core.svn_log_entry_dup(*args) | 29,173 |
def input_stream() -> IO:
"""Input stream fixture."""
return StringIO(
"""mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0"""
) | 29,174 |
def get_lr_scheduler(optimizer: Optimizer, cfg: CfgNode, start_epoch: int = 0):
"""Returns LR scheduler module"""
# Get mode
if cfg.TRAIN.LOSS.TYPE in ["categorical_crossentropy", "focal_loss"]:
mode = "min"
else:
raise NotImplementedError
if cfg.TRAIN.SCHEDULER.TYPE == "ReduceLROn... | 29,175 |
async def create_and_open_pool(pool_name, pool_genesis_txn_file):
"""
Creates a new local pool ledger configuration.
Then open that pool and return the pool handle that can be used later
to connect pool nodes.
:param pool_name: Name of the pool ledger configuration.
:param pool_genesis_txn_file... | 29,176 |
def rotate_char(c, n):
"""Rotate a single character n places in the alphabet
n is an integer
"""
# alpha_number and new_alpha_number will represent the
# place in the alphabet (as distinct from the ASCII code)
# So alpha_number('a')==0
# alpha_base is the ASCII code for the first letter of ... | 29,177 |
def subset_language(vocabulary, vectors, wordlist, N=32768):
"""
Subset the vocabulary/vectors to those in a wordlist.
The wordlist is a list arranged in order of 'preference'.
Note: we hope the vocabulary is contained in the wordlist,
but it might not be. N is the number of words we require.
If... | 29,178 |
def compile_subject(*, subject_id, date_of_birth, sex):
"""Compiles the NWB Subject object."""
return Subject(subject_id=subject_id, date_of_birth=date_of_birth, sex=sex) | 29,179 |
def plot_from_data(data_list, exp2dataset=None, exp_to_plot=None, figsize=None, xaxis='TotalEnvInteracts',
value_list=['Performance',], color_list=None, linestyle_list=None, label_list=None,
count=False,
font_scale=1.5, smooth=1, estimator='mean', no_legend=False... | 29,180 |
def circulation(**kwargs: Any) -> str:
"""Url to get :class:`~pymultimatic.model.component.Circulation` details."""
return _CIRCULATION.format(**kwargs) | 29,181 |
def split_parentheses(info):
"""
make all strings inside parentheses a list
:param s: a list of strings (called info)
:return: info list without parentheses
"""
# if we see the "(" sign, then we start adding stuff to a temp list
# in case of ")" sign, we append the temp list to the new_info ... | 29,182 |
def event(
name: Optional[str] = None, *, handler: bool = False
) -> Callable[[EventCallable], EventCallable]:
"""Create a new event using the signature of a decorated function.
Events must be defined before handlers can be registered using before_event, on_event, after_event, or
event_handler.
:p... | 29,183 |
def getcallargs(func, *positional, **named):
"""Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'."""
args, varargs, varkw, d... | 29,184 |
def add_target_to_anchors(string_to_fix, target="_blank"):
"""Given arbitrary string, find <a> tags and add target attributes"""
pattern = re.compile("<a(?P<attributes>.*?)>")
def repl_func(matchobj):
pattern = re.compile("target=['\"].+?['\"]")
attributes = matchobj.group("attributes")... | 29,185 |
def find_test(test_name):
"""
Find test will walk the test repo for a specific key value.
"""
pass | 29,186 |
def set_owner():
"""Handles 'mrlist setowner'."""
mlist = List(client, args.list)
new_owner = resolve_member(args.owner, False)
if not new_owner:
raise UserError('Unable to determine owner type')
mlist.setOwner(new_owner)
print "Successfully changed owner of list %s to %s" % (common.em... | 29,187 |
def startup():
"""
Entry point when not imported but executed
"""
args = get_argparser().parse_args()
main(**vars(args)) | 29,188 |
def run(dataset, runs, seasons, steering, relative=None, reference_span=30,
reference_period=None, plottype='png', writecsv=False):
"""DUMMY DOCSTRING"""
if reference_period is None:
reference_period = default_config['data']['cmip']['control_period']
if relative is None:
relative =... | 29,189 |
def calcInvariants(S, R, gradT, with_tensor_basis=False, reduced=True):
"""
This function calculates the invariant basis at one point.
Arguments:
S -- symmetric part of local velocity gradient (numpy array shape (3,3))
R -- anti-symmetric part of local velocity gradient (numpy array shape (3,... | 29,190 |
def with_uproot(histo_path: str) -> bh.Histogram:
"""Reads a histogram with uproot and returns it.
Args:
histo_path (str): path to histogram, use a colon to distinguish between path to
file and path to histogram within file (example: ``file.root:h1``)
Returns:
bh.Histogram: his... | 29,191 |
def slide5x5(xss):
"""Slide five artists at a time."""
return slidingwindow(5, 5, xss) | 29,192 |
def compute_consensus_rule(
profile,
committeesize,
algorithm="fastest",
resolute=True,
max_num_of_committees=MAX_NUM_OF_COMMITTEES_DEFAULT,
):
"""
Compute winning committees with the Consensus rule.
Based on Perpetual Consensus from
Martin Lackner Perpetual Voting: Fairness in Long... | 29,193 |
def plotprops(labelfontsize=18, legend=True, option=1, loc='upper right'):
"""
Define other properties of the SED plot: additional axis, font size etc.
"""
# Increase the size of the fonts
pylab.rcParams.update({'font.size': 15})
# Defines general properties of the plot
if option==1:
pylab.xlim(8,20) # Nemmen ... | 29,194 |
def addcron():
"""
{
"uid": "张三",
"mission_name": "定时服务名字",
"pid": "c3009c8e62544a23ba894fe5519a6b64",
"EnvId": "9d289cf07b244c91b81ce6bb54f2d627",
"SuiteIdList": ["75cc456d9c4d41f6980e02f46d611a5c"],
"runDate": 1239863854,
"interval": 60,
"alwaysS... | 29,195 |
def dict_expand(d, prefix=None):
"""
Recursively expand subdictionaries returning dictionary
dict_expand({1:{2:3}, 4:5}) = {(1,2):3, 4:5}
"""
result = {}
for k, v in d.items():
if isinstance(v, dict):
result.update(dict_expand(v, prefix=k))
else:
result[k]... | 29,196 |
def parse_config_list(config_list):
"""
Parse a list of configuration properties separated by '='
"""
if config_list is None:
return {}
else:
mapping = {}
for pair in config_list:
if (constants.CONFIG_SEPARATOR not in pair) or (pair.count(constants.CONFIG_SEPARATOR) != 1):
raise Valu... | 29,197 |
def _convert_word2id(insts, operator):
"""
:param insts:
:param operator:
:return:
"""
# print(len(insts))
# for index_inst, inst in enumerate(insts):
for inst in insts:
# copy with the word and pos
for index in range(inst.words_size):
word = inst.words[index]... | 29,198 |
def test_heartrate_reject():
"""Test the correct rejection for invalid heartrate datapoints."""
acc_tester = AcceptanceTester('heartrate')
dp = Datapoint(datetime(2018, 1, 1, 12, 0, 0), 0)
assert acc_tester(dp) is False
dp = Datapoint(datetime(2018, 1, 1, 12, 0, 0), -1)
assert acc_tester(dp) is ... | 29,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.