content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_available_dbms(connection: "Connection", to_dictionary: bool = False, limit: int = None,
**filters) -> Union[List["Dbms"], List[dict]]:
"""List all available database management systems (DBMSs) objects or dicts.
Optionally filter the DBMS by specifying filters.
Args:
... | 5,312,900 |
def loop():
""" Main loop running the bot """
# Initialize the light sensor. Note that the Gpio library
# returns strings...
sensorpin = CFG.get("cfg", "light_sensor_pin")
sensor = onionGpio.OnionGpio(int(sensorpin))
status = int(sensor.setInputDirection())
# Check sensor status
if statu... | 5,312,901 |
def csv_encode(data: np.ndarray) -> bytes:
"""Encodes a NumPy array in CSV.
:param: data: NumPy array to encode
"""
with io.BytesIO() as buffer:
np.savetxt(buffer, data, delimiter=",")
return buffer.getvalue() | 5,312,902 |
def _calculate_global_step(current_step: int) -> int:
"""Calculate the current global step given the current iteration step."""
global_step = 0
for step in range(current_step):
global_step += n_optimize_fn(step)
return global_step | 5,312,903 |
def _format_optvalue(value, script=False):
"""Internal function."""
if script:
# if caller passes a Tcl script to tk.call, all the values need to
# be grouped into words (arguments to a command in Tcl dialect)
value = _stringify(value)
elif isinstance(value, (list, tuple)):
... | 5,312,904 |
def test_convert_input_to_descriptors_with_a_single_list():
"""test_convert_input_to_descriptors."""
sut = StringIO()
sut.write(
"""---
apiVersion: v1
items:
- apiVersion: v1
data:
envoy.json: "some data"
kind: ConfigMap
metadata:
name: grafana-dashboard-statefulset
n... | 5,312,905 |
def write_predictions(dirnames, Y_pred):
""" write out predictions scores and labels to a new file
"""
testset = pd.read_csv(dirnames['test_set'], delim_whitespace=True, header=0)
if not os.path.exists(os.path.join(dirnames['results'])):
os.makedirs(os.path.join(dirnames['results']))
... | 5,312,906 |
def scheme_to_str(exp):
"""Convert a Python object back into a Scheme-readable string."""
if isinstance(exp, ltypes.List):
return "(" + " ".join(map(scheme_to_str, exp)) + ")"
return str(exp) | 5,312,907 |
def log(message, level="INFO"):
"""Log a message.
Valid log levels are: DEBUG, INFO, WARNING, ERROR, CRITICAL
Parameters:
message : value
level (optional, 'INFO') : value
"""
_log(message, level) | 5,312,908 |
def create_dataset(file_name, input_type, size, classes, test_size, add_to):
"""Creates a dataset for training an anomoly ML model"""
if input_type == 'mongo':
create_dataset_mongo(file_name, size, classes, test_size, add_to)
elif input_type == 'json':
create_dataset_json(file_name, size, cl... | 5,312,909 |
def utcTimeFromUTCTimestamp(utcTimestamp: int):
"""
Args:
utcTimestamp: number of seconds since 1970-01-01 00:00:00 UTC
Returns: a (non-timezone aware) datetime object representing the same time as utcTimestamp, in UTC time
"""
return datetime.datetime.utcfromtimestamp(utcTimestamp) | 5,312,910 |
def extract_floats(string):
"""Extract all real numbers from the string into a list (used to parse the CMI gateway's cgi output)."""
return [float(t) for t in re.findall(r'[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?', string)] | 5,312,911 |
def ProbToSequence_Nitem2_Order1(Prob):
"""
Return a random sequence of observations generated based on Prob, a
sequence of first-order transition probability. In other words, the sequence
follows a first-order Markov chain.
Prob is a np array.
"""
length = Prob.shape[1]
seq = np.zeros(... | 5,312,912 |
def add_user(username, password):
"""Add a new user"""
user = User(username=username, password=password)
save_user(user)
print("""New user added:
username: %s
password: %s""" % (username, password)) | 5,312,913 |
def eval(model, data):
"""Function to evaluate a your model
Args:
model (PailabCompatibleModel): model to evaluate
data (DataSet): dataset on which model is evaluated
"""
pass | 5,312,914 |
def print_df(df, season, team, matches, match_number):
"""Print out the dataframe"""
red_alliance, blue_alliance = find_match_alliances(matches, match_number)
saved_index = list(df.index)
df.set_index(
pd.Index(
[
mark_index(i, team=team, red=red_alliance, blue=blue_a... | 5,312,915 |
def binary(n, digits):
"""Returns a tuple of (digits) integers representing the
integer (n) in binary. For example, binary(3,3) returns (0, 1, 1)"""
t = []
for i in range(digits):
n, r = divmod(n, 2)
t.append(r)
return tuple(reversed(t)) | 5,312,916 |
def build_results(interactions: pd.DataFrame,
mean_analysis: pd.DataFrame,
percent_analysis: pd.DataFrame,
clusters_means: dict,
complex_compositions: pd.DataFrame,
counts: pd.DataFrame,
genes: pd.DataFrame,
... | 5,312,917 |
def load_mnist(data_node_name, label_node_name, *args, normalize=True, folder='', **kwargs) -> Tuple[Dataset, Dataset]:
""" Returns the training and testing Dataset objects for MNIST.
@param data_node_name The graph node name for the data inputs.
@param label_node_name The graph node name for the gr... | 5,312,918 |
def test_api_group_in_role_template(admin_mc, admin_pc, user_mc,
remove_resource):
"""Test that a role moved into a cluster namespace is translated as
intended and respects apiGroups
"""
# If the admin can't see any nodes this test will fail
if len(admin_mc.client... | 5,312,919 |
def voc_ap(rec, prec):
"""
Compute VOC AP given precision and recall.
Taken from https://github.com/marvis/pytorch-yolo2/blob/master/scripts/voc_eval.py
Different from scikit's average_precision_score (https://github.com/scikit-learn/scikit-learn/issues/4577)
"""
# first append sentinel values a... | 5,312,920 |
def GetShapeFunctionDefinitionLine3D3N(x,xg):
""" This computes the shape functions on 3D line
Keyword arguments:
x -- Definition of line
xg -- Gauss point
"""
N = sympy.zeros(3)
N[1] = -(((x[1,2]-x[2,2])*(x[2,0]+x[2,1]-xg[0]-xg[1])-(x[1,0]+x[1,1]-x[2,0]-x[2,1])*(x[2,2]-xg[2]))/(-(x[1,0]+x[... | 5,312,921 |
def get_next_version(release_type):
"""Increment a version for a particular release type."""
if not isinstance(release_type, ReleaseType):
raise TypeError()
version = Version(get_current_version())
if release_type is ReleaseType.major:
return str(version.next_major())
if release_t... | 5,312,922 |
def get_user_subscriptions(user=None):
"""
Get user subscriptions.
:param user: The user to query for.
:type user: str or CRITsUser
:returns: str
"""
if user is None:
return None
if not hasattr(user, 'username'):
from crits.core.user import CRITsUser
user = str... | 5,312,923 |
def picasso() -> dict:
"""Handler for service discovery
:returns: picasso service descriptor
:rtype: dict
"""
return {"app": "demo-man", "svc": "picasso", "version": os.environ["VERSION"]} | 5,312,924 |
def test_genomehubs_init_cli_returns_usage():
"""Test genomehubs init returns usage when called with no arguments."""
testargs = ["genomehubs", "init"]
with patch.object(sys, "argv", testargs):
with pytest.raises(DocoptExit):
cli() | 5,312,925 |
def calc_zvals(opt: Optimizer, std_errors=None,
information='expected'):
"""Calculates z-scores.
Keyword arguments:
opt -- Optimizer containing proper parameters' values.
std_errors -- Standard errors in case they were already calculated.
... | 5,312,926 |
def test_optional_parameter_group():
"""Reproduces issue #28 :
https://github.com/lebrice/SimpleParsing/issues/28#issue-663689719
"""
parent: Parent = Parent.setup("--breed Shitzu")
assert parent.dog == Dog(breed="Shitzu")
assert parent.child == None
parent: Parent = Parent.setup("--name Dy... | 5,312,927 |
def test_background_origin():
"""Test the background-origin property."""
def test_value(value, pixels, css=None):
assert_pixels('background_origin_' + value, 12, 12, pixels, '''
<style>
@page { size: 12px }
html { background: #fff }
body { marg... | 5,312,928 |
def observe_on(scheduler: typing.Scheduler) -> Callable[[Observable], Observable]:
"""Wraps the source sequence in order to run its observer callbacks
on the specified scheduler.
Args:
scheduler: Scheduler to notify observers on.
This only invokes observer callbacks on a scheduler. In case the... | 5,312,929 |
def generate_grande_signature_regex(signataire_titre):
"""
Create a regex for a grande signature using the appropriate titres (main signatory, or secretary)
signataire_titre : the list of usable titres (president, conseiller national, secretaire...) for the signature
Return : (grande_signature_regex, ti... | 5,312,930 |
async def store_key(key: str, value: str) -> None:
"""
.. function:: store_key(key, value)
:param key: The key as to who own the value
:param value: The litteral value to store
Store the value as specified key into redis cache
"""
conn = None
try:
redis_conn = get_redis_url()... | 5,312,931 |
def list_product_images():
"""Retrieve a paginated list of product images with optional filters."""
shelf_image_id = request.args.get('shelfImageId')
print(shelf_image_id)
upc = request.args.get('upc')
review_status = request.args.get('reviewStatus')
skip = int(request.args.get('skip', 0))
l... | 5,312,932 |
def variables() -> Dict[str, Any]:
"""Contents of ruinway.variables.yml."""
return yaml.safe_load((CURRENT_DIR / "runway.variables.yml").read_bytes()) | 5,312,933 |
def test_standby_with_most_wal_gets_promoted2(cluster_context: ClusterContext):
"""
Similar to test_standby_with_most_wal_gets_promoted1, but trick pacemaker
into promoting the wrong standby at first to make sure the correct standby
is still promoted in the end """
cluster_context.setup()
cluste... | 5,312,934 |
def csi_fsmn(
frame,
l_filter,
r_filter,
frame_sequence,
frame_counter,
l_order,
r_order,
l_stride,
r_stride,
unavailable_frames,
out_dtype,
q_params,
layer_name="",
):
"""Quantized fsmn operator.
Parameters
----------
Input : tvm.te.Tensor
2-... | 5,312,935 |
def get_line_context(line: str) -> tuple[str, None] | tuple[str, str]:
"""Get context of ending position in line (for completion)
Parameters
----------
line : str
file line
Returns
-------
tuple[str, None]
Possible string values:
`var_key`, `pro_line`, `var_only`, `... | 5,312,936 |
def list_accounts_for_identity(identity_key, id_type):
"""
Returns a list of all accounts for an identity.
:param identity: The identity key name. For example x509 DN, or a username.
:param id_type: The type of the authentication (x509, gss, userpass, ssh, saml).
returns: A list of all accounts fo... | 5,312,937 |
def stop():
"""Kill existing process if exists."""
with suppress(FileNotFoundError):
pid = int(pidfp.read_text())
pidfp.unlink()
log.info(f'Killing {pid}.')
os.kill(pid, SIGTERM) | 5,312,938 |
def test_champion_itemsets(champion_name, champion_data, all_items):
"""Test the item sets recommended for a champion are consistent.
Return a list of errors that were encountered."""
itemset_data = champion_data["data"][champion_name]["recommended"]
all_items_data = all_items['data']
errors = list... | 5,312,939 |
def to_tuple(
value: Any,
length: int = 1,
) -> Tuple[TypeNumber, ...]:
"""
to_tuple(1, length=1) -> (1,)
to_tuple(1, length=3) -> (1, 1, 1)
If value is an iterable, n is ignored and tuple(value) is returned
to_tuple((1,), length=1) -> (1,)
to_tuple((1, 2), length=1) -> ... | 5,312,940 |
def main():
"""Console script for copyright_automation."""
parse_args(sys.argv[1:])
return 0 | 5,312,941 |
def test_update_output_rank_vote():
"""Tests morpheus_core.update_output with rank_vote aggregation"""
aggregate_method = morpheus_core.AGGREGATION_METHODS.RANK_VOTE
update_map = np.ones([10, 10])
stride = (1, 1)
n = np.zeros([100, 100])
outputs = np.zeros([100, 100, 1])
batch_out = np.ones... | 5,312,942 |
def makenodelogin():
"""make a node login
"""
if request.method == 'POST':
ipaddr=request.form['ip']
iqn=request.form['iqn']
cmdres="iscsiadm -m node "+ iqn + "-p " +ipaddr + "-o update -n node.startup -v automatic"
res=cmdline(cmdres)
return Response(response=res,sta... | 5,312,943 |
def calc_mean_SD_transition(list_of_transition_delays, transition_id):
"""
So the delays for each transition t_A, t_B t_D were compiled into a list for analysis. We are just calculating the mean and standard deviation for those lists here.
"""
the_mean_t_A = np.mean(list_of_transition_delays)
SD_t_A... | 5,312,944 |
def _sorted_photon_data_tables(h5file):
"""Return a sorted list of keys "photon_dataN", sorted by N.
If there is only one "photon_data" (with no N) it returns the list
['photon_data'].
"""
prefix = 'photon_data'
ph_datas = [n for n in h5file.root._f_iter_nodes()
if n._v_name.sta... | 5,312,945 |
def apatch(mocker: MockerFixture):
"""Return a function that let you patch an async function."""
def patch(target: str, return_value: Any):
return mocker.patch(target, side_effect=mocker.AsyncMock(return_value=return_value))
yield patch | 5,312,946 |
def test():
"""
定义一个reader来获取测试数据集及其标签
Args:
Return:
read_data: 用于获取测试数据集及其标签的reader
"""
global TEST_SET
return read_data(TEST_SET) | 5,312,947 |
def main():
""" Installs d3dxof
"""
log('Applying fixes for SUGURI 2')
# https://github.com/ValveSoftware/Proton/issues/970#issuecomment-420421289
util.protontricks('d3dxof') | 5,312,948 |
def structure_sample_ks_convergence_diagnostics(fit, max_nonzero=None,
indicator_var='k',
batch=True, **kwargs):
"""Calculate chi squared convergence diagnostics."""
if batch and hasattr(fit, 'warmup_posterior'):
... | 5,312,949 |
def prepare_wld(bbox, mwidth, mheight):
"""Create georeferencing world file"""
pixel_x_size = (bbox.maxx - bbox.minx) / mwidth
pixel_y_size = (bbox.maxy - bbox.miny) / mheight
left_pixel_center_x = bbox.minx + pixel_x_size * 0.5
top_pixel_center_y = bbox.maxy - pixel_y_size * 0.5
return ''.join(... | 5,312,950 |
def set_log_level(level):
"""Set global low lovel log level"""
global _log_level
if level is None:
level = 0
level = max(level, LOG_LEVELS['NEVER'])
level = min(level, LOG_LEVELS['DEBUG4'])
_log_level = level | 5,312,951 |
def test_m_ndp_post(arm_metrics, detection_files, expected_ar_m_ndp_post_values):
"""
Test m_ndp_post computation.
Args:
arm_metrics (ActivityRecognitionMetrics): An instance of ActivityRecognitionMetrics
detection_files (Tuple): A tuple of data frames containing detection and ground truth
... | 5,312,952 |
def graphql_refresh_token_mutation(client, variables):
"""
Refreshes an auth token
:param client:
:param variables: contains a token key that is the token to update
:return:
"""
return client.execute('''
mutation refreshTokenMutation($token: String!) {
refreshToken(token: $to... | 5,312,953 |
def sintef_d50(u0, d0, rho_p, mu_p, sigma, rho):
"""
Compute d_50 from the SINTEF equations
Returns
-------
d50 : float
Volume median diameter of the fluid phase of interest (m)
Notes
-----
This function is called by the `sintef()` function after several
intermedia... | 5,312,954 |
def skip_description(session, context, poll):
"""Skip description creation step."""
context.user.expected_input = ExpectedInput.options.name
session.commit()
context.query.message.edit_text(
i18n.t('creation.option.first', locale=context.user.locale),
reply_markup=get_open_datepicker_key... | 5,312,955 |
def get_jinja2_function_names():
"""Gets functions dynamically from python files.
Returns:
list: List of function names form python files.
"""
function_names = []
python_files = [y[9:-3] for x in os.walk("netutils/") for y in glob(os.path.join(x[0], "*.py"))]
filtered_python_files = [fi... | 5,312,956 |
def check_duplicate_stats(stats1, stats2, threshold=0.01):
"""
Check two lists of paired statistics for duplicates.
Returns a list of the pairs that agree within to <1%.
INPUTS:
STATS1 : List of first statistical metric, e.g. Standard Deviations
STATS2 : List of second statistical metric, e.g.... | 5,312,957 |
def get_width(panel: Panel) -> int:
"""Return the width of the panel"""
if isinstance(panel, RowPanel):
return GRID_WIDTH
if panel.gridPos is None:
return 0 # unknown width
return panel.gridPos.w | 5,312,958 |
def tensor_abs(inputs):
"""Apply abs function."""
return P.Abs()(inputs) | 5,312,959 |
def _parse_uci_regression_dataset(name_str):
"""Parse name and seed for uci regression data.
E.g. yacht_2 is the yacht dataset with seed 2.
"""
pattern_string = "(?P<name>[a-z]+)_(?P<seed>[0-9]+)"
pattern = re.compile(pattern_string)
matched = pattern.match(name_str)
if matched:
name = matched.group(... | 5,312,960 |
def http_request(method, path, other_params=None):
"""
HTTP request helper function
Args:
method: HTTP Method
path: part of the url
other_params: Anything else that needs to be in the request
Returns: request result
"""
params = {'app_partner': 'demisto',
... | 5,312,961 |
def preprocess(text, remove_punct=False, remove_num=True):
"""
preprocess text into clean text for tokenization
"""
# 1. normalize
text = normalize_unicode(text)
# 2. remove new line
text = remove_newline(text)
# 3. to lower
text = text.lower()
# 4. de-contract
text = decontr... | 5,312,962 |
def get_world_trans(m_obj):
"""
Extracts the translation from the worldMatrix of the MObject.
Args:
m_obj
Return:
trans
"""
plug = get_world_matrix_plug(m_obj, 0)
matrix_obj = plug.asMObject()
matrix_data = oMa.MFnMatrixData(matrix_obj)
matrix = matrix_data.matrix()
... | 5,312,963 |
def cmd_exe(cmd, timeout=-1, cap_stderr=True, pipefail=False):
"""
Executes a command through the shell.
timeout in minutes! so 1440 mean is 24 hours.
-1 means never
returns namedtuple(ret_code, stdout, stderr, run_time)
where ret_code is the exit code for the command executed
stdout/err is ... | 5,312,964 |
def isip46(value):
"""Assert value is a valid IPv4 or IPv6 address.
On Python < 3.3 requires ipaddress module to be installed.
"""
import ipaddress # requires "pip install ipaddress" on python < 3.3
if not isinstance(value, basestring):
raise ValidationError("expected a string, got %r" % va... | 5,312,965 |
def wrap_with_arctan_tan(angle):
""" Normalize angle to be in the range of [-np.pi, np.pi[.
Beware! Every possible method treats the corner case -pi differently.
>>> wrap_with_arctan_tan(-np.pi)
-3.141592653589793
>>> wrap_with_arctan_tan(np.pi)
3.141592653589793
:param angle: Angle as nu... | 5,312,966 |
def open_brower(url, time=1):
"""
open new brower
Args:
url: url to open in brower
time: time delay to open brower
"""
threading.Timer(time, lambda: webbrowser.open(url)).start() | 5,312,967 |
def get_params(proto):
""" get the list of parameters from a function prototype
example: proto = "int main (int argc, char ** argv)"
returns: ['int argc', 'char ** argv']
"""
import re
paramregex = re.compile('.*\((.*)\);')
a = paramregex.findall(proto)[0].split(', ')
#a = [i.replace('co... | 5,312,968 |
def _preprocess(state, mode='min-max-1'):
"""
Implements preprocessing of `state`.
Parameters
----------
state : np.array
2D array of features. rows are variables and columns are features.
Return
------
(np.array) : same shape as state but with transformed variables
"""
... | 5,312,969 |
def _parse_basic_txt_scorefile(file, epoch_len=pysleep_defaults.epoch_len):
"""
Parse the super basic sleep files from Dinklmann
No starttime is available.
:param file:
:return:
"""
dict_obj = {"epochstages": [], "epochoffset": 0}
for line in file:
temp = line.split(' ')
... | 5,312,970 |
def autoremove():
"""Removes all unneeded packages."""
ret_info = execute(
"Obtaining orphans",
[CMD_PKGR, ORPHAN_ARGS],
capture_output=True)
if ret_info.returncode == 0:
pkg_info = ret_info.stdout.split()
print( "pks:"... | 5,312,971 |
def DominantModeStructured(amps, dt, N = 250):
"""
Compute the period and amplitude of the dominant mode in an even data series.
"""
def Omegas(ts):
return [2.0 * math.pi / t for t in ts]
nScans = len(amps)
times = [i * dt for i in range(nScans)]
tMin = 2.0 * dt
tMax = nScans * dt
re... | 5,312,972 |
def decode_record(record, name_to_features=name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.io.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):... | 5,312,973 |
def test_find_groups(img):
"""Test that all metrics for a specific group can be collected"""
common_group = []
for name, Metric in img.common.items():
assert Metric.name in globals.metric_groups[0]
assert len(Metric.variables) == 1
common_group.append(name)
double_group = []
... | 5,312,974 |
def setFFmpegPath(path):
""" Sets up the path to the directory containing both ffmpeg and ffprobe
Use this function for to specify specific system installs of FFmpeg. All
calls to ffmpeg and ffprobe will use this path as a prefix.
Parameters
----------
path : string
... | 5,312,975 |
def parse_arguments(description):
"""Parse the arguments for the scripts."""
parser = argparse.ArgumentParser(description=description)
task = "lab"
parser.add_argument(
"-n", "--name", type=str, help=f"name of {task}", default="all", dest="name"
)
args = parser.parse_args()
# We c... | 5,312,976 |
def have_color(parent, is_levels=False):
"""Checks that the color directories have images.
Args:
parent: class instance
is_levels (bool, optional): Whether or not to use full-size (False) or
level_0 images (True).
Returns:
dict[str, bool]: Map of color directories and w... | 5,312,977 |
def _IsType(clean_lines, nesting_state, expr):
"""Check if expression looks like a type name, returns true if so.
Args:
clean_lines: A CleansedLines instance containing the file.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks b... | 5,312,978 |
def return_figures(countries=country_default, start_year=1990, end_year=2014):
"""Creates four plotly visualizations using the World Bank API
# Example of the World Bank API endpoint:
# arable land for the United States and Brazil from 1990 to 2015
# http://api.worldbank.org/v2/countries/usa;bra/indicators/AG.... | 5,312,979 |
def generate_info(kd: KnossosDataset) -> dict:
"""Generate Neuroglancer precomputed volume info for a Knossos
dataset
Args:
kd (KnossosDataset):
Returns:
dict: volume info
"""
info = {}
info["@type"] = "neuroglancer_multiscale_volume"
info["type"] = None
info["... | 5,312,980 |
def run(*script_args):
"""
Script to create some initial data structures.
No arguments required.
"""
# Create the instructor group if it does not exist
print('Step 1: Creating instructor group')
if not Group.objects.filter(name='instructor').exists():
group = Group(name='instructor... | 5,312,981 |
def cleanup(ftp):
"""
quit /close the ftp connection
"""
#print("I'm in "+sys._getframe().f_code.co_name)
response = ftp.quit()
logging.info('[%s] -- *** DONE *** -- %s', now(), response.splitlines()[0])
sys.exit() | 5,312,982 |
def plugwise_command(
func: Callable[Concatenate[_T, _P], Awaitable[_R]] # type: ignore[misc]
) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, _R]]: # type: ignore[misc]
"""Decorate Plugwise calls that send commands/make changes to the device.
A decorator that wraps the passed in function, catches ... | 5,312,983 |
def order_parsed_fields(parsed, types, names=None):
"""Order parsed fields using a template file."""
columns = {}
fields = {}
ctr = 0
types = add_names_to_types(names, types)
for group, entries in types.items():
for field, attrs in entries.items():
header = False
... | 5,312,984 |
def cvSeqSort(*args):
"""cvSeqSort(CvSeq seq, CvCmpFunc func, void userdata=None)"""
return _cv.cvSeqSort(*args) | 5,312,985 |
def dice_coef_fn(y_true, y_pred, axis=1, eps=1e-6):
"""Calculate the Dice score."""
intersection = tf.reduce_sum(input_tensor=y_pred * y_true, axis=axis)
union = tf.reduce_sum(input_tensor=y_pred * y_pred +
y_true * y_true, axis=axis)
dice = (2. * intersection + eps) / (union +... | 5,312,986 |
def bootstrap_flask_app(app):
"""
Create a new, fully initialized Flask app.
:param obj app: A Stormpath Application resource.
:rtype: obj
:returns: A new Flask app.
"""
a = Flask(__name__)
a.config['DEBUG'] = True
a.config['SECRET_KEY'] = uuid4().hex
a.config['STORMPATH_API_KEY... | 5,312,987 |
def gram_counter(value: str, gram_size: int = 2) -> dict:
"""Counts the ngrams and their frequency from the given value
Parameters
----------
value: str
The string to compute the n-grams from
gram_size: int, default= 2
The n in the n-gram
Returns
-------
dict
""... | 5,312,988 |
def get_nucl_data_from_fasta(wd, all_projections):
"""Extract nucleotide data."""
meta_data = os.path.join(wd, "temp", "exons_meta_data.tsv")
nucl_fasta = os.path.join(wd, "nucleotide.fasta")
exon_to_meta_data = extract_exons_meta_data(meta_data)
projection_to_ref, projection_to_q = extract_full_nuc... | 5,312,989 |
def check(request):
"""SQL检测按钮, 此处没有产生工单"""
sql_content = request.POST.get('sql_content')
instance_name = request.POST.get('instance_name')
instance = Instance.objects.get(instance_name=instance_name)
db_name = request.POST.get('db_name')
result = {'status': 0, 'msg': 'ok', 'data': {}}
# 服务... | 5,312,990 |
def div_ext(
ticker: str,
viewer: viewers.Viewer = bootstrap.VIEWER,
) -> pd.DataFrame:
"""Сводная информация из внешних источников по дивидендам."""
df = viewer.get_df(ports.DIV_EXT, ticker)
return df.loc[bootstrap.START_DATE :] | 5,312,991 |
def is_pyside():
"""
Returns True if the current Qt binding is PySide
:return: bool
"""
return __binding__ == 'PySide' | 5,312,992 |
def filter_ocel_object_types_allowed_activities(ocel: OCEL, correspondence_dict: Dict[str, Collection[str]]) -> OCEL:
"""
Filters an object-centric event log keeping only the specified object types
with the specified activity set (filters out the rest).
Parameters
----------------
ocel
... | 5,312,993 |
def upload():
"""
Accepts a file upload and stores it on disk.
"""
f = request.files['file']
filename = secure_filename(f.filename)
f.save(path.join(app.config['UPLOAD_FOLDER'], filename))
return "%s uploaded successfully" % f.filename | 5,312,994 |
def parse_variables(config, variables, logger):
"""Parse configuration variables and add them to the config dict
The command line variables should be specified as key=value.
The key string can include dots, such as interp.order=2, which means to set::
config['interp']['order'] = 2
:param conf... | 5,312,995 |
def parse_sources_data(data, origin='<string>', model=None):
"""
Parse sources file format (tags optional)::
# comments and empty lines allowed
<type> <uri> [tags]
e.g.::
yaml http://foo/rosdep.yaml fuerte lucid ubuntu
If tags are specified, *all* tags must match the current
co... | 5,312,996 |
def list_module_public_functions(mod, excepted=()):
""" Build the list of all public functions of a module.
Args:
mod: Module to parse
excepted: List of function names to not include. Default is none.
Returns:
List of public functions declared in this module
"""
return [t[... | 5,312,997 |
def twovec(
axdef: Iterable[float], indexa: int, plndef: Iterable[float], indexp: int
) -> ndarray:
"""
Find the transformation to the right-handed frame having a
given vector as a specified axis and having a second given
vector lying in a specified coordinate plane.
https://naif.jpl.nasa.gov/p... | 5,312,998 |
def linter(src, fix=False, *, clang_format=False, cpplint=False,
clang_tidy=False, iwyu=False, iwyu_all=False,
python=False, numpydoc=False, cmake_format=False, rat=False,
r=False, rust=False, docker=False):
"""Run all linters."""
with tmpdir(prefix="arrow-lint-") as root:
... | 5,312,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.