content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_all_reports_url(url_1,url_2, headers=None):
""" Returns all reports URLs on a single 'url' """
if headers == None:
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'}
else:
header = headers
... | 17,700 |
def generate_url_with_signature(endpoint, signature):
"""Generate a url for an endpoint with a signature.
Args:
endpoint: An endpoint referencing a method in the backend.
signature: A signature serialized with releant data and the secret
salt.
Returns:
url for the given en... | 17,701 |
def is_scalar(dt): # real signature unknown; restored from __doc__
"""
Return True if given value is scalar.
Parameters
----------
val : object
This includes:
- numpy array scalar (e.g. np.int64)
- Python builtin numerics
- Python... | 17,702 |
def left_shift(k, n=32):
"""
Returns the n*n matrix corresponding to the operation
lambda v: vec_from_int(int_from_vec(v) << k, n)
>>> print_mat(left_shift(2, 6))
000000
000000
100000
010000
001000
000100
>>> int_from_vec(left_shift(2) * vec_from_int(42)) == 42 << 2
... | 17,703 |
def get_tensorboard_logger(
trainer: Engine, evaluators: ThreeEvaluators, metric_names: List[str]
) -> TensorboardLogger:
"""
creates a ``tensorboard`` logger which read metrics from given evaluators and attaches it to a given trainer
:param trainer: an ``ignite`` trainer to attach to
:param evalua... | 17,704 |
def get_vocabs(datasets):
"""Build vocabulary from an iteration of dataset objects
Args:
dataset: a list of dataset objects
Returns:
two sets of all the words and tags respectively in the dataset
"""
print("Building vocabulary...")
vocab_words = set()
vocab_tags = set()
... | 17,705 |
def check_row_uniqueness(board: list) -> bool:
"""
Return True if each row has no repeated digits.
Return False otherwise.
>>> check_row_uniqueness([\
"**** ****",\
"***1 ****",\
"** 3****",\
"* 4 1****",\
" 9 5 ",\
" 6 83 *",\
"3 1 **",\
" 8 2***",\
" 2 ****"\
])
True
>... | 17,706 |
def calculate_distance_to_divide(
grid, longest_path=True, add_to_grid=False, clobber=False
):
"""Calculate the along flow distance from drainage divide to point.
This utility calculates the along flow distance based on the results of
running flow accumulation on the grid. It will use the connectivity
... | 17,707 |
def run_example(device_id, do_plot=False):
"""
Run the example: Connect to a Zurich Instruments UHF Lock-in Amplifier or
UHFAWG, UHFQA, upload and run a basic AWG sequence program. It then demonstrates
how to upload (replace) a waveform without changing the sequencer program.
Requirements:
U... | 17,708 |
def string_unquote(value: str):
"""
Method to unquote a string
Args:
value: the value to unquote
Returns:
unquoted string
"""
if not isinstance(value, str):
return value
return value.replace('"', "").replace("'", "") | 17,709 |
def test_vertical_interpolation_target_depth(vertical_values):
"""Test vertical interpolation of u/v to default target depth."""
u_target_depth, v_target_depth = vertical_interpolation(vertical_values.u, vertical_values.v, vertical_values.depth,
vertic... | 17,710 |
def test_datasets_ls_files_lfs(tmpdir, large_file, runner, project):
"""Test file listing lfs status."""
# NOTE: create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code, format_result_exception(result)
assert "OK" in result.output
# NOTE: c... | 17,711 |
def main():
"""
询问用户的姓名和年龄,并根据年龄确定该玩哪个游戏。
"""
name = input("Hello, What's your name? ")
valid_input, age = False, -1
while not valid_input:
valid_input, age = validate_age(name)
game = FrogWorld if age < 18 else WizardWorld
env = GameEvn(game(name))
env.play() | 17,712 |
def translate(tx, ty, tz):
"""Translate."""
return affine(t=[tx, ty, tz]) | 17,713 |
def job_complete_worker(
completed_work_queue, work_db_path, clean_result, n_expected):
"""Update the database with completed work.
Args:
completed_work_queue (queue): queue with (working_dir, job_id)
incoming from each stitched raster
work_db_path (str): path to the work da... | 17,714 |
def randomized_svd_gpu(M, n_components, n_oversamples=10, n_iter='auto',
transpose='auto', random_state=0, lib='pytorch',tocpu=True):
"""Computes a truncated randomized SVD on GPU. Adapted from Sklearn.
Parameters
----------
M : ndarray or sparse matrix
Matrix to decompos... | 17,715 |
def clean_column_names(df: pd.DataFrame) -> pd.DataFrame:
"""Cleans the column names of the given dataframe by applying the following steps
after using the janitor `clean_names` function:
* strips any 'unnamed' field, for example 'Unnamed: 0'
* replaces the first missing name with 'is_away'
... | 17,716 |
def cos(x):
"""Return the cosine.
INPUTS
x (Variable object or real number)
RETURNS
if x is a Variable, then return a Variable with val and der.
if x is a real number, then return the value of np.cos(x).
EXAMPLES
>>> x = Variable(0, name='x')
>>> t = cos(x)
>>> print(t.val, t.der['x'])
1.0 0.0
"""
t... | 17,717 |
def write_match(out, superlocus, name, match_status, match_type):
"""Write match to output file."""
if not out:
return
for locus in sorted(superlocus, key=NormalizedLocus.record_order_key):
sample = locus.record.samples[name]
sample['BD'] = match_status
sample['BK'] = ... | 17,718 |
def _get_regions(connection):
""" Get list of regions in database excluding GB. If no regions are found,
a ValueError is raised.
"""
query_regions = connection.execute(
db.select([models.Region.code]).where(models.Region.code != "GB")
)
regions = [r[0] for r in query_regions]
if... | 17,719 |
def process_audit(logger, settings, sc_client, audit, get_started):
"""
Export audit in the format specified in settings. Formats include PDF, JSON, CSV, MS Word (docx), media, or
web report link.
:param logger: The logger
:param settings: Settings from command line and configuration file
... | 17,720 |
def word_embedding_forward(x, W):
"""
Forward pass for word embeddings. We operate on minibatches of size N where
each sequence has length T. We assume a vocabulary of V words, assigning each
to a vector of dimension D.
Inputs:
- x: Integer array of shape (N, T) giving indices of words. Each element idx
... | 17,721 |
def retrieve_from_stream(iden, interval=60):
"""
Return messages from a stream.
:param iden: Identifier of the stream.
:param interval: defaults to messages of last 60 seconds.
"""
return stm_str.get_messages(str(UID), str(TOKEN), interval, iden) | 17,722 |
def assert_allowed_methods(path, methods, app):
"""Ensures that a URL only allows a set of HTTP methods.
It not only checks that the HTTP methods passed in the ``methods`` parameter
are allowed, but also that the URL does not allow methods not included in
the list.
If the path provided does not ex... | 17,723 |
def _raise_runtime_error(info, param=None):
"""
Raise RuntimeError in both graph/pynative mode
Args:
info(str): info string to display
param(python obj): any object that can be recognized by graph mode. If is
not None, then param's value information will be extracted and display... | 17,724 |
def post_tweet(status):
"""This Function will submit a Tweet for you. In order to do this
you need to call the function with a valid string. Note you can also
add emojis. E.g
post_status("Python is awesome") """
twitter = authenticate()
twitter.update_status(status=status) | 17,725 |
def train_op(tot_loss, lr, var_opt, name):
"""
When only the discriminator is trained, the learning rate is set to be 0.0008
When the generator model is also trained, the learning rate is set to be 0.0004
Since there are batch_normalization layers in the model, we need to use update_op for keeping train... | 17,726 |
def logadd(x, y):
"""Adds two log values.
Ensures accuracy even when the difference between values is large.
"""
if x < y:
temp = x
x = y
y = temp
z = math.exp(y - x)
logProb = x + math.log(1.0 + z)
if logProb < _MinLogExp:
return _MinLogExp
els... | 17,727 |
def getResourceNameString(ro_config, rname, base=None):
"""
Returns a string value corresoponding to a URI indicated by the supplied parameter.
Relative references are assumed to be paths relative to the supplied base URI or,
if no rbase is supplied, relative to the current directory.
"""
rsplit... | 17,728 |
def NMFcomponents(ref, ref_err = None, n_components = None, maxiters = 1e3, oneByOne = False, path_save = None):
"""Returns the NMF components, where the rows contain the information.
Input: ref and ref_err should be (N * p) where n is the number of references, p is the number of pixels in each reference.
path... | 17,729 |
def parse_args():
"""
Parses arguments provided through the command line.
"""
# Initialize
parser = argparse.ArgumentParser()
# Arguments
parser.add_argument("meme_file", metavar="motifs.meme")
parser.add_argument("tomtom_file", metavar="tomtom.txt")
parser.add_argument("clusters_f... | 17,730 |
def get_mean_from_protobin(filename):
"""Get image mean from protobinary and return ndarray with skimage format.
"""
img = read_caffe_protobin(filename)
size = (img.channels, img.height, img.width)
img = caffe.io.blobproto_to_array(img).reshape(size)
img = img.transpose([1, 2, 0])
return img | 17,731 |
def has_key(key):
"""
Check if key is in the minion datastore
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' data.has_key <mykey>
"""
store = load()
return key in store | 17,732 |
def delete_file(file):
"""
Delete the file if exist
:param file: the file to delete
:type file: str
:return: None
"""
if os.path.isfile(file):
os.remove(file) | 17,733 |
def add_subprofile(subprofile, user_id, data):
"""Create a news subprofile for for a user."""
user = User.query.filter(User.id == user_id).first()
if not user:
raise KeyError('Cannot find user with id: ' + str(user_id))
url = "https://api.copernica.com/profile/{}/subprofiles/{}?access_token={}"... | 17,734 |
def __create_setting(ingest):
"""Creates the setting for a particular family"""
signer, addresser, auth_keys, threshold = ingest
settings = Settings(
auth_list=','.join(auth_keys),
threshold=threshold)
return (
signer,
addresser,
SettingPayload(
action... | 17,735 |
def test_separation(expected_great_circle):
"""
Tests that all separation functions return a dataframe using a variety of inputs.
"""
cmd = reset_simulation()
assert cmd == True
cmd = create_aircraft(
aircraft_id=aircraft_id,
type=type,
latitude=latitude,
longitu... | 17,736 |
def paser_bs(sent):
"""Convert compacted bs span to triple list
Ex:
"""
sent=sent.strip('<sos_b>').strip('<eos_b>')
sent = sent.split()
belief_state = []
domain_idx = [idx for idx,token in enumerate(sent) if token in all_domain]
for i,d_idx in enumerate(domain_idx):
next_d_... | 17,737 |
def app_factory(global_conf, **local_conf):
"""paste.deploy app factory for creating WSGI container server apps."""
conf = global_conf.copy()
conf.update(local_conf)
return ContainerController(conf) | 17,738 |
def retrieve_succinct_traceback() -> str:
"""
A utility that retrive succint traceback digest from a complete traceback string.
"""
tb = traceback.format_exc()
return "\n".join(pg.splitlines()[-1] for pg in split_paragraphs(tb)) | 17,739 |
def get_canonical_format_name(format_name):
"""
Get the canonical format name for a possible abbreviation
Args:
format_name (str): Format name or abbreviation
Returns:
The canonical name from CANONICAL_FORMATS, or None if the format is
not recognized.
"""
try:
r... | 17,740 |
def build_protoc_args(
ctx,
plugin,
proto_infos,
out_arg,
extra_options = [],
extra_protoc_args = [],
short_paths = False,
resolve_tools = True):
"""
Build the args for a protoc invocation.
This does not include the paths to the .proto files, ... | 17,741 |
def test_opf_sgen_voltage():
""" Testing a simple network with transformer for voltage
constraints with OPF using a static generator """
# boundaries
vm_max = 1.04
vm_min = 0.96
# create net
net = pp.create_empty_network()
pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=1... | 17,742 |
def cycle_left(state):
"""Rotates the probabilityfunction, translating each discrete left by one site.
The outcome is the same as if the probabilityfunction was fully local, with n_discretes
indices, and the indices were permuted with (1, 2, ..., n_discretes-1, 0).
Args:
state: The probabilityfunction to ... | 17,743 |
def make(ctx, checks, version, initial_release, skip_sign, sign_only):
"""Perform a set of operations needed to release checks:
\b
* update the version in __about__.py
* update the changelog
* update the requirements-agent-release.txt file
* update in-toto metadata
* commit the ab... | 17,744 |
def make_rare_deleterious_variants_filter(sample_ids_list=None):
""" Function for retrieving rare, deleterious variants """
and_list = [
{
"$or":
[
{"cadd.esp.af": {"$lt": 0.051}},
... | 17,745 |
def CreateTensorPileup(args):
"""
Create pileup tensor for pileup model training or calling.
Use slide window to scan the whole candidate regions, keep all candidates over specific minimum allelic frequency
and minimum depth, use samtools mpileup to store pileup info for pileup tensor generation. Only s... | 17,746 |
def upilab6_1_9 () :
"""6.1.9. Exercice UpyLaB 6.6 - Parcours rouge
Écrire une fonction symetrise_amis qui reçoit un dictionnaire d d’amis où les clés sont des prénoms et les valeurs, des
ensembles de prénoms représentant les amis de chacun.
Cette fonction modifie le dictionnaire d de sorte que si une clé preno... | 17,747 |
def PluginCompleter(unused_self, event_object):
"""Completer function that returns a list of available plugins."""
ret_list = []
if not IsLoaded():
return ret_list
if not '-h' in event_object.line:
ret_list.append('-h')
plugins_list = parsers_manager.ParsersManager.GetWindowsRegistryPlugins()
fo... | 17,748 |
def analyze_violations(files, layers, flow_graph, _assert):
"""Analyze violations provided the flow graph"""
# Get layer sizes
sizes = get_layers_size(layers.keys(), layers)
# Back calls
back_calls = get_back_calls(flow_graph, layers)
if back_calls != []:
logging.warning('Back Calls')... | 17,749 |
def train_model(item_user_data) -> []:
""""Returns trained model"""
model = implicit.als.AlternatingLeastSquares(factors=50)
model.fit(item_user_data)
return model | 17,750 |
def refresh_blind_balances(wallet, balances, storeback=True):
""" Given a list of (supposedly) unspent balances, iterate over each one
and verify it's status on the blockchain. Each balance failing
this verification updates own status in the database (if storeback is True).
Returns a list of... | 17,751 |
def command_up(
stairlight: StairLight, args: argparse.Namespace
) -> Union[dict, "list[dict]"]:
"""Execute up command
Args:
stairlight (StairLight): Stairlight class
args (argparse.Namespace): CLI arguments
Returns:
Union[dict, list]: Upstairs results
"""
return search... | 17,752 |
def hull_area(par, llhs, above_min=1):
"""Estimate projected area of llh minimum for single parameter
Parameters
----------
par : np.ndarray
the parameter values
llhs : np.ndarray
the llh values
Returns
-------
float
"""
min_llh = llhs.min()
try:
Hul... | 17,753 |
def send_images_via_email(email_subject, email_body, image_file_paths, sender_email="ozawamariajp@gmail.com", recipient_emails=["ozawamariajp@gmail.com"]):
"""
Send image via email
"""
# libraries to be imported
import os
import smtplib
from email.mime.multipart import MIMEMultipart
f... | 17,754 |
def assemble_chain(leaf, store):
"""Assemble the trust chain.
This assembly method uses the certificates subject and issuer common name and
should be used for informational purposes only. It does *not*
cryptographically verify the chain!
:param OpenSSL.crypto.X509 leaf: The leaf certificate from which to bu... | 17,755 |
def spin(node: 'Node', executor: 'Executor' = None) -> None:
"""
Execute work and block until the context associated with the executor is shutdown.
Callbacks will be executed by the provided executor.
This function blocks.
:param node: A node to add to the executor to check for work.
:param e... | 17,756 |
def test_load_facts_mismatch_version(tmpdir):
"""Test load facts when loaded nodes have different format versions."""
version1 = "version1"
node1 = {"node1": "foo"}
version2 = "version2"
node2 = {"node2": "foo"}
tmpdir.join("node1.yml").write(_encapsulate_nodes_facts(node1, version1))
tmpdir... | 17,757 |
def hcp_mg_relax_cell() -> tuple:
"""
HCP Mg relax cell, wyckoff='c'.
"""
aiida_twinpy_dir = os.path.dirname(
os.path.dirname(aiida_twinpy.__file__))
filename = os.path.join(aiida_twinpy_dir,
'tests',
'data',
... | 17,758 |
def dilate( data, iterations=1, structure=None ):
"""Dilate a binary ND array by a number of iterations."""
# Convert to binary, just in case.
mask = binarise(data).astype(int)
if not structure:
structure = ndimage.generate_binary_structure(3,1)
# Check we have positive iterat... | 17,759 |
def text_from_pdf(file_name : str) -> str:
"""
Extract text from PDF file
==========================
Parameters
----------
file_name : str
Name of the file to extract text from.
Returns
-------
str
The extracted text.
"""
from PyPDF4 import ... | 17,760 |
def read_section(section, fname):
"""Read the specified section of an .ini file."""
conf = configparser.ConfigParser()
conf.read(fname)
val = {}
try:
val = dict((v, k) for v, k in conf.items(section))
return val
except configparser.NoSectionError:
return None | 17,761 |
def _onnx_export(
model: nn.Module,
path_to_save: str,
):
"""
Export PyTorch model to ONNX.
"""
model.cpu()
model.eval()
# hardcoded [batch_size, seq_len] = [1, 1] export
tokens = torch.tensor([[0]], dtype=torch.long)
lengths = torch.tensor([1], dtype=torch.long)
with torc... | 17,762 |
async def test(ctx):
"""A test for dummies"""
member = ctx.message.author
# for row in bot.servers:
# print(row)
guilds = []
[guilds.append(x) for x in bot.guilds]
guild = guild[0]
role = discord.utils.get(ctx.message.guild.roles, name='dumb')
await bot.add_roles(member, role) | 17,763 |
def calculate_gene_coverage_fragments( annot, frags ):
"""
Iterates through the fragments aligned to a reference molecule and tracks the
overlaps of each fragment with the genes that are annotated on that reference
"""
## this can be reduced to a sliding analysis window if this performs unreasonably... | 17,764 |
def valid_tmpl(s: str):
"""check if s is valid template name"""
pattern = re.compile(r"TMPL_[A-Z0-9_]+")
if pattern.fullmatch(s) is None:
raise TealInputError("{} is not a valid template variable".format(s)) | 17,765 |
def freqz(
b, a=1, worN=512, whole=False, fs=2 * np.pi, log=False, include_nyquist=False
):
"""Compute the frequency response of a digital filter."""
h = None
lastpoint = 2 * np.pi if whole else np.pi
if log:
w = np.logspace(0, lastpoint, worN, endpoint=include_nyquist and not whole)
... | 17,766 |
def _helper_fit_partition(self, pnum, endog, exog, fit_kwds,
init_kwds_e={}):
"""handles the model fitting for each machine. NOTE: this
is primarily handled outside of DistributedModel because
joblib cannot handle class methods.
Parameters
----------
self : Distributed... | 17,767 |
def test_fox_wl() -> None:
""" Test on fox """
run_test(['-wl', FOX], './tests/expected/fox.txt.wl.out') | 17,768 |
def generate_2d_scatter(data, variables, class_data=None, class_names=None,
nrows=None, ncols=None, sharex=False, sharey=False,
show_legend=True, xy_line=False, trendline=False,
cmap_class=None, shorten_variables=False,
**kw... | 17,769 |
def getOptions(options):
"""translate command line options to PAML options."""
codeml_options = {}
if options.analysis == "branch-specific-kaks":
codeml_options["seqtype"] = "1"
codeml_options["model"] = "1"
elif options.analysis == "branch-fixed-kaks":
codeml_options["seqtype... | 17,770 |
def deserialize_block_to_json(block: Block) -> str:
"""Deserialize Block object to JSON string
Parameters
----------
block : Block
Block object
Returns
-------
str
JSON string
"""
try:
if block:
return json.dumps(
{
... | 17,771 |
def get_invocations(benchmark: Benchmark):
"""
Returns a list of invocations that invoke the tool for the given benchmark.
It can be assumed that the current directory is the directory from which execute_invocations.py is executed.
For QCOMP 2020, this should return a list of invocations for all tracks ... | 17,772 |
def see(node: "Position", move: Move = None) -> float:
"""Static-Exchange-Evaluation
Args:
node: The current position to see
move (Move, optional): The capture move to play. Defaults to None.
Returns:
float: The score associated with this capture. Positive is good.
"""
c = ... | 17,773 |
def new(option):
"""
Create a new message queue object; options must contain the type of
queue (which is the name of the child class), see above.
"""
options = option.copy()
qtype = options.pop("type", "DQS")
try:
__import__("messaging.queue.%s" % (qtype.lower()))
except SyntaxEr... | 17,774 |
def rk4(f, t0, y0, h, N):
""""Solve IVP given by y' = f(t, y), y(t_0) = y_0 with step size h > 0, for N steps,
using the Runge-Kutta 4 method.
Also works if y is an n-vector and f is a vector-valued function."""
t = t0 + np.array([i * h for i in range(N+1)])
m = len(y0)
y = np.zeros((N+1, m))
... | 17,775 |
def main():
"""
Example entry point; please see Enumeration example for more in-depth
comments on preparing and cleaning up the system.
:return: True if successful, False otherwise.
:rtype: bool
"""
# Since this application saves images in the current folder
# we must ensure that we ha... | 17,776 |
def parse_predictions(est_data, gt_data, config_dict):
""" Parse predictions to OBB parameters and suppress overlapping boxes
Args:
est_data, gt_data: dict
{point_clouds, center, heading_scores, heading_residuals,
size_scores, size_residuals, sem_cls_scores}
config_dict:... | 17,777 |
def benchmark_op(op, burn_iters: int = 2, min_iters: int = 10):
"""Final endpoint for all kb.benchmarks functions."""
assert not tf.executing_eagerly()
with tf.compat.v1.Session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
bm = tf.test.Benchmark()
result = bm.run_... | 17,778 |
def main():
""""The main function, creates everything and starts the polling loop."""
if len(sys.argv) < 2:
print("No config file specified on the command line! Usage: "
"python3 sensorReporter.py [config].ini")
sys.exit(1)
config_file = sys.argv[1]
global poll_mgr
po... | 17,779 |
def run_truncated_sprt(list_alpha, list_beta, logits_concat, labels_concat, verbose=False):
""" Calculate confusion matrix, mean hitting time, and truncate rate of a batch.
Args:
list_alpha: A list of floats.
list_beta: A list of floats with the same length as list_alpha's.
logits_concat... | 17,780 |
def get_users(metadata):
"""
Pull users, handles hidden user errors
Parameters:
metadata: sheet of metadata from mwclient
Returns:
the list of users
"""
users = []
for rev in metadata:
try:
users.append(rev["user"])
except (KeyError):
u... | 17,781 |
def solve(FLT_MIN, FLT_MAX):
"""Solving cos(x) <= -0.99, dx/dt=1, x(0) = 0
# Basic steps:
# 1. First compute the n terms for each ode
# 2. Next replace the guard with ode(t), so that it is only in t
# 3. Then compute the number of terms needed for g(t)
# 4. Finally, compute g(t) = 0 and g(t)-2g(... | 17,782 |
def run_tvm_graph(
coreml_model, target, device, input_data, input_name, output_shape, output_dtype="float32"
):
"""Generic function to compile on relay and execute on tvm"""
if isinstance(input_data, list):
shape_dict = {}
dtype_dict = {}
for i, e in enumerate(input_name):
... | 17,783 |
def detect_peaks(data, srate):
"""
obrain maximum and minimum values from blood pressure or pleth waveform
the minlist is always one less than the maxlist
"""
ret = []
if not isinstance(data, np.ndarray):
data = np.array(data)
raw_data = np.copy(data)
raw_srate = srate
# r... | 17,784 |
def unsubscribe_user( address ):
""" Unsubscribe user completely from the Mechanical Mooc - all sequences
"""
# remove from sequence group
signups = signup_model.get_all_user_signups(address)
for user_signup in signups:
sequence_list = sequence_model.sequence_list_name(user_signup['sequence... | 17,785 |
def add_entity_to_watchlist(client: Client, args) -> Tuple[str, Dict, Dict]:
"""Adds an entity to a watchlist.
Args:
client: Client object with request.
args: Usually demisto.args()
Returns:
Outputs.
"""
watchlist_name = args.get('watchlist_name')
entity_type = args.get(... | 17,786 |
def install():
"""install openssl locally."""
# clone repository
try:
clone_repository(openssl_repo_link, openssl_repo_path, openssl_name)
except LocationExists as exception:
pass
# remove local changes
try:
remove_local_changes(openssl_repo_path, openssl_name)
excep... | 17,787 |
def is_base255(channels):
"""check if a color is in base 01"""
if isinstance(channels, str):
return False
return all(_test_base255(channels).values()) | 17,788 |
def make_unrestricted_prediction(solution: SolverState) -> tuple[Role, ...]:
"""
Uses a list of true/false statements and possible role sets
to return a rushed list of predictions for all roles.
Does not restrict guesses to the possible sets.
"""
all_role_guesses, curr_role_counts = get_basic_gu... | 17,789 |
def get_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description="Expression aggregator")
parser.add_argument(
"-e", "--expressions", nargs="+", help="Expressions", required=True
)
parser.add_argument(
"-d", "--descriptors", nargs="+", help="Descriptor... | 17,790 |
def check(value, msg=""):
"""Check value for membership; raise ValueError if fails."""
if not value:
raise ValueError(f"ERROR {msg}: {value} should be true") | 17,791 |
def initworker(logq, progq, ctrlq, stdin=None):
"""initializer that sets up logging and progress from sub procs """
logToQueue(logq)
progressToQueue(progq)
controlByQueue(ctrlq)
setproctitle(current_process().name)
signal.signal(signal.SIGINT, signal.SIG_IGN)
if hasattr(signal, 'SIGBREAK'):
... | 17,792 |
def computeFourteenMeVPoint(xs, E14='14.2 MeV', useCovariance=True, covariance=None):
"""
Compute the value of the cross section at 14.2 MeV.
If the covariance is provided, the uncertainty on the 14.2 MeV point will be computed.
:param xs: reference to the cross section
:param E14: the 14 MeV point... | 17,793 |
def conn_reshape_directed(da, net=False, sep='-', order=None, rm_missing=False,
fill_value=np.nan, to_dataframe=False,
inplace=False):
"""Reshape a raveled directed array of connectivity.
This function takes a DataArray of shape (n_pairs, n_directions) or
... | 17,794 |
def cmd_appetite(manifest, extra_params, num_threads=1, delete_logs=False):
"""Run appetite with defined params
:param manifest: manifest to reference
:param extra_params: extra params if needed
:param num_threads: Number of threads to use
:param delete_logs: Delete logs before running
:return: ... | 17,795 |
def args_fixup():
"""
Various cleanups/initializations based on result of parse_args().
"""
global saved_key_handle
saved_key_handle = args.hmac_kh
args.key_handle = pyhsm.util.key_handle_to_int(args.hmac_kh)
if not (args.mode_otp or args.mode_short_otp or args.mode_totp or args.mode_hotp ... | 17,796 |
def create_manager(user):
"""
Return a ManageDNS object associated with user (for history)
"""
if 'REVERSE_ZONE' in app.config:
revzone = app.config['REVERSE_ZONE']
else:
revzone = None
return ManageDNS(nameserver=app.config['SERVER'], forward_zone=app.config['FORWARD_ZONE'],
... | 17,797 |
def ncar_topo_adj(input_forcings,ConfigOptions,GeoMetaWrfHydro,MpiConfig):
"""
Topographic adjustment of incoming shortwave radiation fluxes,
given input parameters.
:param input_forcings:
:param ConfigOptions:
:return:
"""
if MpiConfig.rank == 0:
ConfigOptions.statusMsg = "Perfo... | 17,798 |
def rank_urls(urls, year=None, filename=None):
"""
Takes a list of URLs and searches for them in
Hacker News submissions. Prints or saves each
URL and its total points to a given filename
in descending order of points. Searches for
submissions from all years, unless year is given.
"""
now = datetime.now()
if y... | 17,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.