id int64 11 59.9k | original stringlengths 33 150k | modified stringlengths 37 150k |
|---|---|---|
38,953 | def normalize(name: str) -> str:
return " ".join((word.capitalize()) for word in name.split(" "))
| def normalize(name: str) -> str:
return ' '.join(word.capitalize() for word in name.split(' '))
|
44,297 | def sparse_expand_matrix(base_matrix, wires, wire_order=None, format="csr"):
"""Re-express a sparse base matrix acting on a subspace defined by a set of wire labels
according to a global wire order.
Args:
base_matrix (tensor_like): base matrix to expand
wires (Iterable): wires determining t... | def sparse_expand_matrix(base_matrix, wires, wire_order=None, format="csr"):
"""Re-express a sparse base matrix acting on a subspace defined by a set of wire labels
according to a global wire order.
Args:
base_matrix (tensor_like): base matrix to expand
wires (Iterable): wires determining t... |
27,394 | def uncomment(lines: List[str]) -> str:
""" Remove comments from lines in an .xvg file
Parameters
----------
lines : list of str
Lines as directly read from .xvg file
Yields
------
str
The next non-comment line, with any trailing comments removed
"""
for line in lin... | def uncomment(lines: List[str]) -> Generator[str, None, None]:
""" Remove comments from lines in an .xvg file
Parameters
----------
lines : list of str
Lines as directly read from .xvg file
Yields
------
str
The next non-comment line, with any trailing comments removed
... |
29,672 | def test_expects_comm():
class A:
def empty(self):
...
def one_arg(self, arg):
...
def comm_arg(self, comm):
...
def stream_arg(self, stream):
...
def two_arg(self, arg, other):
...
def comm_arg_other(se... | def test_expects_comm():
class A:
def empty(self):
...
def one_arg(self, arg):
...
def comm_arg(self, comm):
...
def stream_arg(self, stream):
...
def two_arg(self, arg, other):
...
def comm_arg_other(se... |
4,600 | def fmriprep_confounds_strategy(img_files, denoise_strategy="simple",
**kwargs):
"""
Use preset strategy to load confounds from :term:`fMRIPrep`.
`fmriprep_confounds_strategy` provides an interface to select confounds
based on past literature with limited parameters for ... | def fmriprep_confounds_strategy(img_files, denoise_strategy="simple",
**kwargs):
"""
Use preset strategy to load confounds from :term:`fMRIPrep`.
`fmriprep_confounds_strategy` provides an interface to select confounds
based on past literature with limited parameters for ... |
8,945 | def setup(bot):
"""Setup the coretasks plugin.
The setup phase is used to activate the throttle feature to prevent a flood
of JOIN commands when there are too many channels to join.
"""
bot.memory['join_events_queue'] = collections.deque()
# Manage JOIN flood protection
if bot.settings.cor... | def setup(bot):
"""Set up the coretasks plugin.
The setup phase is used to activate the throttle feature to prevent a flood
of JOIN commands when there are too many channels to join.
"""
bot.memory['join_events_queue'] = collections.deque()
# Manage JOIN flood protection
if bot.settings.co... |
34,878 | def device_copy(data, src_dev, dst_dev):
"""Copy data from thte source device to the destination device. This
operator helps data transferring between difference contexts for
heterogeneous execution.
Parameters
----------
data : tvm.relay.Expr
The tensor to be copied.
src_dev : Uni... | def device_copy(data, src_dev, dst_dev):
"""Copy data from the source device to the destination device. This
operator helps data transferring between difference contexts for
heterogeneous execution.
Parameters
----------
data : tvm.relay.Expr
The tensor to be copied.
src_dev : Unio... |
46,880 | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--data_dir",
default=None,
type=str,
required=True,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
)
parser.add_argument(... | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--data_dir",
default=None,
type=str,
required=True,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
)
parser.add_argument(... |
31,678 | def test_copy_dict_value():
"""
Scenario: Copy a value from one Dict toi another.
Given:
- 2 Dicts and 2 keys.
When:
- Generic method.
Then:
- Copy the value, if present.
"""
from GoogleDrive import copy_dict_value
dict_1 = {
'key1': 'val1',
'key2': 'val2'... | def test_copy_dict_value():
"""
Scenario: Copy a value from one Dict to another.
Given:
- 2 Dicts and 2 keys.
When:
- Generic method.
Then:
- Copy the value, if present.
"""
from GoogleDrive import copy_dict_value
dict_1 = {
'key1': 'val1',
'key2': 'val2',... |
10,537 | def main():
ORIGINAL_FILE = 'requirements.txt'
VENDORED_COPY = 'test/lib/ansible_test/_data/requirements/sanity.import-plugins.txt'
requirements_1 = read_file(ORIGINAL_FILE)
requirements_2 = read_file(VENDORED_COPY)
if requirements_1 is not None and requirements_2 is not None:
if requiremen... | def main():
ORIGINAL_FILE = 'requirements.txt'
VENDORED_COPY = 'test/lib/ansible_test/_data/requirements/sanity.import-plugins.txt'
requirements_1 = read_file(ORIGINAL_FILE)
requirements_2 = read_file(VENDORED_COPY)
if requirements_1 is not None and requirements_2 is not None:
if requiremen... |
49,948 | def _save(im, fp, filename):
fp.write(_MAGIC) # (2+2)
sizes = im.encoderinfo.get(
"sizes",
[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
)
width, height = im.size
sizes = filter(
lambda x: False
if (x[0] > width or x[1] > height or x[0] ... | def _save(im, fp, filename):
fp.write(_MAGIC) # (2+2)
sizes = im.encoderinfo.get(
"sizes",
[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
)
width, height = im.size
sizes = filter(
lambda x: False
if (x[0] > width or x[1] > height or x[0] ... |
8,867 | def subreddit_sorting(bot, trigger, s, sorting):
if sorting == 'new':
submissions = list(s.new())
elif sorting == 'top':
submissions = list(s.top())
elif sorting == 'hot':
submissions = list(s.hot())
elif sorting == 'controversial':
submissions = list(s.controversial())
... | def subreddit_sorting(bot, trigger, s, sorting):
if sorting == 'new':
submissions = list(s.new())
elif sorting == 'top':
submissions = list(s.top())
elif sorting == 'hot':
submissions = list(s.hot())
elif sorting == 'controversial':
submissions = list(s.controversial())
... |
28,559 | def plot_joint(
ax,
figsize,
plotters,
kind,
contour,
fill_last,
joint_kwargs,
gridsize,
textsize,
marginal_kwargs,
backend_kwargs,
show,
):
"""Bokeh joint plot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kw... | def plot_joint(
ax,
figsize,
plotters,
kind,
contour,
fill_last,
joint_kwargs,
gridsize,
textsize,
marginal_kwargs,
backend_kwargs,
show,
):
"""Bokeh joint plot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kw... |
4,702 | def figure(num=None, # autoincrement if None, else integer from 1-N
figsize=None, # defaults to rc figure.figsize
dpi=None, # defaults to rc figure.dpi
facecolor=None, # defaults to rc figure.facecolor
edgecolor=None, # defaults to rc figure.edgecolor
frameon=... | def figure(num=None, # autoincrement if None, else integer from 1-N
figsize=None, # defaults to rc figure.figsize
dpi=None, # defaults to rc figure.dpi
facecolor=None, # defaults to rc figure.facecolor
edgecolor=None, # defaults to rc figure.edgecolor
frameon=... |
29,741 | def _ffmpeg_call(infile, output, fmt='f32le', sample_rate=None, num_channels=1,
skip=None, max_len=None, cmd='ffmpeg',
rg_mode=None, rg_preamp_db=0.0):
"""
Create a sequence of strings indicating ffmpeg how to be called as well as
the parameters necessary to decode the give... | def _ffmpeg_call(infile, output, fmt='f32le', sample_rate=None, num_channels=1,
skip=None, max_len=None, cmd='ffmpeg',
replaygain_mode=None, replaygain_preamp=0.):
"""
Create a sequence of strings indicating ffmpeg how to be called as well as
the parameters necessary to dec... |
43,627 | def decompose_hamiltonian(H, hide_identity=False):
"""Decomposes a Hermitian matrix into a linear combination of Pauli operators.
Args:
H (array[complex]): an Hermitian matrix of dimension :math:`2^n\times 2^n`
Keyword Args:
hide_identity (bool): always show ~.Identity observables in the r... | def decompose_hamiltonian(H, hide_identity=False):
r"""Decomposes a Hermitian matrix into a linear combination of Pauli operators.
Args:
H (array[complex]): an Hermitian matrix of dimension :math:`2^n\times 2^n`
Keyword Args:
hide_identity (bool): always show ~.Identity observables in the ... |
1,308 | def test_bagging_classifier_voting():
# Test BaggingClassifier when base_estimator doesn't define predict_proba
A = np.random.rand(10, 4)
Y = np.random.randint(2, size=10, dtype=np.bool)
bagging_classifier = BaggingClassifier(DummyVoteClassifier())
bagging_classifier.fit(A, Y)
# All ensemble mem... | def test_bagging_classifier_voting():
# Test BaggingClassifier when base_estimator doesn't define predict_proba
A = np.random.rand(10, 4)
Y = np.random.randint(2, size=10, dtype=np.bool)
bagging_classifier = BaggingClassifier(DummyVoteClassifier())
bagging_classifier.fit(A, Y)
assert bagging_cla... |
31,857 | def ignore_ransomware_anomaly_command(client: Client, args: Dict[str, Any]) -> str:
"""Ignore detected anomalous object on Helios.
:type client: ``Client``
:param Client: cohesity helios client to use.
:type args: ``Dict[str, Any]``
:param args: Dictionary with ignore anomaly para... | def ignore_ransomware_anomaly_command(client: Client, args: Dict[str, Any]) -> str:
"""Ignore detected anomalous object on Helios.
:type client: ``Client``
:param Client: cohesity helios client to use.
:type args: ``Dict[str, Any]``
:param args: Dictionary with ignore anomaly para... |
31,948 | def fetch_incidents():
last_run = demisto.getLastRun()
if 'last_fetch_time' in last_run:
last_fetch_time = datetime.strptime(last_run['last_fetch_time'], DATETIME_FORMAT)
demisto.info(f'Found last run, fetching new alerts from {last_fetch_time}')
else:
days_back = int(demisto.params(... | def fetch_incidents():
last_run = demisto.getLastRun()
if 'last_fetch_time' in last_run:
last_fetch_time = datetime.strptime(last_run['last_fetch_time'], DATETIME_FORMAT)
demisto.info(f'Found last run, fetching new alerts from {last_fetch_time}')
else:
days_back = int(demisto.params(... |
31,575 | def fetch_records(client: Client, url_suffix, prefix, key, params):
results = fetch_record_command(client, url_suffix, prefix, key, params, None)
return_results(results)
| def fetch_records(client: Client, url_suffix, prefix, key, params):
results = fetch_record_command(client, url_suffix, prefix, key, params)
return_results(results)
|
3,022 | def interpolate_1d_fill(
values,
method="pad",
axis=0,
limit=None,
limit_area=None,
fill_value=None,
dtype=None,
):
"""
This is a 1D-versoin of `interpolate_2d`, which is used for methods `pad`
and `backfill` when interpolating. This 1D-version is necessary to be
able to han... | def interpolate_1d_fill(
values,
method="pad",
axis=0,
limit=None,
limit_area: Optional[str] = None,
fill_value=None,
dtype=None,
):
"""
This is a 1D-versoin of `interpolate_2d`, which is used for methods `pad`
and `backfill` when interpolating. This 1D-version is necessary to b... |
47,199 | def get_list_of_files(
path_or_repo: Union[str, os.PathLike],
revision: Optional[str] = None,
use_auth_token: Optional[Union[bool, str]] = None,
) -> List[str]:
"""
Gets the list of files inside :obj:`path_or_repo`.
Args:
path_or_repo (:obj:`str` or :obj:`os.PathLike`):
Can ... | def get_list_of_files(
path_or_repo: Union[str, os.PathLike],
revision: Optional[str] = None,
use_auth_token: Optional[Union[bool, str]] = None,
) -> List[str]:
"""
Gets the list of files inside :obj:`path_or_repo`.
Args:
path_or_repo (:obj:`str` or :obj:`os.PathLike`):
Can ... |
42,465 | def fstring_contains_expr(s: str) -> bool:
return any(True for _ in iter_fexpr_spans(s))
| def fstring_contains_expr(s: str) -> bool:
return any(iter_fexpr_spans(s))
|
57,830 | def main():
try:
recipients = collect_campaign_recipients()
update_campaign_email_to_field(recipients)
except Exception as e:
return_error(f'Failed to execute CollectCampaignRecipients. Error: {str(e)}')
| def main():
try:
args = demisto.args()
recipients = collect_campaign_recipients(args)
update_campaign_email_to_field(recipients)
except Exception as e:
return_error(f'Failed to execute CollectCampaignRecipients. Error: {str(e)}')
|
20,543 | def main(argv=None):
parser = get_parser()
arguments = parser.parse_args(argv)
verbose = arguments.v
set_loglevel(verbose=verbose)
# Default params
param = Param()
# Get parser info
fname_data = arguments.i
fname_mask = arguments.m
fname_mask_noise = arguments.m_noise
m... | def main(argv=None):
parser = get_parser()
arguments = parser.parse_args(argv)
verbose = arguments.v
set_loglevel(verbose=verbose)
# Default params
param = Param()
# Get parser info
fname_data = arguments.i
fname_mask = arguments.m
fname_mask_noise = arguments.m_noise
m... |
42,556 | def test_all_location_in_db(database):
"""
Test that all locations in DB deserialize to a valid Location
"""
# Query for all locations
cursor = database.conn.cursor()
locations = cursor.execute("SELECT location,seq from location")
# We deserialize, then serialize and compare the result
... | def test_all_location_in_db(database):
"""
Test that all locations in DB deserialize to a valid Location
"""
# Query for all locations
cursor = database.conn.cursor()
locations = cursor.execute('SELECT location,seq from location')
# We deserialize, then serialize and compare the result
... |
28,021 | def is_windows():
return sys.platform == "win32"
| def is_windows():
return sys.platform == "win32"
|
3,865 | def _apply_move(soln, move, seed):
"""
Apply a move to a solution to generate a neighbor solution.
Parameters
----------
soln : list of nodes
Current solution (list of nodes)
move : string
Move to be applied
seed : integer, random_state, or None (default)
Indicator... | def _apply_move(soln, move, seed):
"""
Apply a move to a solution to generate a neighbor solution.
Parameters
----------
soln : list of nodes
Current solution (list of nodes)
move : string
Move to be applied
seed : integer, random_state, or None (default)
Indicator... |
22,481 | def main(argv=None):
"""Main entry-point for the CLI tool."""
parser = arg_parser(argv, globals())
parser.add_argument('targets', metavar="TARGETS", default=None, help="Comma-separated packages for calculating the mulled hash.")
parser.add_argument('--hash', dest="hash", choices=["v1", "v2"], default="v... | def main(argv=None):
"""Main entry-point for the CLI tool."""
parser = arg_parser(argv, globals())
parser.add_argument('targets', metavar="TARGETS", default=None, help="Comma-separated packages for calculating the mulled hash.")
parser.add_argument('--hash', dest="hash", choices=["v1", "v2"], default="v... |
30,569 | def get_test_list(files_string, branch_name, two_before_ga_ver='0', conf=None, id_set=None):
"""Create a test list that should run"""
(modified_files, modified_tests_list, changed_common, is_conf_json, sample_tests, is_reputations_json,
is_indicator_json) = get_modified_files(files_string)
tests = set... | def get_test_list(files_string, branch_name, two_before_ga_ver='0', conf=None, id_set=None):
"""Create a test list that should run"""
(modified_files, modified_tests_list, changed_common, is_conf_json, sample_tests, is_reputations_json,
is_indicator_json) = get_modified_files(files_string)
tests = set... |
4,117 | def p_c_simple_base_type(s, nonempty, templates = None):
is_basic = 0
signed = 1
longness = 0
complex = 0
module_path = []
pos = s.position()
# Handle const/volatile
is_const = is_volatile = 0
while s.sy == 'IDENT':
if s.systring == 'const':
if is_const: error(po... | def p_c_simple_base_type(s, nonempty, templates=None):
is_basic = 0
signed = 1
longness = 0
complex = 0
module_path = []
pos = s.position()
# Handle const/volatile
is_const = is_volatile = 0
while s.sy == 'IDENT':
if s.systring == 'const':
if is_const: error(pos,... |
7,439 | def threshold_multiotsu(image=None, classes=3, nbins=256, *, hist=None):
r"""Generate `classes`-1 threshold values to divide gray levels in `image`,
following Otsu's method for multiple classes.
The threshold values are chosen to maximize the total sum of pairwise
variances between the thresholded gray... | def threshold_multiotsu(image=None, classes=3, nbins=256, *, hist=None):
r"""Generate `classes`-1 threshold values to divide gray levels in `image`,
following Otsu's method for multiple classes.
The threshold values are chosen to maximize the total sum of pairwise
variances between the thresholded gray... |
2,568 | def _smacof_single(
dissimilarities,
metric=True,
n_components=2,
init=None,
max_iter=300,
verbose=0,
eps=1e-3,
random_state=None,
normalize=False,
):
"""Computes multidimensional scaling using SMACOF algorithm.
Parameters
----------
dissimilarities : ndarray of shap... | def _smacof_single(
dissimilarities,
metric=True,
n_components=2,
init=None,
max_iter=300,
verbose=0,
eps=1e-3,
random_state=None,
normalize=False,
):
"""Computes multidimensional scaling using SMACOF algorithm.
Parameters
----------
dissimilarities : ndarray of shap... |
9,691 | def main():
"""Validate BOTMETA"""
path = '.github/BOTMETA.yml'
try:
with open(path, 'r') as f_path:
botmeta = yaml.safe_load(f_path)
except yaml.error.MarkedYAMLError as ex:
print('%s:%d:%d: YAML load failed: %s' % (path, ex.context_mark.line + 1, ex.context_mark.column + 1... | def main():
"""Validate BOTMETA"""
path = '.github/BOTMETA.yml'
try:
with open(path, 'r') as f_path:
botmeta = yaml.safe_load(f_path)
except yaml.error.MarkedYAMLError as ex:
print('%s:%d:%d: YAML load failed: %s' % (path, ex.context_mark.line + 1, ex.context_mark.column + 1... |
40,427 | def test_graph_store_conversion():
graph_store = MyGraphStore()
edge_index = get_edge_index(100, 100, 300)
edge_index = sort_edge_index(edge_index, sort_by_row=False)
adj = SparseTensor.from_edge_index(edge_index, sparse_sizes=(100, 100))
coo = (edge_index[0], edge_index[1])
csr = adj.csr()[:2]... | def test_graph_store_conversion():
graph_store = MyGraphStore()
edge_index = get_edge_index(100, 100, 300)
edge_index = sort_edge_index(edge_index, sort_by_row=False)
adj = SparseTensor.from_edge_index(edge_index, sparse_sizes=(100, 100))
coo = (edge_index[0], edge_index[1])
csr = adj.csr()[:2]... |
46,091 | def get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
| def _get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
|
16,478 | def report_integration(
what: str,
integration_frame: tuple[FrameSummary, str, str],
level: int = logging.WARNING,
) -> None:
"""Report incorrect usage in an integration.
Async friendly.
"""
found_frame, integration, path = integration_frame
# Keep track of integrations already reporte... | def report_integration(
what: str,
integration_frame: tuple[FrameSummary, str, str],
level: int = logging.WARNING,
) -> None:
"""Report incorrect usage in an integration.
Async friendly.
"""
found_frame, integration, path = integration_frame
# Keep track of integrations already reporte... |
38,807 | def generate_testcases(checks, prepare=False):
'''Generate concrete test cases from checks.
If `prepare` is true then each of the cases will also be prepared for
being sent to the test pipeline. Note that setting this true may slow down
the test case generation.
'''
rt = runtime.runtime()
... | def generate_testcases(checks, prepare=False):
'''Generate concrete test cases from checks.
If `prepare` is true then each of the cases will also be prepared for
being sent to the test pipeline. Note that setting this to true may slow down
the test case generation.
'''
rt = runtime.runtime()
... |
31,572 | def search_logs_command(client, args):
query = args.get('query')
time_range = args.get('time_range') if args.get('time_range') else 'Last 5 minutes'
limit = args.get('limit') if args.get('limit') else 100
repos = argToList(args.get('repos')) if args.get('repos') else []
if limit:
try:
... | def search_logs_command(client, args):
query = args.get('query')
time_range = args.get('time_range') if args.get('time_range') else 'Last 5 minutes'
limit = args.get('limit') if args.get('limit') else 100
repos = argToList(args.get('repos'))
if limit:
try:
limit = int(limit)
... |
48,803 | def validate_group_key(k: str, max_length: int = 200) -> bool:
"""Validates value used as a group key."""
if not isinstance(k, str):
raise TypeError(f"The key has to be a string and is {type(k)}:{k}")
elif len(k) > max_length:
raise AirflowException(f"The key has to be less than {max_length}... | def validate_group_key(k: str, max_length: int = 200) -> bool:
"""Validates value used as a group key."""
if not isinstance(k, str):
raise TypeError(f"The key has to be a string and is {type(k)}:{k}")
if len(k) > max_length:
raise AirflowException(f"The key has to be less than {max_length} c... |
23,031 | def test_asanyarray():
y = da.asarray(xr.DataArray([1, 2, 3.0]))
assert isinstance(y, da.array)
assert_eq(y, y)
| def test_asanyarray():
y = da.asanyarray(xr.DataArray([1, 2, 3.0]))
assert isinstance(y, da.array)
assert_eq(y, y)
|
33,043 | def pam_add_autologin(root: Path, ttys: List[str]) -> None:
login = root / "etc/pam.d/login"
if login.exists():
with open(login) as f:
original = f.read()
else:
original = ""
with open(login, "w") as f:
for tty in ttys:
# Some PAM versions require the /de... | def pam_add_autologin(root: Path, ttys: List[str]) -> None:
login = root / "etc/pam.d/login"
original = login.read_text() if login.exists() else ""
with open(login, "w") as f:
for tty in ttys:
# Some PAM versions require the /dev/ prefix, others don't. Just add both variants.
... |
48,403 | def syspatch_run(module):
cmd = module.get_bin_path('syspatch', True)
changed = False
reboot_needed = False
warnings = []
run_flag = []
check_flag = []
if module.params['revert']:
check_flag = ['-l']
if module.params['revert'] == 'all':
run_flag = ['-R']
... | def syspatch_run(module):
cmd = module.get_bin_path('syspatch', True)
changed = False
reboot_needed = False
warnings = []
# Set safe defaults for run_flag and check_flag
run_flag = ['-c']
check_flag = []
if module.params['revert']:
check_flag = ['-l']
if module.params['... |
46,905 | def test_finetune_lr_shedulers():
args_d: dict = CHEAP_ARGS.copy()
task = "summarization"
tmp_dir = make_test_data_dir()
model = BART_TINY
output_dir = tempfile.mkdtemp(prefix="output_1_")
args_d.update(
data_dir=tmp_dir,
model_name_or_path=model,
output_dir=output_dir... | def test_finetune_lr_schedulers():
args_d: dict = CHEAP_ARGS.copy()
task = "summarization"
tmp_dir = make_test_data_dir()
model = BART_TINY
output_dir = tempfile.mkdtemp(prefix="output_1_")
args_d.update(
data_dir=tmp_dir,
model_name_or_path=model,
output_dir=output_di... |
52,995 | def gen_function_cpp(name, msg=None, includes=None, calls=None, preprocessor=None):
t = Template(_function_cpp)
msg = msg or name
includes = includes or []
calls = calls or []
preprocessor = preprocessor or []
return t.render(name=name, msg=msg, includes=includes, calls=calls, preprocessor=prepr... | def gen_function_cpp(**context):
t = Template(_function_cpp)
return t.render(**context)
|
30,094 | def subparser(subparsers):
subparser = subparsers.add_parser('dna', aliases=['rna'],
usage=usage)
subparser.add_argument(
'--license', default='CC0', type=str,
help='signature license. Currently only CC0 is supported.'
)
subparser.add_argument(
... | def subparser(subparsers):
subparser = subparsers.add_parser('dna', aliases=['rna', 'nucleotide'],
usage=usage)
subparser.add_argument(
'--license', default='CC0', type=str,
help='signature license. Currently only CC0 is supported.'
)
subparser.add_a... |
31,788 | def accept_invitation(args):
try:
client = aws_session(
region=args.get('region'),
roleArn=args.get('roleArn'),
roleSessionName=args.get('roleSessionName'),
roleSessionDuration=args.get('roleSessionDuration'),
)
response = client.accept_invita... | def accept_invitation(args):
try:
client = aws_session(
region=args.get('region'),
roleArn=args.get('roleArn'),
roleSessionName=args.get('roleSessionName'),
roleSessionDuration=args.get('roleSessionDuration'),
)
response = client.accept_invita... |
29,870 | def _get_directory(output: Optional[str]) -> Optional[str]:
"""Get directory to output the snap file to.
:param output: Snap file name or directory.
:return: The directory to output the snap file to.
If no directory is provided, return None.
If directory is current working directory, return No... | def _get_directory(output: Optional[str]) -> Path:
"""Get directory to output the snap file to.
:param output: Snap file name or directory.
:return: The directory to output the snap file to.
If no directory is provided, return None.
If directory is current working directory, return None.
"... |
4,236 | def parse_impedance_ranges(settings):
"""Parse the selected electrode impedance ranges from the header.
:param settings: header settings lines
:type settings: list
:returns parsed electrode impedances
:rtype dict
"""
impedance_ranges = [item for item in settings if
"... | def _parse_impedance_ranges(settings):
"""Parse the selected electrode impedance ranges from the header.
:param settings: header settings lines
:type settings: list
:returns parsed electrode impedances
:rtype dict
"""
impedance_ranges = [item for item in settings if
... |
45,864 | def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to Rodrigues vector.
Args:
rotation_matrix: rotation matrix.
Returns:
Rodrigues vector transformation.
Shape:
- Input: :math:`(N, 3, 3)`
... | def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to Rodrigues vector.
Args:
rotation_matrix: rotation matrix.
Returns:
Rodrigues vector transformation.
Shape:
- Input: :math:`(N, 3, 3)`
... |
44,077 | def graph_to_tape(graph: MultiDiGraph) -> QuantumTape:
"""
Converts a directed multigraph to the corresponding quantum tape.
Args:
graph (MultiDiGraph): directed multigraph containing measure to be
converted to a tape
Returns:
tape (QuantumTape): the quantum tape correspond... | def graph_to_tape(graph: MultiDiGraph) -> QuantumTape:
"""
Converts a directed multigraph to the corresponding quantum tape.
Args:
graph (MultiDiGraph): directed multigraph to be converted to a tape
Returns:
tape (QuantumTape): the quantum tape corresponding to the input
**Example... |
41,923 | def plot_contour(
study: Study,
params: Optional[List[str]] = None,
target: Optional[Callable[[FrozenTrial], float]] = None,
target_name: str = "Objective Value",
) -> "go.Figure":
"""Plot the parameter relationship as contour plot in a study.
Note that, If a parameter contains missing values, ... | def plot_contour(
study: Study,
params: Optional[List[str]] = None,
target: Optional[Callable[[FrozenTrial], float]] = None,
target_name: str = "Objective Value",
) -> "go.Figure":
"""Plot the parameter relationship as contour plot in a study.
Note that, If a parameter contains missing values, ... |
55,046 | def net_flow_constraint(graph: nx.DiGraph) -> qml.Hamiltonian:
r"""Calculates the `net flow constraint <https://doi.org/10.1080/0020739X.2010.526248>`__
Hamiltonian.
The net-zero flow constraint is, for all :math:`i`:
.. math:: \sum_{j, (i, j) \in E} x_{ij} = \sum_{j, (j, i) \in E} x_{ji},
where ... | def net_flow_constraint(graph: nx.DiGraph) -> qml.Hamiltonian:
r"""Calculates the `net flow constraint <https://doi.org/10.1080/0020739X.2010.526248>`__
Hamiltonian.
The net-zero flow constraint is, for all :math:`i`:
.. math:: \sum_{j, (i, j) \in E} x_{ij} = \sum_{j, (j, i) \in E} x_{ji},
where ... |
24,391 | def resolve_db_host(db_host):
agent_hostname = datadog_agent.get_hostname()
if not db_host or db_host in {'localhost', '127.0.0.1'}:
return agent_hostname
try:
host_ip = socket.gethostbyname(db_host)
except socket.gaierror as e:
# could be connecting via a unix domain socket
... | def resolve_db_host(db_host):
agent_hostname = datadog_agent.get_hostname()
if not db_host or db_host in {'localhost', '127.0.0.1'}:
return agent_hostname
try:
host_ip = socket.gethostbyname(db_host)
except socket.gaierror as e:
# could be connecting via a unix domain socket
... |
43,929 | def _boys(n, t):
r"""Evaluate Boys function.
The :math:`n`-th order `Boys function <https://arxiv.org/abs/2107.01488>`_ is defined as
.. math::
F_n(t) = \int_{0}^{1}x^{2n} e^{-tx^2}dx.
The Boys function is related to the lower incomplete Gamma
`function <https://en.wikipedia.org/wiki/Inc... | def _boys(n, t):
r"""Evaluate the Boys function.
The :math:`n`-th order `Boys function <https://arxiv.org/abs/2107.01488>`_ is defined as
.. math::
F_n(t) = \int_{0}^{1}x^{2n} e^{-tx^2}dx.
The Boys function is related to the lower incomplete Gamma
`function <https://en.wikipedia.org/wiki... |
4,920 | def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
"""
Create a subplot at a specific location inside a regular grid.
Parameters
----------
shape : (int, int)
Number of rows and of columns of the grid in which to place axis.
loc : (int, int)
Row number and c... | def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
"""
Create a subplot at a specific location inside a regular grid.
Parameters
----------
shape : (int, int)
Number of rows and of columns of the grid in which to place axis.
loc : (int, int)
Row number and c... |
462 | def _modify_user_status(request, domain, user_id, is_active):
user = CommCareUser.get_by_user_id(user_id, domain)
if (not _can_edit_workers_location(request.couch_user, user)
or (is_active and not can_add_extra_mobile_workers(request))):
return json_response({
'error': _("No Perm... | def _modify_user_status(request, domain, user_id, is_active):
user = CommCareUser.get_by_user_id(user_id, domain)
if (not _can_edit_workers_location(request.couch_user, user)
or (is_active and not can_add_extra_mobile_workers(request))):
return json_response({
'error': _("No Perm... |
44,831 | def _get_or_create_conda_env_root_dir(nfs_root_dir):
global _CONDA_ENV_ROOT_DIR
if _CONDA_ENV_ROOT_DIR is None:
if nfs_root_dir is not None:
# In databricks, the '/local_disk0/.ephemeral_nfs' is mounted as NFS disk
# the data stored in the disk is shared with all remote nodes.
... | def _get_or_create_conda_env_root_dir(nfs_root_dir):
global _CONDA_ENV_ROOT_DIR
if _CONDA_ENV_ROOT_DIR is None:
if nfs_root_dir is not None:
# In databricks, the '/local_disk0/.ephemeral_nfs' is mounted as NFS disk
# the data stored in the disk is shared with all remote nodes.
... |
57,836 | def format_cloud_resource_data(cloud_resources: List[Dict[str, Any]]) -> List[CommandResults]:
cloud_resource_data_list: List[Dict[str, Any]] = []
command_results = []
hr_cloud_resource_list = []
for cloud_resource_data in cloud_resources:
cloud_resource_data_list.append(cloud_resource_data)
... | def format_cloud_resource_data(cloud_resources: List[Dict[str, Any]]) -> List[CommandResults]:
cloud_resource_data_list: List[Dict[str, Any]] = []
command_results = []
hr_cloud_resource_list = []
for cloud_resource_data in cloud_resources:
cloud_resource_data_list.append(cloud_resource_data)
... |
40,415 | def run(args: argparse.ArgumentParser) -> None:
print("BENCHMARK STARTS")
for dataset_name in args.datasets:
print("Dataset: ", dataset_name)
if args.datasets_root == 'data':
root = osp.join(osp.dirname(osp.realpath(__file__)), '../..',
'data',
... | def run(args: argparse.ArgumentParser) -> None:
print("BENCHMARK STARTS")
for dataset_name in args.datasets:
print("Dataset: ", dataset_name)
if args.datasets_root == 'data':
root = osp.join(osp.dirname(osp.realpath(__file__)), '../..',
'data',
... |
34,024 | def format_error_message(exception_message: str, task_exception=False):
"""Improve the formatting of an exception thrown by a remote function.
This method takes a traceback from an exception and makes it nicer by
removing a few uninformative lines and adding some space to indent the
remaining lines nic... | def format_error_message(exception_message: str, task_exception: bool = False):
"""Improve the formatting of an exception thrown by a remote function.
This method takes a traceback from an exception and makes it nicer by
removing a few uninformative lines and adding some space to indent the
remaining l... |
26,030 | def managed_db_log_replay_stop(
cmd,
client,
database_name,
managed_instance_name,
resource_group_name):
'''
Stop log replay restore.
'''
restore_details_client = get_sql_managed_database_restore_details_operations(cmd.cli_ctx, None)
# Determine if managed D... | def managed_db_log_replay_stop(
cmd,
client,
database_name,
managed_instance_name,
resource_group_name):
'''
Stop log replay restore.
'''
restore_details_client = get_sql_managed_database_restore_details_operations(cmd.cli_ctx, None)
# Determine if managed D... |
27,992 | def collect_file_info(files):
"""Collect file information about given list of files like:
- last modification time
- content hash
If the file is missing the corresponding data will
be empty.
"""
res = {}
for sf in files:
res[sf] = {}
if os.path.isfile(sf):
... | def collect_file_info(files):
"""Collect file information about given list of files like:
- last modification time
- content hash
If the file is missing the corresponding data will
be empty.
"""
res = {}
for sf in files:
res[sf] = {}
if os.path.isfile(sf):
... |
5,997 | def get_simd_group_size(dev, type_size):
"""Return an estimate of how many work items will be executed across SIMD
lanes. This returns the size of what Nvidia calls a warp and what AMD calls
a wavefront.
Only refers to implicit SIMD.
:arg type_size: number of bytes in vector entry type.
"""
... | def get_simd_group_size(dev, type_size):
"""Return an estimate of how many work items will be executed across SIMD
lanes. This returns the size of what Nvidia calls a warp and what AMD calls
a wavefront.
Only refers to implicit SIMD.
:arg type_size: number of bytes in vector entry type.
"""
... |
31,532 | def trustwave_seg_spiderlabs_forward_quarantine_message_as_spam_command(client: Client,
block_number: str,
edition: str,
... | def trustwave_seg_spiderlabs_forward_quarantine_message_as_spam_command(client: Client,
block_number: str,
edition: str,
... |
26,617 | def _tabulate_dag_runs(dag_runs: List[DagRun], tablefmt="fancy_grid"):
tabulat_data = (
{
'ID': dag_run.id,
'Run ID': dag_run.run_id,
'State': dag_run.state,
'DAG ID': dag_run.dag_id,
'Execution date': dag_run.execution_date.isoformat() if dag_run.... | def _tabulate_dag_runs(dag_runs: List[DagRun], tablefmt="fancy_grid"):
tabulat_data = (
{
'ID': dag_run.id,
'Run ID': dag_run.run_id,
'State': dag_run.state,
'DAG ID': dag_run.dag_id,
'Execution date': dag_run.execution_date.isoformat() if dag_run.... |
35,846 | def test_msg_data_internal_fn_usage_denied(get_contract):
code = """
@internal
def foo() -> Bytes[4]:
return msg.data[4]
@external
def bar() -> Bytes[4]:
return self.foo()
"""
with pytest.raises(StateAccessViolation):
compiler.compile_code(code)
| def test_msg_data_internal_fn_usage_denied(get_contract):
code = """
@internal
def foo() -> Bytes[4]:
return slice(msg.data, 0, 4)
@external
def bar() -> Bytes[4]:
return self.foo()
"""
with pytest.raises(StateAccessViolation):
compiler.compile_code(code)
|
32,928 | def truncate_to_length(value, max_length, suffix="..."):
"""Truncate a string to a maximum length and append a suffix."""
if not value or len(value) <= max_length:
return value
return value[:max_length] + suffix
| def truncate_to_length(value, max_length, suffix="..."):
"""Truncate a string to a maximum length and append a suffix."""
if not value or len(value) <= max_length:
return value
return value[:max_length-len(suffix)] + suffix
|
42,594 | def test_coingecko_identifiers_are_reachable():
"""
Test that all assets have a coingecko entry and that all the identifiers exist in coingecko
"""
coingecko = Coingecko()
all_coins = coingecko.all_coins()
# If coingecko identifier is missing test is trying to suggest possible assets.
symbol... | def test_coingecko_identifiers_are_reachable():
"""
Test that all assets have a coingecko entry and that all the identifiers exist in coingecko
"""
coingecko = Coingecko()
all_coins = coingecko.all_coins()
# If coingecko identifier is missing test is trying to suggest possible assets.
symbol... |
33,276 | def _transcribe(item, parent=None, editRate=24, masterMobs=None):
result = None
metadata = {}
# First lets grab some standard properties that are present on
# many types of AAF objects...
metadata["Name"] = _get_name(item)
metadata["ClassName"] = _get_class_name(item)
if isinstance(item, a... | def _transcribe(item, parent=None, editRate=24, masterMobs=None):
result = None
metadata = {}
# First lets grab some standard properties that are present on
# many types of AAF objects...
metadata["Name"] = _get_name(item)
metadata["ClassName"] = _get_class_name(item)
if isinstance(item, a... |
31,551 | def search(post_to_warroom: bool = True) -> Tuple[dict, Any]:
"""
will search in MISP
Returns
dict: Object with results to demisto:
"""
d_args = demisto.args()
# List of all applicable search arguments
search_args = [
'event_id',
'value',
'type',
'categor... | def search(post_to_warroom: bool = True) -> Tuple[dict, Any]:
"""
will search in MISP
Returns
dict: Object with results to demisto:
"""
d_args = demisto.args()
# List of all applicable search arguments
search_args = [
'event_id',
'value',
'type',
'categor... |
3,484 | def track_info(recording, index=None, medium=None, medium_index=None,
medium_total=None):
"""Translates a MusicBrainz recording result dictionary into a beets
``TrackInfo`` object. Three parameters are optional and are used
only for tracks that appear on releases (non-singletons): ``index``,
... | def track_info(recording, index=None, medium=None, medium_index=None,
medium_total=None):
"""Translates a MusicBrainz recording result dictionary into a beets
``TrackInfo`` object. Three parameters are optional and are used
only for tracks that appear on releases (non-singletons): ``index``,
... |
30,563 | def splunk_job_status(service):
job = service.job(demisto.args()['sid'])
status = job.state.content['dispatchState']
entry_context = {
'SID': demisto.args()['sid'],
'Status': status
}
context = {'Splunk.JobStatus(val.ID && val.ID === obj.ID)': entry_context}
human_readable = tab... | def splunk_job_status(service):
job = service.job(demisto.args()['sid'])
status = job.state.content['dispatchState']
entry_context = {
'SID': demisto.args()['sid'],
'Status': status
}
context = {'Splunk.JobStatus(val.SID && val.ID === obj.SID)': entry_context}
human_readable = t... |
28,581 | def plot_ppc(
data,
kind="kde",
alpha=None,
mean=True,
observed=True,
color=None,
colors=None,
grid=None,
figsize=None,
textsize=None,
data_pairs=None,
var_names=None,
filter_vars=None,
coords=None,
flatten=None,
flatten_pp=None,
num_pp_samples=None,
... | def plot_ppc(
data,
kind="kde",
alpha=None,
mean=True,
observed=True,
color=None,
colors=None,
grid=None,
figsize=None,
textsize=None,
data_pairs=None,
var_names=None,
filter_vars=None,
coords=None,
flatten=None,
flatten_pp=None,
num_pp_samples=None,
... |
31,589 | def get_rules(client_obj, args: Dict[str, str]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Returns context data and raw response for gcb-list-rules command.
:type client_obj: Client
:param client_obj: client object which is used to get response from api
:type args: Dict[str, str]
:param ar... | def get_rules(client_obj, args: Dict[str, str]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Returns context data and raw response for gcb-list-rules command.
:type client_obj: Client
:param client_obj: client object which is used to get response from api
:type args: Dict[str, str]
:param ar... |
390 | def test_posdef_symmetric3():
"""The test return 0 if the matrix has 0 eigenvalue.
Is this correct?
"""
data = np.array([[1.0, 1], [1, 1]], dtype=aesara.config.floatX)
assert posdef(data) == 0
| def test_posdef_symmetric3():
"""The test returns 0 if the matrix has 0 eigenvalue.
Is this correct?
"""
data = np.array([[1.0, 1], [1, 1]], dtype=aesara.config.floatX)
assert posdef(data) == 0
|
50,526 | def _generate_spiketrains(freq, length, trigger_events, injection_pos,
trigger_pre_size, trigger_post_size,
time_unit=1*pq.s):
"""
Generate two spiketrains from a homogeneous Poisson process with
injected coincidences.
"""
st1 = homogeneous_poisson... | def _generate_spiketrains(freq, length, trigger_events, injection_pos,
trigger_pre_size, trigger_post_size,
time_unit=1*pq.s):
"""
Generate two spiketrains from a homogeneous Poisson process with
injected coincidences.
"""
st1 = StationaryPoissonPr... |
21,217 | def generate_command_cache(bench_path='.'):
"""Caches all available commands (even custom apps) via Frappe
Default caching behaviour: generated the first time any command (for a specific bench directory)
"""
python = get_env_cmd('python', bench_path=bench_path)
sites_path = os.path.join(bench_path, 'sites')
if ... | def generate_command_cache(bench_path='.'):
"""Caches all available commands (even custom apps) via Frappe
Default caching behaviour: generated the first time any command (for a specific bench directory)
"""
python = get_env_cmd('python', bench_path=bench_path)
sites_path = os.path.join(bench_path, 'sites')
if ... |
27,452 | def lintify(meta, recipe_dir=None, conda_forge=False):
lints = []
hints = []
major_sections = list(meta.keys())
# If the recipe_dir exists (no guarantee within this function) , we can
# find the meta.yaml within it.
meta_fname = os.path.join(recipe_dir or "", "meta.yaml")
sources_section =... | def lintify(meta, recipe_dir=None, conda_forge=False):
lints = []
hints = []
major_sections = list(meta.keys())
# If the recipe_dir exists (no guarantee within this function) , we can
# find the meta.yaml within it.
meta_fname = os.path.join(recipe_dir or "", "meta.yaml")
sources_section =... |
6,920 | def get_users_for_mentions():
return frappe.get_all('User',
fields=['name as id', 'full_name as value'],
filters={
'name': ['not in', ('Administrator', 'Guest')],
'allowed_in_mentions': True,
'user_type': 'System User',
'enabled': 1
})
| def get_users_for_mentions():
return frappe.get_all('User',
fields=['name as id', 'full_name as value'],
filters={
'name': ['not in', ('Administrator', 'Guest')],
'allowed_in_mentions': True,
'user_type': 'System User',
'enabled': True,
})
|
45,511 | def test_posting_env_config_return_400_when_slack_project_config_does_not_exists(
admin_client, environment, environment_api_key
):
# Given
url = reverse(
"api-v1:environments:integrations-slack-list",
args=[environment_api_key],
)
# When
response = admin_client.post(
url... | def test_posting_env_config_return_400_when_slack_project_config_does_not_exist(
admin_client, environment, environment_api_key
):
# Given
url = reverse(
"api-v1:environments:integrations-slack-list",
args=[environment_api_key],
)
# When
response = admin_client.post(
url,... |
19,991 | def find_color_card(img, threshold='adaptgauss', threshvalue=125, blurry=False, background='dark'):
"""Automatically detects a color card and output info to use in create_color_card_mask function
Inputs:
img = Input RGB image data containing a color card.
threshold = Threshold method, e... | def find_color_card(img, threshold='adaptgauss', threshvalue=125, blurry=False, background='dark'):
"""Automatically detects a color card and output info to use in create_color_card_mask function
Inputs:
img = Input RGB image data containing a color card.
threshold = Threshold method, e... |
53,976 | def nae3sat(variables: typing.Union[int, typing.Sequence[dimod.typing.Variable]],
rho: float = 2.1,
*,
seed: typing.Union[None, int, np.random.Generator] = None,
replace: bool = True,
) -> BinaryQuadraticModel:
"""Generator for Not-All-Equal 3-SAT (NAE3SAT... | def nae3sat(variables: typing.Union[int, typing.Sequence[dimod.typing.Variable]],
rho: float = 2.1,
*,
seed: typing.Union[None, int, np.random.Generator] = None,
replace: bool = True,
) -> BinaryQuadraticModel:
"""Generator for Not-All-Equal 3-SAT (NAE3SAT... |
27,990 | def add_arguments_to_parser(parser):
"""
Add the subcommand's arguments to the given argparse.ArgumentParser.
"""
parser.add_argument('input',
type=str,
nargs='+',
metavar='folder',
help="The analysis result... | def add_arguments_to_parser(parser):
"""
Add the subcommand's arguments to the given argparse.ArgumentParser.
"""
parser.add_argument('input',
type=str,
nargs='+',
metavar='folder',
help="The analysis result... |
3,808 | def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
precision=6, equal_nan=True, equal_inf=True,
strict=False):
__tracebackhide__ = True # Hide traceback for py.test
from numpy.core import array, array2string, isnan, inf, bool_, errs... | def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
precision=6, equal_nan=True, equal_inf=True,
*, strict=False):
__tracebackhide__ = True # Hide traceback for py.test
from numpy.core import array, array2string, isnan, inf, bool_, e... |
31,271 | def main():
try:
indicator = demisto.args()['indicator']
resp = demisto.executeCommand("getIndicator", {'value': indicator})
if isError(resp) or not resp:
demisto.results(resp)
sys.exit(0)
data = resp[0].get("Contents")
if not data:
demi... | def main():
try:
indicator = demisto.args()['indicator']
resp = demisto.executeCommand("getIndicator", {'value': indicator})
if isError(resp) or not resp:
demisto.results(resp)
sys.exit(0)
data = resp[0].get("Contents")
if not data:
demi... |
46,292 | def is_diagonal(matrix, tol=1e-8):
"""Determine whether affine is a diagonal matrix.
Parameters
----------
matrix : 2-D array
The matrix to test.
tol : float, optional
Consider any entries with magnitude < `tol` as 0.
Returns
-------
is_diag : bool
Boolean indic... | def is_diagonal(matrix, tol=1e-8):
"""Determine whether a square matrix is diagonal up to some tolerance.
Parameters
----------
matrix : 2-D array
The matrix to test.
tol : float, optional
Consider any entries with magnitude < `tol` as 0.
Returns
-------
is_diag : bool
... |
50,372 | def _send_email_to_user(request, user, msg, *, email=None, allow_unverified=False):
# If we were not given a specific email object, then we'll default to using
# the User's primary email address.
if email is None:
email = user.primary_email
# If we were not able to locate an email address for t... | def _send_email_to_user(request, user, msg, *, email=None, allow_unverified=False):
# If we were not given a specific email object, then we'll default to using
# the User's primary email address.
if email is None:
email = user.primary_email
# If we were not able to locate an email address for t... |
40,709 | def _check_output_types(output: Any):
y_pred, y = output
if y_pred.dtype not in (torch.float16, torch.float32, torch.float64):
raise TypeError("Input y_pred dtype should be float 16, 32 or 64, but given {}".format(y_pred.dtype))
if y.dtype not in (torch.float16, torch.float32, torch.float64):
... | def _check_output_types(output: Tuple[torch.Tensor, torch.Tensor]):
y_pred, y = output
if y_pred.dtype not in (torch.float16, torch.float32, torch.float64):
raise TypeError("Input y_pred dtype should be float 16, 32 or 64, but given {}".format(y_pred.dtype))
if y.dtype not in (torch.float16, torch.... |
41,905 | def _get_contour_plot(study: Study, params: Optional[List[str]] = None) -> "go.Figure":
layout = go.Layout(title="Contour Plot")
trials = [trial for trial in study.trials if trial.state == TrialState.COMPLETE]
if len(trials) == 0:
_logger.warning("Your study does not have any completed trials.")
... | def _get_contour_plot(study: Study, params: Optional[List[str]] = None) -> "go.Figure":
layout = go.Layout(title="Contour Plot")
trials = [trial for trial in study.trials if trial.state == TrialState.COMPLETE]
if len(trials) == 0:
_logger.warning("Your study does not have any completed trials.")
... |
1,249 | def proc_file(f, opts):
verbose(1, f"Loading {f}")
row = [f"@l{f}"]
try:
vol = nib.load(f)
h = vol.header
except Exception as e:
row += ['failed']
verbose(2, f"Failed to gather information -- {str(e)}")
return row
row += [str(safe_get(h, 'data_dtype')),
... | def proc_file(f, opts):
verbose(1, f"Loading {f}")
row = [f"@l{f}"]
try:
vol = nib.load(f)
h = vol.header
except Exception as e:
row += ['failed']
verbose(2, f"Failed to gather information -- {str(e)}")
return row
row += [str(safe_get(h, 'data_dtype')),
... |
57,510 | def validator(
*fields: str,
pre: bool = False,
each_item: bool = False,
always: bool = False,
check_fields: bool = True,
whole: bool = None,
allow_reuse: bool = False,
) -> Callable[[AnyCallable], classmethod]:
"""
Decorate methods on the class indicating that they should be used to... | def validator(
*fields: str,
pre: bool = False,
each_item: bool = False,
always: bool = False,
check_fields: bool = True,
whole: bool = None,
allow_reuse: bool = False,
) -> Callable[[AnyCallable], classmethod]:
"""
Decorate methods on the class indicating that they should be used to... |
30,389 | def decrypt_email_body(client: Client, args: Dict):
""" Decrypt the message
Args:
client: Client
args: Dict
"""
encrypt_message = demisto.getFilePath(args.get('encrypt_message'))
# Load private key and cert.
client.smime.load_key(client.private_key_file, client.public_key_file)... | def decrypt_email_body(client: Client, args: Dict):
""" Decrypt the message
Args:
client: Client
args: Dict
"""
encrypt_message = demisto.getFilePath(args.get('encrypt_message'))
# Load private key and cert.
client.smime.load_key(client.private_key_file, client.public_key_file)... |
12,066 | def test_no_candidates(pip_conf, runner):
with open("requirements", "w") as req_in:
req_in.write("small-fake-a==>0.3b1,<0.3b1")
out = runner.invoke(cli, ["-n", "requirements"])
assert out.exit_code == 2
assert "Skipped pre-versions:" in out.stderr
| def test_no_candidates(pip_conf, runner):
with open("requirements", "w") as req_in:
req_in.write("small-fake-a>0.3b1,<0.3b1")
out = runner.invoke(cli, ["-n", "requirements"])
assert out.exit_code == 2
assert "Skipped pre-versions:" in out.stderr
|
49,070 | def test_ContinuousRV():
pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution
# X and Y should be equivalent
X = ContinuousRV(x, pdf, check=True)
Y = Normal('y', 0, 1)
assert variance(X) == variance(Y)
assert P(X > 0) == P(Y > 0)
Z = ContinuousRV(z, exp(-z), set=Interval(0, oo))
... | def test_ContinuousRV():
pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution
# X and Y should be equivalent
X = ContinuousRV(x, pdf, check=True)
Y = Normal('y', 0, 1)
assert variance(X) == variance(Y)
k = 2
n = 10
samples = dict(scipy=[], numpy=[], pymc3=[])
for lib in sa... |
32,005 | def get_impacted_resources(client: PrismaCloudComputeClient, args: dict) -> CommandResults:
"""
Get the impacted resources list.
Implement the command 'prisma-cloud-compute-vulnerabilities-impacted-resources-list'
Args:
client (PrismaCloudComputeClient): prisma-cloud-compute client.
arg... | def get_impacted_resources(client: PrismaCloudComputeClient, args: dict) -> CommandResults:
"""
Get the impacted resources list.
Implement the command 'prisma-cloud-compute-vulnerabilities-impacted-resources-list'
Args:
client (PrismaCloudComputeClient): prisma-cloud-compute client.
arg... |
12,206 | def list_all_known_prefixes():
all_env_paths = set()
# If the user is an admin, load environments from all user home directories
if is_admin():
if on_win:
home_dir_dir = dirname(expand('~'))
search_dirs = tuple(entry.path for entry in scandir(home_dir_dir))
else:
... | def list_all_known_prefixes():
all_env_paths = set()
# If the user is an admin, load environments from all user home directories
if is_admin():
if on_win:
home_dir_dir = dirname(expand('~'))
search_dirs = tuple(entry.path for entry in scandir(home_dir_dir))
else:
... |
30,020 | def rk4(derivs, y0, t):
"""
Integrate 1-D or N-D system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy. Otherwise use
:func:`scipy.integrate`.
Example::
>>> ### 2D system
>>> def derivs... | def rk4(derivs, y0, t):
"""
Integrate 1-D or N-D system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy. Otherwise use
:func:`scipy.integrate`.
Example:
>>> ### 2D system
>>> def derivs(... |
2,441 | def spectral_embedding(
adjacency,
*,
n_components=8,
eigen_solver=None,
random_state=None,
eigen_tol=0.0,
norm_laplacian=True,
drop_first=True,
):
"""Project the sample on the first eigenvectors of the graph Laplacian.
The adjacency matrix is used to compute a normalized graph ... | def spectral_embedding(
adjacency,
*,
n_components=8,
eigen_solver=None,
random_state=None,
eigen_tol=0.0,
norm_laplacian=True,
drop_first=True,
):
"""Project the sample on the first eigenvectors of the graph Laplacian.
The adjacency matrix is used to compute a normalized graph ... |
10,512 | def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']),
state=dict(type='str', default='present', choices=['absent', 'present']),
regexp=dict(type='str', aliases=['regex']),
literal=d... | def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']),
state=dict(type='str', default='present', choices=['absent', 'present']),
regexp=dict(type='str', aliases=['regex']),
literal=d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.