content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pickle_loads(inbox):
"""
Deserializes the first element of the input using the pickle protocol.
"""
gc.disable()
obj = cPickle.loads(inbox[0])
gc.enable()
return obj | 52,000 |
def NOT_TENSOR_FILTER(arg_value):
"""Only keeps a value if it is not a Tensor or SparseTensor."""
return not arg_value.is_tensor and not arg_value.is_sparse_tensor | 52,001 |
def test_4():
"""
Test PCE coefficients w/ ridge
"""
polynomial_basis = TotalDegreeBasis(dist, max_degree)
ridge = RidgeRegression()
pce = PolynomialChaosExpansion(polynomial_basis=polynomial_basis, regression_method=ridge)
pce.fit(x, y)
assert round(pce.coefficients[0][0], 4) == 0.0276 | 52,002 |
def rod_3D(x, gm=None, median=None, scaler1=None, scaler2=None):
"""Find ROD scores for 3D Data. note that gm, scaler1 and scaler2 will be
returned "as they are" and without being changed if the model has been fit
already.
Parameters
----------
x : array-like, 3D data points.
gm: list (defa... | 52,003 |
def check_if_neighbors_match(src_neighbor, trg_neighbor):
"""Check if any source and target neighbors match and return matches
Args:
src_neighbor (list): Source Neighbor List
trg_neighbor (list): Target Neighbor List
Returns:
list: Matching of neighbors.
"""
matching = {}
... | 52,004 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Wink platform."""
for camera in pywink.get_cameras():
# get_cameras returns multiple device types.
# Only add those that aren't sensors.
try:
camera.capability()
except AttributeError:... | 52,005 |
def cluster_down_cmd(config, args):
"""
Command line function. See cluster_down() for documentation.
"""
cluster_down(config) | 52,006 |
def build_torch_optimizer_for_bert(model, opt):
"""
no_decay = ["bias", "LayerNorm.weight"]
encoder_params = [
{
"params": [p for n, p in model.encoder.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
},
{
... | 52,007 |
def test_image_to_cat_id_2(dp_image_fully_segmented: Image) -> None:
"""
test func: image_to_cat_id returns extraction of category_ids
"""
# Arrange
category_names = [names.C.TAB, names.C.ROW, names.C.COL]
expected_output = {names.C.TAB: [2], names.C.ROW: [6, 6], names.C.COL: [7, 7]}
# Act... | 52,008 |
def docker_compose(command):
"""
Run a docker-compose command
:param command: Command you want to run
"""
with env.cd(env.project_dir):
return env.run("docker-compose -f {file} {command}".format(file=env.compose_file, command=command)) | 52,009 |
def scale_image(filepath, scale):
"""Scale a saved image"""
for f in sorted(glob.glob(filepath)):
with Image.open(f) as im:
orig_w, orig_h = im.size
im = im.resize((scale * orig_w, scale * orig_h), resample=Image.BOX)
im.save(f) | 52,010 |
def _get_event_id(oracle_cursor): # -> (int)
"""gets the event_id to be used for updating the NR history
:oracle_conn : a Cx_Oracle connection to the NRO database
:returns (int): a valid NRO event_id to be used for updating NRO records
"""
oracle_cursor.execute("""select event_seq.NEXTVAL from dua... | 52,011 |
async def test_webhook_finish_release(
doof, mocker, test_repo, library_test_repo, mock_labels
): # pylint: disable=unused-argument
"""
Finish the release
"""
doof.repos_info = [test_repo, library_test_repo]
pr_body = ReleasePR(
version="version",
url="url",
body="body"... | 52,012 |
def matches_ground_truth(
candidate: MissionTrace,
truth: List[MissionTrace],
tolerance_factor: float = 1.0
) -> bool:
"""
Determines whether a given trace, referred to as the candidate trace,
is approximately equivalent to a set of ground truth traces for the
same missio... | 52,013 |
def broken_model():
"""Create a non-functional model object."""
r = MockRedis()
r.set("1.2.0", pickle.dumps("lol"))
return lambda: r | 52,014 |
def _envFile(self, s, *args, **kw):
"""Same as Environmet.File but without expanding $VAR logic
"""
if SCons.Util.is_Sequence(s):
result=[]
for e in s:
result.append(self.fs.File((e,) + args, kw))
return result
return self.fs.File((s,) + args, kw) | 52,015 |
def xception_model(num_classes, pretrained=True, **kwargs):
"""Constructs a xception model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
encoder = AlignedXception(num_classes=1000)
# encoder = pretrainedmodels.models.xception()
if pretrained:
sta... | 52,016 |
def create_directory(directory: str):
"""Creates a directory if it does not exist.
Params:
- directory (str): The path to the directory to be created
Raises:
- OSError: if the directory creation fails
"""
try:
if os.path.dirname(directory):
os.makedirs(os.pat... | 52,017 |
def lwdown(atemp,clouds):
"""Call signature::
lwd = lwdown(atemp,clouds)
estimate downward (incoming) radiation in long wave wave band from air
temperature according to Parkinson and Washington (1979), A Large-Scale
Numerical Model of Sea Ice, JGR, 84(C1), 311-337.
INPUT: atemp :: air temp... | 52,018 |
def render_volume(workspace, cutoff=None, solid_color=(1., 1., 1.), style='surface', origin=(0., 0., 0.),
window_size=(1920, 1200), opacity=1., background=(0.3, 0.3, 0.3), show_grid=True, plot_directly=True,
show_axes=True, show_outline=True, cmap='gray', add_to_plot=None, notebook=F... | 52,019 |
def cutoff_list(a,feature=int(0)):
"""
for list a, apply function cutoff to each element
"""
for i in range(len(a)):
a[i]=cutoff(a[i],feature=feature)
return a | 52,020 |
def carla_location_to_pose(carla_location):
"""
Convert a carla location to a icv pose
See carla_location_to_icv_point() for details.
pose quaternion remains zero.
:param carla_location: the carla location
:type carla_location: carla.Location
:return: a icv pose
:rtype: geometry_msgs.m... | 52,021 |
def estimate_biases(model_dat, ymdat):
"""numerical optimize modification indicators for equations, one at a time"""
tau = model_dat["xdat"].shape[1]
biases = zeros(model_dat["ndim"])
biases_std = zeros(model_dat["ndim"])
for bias_ind in range(model_dat["ndim"]):
# compute biases
bi... | 52,022 |
def _get_l10n_term(term: str) -> str:
"""get localized term when possible from an predictable string input
Args:
term (str): the term, example: vkg.attr.descriptionem
Returns:
str: if possible, the term on user language. It will fallback to
the term itself
"""
... | 52,023 |
def find_bad_positions(coverage_matrix, target_folder = None, trait = None, samplename = None,
trait_cutoff = None, whitelist = None):
"""
Walk through all bases and find contigous regions of bases that fail the coverage/strandbias cutoff
Create an output file of these region... | 52,024 |
def iter_public_props(obj, predicate=None):
""" Iterate over public properties of an object.
:param Any obj:
The object we want to get the properties of.
:param function predicate:
Additional predicate to filter out properties we're interested in. This
function will be called on eve... | 52,025 |
def s_norm(p_string, uppercase=False):
"""
Filters out all punctuation, normalizes the casing to either
lowercase or uppercase of all letters, and removes extraneous
whitespace between characters. That is, all whitespace will
be replaced by a single space character separating the words.
:param p_string
The str... | 52,026 |
def _venv_changed(session: nox.sessions.Session) -> bool:
"""Return True if the installed session is different to that specified in the lockfile."""
result = False
if _venv_populated(session):
expected = _file_content(_session_lockfile(session))
actual = _file_content(_session_cachefile(sess... | 52,027 |
def greedy_policy(A, s, Q, epsilon = None):
"""在给定一个状态下,从行为空间A中选择一个行为a,使得Q(s,a) = max(Q(s,))
考虑到多个行为价值相同的情况
"""
max_q, a_max_q = -float('inf'), []
for a_opt in A:
q = get_dict(Q, s, a_opt)
if q > max_q:
max_q = q
a_max_q = [a_opt]
elif q == max_q:
... | 52,028 |
def test_ordering(api_request, mocker):
"""Filter by query parameter"""
has_permission = mocker.spy(WorkflowPermission, "has_permission")
WorkflowFactory(name="alpha", description="hello")
WorkflowFactory(name="beta", description="world")
response = api_request("get", "approval:workflow-list")
c... | 52,029 |
def login_user(cursor, username):
""" create new session for user with username, return session key """
userid = get_userid(cursor, username)
key = token_urlsafe()
cursor.execute(
"REPLACE INTO sessions ('userid', 'key') VALUES (?, ?)",
(userid, key)
)
return key | 52,030 |
def tapisize(fieldKeyName):
"""Transforms a string into a Tapis query parameter
"""
return fieldKeyName.lower() | 52,031 |
def get_minions(returner):
"""
Return a list of all minions
CLI Example:
.. code-block:: bash
salt '*' ret.get_minions mysql
"""
returners = salt.loader.returners(__opts__, __salt__)
return returners["{0}.get_minions".format(returner)]() | 52,032 |
def count_by_province(datafile, plotfile):
"""Create histogram of measurements by province."""
df = read_clean_data(datafile)
category_orders = {"province": df["province"].cat.categories}
fig = px.histogram(df, x="province", category_orders=category_orders)
fig.write_image(plotfile) | 52,033 |
def nx_second_order_proximity(
G: Union[nx.Graph, nx.DiGraph],
node_ids: Union[Tensor, ndarray, list],
whole_graph_proximity: bool = True,
to_batch: bool = False,
distance_metric: str = "cosine",
norm_rows_in_sample: bool = False,
norm_rows: bool = True,
) -> Tensor:
"""
Ta... | 52,034 |
def calculate_average_resolution(sizes):
"""Returns the average dimensions for a list of resolution tuples."""
count = len(sizes)
horizontal = sum([x[0] for x in sizes]) / count
vertical = sum([x[1] for x in sizes]) / count
return (horizontal, vertical) | 52,035 |
def is_enum0(*args):
"""
is_enum0(F) -> bool
Is the first operand a symbolic constant (enum member)?
@param F (C++: flags_t)
"""
return _ida_bytes.is_enum0(*args) | 52,036 |
def view(image, ui_collapsed=False, annotations=True, interpolation=True,
cmap=cm.viridis, mode='v', shadow=True, slicing_planes=False, gradient_opacity=0.2):
"""View the image.
Creates and returns an ipywidget to visualize the image.
The image can be 2D or 3D.
The type of the image can be an... | 52,037 |
def install_chute(ctx, chute, node, follow, version):
"""
Install a chute from the store.
CHUTE must be the name of a chute in the store. NODE must be the
name of a node that you control.
"""
client = ControllerClient()
result = client.install_chute(chute, node, select_version=version)
... | 52,038 |
def create_folder(subfolder: str,
folder: str) -> None:
"""
Function for creating folder structure for saved stationdata
"""
path_to_create = Path(folder, subfolder)
Path(path_to_create).mkdir(parents=True, exist_ok=True)
return None | 52,039 |
def fit(
context: MLClientCtx,
dataset: DataItem,
num_boost_round: int = 10,
evals: List[Tuple[DMatrix, str]] = [],
obj: Union[Callable, str] = "",
feval: Union[Callable, str] = None,
maximize: bool = False,
early_stopping_rounds: int = None,
evals... | 52,040 |
def test_dbapi_raw_w_pool(n):
"""Individual INSERT/COMMIT pairs w/ DBAPI + connection pool"""
_test_dbapi_raw(n, False) | 52,041 |
def source_provider_blender(filename):
"""
Return source code of the file referred by filename.
Support for debugging of Blender Python scripts.
Blender scripts are not always saved on disk, and their
source has to be queried directly from the Blender API.
http://www.blender.org
"""
... | 52,042 |
def locate_spikes_peakutils(
data, fps=58.21, thresh=0.7, min_dist=None, max_allowed_firing_rate=1
) -> np.ndarray:
"""
Find spikes from a dF/F matrix using the peakutils package.
The fps parameter is used to calculate the minimum allowed distance \
between consecutive spikes, and to disqualify cell... | 52,043 |
def has_valuable(camera):
"""Function checks if the camera sees any valuable.
@param camera: webots camera object to use for the recognition
@returns True if a valuable is detected, False otherwise
"""
# Check if camera has recogniton and is enabled
if not camera.hasRecognition() or camera.getRe... | 52,044 |
def _partition_fold(v,data):
"""
partition the data ready for cross validation
Inputs:
v: (int) cross validation parameter, number of cross folds
data: (np.array) training data
Outputs:
list of partitioned indicies
"""
partition = []
for i in range(v):
if i... | 52,045 |
def test_get_convergence_tolerance():
"""Test getting the convergence_tolerance property."""
assert_is_none(c.convergence_tolerance) | 52,046 |
def get_distance(m, M, Av=0):
"""
calculate distance [in pc] from extinction-corrected magnitude
using the equation: d=10**((m-M+5-Av)/5)
Note: m-M=5*log10(d)-5+Av
see http://astronomy.swin.edu.au/cosmos/I/Interstellar+Reddening
Parameters
---------
m : apparent magnitude
M : absol... | 52,047 |
def get_csr_as_text(csr_filename):
"""Convert CSR file to plaintext with OpenSSL."""
return _run_openssl(['req', '-in', csr_filename, '-noout', '-text']).decode('utf-8') | 52,048 |
def search_filter_sort_paginate(
db_session,
model,
query_str: str = None,
filter_spec: List[dict] = None,
page: int = 1,
items_per_page: int = 5,
sort_by: List[str] = None,
descending: List[bool] = None,
current_user: DispatchUser = None,
role: UserRoles = UserRoles.member,
):
... | 52,049 |
def rename_entry(*args):
"""
rename_entry(ord, name, flags=0x0) -> bool
Rename entry point.
@param ord: ordinal number of the entry point (C++: uval_t)
@param name: name of entry point. If the specified location already
has a name, the old name will be appended to a repeatable
... | 52,050 |
def skip_ok_unless_installed(*packages_or_dependencies, **kwargs):
"""Check that all given RPM packages or dependencies are installed and skip
the test if not.
Accepts the following keyword arguments:
- 'message' is the text to include in the Exception (a generic 'missing
$package' will be used o... | 52,051 |
def test_workflow_postproc_client(local_service, hello_world):
"""Test preparing and accessing post-processing results."""
# -- Setup ----------------------------------------------------------------
#
# Create four groups for the 'Hello World' workflow with one successful
# run each.
with local_... | 52,052 |
def split_file_to_annotations_and_definitions(lines: Iterable[str]) -> Tuple[EnumLines, EnumLines, EnumLines]:
"""Enumerate a line iterable and splits into 3 parts."""
enum_lines = sanitize_file_lines(lines)
metadata, definitions, statements = multi_split_by(enum_lines, [_predicate_1, _predicate_2])
ret... | 52,053 |
def _SafeCreateLogoutURL(mr):
"""Make a logout URL w/ a detailed continue URL, otherwise use a short one."""
try:
return users.create_logout_url(mr.current_page_url)
except users.RedirectTooLongError:
if mr.project_name:
return users.create_logout_url('/p/%s' % mr.project_name)
else:
retur... | 52,054 |
def random_speech_to_text(
draw
) -> st.SearchStrategy[Tuple[SpeechToTextGen, Dict]]:
"""Generates different speech_to_text functions."""
kwargs = draw(random_speech_to_text_kwargs())
return speech_to_text(**kwargs), kwargs | 52,055 |
def status(ctx):
"""
Communication Node Status information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/nodestatus.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(da... | 52,056 |
def test_repeat_with_no_arg_void_function_valid():
"""
Test repeating with a function that takes no arguments doesn't throw an
exception
"""
count = 0
def exit_when_3():
nonlocal count
count += 1
if count == 3:
raise KeyboardInterrupt
misc_utils.repeat_u... | 52,057 |
def line_neighbor_score(mat, idx, line_width=1, distance_range=(20, 40), window_size=5,
line_trick='min', neighbor_trick='mean', metric='diff'):
"""
:math: enrichment-score = line-trick(line) - neighbor-trick(neighbor)
:param idx: (int) stripe location index
:param mat: (2... | 52,058 |
def run_locally(deployment):
"""
Run the local flask server for `app`. Just for local development, not production use.
Parameters
----------
deployment : str
If the 'vontsira.settings.local_config.Config' is to be used
deployment=local_config
"""
app = create_app(f'vontsira.... | 52,059 |
def plugin_name_to_layerapi2_label(plugin_name):
"""Get a layerapi2 label from a plugin name.
Args:
plugin_name (string): the plugin name from which we create the label.
Returns:
(string): the layerapi2 label.
"""
return "plugin_%s@%s" % (plugin_name, MFMODULE_LOWERCASE) | 52,060 |
def download_file(user_parameters_url, data_type, filename, file_destination):
"""
Download data from the web and save files to a specified file destination
with a specified filename.
Parameters
----------
user_parameters_url : str
String encoded url based on user request file.
... | 52,061 |
def test_interval_policy_connected_completed(monkeypatch):
"""Test interval returned with policy set to connected and charging completed."""
_mock = TeslaMock(monkeypatch)
_controller = Controller(None)
monkeypatch.setitem(_controller.car_online, VIN, True)
monkeypatch.setitem(_controller.car_stat... | 52,062 |
def unscii(font_name):
"""
Given a font name, return a font object for usage.
"""
return UnsciiFont(font_name) | 52,063 |
def pytest_addoption(parser):
"""Specify command-line options for all plugins"""
parser.addoption(
"--test_conf",
type=Path,
help="Path to test config",
default=Path(__file__).parent / "test_config.yml"
)
parser.addoption(
"--exe",
required=True,
d... | 52,064 |
def note(message):
"""
Sends a message to stdout.
"""
click.secho(message, fg="yellow", bold=True) | 52,065 |
def get_environ_dict():
"""Return a dictionary of all environment keys/values."""
return {
'os.environ': _get_os_environ_dict((
'AUTH_DOMAIN',
'CURRENT_CONFIGURATION_VERSION',
'CURRENT_MODULE_ID',
'CURRENT_VERSION_ID',
'DEFAULT_VERSION_HOSTNAME',
'FE... | 52,066 |
def k_from_a_ea(a, e_a, temp, r_gas):
"""
convert using "alternate" form of Arrhenius eq
:param a: pre-exponential factor
:param e_a: activation energy with units consistent with given r_gas
:param temp: temperature in K
:param r_gas: universal gas constant in units consistent with e_a and temps... | 52,067 |
def get_args_parser(PORT: int = 4500):
"""
Extendable parser for input arguments
Args:
PORT: default port to be exposed
"""
parser = argparse.ArgumentParser(add_help=True,
description="Backend service API")
parser.add_argument('-p', '--port'... | 52,068 |
def extract_source_info(df_adverse_ev):
""" Find information about who submitted the report """
qual_list = []
for i in range(0,len(df_adverse_ev)):
if df_adverse_ev.iloc[i]['primarysource'] is not None:
col_names = list(df_adverse_ev.iloc[i]['primarysource'].keys())
if 'qual... | 52,069 |
def load_base_models_json(filename="base_models.json"):
"""Load base models json to allow selecting pre-trained model.
Args:
filename (str) - filename for the json file with pre-trained models
Returns:
base_models - python dict version of JSON key-value pairs
"""
with open(filename... | 52,070 |
def _parsedatetime_parse(date_string):
"""Parse the given date_string using the parsedatetime module."""
# for more details on how the parsedatetime.Calendar.parse function works, see:
# https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/__init__.py#L1779
c... | 52,071 |
def setFillValue(ncin, value):
"""
Arguments
---------
ncin : Instance of an object with a _FillValue attribute
(i.e. NcVariable)
Return
------
Numeric
Purpose
-------
Return the value of the attribute _FillValue
"""
ncin.setncattr("_FillValue", value) | 52,072 |
def main(argv=None, directory=None):
"""
Main entry point for the tool, used by setup.py
Returns a value that can be passed into exit() specifying
the exit code.
1 is an error
0 is successful run
"""
argv = argv or sys.argv
# Init the path tool to work with the specified directory,
... | 52,073 |
def read_tsv_or_parquet(filepath):
"""Read either a TSV or a parquet file by file extension."""
filepath = Path(filepath)
if not filepath.exists():
logger.error(f'File "{filepath}" does not exist.')
sys.exit(1)
ext = filepath.suffix.lstrip(".")
if ext in PARQUET_EXTENSIONS:
r... | 52,074 |
def main():
"""
This program simulates a bouncing ball at (START_X, START_Y)
that has VX as x velocity and 0 as y velocity. Each bounce reduces
y velocity to REDUCE of itself.
"""
ball.filled = True
window.add(ball, START_X, START_Y)
window.add(title, 0, title.height)
onmous... | 52,075 |
def test_get_ignore_pack_tests__ignore_test(tmpdir, mocker):
"""
Given
- Pack have .pack-ignore file
- There are skipped tests in .pack-ignore
When
- Collecting packs' ignored tests - running `get_ignore_pack_tests()`
Then:
- returns a list with the skipped tests
"""
fake_pack_na... | 52,076 |
def BFMM(
source,
target = None,
charge = None,
dipole1 = None,
dipole2 = None,
compute_source_velocity = False,
compute_source_analytic_gradient = False,
compute_source_anti_analytic_gradient = False,
compute_target_velocity =... | 52,077 |
def blast(args):
"""
%prog blast fastafile
Run BLASTN against database (default is UniVec_Core). Output .bed format
on the vector/contaminant ranges.
"""
p = OptionParser(blast.__doc__)
p.add_option(
"--dist",
default=100,
type="int",
help="Merge adjacent HS... | 52,078 |
def _ul_unsupported_opt(opt, stderr):
"""Print an unsupported option message to stderr"""
print(f"ulimit: Unsupported option: -{opt}", file=stderr, flush=True)
print("Try 'ulimit --help' for more information", file=stderr, flush=True) | 52,079 |
def get_dihedrals(a, b, c, d):
"""
A function that gets dihedral angles between two residues.
See set_neighbors6D for usage.
"""
b0 = -1.0*(b - a)
b1 = c - b
b2 = d - c
b1 /= np.linalg.norm(b1, axis=-1)[:,None]
v = b0 - np.sum(b0*b1, axis=-1)[:,None]*b1
w = b2 - np.sum(b2*b1, ... | 52,080 |
def iexact(self, compiler, connection):
"""A method to extend Django IExact class. Case-insensitive exact match.
If the value provided for comparison is None, it will be interpreted as
an SQL NULL.
:type self: :class:`~django.db.models.lookups.IExact`
:param self: the instance of the class that own... | 52,081 |
def load_data_from_json(jsonfile):
"""Load the data contained in a .json file and return the corresponding Python object.
:param jsonfile: The path to the .json file
:type jsonfile: str
:rtype: list or dict
"""
jsondata = open(jsonfile).read()
data = json.loads(jsondata)
return data | 52,082 |
def grpc_check(fpath):
"""
Check whether grpc service is enabled in this .proto file.
Note: only proto file with the following form will pass our check.
service MyService {
rpc MethodA(XXX) returns (XXX) {
rpc MethodB(XXX)
returns (XXX) {
}
}
"""
if not f... | 52,083 |
def bb_intersection_over_union(boxA, boxB):
"""
Computes IoU (Intersection over Union for 2 given bounding boxes)
Args:
boxA (list): A list of 4 elements holding bounding box coordinates (x1, y1, x2, y2)
boxB (list): A list of 4 elements holding bounding box coordinates (x1,... | 52,084 |
def apath(path='', r=None):
"""Builds a path inside an application folder
Args:
path(str): path within the application folder
r: the global request object
"""
opath = up(r.folder)
while path[:3] == '../':
(opath, path) = (up(opath), path[3:])
return os.path.join(opath,... | 52,085 |
def area(boxlist, axis=-1):
"""Computes area of boxes.
Args:
boxlist: BoxList holding N boxes
scope: name scope.
Returns:
a tensor with shape [N] representing box areas.
"""
with tf.name_scope('Area'):
x_min, y_min, x_max, y_max = tf.split(value=boxlist, num_or_... | 52,086 |
def _MatrixTriangularSolveGrad(op, grad):
"""Gradient for MatrixTriangularSolve."""
a = op.inputs[0]
adjoint_a = op.get_attr("adjoint")
lower_a = op.get_attr("lower")
c = op.outputs[0]
grad_b = linalg_ops.matrix_triangular_solve(
a, grad, lower=lower_a, adjoint=not adjoint_a)
if adjoint_a:
grad_... | 52,087 |
def list_persons_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""Get persons list from TOPdesk.
Args:
client: The client to preform command on.
args: The arguments of the persons command.
Return CommadResults of list of persons.
"""
persons = client.get_list_wi... | 52,088 |
def group_user_delete(user, group):
"""Delete an user from a certain group"""
if not pagure_config.get("ENABLE_USER_MNGT", True):
flask.abort(404)
if not pagure_config.get("ENABLE_GROUP_MNGT", False):
flask.abort(404)
form = pagure.forms.ConfirmationForm()
if form.validate_on_submi... | 52,089 |
def repair_follow_organization_view(request):
"""
Process the new or edit organization forms
:param request:
:return:
"""
# admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer
authority_required = {'verified_volunteer'}
if not v... | 52,090 |
def vect3_add(v1, v2):
"""
Adds two 3d vectors.
v1, v2 (3-tuple): 3d vectors
return (3-tuple): 3d vector
"""
return (v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]) | 52,091 |
def voucher_received(cadde_provider=None, cadde_consumer=None, cadde_contract_id=None, hash_get_data=None, contract_management_service_url=None): # noqa: E501
"""API. データ証憑通知(受信)
来歴管理I/Fにデータ証憑通知(受信)を依頼する。
Response:
* 処理が成功した場合は200を返す
* 処理に失敗した場合は、2xx以外を返す。Responsesセクション参照。 # noqa: E501
:... | 52,092 |
def get_task_pool(thread=False):
"""
Get a new task pool, which is either a single-thread or process pool depending on the current config.
Returns:
A new :class:`multiprocessing.pool.Pool` instance.
"""
if thread or not config['app_multicore'] or config['enable_backtest'] and config['backt... | 52,093 |
def test_dcgm_standalone_health_check_power(handle, gpuIds):
"""
Verifies that a check error occurs when an error is injected
Checks for call errors are done in the bindings except dcgmClientHealthCheck
"""
handleObj = pydcgm.DcgmHandle(handle=handle)
systemObj = handleObj.GetSystem()
groupO... | 52,094 |
def test_getThreatReport_ir_command():
"""
Given:
- an URL
When:
- running ThreatReport command and fetch IA/IR
Then:
- return command results containing UUID, dbotscore
"""
url = 'https://test.com/rest/document/v0/bdc9d16f-6040-4894-8544-9c98986a41fd'
status_code ... | 52,095 |
def get_date(article: ElementTree) -> int:
"""
Extracts the year of the article. If ArticleDate exist use its year
otherwise use the year form JournalIssue
"""
d = article.find("ArticleDate")
if d is not None:
return int(d.find("Year").text)
d = article.find("Journal").find("JournalI... | 52,096 |
def split(column, pattern=''):
"""
Splits str around pattern (pattern is a regular expression)
> pattern is a string representation of the regular expression
"""
return _with_expr(exprs.StringSplit, column, pattern) | 52,097 |
def date_range(
start: Literal["4-15-2000"], end: Literal["5-15-2000"], freq: Literal["D"]
):
"""
usage.dask: 1
"""
... | 52,098 |
def convert(
model,
source="auto",
inputs=None,
outputs=None,
classifier_config=None,
minimum_deployment_target=None,
convert_to='nn_proto',
**kwargs
):
"""
Convert TensorFlow or Pytorch models to the Core ML model format. Whether a
parameter is required may differ between fr... | 52,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.