content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_workflow_entrypoint(definition_class, workflow_name, workflow_version):
"""Get the entry point information from *workflow_class*.
This function provides a convenient way to extract the parameters
that need to be returned the *get_workflow* argument to
:py:class:`~.GenericWorkflowWorker`
:p... | 41,700 |
def expect_types(*_pos, **named):
"""
Preprocessing decorator that verifies inputs have expected types.
Usage
-----
>>> @expect_types(x=int, y=str)
... def foo(x, y):
... return x, y
...
>>> foo(2, '3')
(2, '3')
>>> foo(2.0, '3')
Traceback (most recent call last):
... | 41,701 |
def squash_by(child_parent_ids, *attributes):
"""Squash a child-parent relationship
Arguments
---------
child_parent_ids - array of ids (unique values that identify the parent)
*attributes - other arrays that need to follow the sorting of ids
Returns
-------
child_parents_idx - an arra... | 41,702 |
def _generate_quantsets(num_vars, num_qsets, ratio):
"""
_generate_quantsets(num_vars : int,
num_qsets : int,
ratio : float)
return (quantsets : list)
Generates a list of random quantifier sets according to given arguments
returns it.
Retu... | 41,703 |
def get_parser():
"""
Parses the command line arguments.
:returns: a parser with command line arguments
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description="Modbus Slave Endpoint.")
port_choices = SerialPort.list_serial_ports() + ['tcp:502', 'udp:5020']
pa... | 41,704 |
def execute_only(*args, commit=False, connector=None):
"""
Execute a serie of queries to known cursor
=====================================================
>>> from zilean import execute_sql
>>> from zilean import mysql_local_connection
>>> crs = m()
>>> execute_sql(query1, query2, cursor=cr... | 41,705 |
def save_headless_outputs(imagelist : list):
"""
Save headless output of raw images
==================================
Parameters
----------
imagelist : list
List of raw images to save as the concatenation of the outputs of the
headless models.
"""
# pylint:... | 41,706 |
def encoder(src_embedding, src_sequence_length):
"""Encoder: Bidirectional GRU"""
encoder_fwd_cell = layers.GRUCell(hidden_size=hidden_dim)
encoder_fwd_output, fwd_state = layers.rnn(
cell=encoder_fwd_cell,
inputs=src_embedding,
sequence_length=src_sequence_length,
time_major... | 41,707 |
def _class_search_post_url_from(absolute_url, form):
"""Determines absolute URL to submit HTTP POST query request to"""
method = form.get(HTTP_METHOD)
if method != POST:
raise ValueError("Expected POST form submission method; Got "+repr(method))
action = form.get(ACTION)
dest_url = urljoin(a... | 41,708 |
def pcmh_2_2d__3_5_6_7_8():
"""Huddles, Meetings & Trainings"""
huddle_sheet_url = URL('init', 'word', 'huddle_sheet.doc', vars=dict(**request.get_vars), hmac_key=MY_KEY,
salt=session.MY_SALT, hash_vars=["app_id"])
# referral tracking chart
huddle_sheet = MultiQNA(
... | 41,709 |
def CallCountsToMockFunctions(mock_function):
"""A decorator that passes a call count to the function it decorates.
Examples:
@CallCountsToMockFunctions
def foo(call_count):
return call_count
...
...
[foo(), foo(), foo()]
[0, 1, 2]
"""
counter = [0]
def Result(*args, **kwargs)... | 41,710 |
def multi_start_maximise(objective_function: Callable,
initial_points: ndarray, **kwargs) -> Tuple[ndarray, float]:
"""Run multi-start maximisation of the given objective function.
Warnings
--------
This is a hack to take advantage of fast vectorised computation and avoid... | 41,711 |
def test_install_error(capsys):
"""Package installation error report detailed message."""
with patch("subprocess.check_output") as check_output:
check_output.side_effect = CalledProcessError(cmd="cmd", returncode=1)
with pytest.raises(CalledProcessError) as exception:
installed = in... | 41,712 |
async def ping():
"""
.ping: respond with pong
"""
return "pong" | 41,713 |
def stationarity_check(TS,plot=True,col=None):
"""From: https://learn.co/tracks/data-science-career-v2/module-4-a-complete-data-science-project-using-multiple-regression/working-with-time-series-data/time-series-decomposition
"""
# Import adfuller
from statsmodels.tsa.stattools import adfuller... | 41,714 |
def generate_modelname(tpl,
nlayers: int = -1,
nhid: int = -1,
nagts=-1,
bptt: int = -1,
pre: bool = False,
arch: str = None):
"""
Generates model name from parameters.
... | 41,715 |
def file_exists(session, ds_browser, ds_path, file_name):
"""Check if the file exists on the datastore."""
client_factory = session._get_vim().client.factory
search_spec = vm_util.search_datastore_spec(client_factory, file_name)
search_task = session._call_method(session._get_vim(),
... | 41,716 |
def copy_id_maps(old_conn_str, new_conn_str, id_name, skipsites, addsites, ):
"""Using pg_dump, copy id_maps and dcc_ids tables from old database to new database
:param old_conn_str: connection string for old target database
:type: str
:param new_conn_str: connection string for new target database
... | 41,717 |
def convert_binary_to_unicode(binary_input):
"""
converts binary string of length 18 input to unicode
:param binary_input: String
:return: String
"""
unicode_output = ''
for starting_position in range(0, len(binary_input), 18):
unicode_output += chr(int(binary_input[startin... | 41,718 |
def get_rating(comment):
"""
"""
return comment.xpath(
".//div[@itemprop=\"reviewRating\"]/meta[@itemprop=\"ratingValue\"]"
)[0].attrib.get("content") | 41,719 |
def count_letters(in_fasta, out, threshold=10):
"""this is a function check for illegal
characters in fasta. If len is greater than threshold
it writes out the passed seq.
Take in a fasta, writes out a fasta"""
threshold = int(threshold)
aminos = set("ABRNDCQEGHIJLKMOFPSTWYVXZU")
names = set... | 41,720 |
def creat_netmiko_connection(username, password, host, port) -> object:
"""Logs into device and returns a connection object to the caller. """
credentials = {
'device_type': 'cisco_ios',
'host': host,
'username': username,
'password': password,
'port': port,
... | 41,721 |
def isPlaying(*args, **kwargs):
""" Returns if the program is playing or stopped """
pass | 41,722 |
def parse_arguments(args: List[str] = None):
"""
Parse arguments with argparse.ArgumentParser
Args:
args: List of arguments from cmdline
Returns: Parsed arguments
Raises:
Exception: On generic failure
"""
parser = argparse.ArgumentParser(description='Xbox SmartGlass clien... | 41,723 |
def get_requirements():
"""Read the requirements file."""
requirements = read("requirements.txt")
return [r for r in requirements.strip().splitlines()] | 41,724 |
def handler(fmt, station, issued):
"""Handle the request, return dict"""
pgconn = get_dbconn("asos")
if issued is None:
issued = utc()
if issued.tzinfo is None:
issued = issued.replace(tzinfo=timezone.utc)
df = read_sql(
f"""
WITH forecast as (
select id ... | 41,725 |
def index_count(index_file=config.vdb_bin_index):
"""
Method to return the number of indexed items
:param index_file: Index DB file
:return: Count of the index
"""
return len(storage.stream_read(index_file)) | 41,726 |
def strexc():
"""Return current exception formatted as a single line suitable
for logging.
"""
try:
exc_type, exc_value, tb = sys.exc_info()
if exc_type is None:
return ""
# find last frame in this script
lineno, func = 0, ""
for frame in traceback.... | 41,727 |
def asc_to_dict(filename: str) -> dict:
"""
Load an asc file into a dict object.
:param filename: The file to load.
:return dict: A dict object containing data.
"""
return list_to_dict(asc_to_list(filename)) | 41,728 |
def doUpgrade(upgrader):
"""
Do the required upgrade steps. Also, make sure we correctly set the store for having attachments enabled.
"""
# Ignore if the store is not enabled for managed attachments
if not upgrader.sqlStore.enableManagedAttachments:
upgrader.log.warn("No dropbox migration ... | 41,729 |
def merge_sort(array):
"""
Merge Sort
Complexity: O(NlogN)
"""
if len(array) > 1:
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
left = merge_sort(left)
right = merge_sort(right)
array = []
# This is a queue implem... | 41,730 |
def test_create_code_list(mocker: MockerFixture) -> None:
"""Code Lists are correctly created and and code elements added to orphan graph."""
identifier = "identifier"
title = {None: "title"}
description = {None: "description"}
enum = ["1", "2", "3"]
mock_component = mocker.MagicMock()
mock... | 41,731 |
def semi_major_axis(P, Mtotal):
"""Semi-major axis
Kepler's third law
Args:
P (float): Orbital period [days]
Mtotal (float): Mass [Msun]
Returns:
float or array: semi-major axis in AU
"""
# convert inputs to array so they work with units
P = np.array(P)
Mtotal... | 41,732 |
def parse_dependency_string(value: str) -> Dependency:
"""
Convert *value* to a representation as a #Dependency subclass.
* In addition to the [PEP 508][] dependency specification, the function supports a `--hash` option as is also
supported by Pip. Hashes in URL fragments are also parsed into #Depen... | 41,733 |
def _check_df_load(df):
"""Check if `df` is already loaded in, if not, load from file."""
if isinstance(df, str):
if df.lower().endswith('json'):
return _check_gdf_load(df)
else:
return pd.read_csv(df)
elif isinstance(df, pd.DataFrame):
return df
else:
... | 41,734 |
def confirm(question, assume_yes=True):
"""
Ask user a yes/no question and return their response as a boolean.
``question`` should be a simple, grammatically complete question such as
"Do you wish to continue?", and will have a string similar to ``" [Y/n] "``
appended automatically. This function w... | 41,735 |
def ping(host, timeout=False, return_boolean=False):
"""
Performs an ICMP ping to a host
.. versionchanged:: 2015.8.0
Added support for SunOS
CLI Example:
.. code-block:: bash
salt '*' network.ping archlinux.org
.. versionadded:: 2015.5.0
Return a True or False instead ... | 41,736 |
def comp_wind_sym(wind_mat):
"""Computes the winding pattern periodicity and symmetries
Parameters
----------
wind_mat : numpy.ndarray
Matrix of the Winding
Returns
-------
Nperw: int
Number of electrical period of the winding
"""
assert len(wind_mat.shape) == 4, "... | 41,737 |
def FindRepoDir(path):
"""Returns the nearest higher-level repo dir from the specified path.
Args:
path: The path to use. Defaults to cwd.
"""
return osutils.FindInPathParents(
'.repo', path, test_func=os.path.isdir) | 41,738 |
def row(data, widths="auto", spacing=3, aligns=None):
"""Format data as a table row.
data (iterable): The individual columns to format.
widths (iterable or 'auto'): Column widths in order. If "auto", widths
will be calculated automatically based on the largest value.
spacing (int): Spacing betw... | 41,739 |
def _increment_date(date, grain):
"""
Creates a range of dates where the starting date is the given date and the
ending date is the given date incremented for 1 unit of the given grain
(year, month or day).
:param date: the starting date in string format 'YYYY-MM-DD'
:param grain: the grain of ... | 41,740 |
def ErrorCorrect(val,fEC):
"""
Calculates the error correction parameter \lambda_{EC}. Typical val is 1.16.
Defined in Sec. IV of [1].
Parameters
----------
val : float
Error correction factor.
fEC : float
Error correction efficiency.
Returns
-------
float
... | 41,741 |
def test_with_base_date_and_num_runs_and_execution_date_within(admin_client, runs, endpoint):
"""
Tests view with base_date and num_runs and execution-date URL parameters.
Scenario: change the base date and num runs and press "Go",
the selected execution date is within the new range.
Should only sho... | 41,742 |
def knn_and_naive(table):
""" Analyzes the table based on Knn and Naive Bayes
:param table: the table of the titanic dataset
:return: nothing
"""
map_columns_table(table)
table = knn.normalize_table(table, [5,7])
# KNN
output.printHeader('K-Nearest Neighbors')
labels = partition_u... | 41,743 |
def BytesGt(left: Expr, right: Expr) -> BinaryExpr:
"""Greater than expression with bytes as arguments.
Checks if left > right, where left and right are interpreted as big-endian unsigned integers.
Arguments must not exceed 64 bytes.
Requires TEAL version 4 or higher.
Args:
left: Must eva... | 41,744 |
def plot_flux_vout(OIII_outflow_results, OIII_outflow_error, flux_line_outflow_results, flux_line_outflow_error, statistical_results, radius, z):
"""
Plots the broad-to-narrow line flux ratio against the outflow velocity, the
outflow velocity dispersion and the outflow velocity offset
Parameters
--... | 41,745 |
def balanceOf(account):
"""
can be invoked at every shard. If invoked at non-root shard, the shard must receive a xshard transfer before. Otherwise the function will throw an exception.
:param account: user address
:return: the token balance of account
"""
if len(account) != 20:
raise Ex... | 41,746 |
def archive_entry(title):
"""
"""
if not session.get('logged_in'):
abort(401)
db = get_db()
# Archive it
stmt = '''
insert into archived_entries select * from entries
where pretty_title like ?
'''
db.execute(stmt,
('%' + title + '%',))
db.execute('delet... | 41,747 |
def test_get_remote_data(mocker):
"""
Given:
- ServiceNow client
- arguments: id and LastUpdate(set to lower then the modification time).
- ServiceNow ticket
When
- running get_remote_data_command.
Then
- The ticket was updated with the entries.
"""
cl... | 41,748 |
def build_census_df(projection_admits: pd.DataFrame, parameters) -> pd.DataFrame:
"""ALOS for each category of COVID-19 case (total guesses)"""
n_days = np.shape(projection_admits)[0]
hosp_los, icu_los, vent_los = parameters.lengths_of_stay
los_dict = {
"Hospitalized": hosp_los,
"ICU": i... | 41,749 |
def indented_kv(key: str, value: str, indent=1, separator="=", suffix=""):
"""Print something as a key-value pair whilst properly indenting. This is useful
for implementations of`str` and `repr`.
Args:
key (str): Key.
value (str): Value.
indent (int, optional): Number of spaces to i... | 41,750 |
async def test_setup_no_config(hass, hass_admin_user):
"""Test component setup with no config."""
count_start = len(hass.states.async_entity_ids())
assert await async_setup_component(hass, DOMAIN, {})
with patch(
"homeassistant.config.load_yaml_config_file", autospec=True, return_value={}
)... | 41,751 |
def are_in_file(file_path, strs_to_find):
"""Returns true if every string in the given strs_to_find array is found in
at least one line in the given file. In particular, returns true if
strs_to_find is empty. Note that the strs_to_find parameter is mutated."""
infile = open(file_path)
for line in i... | 41,752 |
def create(meta_file, db_file, verbose):
"""
Reads the FAA d-TPP xml and creates a sql database from it.
"""
configure_log(verbose)
chart_handler = FAASQLChartHandler(db_file)
handler = FAAHandler(chart_handler.on_cycle_parsed, chart_handler.on_chart_parsed)
read_xml(meta_file,
... | 41,753 |
def load_data(filename: str):
"""
Load house prices dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Series]
"""
... | 41,754 |
def ask_user_for_secrets(credo, source=None):
"""Ask the user for access_key and secret_key"""
typ = "amazon"
choices = []
access_key_name = "AWS_ACCESS_KEY_ID"
secret_key_name = "AWS_SECRET_ACCESS_KEY"
environment = os.environ
if access_key_name in environment and secret_key_name in envir... | 41,755 |
def test_clear_ISD_whitelist():
"""
Creates a ISD whitelist request, sends it to the UDP server.
"""
logging.info('Starting the ISD whitelist test')
# Create a UDP socket
sock = UDPSocket(None, AddrType.IPV4)
req = {"version": "0.1",
"command": "ISD_WHITELIST",
"isds"... | 41,756 |
def slugify(value):
"""
Unicode version of standart slugify.
Converts spaces to hyphens. Removes characters that
aren't unicode letters, underscores, or hyphens. Converts to lowercase.
Also replaces whitespace with hyphens and
strips leading and trailing hyphens.
:param value: String to slug... | 41,757 |
def test_first():
"""Test first returns first arg as tuple."""
actual = transforms.first('foo', 'bar')
assert actual == ('foo',) | 41,758 |
def _generate_Wl(step, evt_type, energy, evtnumber):
"""
Here the settings for the Z ee simulation are added to the process.
Energy parameter is not used.
"""
func_id=mod_id+"["+sys._getframe().f_code.co_name+"]"
common.log( func_id+" Entering... ")
# Choose between muon or ele... | 41,759 |
def binomial_coefficient(n: int, m: int) -> int:
""" Binomial Coefficient
Returns n!/(m!(n-m)!). This is used in combinatronics and binomial theorem."""
from math import factorial as f
return f(n)/(f(m)*f(n-m)) | 41,760 |
def joint(waypoints):
"""
Calculate a trajectory by a joint operation.
"""
# total number of segments
numSegments = len(waypoints) - 1
# every segment has its own polynomial of 4th degree for X,Y and Z and a polynomial of 2nd degree for Yaw
numCoefficients = numSegments * (3*5+3)
# list ... | 41,761 |
async def test_custom_availability_payload(opp, mqtt_mock):
"""Test availability by custom payload with defined topic."""
await help_test_custom_availability_payload(
opp, mqtt_mock, binary_sensor.DOMAIN, DEFAULT_CONFIG
) | 41,762 |
def config(ctx):
"""
Configure Farmer with your LogDNA key.
To create a service key, go to:
<https://app.logdna.com/manage/profile>
"""
logdna_service_key = prompt_logdna_service_key()
sh.farmer.config.set('logdna_service_key', logdna_service_key) | 41,763 |
def logistic(x: float):
"""Logistic function."""
return 1 / (1 + math.exp(-x)) | 41,764 |
def highlight_deleted(obj):
"""
Display in red lines when object is deleted.
"""
obj_str = conditional_escape(text_type(obj))
if not getattr(obj, 'deleted', False):
return obj_str
else:
return '<span class="deleted">{0}</span>'.format(obj_str) | 41,765 |
def range_(stop):
""":yaql:range
Returns an iterator over values from 0 up to stop, not including
stop, i.e. [0, stop).
:signature: range(stop)
:arg stop: right bound for generated list numbers
:argType stop: integer
:returnType: iterator
.. code::
yaql> range(3)
[0, ... | 41,766 |
def my_argument_parser(epilog=None):
"""
Create a parser with some common arguments used by detectron2 users.
Args:
epilog (str): epilog passed to ArgumentParser describing the usage.
Returns:
argparse.ArgumentParser:
"""
parser = argparse.ArgumentParser(
epilog=epilog
... | 41,767 |
def post(filename: str, files: dict, output_type: str):
"""Constructs the http call to the deliver service endpoint and posts the request"""
url = f"http://{CONFIG.DELIVER_SERVICE_URL}/deliver/{output_type}"
logger.info(f"Calling {url}")
try:
response = session.post(url, params={"filename": fil... | 41,768 |
def list_files_recursively(root_dir, basename, suffix='y?ml'):
"""search for filenames matching the pattern: {root_dir}/**/{basename}.{suffix}
"""
root_dir = os.path.join(root_dir, "") # make sure root dir ends with "/"
# TODO - implement skip
if sys.version_info >= (3, 5):
return [filename... | 41,769 |
def is_off(*args):
"""
is_off(F, n) -> bool
is offset?
@param F (C++: flags_t)
@param n (C++: int)
"""
return _ida_bytes.is_off(*args) | 41,770 |
def get_libdcgm_path():
"""
Returns relative path to libdcgm.so.2
"""
return "../../lib/libdcgm.so.2" | 41,771 |
def write_errors(workflow,mof,neb=False):
"""
Write out the unsuccesful job files
Args:
workflow (class): pymofscreen.screen_phases.worfklow class
mof (ASE Atoms object): ASE Atoms object
"""
spin_level = workflow.spin_level
acc_level = workflow.acc_levels[workflow.run_i]
pprint('ERROR: '+spin_level+', '+... | 41,772 |
def method(modelclass, **kwargs):
"""Decorate a ProtoRPC method for use by the endpoints model passed in.
Requires exactly one positional argument and passes the rest of the keyword
arguments to the classmethod "method" on the given class.
Args:
modelclass: An Endpoints model class that can create a metho... | 41,773 |
def detect_on(window, index=3, threshold=5): # threshold value is important: power(watts)
"""input: np array
listens for a change in active power that exceeds threshold
(can use Active/real(P), Apparent(S), and Reactive (Q)(worst..high SNR))
index = index of feature to detect. Used P_real @ index 3
... | 41,774 |
def update_pleroma(self):
"""Update the Pleroma user info with the one retrieved from Twitter
when the User object was instantiated.
This includes:
* Profile image (if exists)
* Banner image (if exists)
* Bio text
* Screen name
* Additional metadata fields
:returns: None
"""
... | 41,775 |
def calculate_target_as_one_column(df:pd.DataFrame, feature_cols:list, target_cols:list):
"""create a row for every new porduct and give the product name as target column, this is done for the train set"""
x = df[target_cols]
x = x[x==1].stack().reset_index().drop(0,1)
df = pd.merge(df, x, left_on=df.in... | 41,776 |
def find_features_with_dtypes(df, dtypes):
"""
Find feature names in df with specific dtypes
df: DataFrame
dtypes: data types (defined in numpy) to look for
e.g, categorical features usually have dtypes np.object, np.bool
and some of them have np.int (with a limited number of unique items)
"""
return np.asarray... | 41,777 |
def test_marker_specifics(testcase, wrangler):
"""Tests specific `marker_start_use_first` and `marker_end_use_first`
scenarios.
Parameters
----------
testcase: DataTestCase
Generates test data for given test case.
wrangler: pywrangler.wrangler_instance.interfaces.IntervalIdentifier
... | 41,778 |
def DeConv2d(net, n_out_channel = 32, filter_size=(3, 3),
out_size = (30, 30), strides = (2, 2), padding = 'SAME', batch_size = None, act = None,
W_init = tf.truncated_normal_initializer(stddev=0.02), b_init = tf.constant_initializer(value=0.0),
W_init_args = {}, b_init_args = {}, name ='decnn2d... | 41,779 |
def parse_release(base: str, path: str) -> List[str]:
"""Extracts built images from the release.yaml at path
Args:
base: The built images will be expected to start with this string,
other images will be ignored
path: The path to the file (release.yaml) that will contain the built im... | 41,780 |
def test_publish_to_broker(pact):
"""
This test does not clean-up previously generated pact.
Sample execution where 2 is an arbitrary version:
`pytest tests/consumer/test_message_consumer.py::test_publish_pact_to_broker`
`pytest tests/consumer/test_message_consumer.py::test_publish_pact_to_broker ... | 41,781 |
def build_config(config_file=get_system_config_directory()):
"""
Construct the config object from necessary elements.
"""
config = Config(config_file, allow_no_value=True)
application_versions = find_applications_on_system()
# Add found versions to config if they don't exist. Versions fo... | 41,782 |
def preProcess(column):
"""
Do a little bit of data cleaning with the help of Unidecode and Regex.
Things like casing, extra spaces, quotes and new lines can be ignored.
"""
column = unidecode(column)
column = re.sub('\n', ' ', column)
column = re.sub('-', '', column)
column = re.sub('/... | 41,783 |
def size_to_pnts(size) -> np.ndarray:
"""
获得图片 size 的四个角点 (4,2)
"""
width = size[0]
height = size[1]
return np.array([[0, 0], [width, 0], [width, height], [0, height]]) | 41,784 |
def create_scenario_mms_datasets(variable_name,
scenario_name,
num_chunks,
data_path,
normalized=False):
"""Create the multi-model statistics dataset for a scenario.
Runs the func... | 41,785 |
def carla_rotation_to_numpy_rotation_matrix(carla_rotation):
"""
Convert a carla rotation to a Cyber quaternion
Considers the conversion from left-handed system (unreal) to right-handed
system (Cyber).
Considers the conversion from degrees (carla) to radians (Cyber).
:param carla_rotation: the... | 41,786 |
def _liquid_viscocity(_T, ranged=True):
"""Pa * s"""
OutOfRangeTest(_T, 59.15, 130, ranged)
A, B, C, D, E = -2.0077E+01, 2.8515E+02, 1.7840E+00, -6.2382E-22, 10.0
return exp(A + B / _T + C * log(_T) + D * _T**E) | 41,787 |
def _interactive(git, name):
"""
Interactive assistant. This will supercede any command line arguments, meaning
that it is pointless to add any other arguments when using the -i argument.
"""
prompt = (
"\n========================================================================\n"
"T... | 41,788 |
def readConfig(filename):
"""Parses a moosicd configuration file and returns the data within.
The "filename" argument specifies the name of the file from which to read
the configuration. This function returns a list of 2-tuples which associate
regular expression objects to the commands that will be us... | 41,789 |
def negative_f1(y_true, y_pred) -:
"""Implements custom negative F1 loss score for use in multi-isotope classifiers.
Args:
y_true: a list of ground truth.
y_pred: a list of predictions to compare against the ground truth.
Returns:
Returns the custom loss score.
... | 41,790 |
def test_create_user_unique_email(admin_client):
"""
...
"""
repeat_email = "admin@django.com"
data: Dict[str, Any] = {
"username": "NEW",
"email": repeat_email,
"password": "123",
"first_name": "name",
"last_name": "name2",
"is_staff": False,
}
... | 41,791 |
def cal_gauss_log_lik(x, mu, log_var=0.0):
"""
:param x: batch of inputs (bn X fn)
:return: gaussian log likelihood, and the mean squared error
"""
MSE = torch.pow((mu - x), 2)
gauss_log_lik = -0.5*(log_var + np.log(2*np.pi) + (MSE/(1e-8 + torch.exp(log_var))))
MSE = torch.mean(torch.sum(MSE... | 41,792 |
def translate_fun_parseInt(x):
"""Converts parseInt(string, radix) to
__extrafunc_parseInt(string, radix=10)
Args:
x (str): JavaScript code to translate.
Returns:
str: Translated JavaScript code.
Examples:
>>> from ee_extra import translate_fun_parseInt
>>> transla... | 41,793 |
def simple_intensity_based_segmentation(image, gaussian_sigma=1, thresh_method="Otsu", smallest_area_of_object=5,label_img_depth = "8bit"):
"""Perform intensity based thresholding and detect objects
Args:
raw_image_path : path to a raw image
gaussian_sigma : sigma to use f... | 41,794 |
def mish(x):
"""mish activation function
Args:
x (Tensor): input tensor.
Returns:
(Tensor): output tensor and have same shape with x.
Examples:
>>> mish(to_tensor([-3.0, -1.0, 0.0, 2.0]))
tensor([-1.4228e-01, -2.6894e-01, 0.0000e+00, 1.7616e+00]
References:
... | 41,795 |
def text_box_end_pos(pos, text_box, border=0):
"""
Calculates end pos for a text box for cv2 images.
:param pos: Position of text (same as for cv2 image)
:param text_box: Size of text (same as for cv2 image)
:param border: Outside padding of textbox
:return box_end_pos: End xy coordinates for t... | 41,796 |
def add_cmd(bundle_id, patch_ids, fmt):
"""Add one or more patches to a bundle.
Append the provided PATCH_IDS to bundle BUNDLE_ID.
Requires API version 1.2 or greater.
"""
LOG.debug('Add to bundle: id=%s, patches=%s', bundle_id, patch_ids)
bundle = _get_bundle(bundle_id)
data = [
... | 41,797 |
def determine_proj_env_in_SDK():
"""
set IS_PROJ_ENV_IN_SDK to True if project environment is located inside of SDK.
"""
global IS_PROJ_ENV_IN_SDK
if(DLG_WORKING_PROJECT_DIRECTORY.startswith(os.path.abspath(DLG_SDK_ROOT_DIRECTORY))):
print("PROJECT ENVIRONMENT LOCATED INSIDE OF SDK ...")
IS_PROJ_ENV_IN_SDK = ... | 41,798 |
def ticket_competence_add_final(request, structure_slug, ticket_id,
new_structure_slug, structure, can_manage, ticket,
office_employee=None):
"""
Adds new ticket competence (second step)
:type structure_slug: String
:type ticket_id: String... | 41,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.