content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def ways_init():
"""Initialize table for final version."""
for i in range(SIZE):
cur[i] = 1 + i // 2
for c in range(2, 8):
prev = cur[:]
for o in range(coin_values[c]):
cur[o] = prev[o]
for o in range(coin_values[c]):
a = prev[o]
for i in r... | 5,297,600 |
def get_dc_token(region_name=constants.SYSTEM_CONTROLLER_REGION):
"""Get token for the dcmanager user.
Note: Although region_name can be specified, the token used here is a
"project-scoped" token (i.e., not specific to the subcloud/region name).
A token obtained using one region_name can be re-used acr... | 5,297,601 |
def calculate_multiplier(aggregate_add_on, value, RC):
"""
Calculates multiplier depending on Replacement Cost (RC).
Returns
-------
Multiplier.
"""
market_value = calculate_market_value(value)
if RC > 0:
multiplier = 1
return multiplier
else:
floor = 0.05
... | 5,297,602 |
def root_cli() -> None:
"""
To get help for a specific command:
\033[1m peltak <command> --help\033[0m
Examples:
\033[1m peltak lint --help\033[0m
\033[1m peltak version bump --help\033[0m
\033[1m peltak release upload --help\033[0m
"""
pass | 5,297,603 |
def gen_col_list(num_signals):
"""
Given the number of signals returns
a list of columns for the data.
E.g. 3 signals returns the list: ['Time','Signal1','Signal2','Signal3']
"""
col_list = ['Time']
for i in range(1, num_signals + 1):
col = 'Signal' + str(i)
col_list.append(c... | 5,297,604 |
def calculate_eigenspaces(kr_max, theta, phi, rad):
"""Calculate the eigenspaces for the corresponding eigenfrequencies of
the sphere
Parameters
----------
k_max : float
The largest wave number to be included
theta : array, float
Azimuth angle
phi : array, float
Elev... | 5,297,605 |
def get_sequence(message, message_object_list, sequence_list, sequence=None, index=None):
"""Returns a sequence i.e. more than 2 messages"""
if not sequence:
sequence = []
index = 0
if message not in sequence and not any(message in s for s in sequence_list) is True:
message[3] = True... | 5,297,606 |
def fit_moffat(arr):
"""
Params
------
arr (2d np array of odd sizes)
Return
------
model (astropy model object)
"""
# sanity check of input data type
if isinstance(arr, ac.kernels.Kernel):
arr = arr.array
elif isinstance(arr, np.ndarray):
pass
else:
raise Exception("[psfmatch] input needs to be a ... | 5,297,607 |
def date_generator(
num_dates: int = 1,
start_year: int = 1950,
end_year: int = current_year,
as_list: bool = False,
):
"""
Function to generate date(s). Specify the number of dates (num_dates, defaults to 1),\n
start year (start_year, defaults to 1950),\n
end year (end_year, defaults to... | 5,297,608 |
def test_batch_create(requests_mock):
"""
Test batch creation
"""
metadata = Gen3Metadata("https://example.com")
metadata_list = [
{"guid": "3c42c819-1dfe-4c3e-8d46-c3ec7eb99bf4", "data": {"foo": "bar"}},
{"guid": "dfa1a1dc-98f4-46be-ba8f-ae9b42b0ee50", "data": {"foo": "bar"}},
]... | 5,297,609 |
def generate_test():
"""
This is only used in debugging.
Generates a test map with plotting on.
"""
o = [];
pos = [384, 288];
note_group_size = GAN_PARAMS["note_group_size"];
generate_set(begin = 3 * note_group_size, start_pos = pos, length_multiplier = dist_multiplier, group_id = 3, plo... | 5,297,610 |
async def m004_ensure_fees_are_always_negative(db):
"""
Use abs() so wallet backends don't have to care about the sign of the fees.
"""
await db.execute("DROP VIEW balances")
await db.execute(
"""
CREATE VIEW balances AS
SELECT wallet, COALESCE(SUM(s), 0) AS balance FROM (
... | 5,297,611 |
def catch(f):
"""
>>> import nuvolaris.testutil as tu
>>> tu.catch(lambda: "ok")
ok
>>> def error():
... raise Exception("error")
>>> tu.catch(error)
<class 'Exception'> error
"""
try: print(f().strip())
except Exception as e:
print(type(e), str(e).strip()) | 5,297,612 |
def replace_index(list_obj: list, element_index: int, replacement_value) -> None:
"""
Convenience function to replace an index's element with another value
:param list_obj: The list instance to operate on
:param element_index: The index of the element to be replaced
:param replacement_value: Value t... | 5,297,613 |
def setup_url_rules(app):
"""Setup URL rules."""
from libcrowds_analyst.api import BP as api_bp
app.register_blueprint(api_bp, url_prefix='/') | 5,297,614 |
def f_isASCII(*args):
"""f_isASCII(flags_t F, void ?) -> bool"""
return _idaapi.f_isASCII(*args) | 5,297,615 |
def generate_ical_string(key: str) -> str:
"""generates iCalendar string from testdata and returns it"""
c = Calendar()
for row in _testdata["iCalendar"].get(key, []):
c.events.add(
Event(
name=row["name"],
begin=row["begin"],
end=row["end"... | 5,297,616 |
def read_parfile(parfile):
"""load a pest-compatible .par file into a pandas.DataFrame
Parameters
----------
parfile : str
pest parameter file name
Returns
-------
pandas.DataFrame : pandas.DataFrame
"""
assert os.path.exists(parfile), "Pst.parrep(): parfile not found: " +... | 5,297,617 |
def int_to_bytes(int_: int, architecture: int = None) -> Bytes:
"""Get Bytes object
:param int_: number integer to convert to Bytes
:type: int
:param architecture: bytes length
:type: int
:return: bytes representation
:type: Bytes
"""
bin_ = f'{bin(int_)[2:]}'
bytes... | 5,297,618 |
async def login_headless(root: Root, url: URL) -> None:
"""
Log into Neuro Platform from non-GUI server environment.
URL is a platform entrypoint URL.
The command works similar to "neuro login" but instead of
opening a browser for performing OAuth registration prints
an URL that should be open... | 5,297,619 |
def send_invite(jid, from_jid=None):
"""Sends an invitation to chat to a JID.
Args:
jid: The JID of the contact to invite.
from_jid: The optional custom JID to use for sending. Currently, the default
is <appid>@appspot.com. This is supported as a value. Custom JIDs can be
of the form <anything>... | 5,297,620 |
def get_collision_fn(body, joints, obstacles=[],
attachments=[], self_collisions=True,
disabled_collisions={},
extra_disabled_collisions={},
custom_limits={},
body_name_from_id=None, **kwargs):
"""get collision check... | 5,297,621 |
def decode_bytes(b):
"""Tries to decode the bytes using XONSH_ENCODING if available,
otherwise using sys.getdefaultencoding().
"""
session = getattr(builtins, "__xonsh__", None)
env = os_environ if session is None else getattr(session, "env", os_environ)
enc = env.get("XONSH_ENCODING") or DEFAUL... | 5,297,622 |
async def test_show_config_form_validate_webhook(hass, webhook_id):
"""Test show configuration form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
... | 5,297,623 |
def evaluate_model(input_model, data_set_test, classes_test_old, get_eth):
"""
It evaluates the model, depends on the target variable
"""
if get_eth:
CM = [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]]
for i in range(250)... | 5,297,624 |
def cropobjects_merge_bbox(cropobjects):
"""Computes the bounding box of a CropObject that would
result from merging the given list of CropObjects."""
# Find extremes. This will define the output cropobject.
t, l, b, r = numpy.inf, numpy.inf, -1, -1
for c in cropobjects:
t = min(t, c.top)
... | 5,297,625 |
def starttime(pid):
"""starttime(pid) -> float
Arguments:
pid (int): PID of the process.
Returns:
The time (in seconds) the process started after system boot
"""
return psutil.Process(pid).create_time() - psutil.boot_time() | 5,297,626 |
def generate_nested_list(root,nodes):
"""
Generates a nested list representation of the tree
with specified node as root. Useful for checking
equality of trees or subtrees.
To do: make the nested list form a property that is computed when needed.
"""
nl = []
if root.children is None: r... | 5,297,627 |
def build_group_objects(env1, admin_api_key1, group_links):
"""
Builds a list of Group objects that will be used to more quickly check for users in groups
"""
Groups_List = [] # initialize a python list of objects
if not (group_links is None):
for i in np.arange(0, np.shape(group_links)[0])... | 5,297,628 |
def before_request():
"""
Load a user object into `g.user` before each request.
"""
# Check whether or not the server-side cookie (session created on log in) exists and is valid
g.user = okta_client.get_user(oidc.user_getfield(
"sub")) if oidc.user_loggedin else None | 5,297,629 |
def queryset_filter_tag(queryset, **kwargs):
""" template tag which allows queryset filtering. Usage:
{% filter_tag books author=author as mybooks %}
{% for book in mybooks %}
{% endfor %}
"""
return queryset.filter(**kwargs) | 5,297,630 |
def render(H, W, focal, cx, cy, chunk=1024*32, rays=None, c2w=None, ndc=True,
near=0., far=1.,
use_viewdirs=False, c2w_staticcam=None,
**kwargs):
"""Render rays
Args:
H: int. Height of image in pixels.
W: int. Width of image in pixels.
focal: float. Focal lengt... | 5,297,631 |
def _ensure_no_jekyll():
"""Create a .nojekyll file.
This prevents Github from messing with folders that start with an
underscore.
"""
logger = logging.getLogger(__name__)
nojekyll = Path('.nojekyll')
if nojekyll.is_file():
logger.debug("%s exists", nojekyll)
else:
logge... | 5,297,632 |
def abstract(func):
"""
An abstract decorator. Raises a NotImplementedError if called.
:param func: The function.
:return: The wrapper function.
"""
# noinspection PyUnusedLocal
# pylint: disable=unused-argument
def wrapper(*args, **kwargs):
raise NotImplementedError('{} has... | 5,297,633 |
def is_greyscale_image(image: np.ndarray) -> bool:
"""
A function that checks if an image is a greyscale image (an image where pixels are a number - has 1 color channel)
:param image: the image to be checked, a numpy array
"""
return len(image.shape) == 2 | 5,297,634 |
def __get_site_amp_ratio(pga: float, db_vs30: float, user_vs30: float, im: IM):
"""
Calculates a PGA_1100 estimate; uses it to calculate a site amplification ratio for the difference in vs30
between the user and the modelled vs30
Scaling is only defined for pSA and PGA otherwise no scaling is applied -... | 5,297,635 |
def move_zero(lst):
"""
Given a list of integers, moves all non-zero numbers to the beginning of the list and
moves all zeros to the end of the list. This function returns nothing and changes the given list itself.
For example:
- After calling move_zero([0,1,0,2,0,3,0,4]), the given list should be... | 5,297,636 |
def cosineXform(a, b, c):
"""
Spherical trig transform to take alpha, beta, gamma to expressions
for cos(alpha*). See ref below.
[1] R. J. Neustadt, F. W. Cagle, Jr., and J. Waser, ``Vector algebra and
the relations between direct and reciprocal lattice quantities''. Acta
Cryst. (1968)... | 5,297,637 |
def load_escolas():
"""Load and return the dadosabertos.poa.br escolas dataset.
The escolas dataset is a public open dataset from Prefeitura de Porto Alegre, Rio Grande do Sul, Brazil.
Examples
--------
>>> from dyrapy.datasets import load_escolas
>>> cadastro, matriculas = load_escolas()
... | 5,297,638 |
def svn_fs_node_created_path(*args):
"""svn_fs_node_created_path(svn_fs_root_t * root, char const * path, apr_pool_t pool) -> svn_error_t"""
return _fs.svn_fs_node_created_path(*args) | 5,297,639 |
def dump(filename, outfile="", parameters=[]):
"""
The rrdtool Python bindings don't have support for dump, so we need to use
the external dump function.
>>> rrdfile = '/tmp/test.rrd'
>>> parameters = [
... '--start',
... '920804400',
... 'DS:speed:COUNTER:600:U:U',
... 'RRA... | 5,297,640 |
def get_circular_orbit_speed(body="Earth", altitude=160):
""" Get speed of LEO (Low Earth Orbit) at designated altitude.
Keyword Arguments:
altitude {int} -- distance above Earth surface in km (default: {160})
Returns:
[int] -- speed in km/s.
"""
if body == "Sun":
mu = SUN... | 5,297,641 |
def load_sce_and_metadata(file_path, local_env_yaml):
"""
For the given SCE audit file (file_path) under the specified environment
(local_env_yaml), parse the file while expanding Jinja macros and read any
metadata headers the file contains. Note that the last keyword of a
specified type is the reco... | 5,297,642 |
def assert_coordinate(**kwargs):
"""Ensure all given values are a sequence of 2 real numbers.
:raises TypeError: if value is not a pair of doubles.
.. versionadded:: 0.6.0
"""
for label, subject in kwargs.items():
if not isinstance(subject, Sequence):
fmt = "'{0}' must be a pai... | 5,297,643 |
def assert_type(obj, name, expected_type):
"""
Raise TypeError if obj is not of the expected type
Args:
obj: object to check
name: name of object (to be included in exception message)
expected_type: type to check obj against
Raises:
TypeError
"""
if not isinstan... | 5,297,644 |
def migrate_user(auth, client, cfgobj):
"""
Migration function that reads data from old matomat sqlite and creates user in the backend
:auth: dict
:client: userauth object
:cfgobj: config dict
:returns: bool
"""
# Check if configured database is there and can be read
try:
m... | 5,297,645 |
def datetime_interpretation(raw):
"""Converts human-readable datetime into normal datetime instance.
Args:
raw (str or unicode): source string with datetime data.
Returns:
datetime: result datetime instance.
None: if couldn't read value.
"""
if isinstance(raw, (unicode, str... | 5,297,646 |
async def test_connection_id_in_to_field_detected(caplog):
"""Test to field is parsed correctly and used for routing."""
logger = logging.getLogger("aea.multiplexer")
with caplog.at_level(logging.DEBUG, logger="aea.multiplexer"):
connection_1 = _make_dummy_connection()
connections = [connect... | 5,297,647 |
def model_3d_deep(n_classes: int, input_size: int, **kwargs) -> tf.keras.Sequential:
"""
Deep 3D convolutional model from: https://arxiv.org/pdf/1907.11935.pdf
:param n_classes: Number of classes in the dataset
:param input_size: Size of the input sample
:param kwargs: Additional arguments.
:re... | 5,297,648 |
async def welcome(user : discord.Member):
"""Say "Welcome" to a user."""
await bot.say("Welcome %s"%user.mention) | 5,297,649 |
def get_ip_loadbalancing_vrac_networks_output(service_name: Optional[pulumi.Input[str]] = None,
subnet: Optional[pulumi.Input[Optional[str]]] = None,
vlan_id: Optional[pulumi.Input[Optional[int]]] = None,
... | 5,297,650 |
def decrypt(steg_image, decrypt_method, password):
"""Extract the secret message from the steg image
Keyword arguments:
steg_image -- PIL Image with the embedded secret
decrypt_method -- either LSB or EMD
password -- the password used for encryption"""
pixels = get_pixels(steg_image, (decrypt_method == 'pvd'))... | 5,297,651 |
def _pairing_consistency_check(files, errors):
"""checks the datastructure for consistency"""
file_list = sorted([f for f in files if not files[f].get('symlink')])
pair_list = []
for f, info in files.items():
# skip links for secondary aliases
if info.get('symlink'):
continue... | 5,297,652 |
def test_2x_only_python_version_deploy():
"""Test setup.py format correct for Python 2.7 only versions support."""
pass | 5,297,653 |
def check_if_type(attribute, att_type, name):
""" Checks if attribute is a meta model
:param attribute: The to be checked attribute
:param att_type: The type the attribute should be
:param name: The name of the attribute
:return: Checks if attribute is of att_type
"""
if not isins... | 5,297,654 |
def get_data_files(dir):
""" Return alphabetical sorted list of all found XML data files in
directory, excluding the main database file (MSDN_INFO_FILE).
Argument:
dir -- path where XML data files reside
"""
data_files = os.listdir(dir)
if MSDN_INFO_FILE in data_files:
data_files.re... | 5,297,655 |
def test_weighted_l2_np():
"""
test of weighted_l2_np
"""
for _ in range(5):
y, y_pred, weights = torch.rand(5), torch.rand(5), torch.rand(5)
loss = smooth_rf.weighted_l2(y,y_pred,weights).item()
assert smooth_rf.weighted_l2_np(y.numpy(), y_pred.numpy(), weights.numpy()) == \
... | 5,297,656 |
def non_related_filter(questions_df, non_related_ids):
"""
Splits a questions dataframe between related and non-related discussions,
based on an Ids list of non-related discussions.
:param questions_df:
> A pandas dataframe of stackoverflow questions containing posts Ids;
:param non_... | 5,297,657 |
def _configure_features_for_binary(
ctx,
requested_features = [],
unsupported_features = []):
"""Creates and returns the feature configuration for binary linking.
This helper automatically handles common features for all Swift
binary-creating targets, like code coverage.
Args:
... | 5,297,658 |
def update_assessment(
db_session: Session, old_assessment: RestBewertungCreate, new_assessment: RestBewertungCreate
) -> RestBewertungReturn:
"""Update the comment and rating of a existing assessment
Args:
db_session (sqlalchemy.orm.Session): Session to the DB -> See `db: Session = Depends(get_db)... | 5,297,659 |
def index(request):
"""index
Args:
request (request): api request
"""
return JsonResponse({"data": "theres nothing at this endpoint"}) | 5,297,660 |
def sin(x):
"""Return sin of x (x is in radians)"""
return math.sin(x) | 5,297,661 |
def get_resource_path():
"""Return the path to general resources.
Returns the path to general resources, terminated with separator.
Resources are kept outside package folder in "resources".
Based on function by Yaroslav Halchenko used in Neurosynth Python package.
Returns
-------
resource_... | 5,297,662 |
def launch(launcher, use_pycuerun=True):
"""
Launch the given L{OutlineLauncher}.
:type launcher: L{OutlineLauncher}
:param launcher: The OutlineLauncher to launch.
:type use_pycuerun: bool
:param use_pycuerun: Enable/Disable pycuerun.
:rtype: opencue.Entity.Job
:return: The opencue jo... | 5,297,663 |
def _paramMinCount(callableObject):
"""
Given a callable object (function, method or callable instance),
return pair (min,d) where min is minimum # of args required, and d
is number of default arguments. The 'self' parameter, in the case
of methods, is not counted.
"""
if type(callableObject... | 5,297,664 |
def acceleration(syn, obs, nt, dt, *args, **kwargs):
"""
Acceleration waveform for migration, second derivative of obs
"""
adj[1:-1] = (-obs[2:] + 2. * obs[1:-1] - obs[0:-2]) / (2. * dt)
return adj | 5,297,665 |
def get_updated_version_copy(existing_version: version.Version,
major: int = None, minor: int = None, micro: int = None) -> version.Version:
"""get_updated_version_copy
Generates a copy of a version.Version with the specified major, minor, micro version.
None values leaves the v... | 5,297,666 |
def apply_scevent(xml_paths: list, output_filename: str):
"""Apply parallely scevent to pruned origins
Parameters
----------
xml_paths : list
List of xml paths of pruned origins
output_filename : str
Name of the output seiscomp event xml
"""
db = 'db_sc = mysql://sysop:sysop... | 5,297,667 |
def format_pin(pnum, relatedpnum):
"""Formats a Parcel ID Number (PIN) from a BS&A PNUM."""
try:
if relatedpnum is None or relatedpnum.startswith('70-15-17-6'):
p = pnum
else:
p = relatedpnum
p = p.split('-')
del p[0]
p = ''.join(p)
except Inde... | 5,297,668 |
def condense_log_events(log_stream, log_events):
"""Condense log events into single strings. expects list of dicts."""
condensed_events = []
for event in log_events:
event_datetime = datetime.fromtimestamp(event['timestamp'] / 1000)
message = "{} | {} | {}".format(log_stream, event_datetime,... | 5,297,669 |
def list_repofiles(c, name):
"""get files from manifest from working or devel repo
"""
if name in all_repos:
path, files = get_repofiles(c, name)
else:
if name == '.':
path = '.'
else:
path = os.path.join(DEVEL, '_' + name)
if not os.path.exist... | 5,297,670 |
def trickle(session_config):
"""Return a dict with "trickled down" / inherited config values.
This will only work if config has been expanded to full form with
:meth:`config.expand`.
tmuxp allows certain commands to be default at the session, window
level. shell_command_before trickles down and pr... | 5,297,671 |
def register_built_in_panel(hass, component_name, sidebar_title=None,
sidebar_icon=None, url_path=None, config=None):
"""Register a built-in panel."""
# pylint: disable=too-many-arguments
path = 'panels/ha-panel-{}.html'.format(component_name)
if hass.wsgi.development:
... | 5,297,672 |
def current_year():
""" Returns the current year. """
import datetime as dt
now = dt.datetime.now()
return now.year | 5,297,673 |
def register():
"""
The register page endpoint
---
get:
parameters:
None
responses:
200:
The register page html
post:
parameters:
None
responses:
301: redirects to login if registered successfully
... | 5,297,674 |
def get_router_port(endpoint):
""" get the network device and port of where the endpoint is connected to.
Args:
endpoint (endpoint): endpoint
A routerport is a dict with the following keys:
router (string): name of the netork device
port (string): port on the router.... | 5,297,675 |
def createGraph(input_edge_list):
"""
From list of edges create and return a graph.
:param input_edge_list: list of edges
:returns G: the graph
"""
# first thing, how are the nodes separated in an edge
with open(input_edge_list, 'r') as f:
l = f.readline()
delimiter = l[1]
... | 5,297,676 |
def test_gdc_get_proj_str():
"""Test that `Geodetic.get_proj_str` returns a correct proj string.
"""
# no offset
crs = pfc.Geodetic()
assert_proj_str_equivalent(
crs.get_proj_str(), '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
# offset is arbitrary as it does not matter here
... | 5,297,677 |
def dummy_callable(obj):
"""A callable that you probably shouldn't be using :)"""
return [] | 5,297,678 |
def get_accessory_files(model_id: str) -> List[DojoSchema.ModelAccessory]:
"""
Get the `accessory files` for a model.
Each `accessory file` represents a single file that is created to be
associated with the model. Here we store key metadata about the
`accessory file` which enables us to find it wi... | 5,297,679 |
def text_to_ascii_text(font, text, cols, lines):
"""Convert text to ASCII art text banner"""
image = Image.new('RGB', (cols - 1, lines - 1), (255, 255, 255))
draw = ImageDraw.Draw(image)
draw.text((0, 0), text, fill='black', font=font)
width, height = image.size
pixels = image.load()
# conve... | 5,297,680 |
def test_bad_gq():
"""
Test what happends when GQ is not a float.
"""
my_genotype = Genotype(**{'GT':'0/1', 'GQ':'A'})
assert my_genotype.genotype == '0/1'
#If dp is wrong we set it to 0
assert my_genotype.genotype_quality == 0 | 5,297,681 |
def api_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
"""
Role `:api:` bridges generated API documentation by epydoc with sphinx.
Add `epydoc_ext` to the list of extensions
Generate the documentation in build folder::
$ mkdir -p _build/html/api
$ epydoc -o _bu... | 5,297,682 |
def compute_auc(xpts, ypts):
"""
Calculates the AUC.
:param xpts: Points on the X axis - the threshold values
:param ypts: Points on the Y axis - the pck value for that threshold
:return: The AUC value computed by integrating over pck values for all thresholds
"""
a = np.min(xpts)
b = np... | 5,297,683 |
def cie76(c1, c2):
"""
Color comparision using CIE76 algorithm.
Returns a float value where 0 is a perfect match and 100 is
opposing colors. Note that the range can be larger than 100.
http://zschuessler.github.io/DeltaE/learn/
LAB Delta E - version CIE76
https://en.wikipedia.org/wiki/Color... | 5,297,684 |
def process_batch_file(batchfile, options):
""" Perform the actions specified in the batch file with the given base options
If options are specified in the batch file that override the options given, those
options will be used instead.
"""
with open(batchfile, 'r') as f:
data = yaml.load_al... | 5,297,685 |
def gaussian_mixture_2d(X, alpha=None, scale=2, fill=False, axes=None, **kwargs):
"""
Plot Gaussian mixture as ellipses in 2-D
Parameters
----------
X : Mixture node
alpha : Dirichlet-like node (optional)
Probabilities for the clusters
scale : float (optional)
Scale for the... | 5,297,686 |
def create_all_test_plots():
"""Creates all plotting functions defined in tests/test_plots.py"""
plot_functions = getmembers(test_plots, isfunction)
for function_name, function in plot_functions:
logging.info(f"Calling {function_name}")
function(output_dir=TEMP_DIR) | 5,297,687 |
def fill_based_other_col(data: DataFrame, col_to_fill: str, ref_col: str, method: str = 'mode',
replace: Any = np.nan) -> Tuple[Series, Any]:
"""Function to fill nulls on a DataFrame column based on other column.
To fill based on multiple columns pass ref_col as a concatenation of the c... | 5,297,688 |
def test_requestid(base_app):
"""Test extraction of header id."""
InvenioApp(base_app)
with base_app.test_client() as client:
assert '1234' == client.get(
'/requestid', headers={'X-Request-ID': '1234'}
).get_data(as_text=True) | 5,297,689 |
def wlan_connect(essid, passphrase):
"""connect to wlan network"""
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect(essid, passphrase)
while not sta_if.isconnected():
pass
print("network: ip %s subnet %s... | 5,297,690 |
def test_user_defined_properties():
"""Get user defined properties"""
for output in outputs.STREAM_OUTPUTS.values():
props = output(REGION, FUNCTION_NAME, CONFIG).get_user_defined_properties()
# The user defined properties should at a minimum contain a descriptor
assert_is_not_none(props... | 5,297,691 |
def mock_controller_connect():
"""Mock a successful connection."""
with patch("homeassistant.components.asuswrt.router.AsusWrt") as service_mock:
service_mock.return_value.connection.async_connect = AsyncMock()
service_mock.return_value.is_connected = True
service_mock.return_value.conne... | 5,297,692 |
def sparse_reset_shape(sp_input, new_shape=None):
"""Resets the shape of a `SparseTensor` with indices and values unchanged.
If `new_shape` is None, returns a copy of `sp_input` with its shape reset
to the tight bounding box of `sp_input`. This will be a shape consisting of
all zeros if sp_input has no values.... | 5,297,693 |
def check_cpix_version(root):
"""
Check CPIX version is 2.3 for Speke v2. It is the only version currently supported
"""
assert float(root.get('version').strip()) == 2.3, \
"Attribute: version value for CPIX element is expected to be 2.3" | 5,297,694 |
def project_new_folder(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /project-xxxx/newFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder
"""
return DXHTTPRequest('/%s/newF... | 5,297,695 |
def get_file_stat(path):
"""
This is a helper function that given a local path return the size of
the file in bytes and time of last modification.
"""
try:
stats = os.stat(path)
except IOError as e:
raise ValueError('Could not retrieve file stat of "%s": %s' % (
path,... | 5,297,696 |
def PolyConvex(poligono):
""" Funcion para calcular el poligono con una serie
de cordenadas dada
"""
points = np.array(poligono)
hull = ConvexHull(points)
ps = set()
for x, y in hull.simplices:
ps.add(x)
ps.add(y)
ps = np.array(list(ps))
p = pd.DataFrame(points)
... | 5,297,697 |
def recycling_to_no3(vs, plankton, no3):
"""Recycling to nitrate needs no scaling"""
return {no3: recycling(vs, plankton, no3, 1)[no3]} | 5,297,698 |
def sharpe_ratio(returns):
"""Computes Sharpe Ratio from simple returns.
Parameters
----------
returns : np.ndarray | pd.Series | pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
Returns
-------
sharpe_ratio : float | np.ndarray | pd.Series
Sharpe ratio.... | 5,297,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.