content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def register_traefik_route(context):
""" Create Traefik route for this Pylon instance """
context.traefik_redis_keys = list()
#
if context.debug and os.environ.get("WERKZEUG_RUN_MAIN") != "true":
log.info("Running in development mode before reloader is started. Skipping registration")
re... | 44,200 |
def show_erps(Ds, align_window, labels=None, show_sem=True, co_data=None,
**kwargs):
"""
Use plot ERPs on electrode_grid
Parameters
----------
Ds: list
list of D tensors (electrodes x time x trials)
align_window: tuple
time before and after stim in seconds
labe... | 44,201 |
def test_methods_are_called(testdir):
"""
Methods `build`, `deploy`, 'cleanup` should be called for every fixture.
"""
# TODO. Test `cleanup`
testdir.makepyfile('''
from pytest_browserstack import make_fixtures
from pytest_browserstack.services import Service
class Containe... | 44,202 |
def test_mecanum_rads_to_rpm_7642():
"""Quelle:https://www.convertunits.com/from/radian/second/to/RPM"""
rads = 7642
exp_rpm = 72975.7245898829
act_rpm = MecanumController.convert_rads_to_rpm(rads)
assert round(exp_rpm, 0) == round(act_rpm, 0) | 44,203 |
async def test_delete_all_keys() -> None:
"""Test a successful call of delete_all_keys.
Delete all keys doesn't care what happens with delete_api_key.
"""
session = Mock()
with patch(
"pydeconz.utils.async_request",
new=CoroutineMock(return_value={"whitelist": {1: "123", 2: "456"}}... | 44,204 |
def insert_with_key_enumeration(agent, agent_data: list, results: dict):
"""
Checks if agent with the same name has stored data already in the given dict and enumerates in that case
:param agent: agent that produced data
:param agent_data: simulated data
:param results: dict to store data into
:... | 44,205 |
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='First Bank of Change',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('value', metavar='int', type=int, help='Sum')
args = parser.parse_args()
if not 0 < a... | 44,206 |
def is_timestamp(s):
"""Check a string to verify that it is a proper Acq timestamp.
Return the utcoffset portion of the string if the string is verified.
Raise an ExpError if the string is not verified.
"""
m = utcoffsetre.search(s)
if m is None:
raise ExpError("Incorrect timestamp for path {:}".f... | 44,207 |
def parse_condition_code(value, is_day: bool) -> str:
"""Convert WeatherAPI condition code to standard weather condition."""
if value is None:
return None
try:
condition_code = int(value)
if condition_code == 1000:
return ATTR_CONDITION_SUNNY if is_day else ATT... | 44,208 |
def test_unpublished_hearing_section_files_download_link_admin(default_hearing, john_smith_api_client):
"""
Files in an unpublished hearing should be downloadable for organisation admin
Test currently skipped, john_smith_api_client results in AnonymousUser in request.user instead of john_smith from the fix... | 44,209 |
def min__to__s():
"""Convert minute to second"""
return '6.0E+1{kind}*{var}' | 44,210 |
def test_abinit_input():
"""
Tests (pychemia.code.abinit) [input] :
"""
if pychemia.HAS_SCIPY and pychemia.HAS_SCIENTIFIC:
from pychemia.code.abinit import AbiFiles, InputVariables
filename = "pychemia/test/data/abinit_01/abinit.files"
abf = AbiFiles(file... | 44,211 |
def move_data(input_fits_file, detector='NRS1', add_ref_pix=False):
"""
This function does the move of the data to the science extension.
Args:
input_fits_file: string, name of the input file
detector: string, expects either NRS1 or NRS2
add_ref_pix: boolean, if True the code will ad... | 44,212 |
def home():
"""Home tab."""
icon = html.I(className="fas fa-home fa-lg", title="Home")
return html.Li(html.Span(icon), id="view-info", className="active") | 44,213 |
def download_cds_satellite_albedo():
"""Download dataset cds-satellite-albedo."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--config_file',
'-c',
default=os.path.join(os.path.dirname(__file__),
... | 44,214 |
def score_per_term(base_t, mis_t, special_t, metric):
"""Computes three distinct similarity scores for each list of terms.
Parameters
----------
base_t, mismatch_t special_t: list of str
Lists of toponym terms identified as base, mismatch or frequent (special) respectively.
metric: str
... | 44,215 |
def _eliminationOrder_OLD(gm, orderMethod=None, nExtra=-1, cutoff=inf, priority=None, target=None):
"""Find an elimination order for a graphical model
Args:
gm (GraphModel): A graphical model object
method (str): Heuristic method; one of {'minfill','wtminfill','minwidth','wtminwidth','random'}
nExtra (i... | 44,216 |
def inject_module(module, *args, **kwargs):
"""
Imports a function from a python module :module: and executes it with *args, **kwargs arguments. Dotted referencing
can be used to specify the function from the module.
For example, the following code will execute func1 and func2 from module mymodule with... | 44,217 |
def get_pretrain_data_loader(mode, pretrain_data_setting):
"""Get pre-training loader.
Args:
mode (str): either "train" or "valid".
pretrain_data_setting (dict, optional): pretrain dataset setting.
Returns:
loader (torch.dataloader): a PyTorch dataloader with all input
datasets.
"""
... | 44,218 |
def a():
"""The `a` command prints an 'a'."""
print "a" | 44,219 |
def do_simple_math(number1, number2, operator):
"""
Does simple math between two numbers and an operator
:param number1: The first number
:param number2: The second number
:param operator: The operator (string)
:return: Float
"""
ans = 0
if operator is "*":
ans = number1 * nu... | 44,220 |
def native(ctx, clean=False):
"""
Compile and install Faasm native tools
"""
if not exists(FAASM_INSTALL_DIR):
makedirs(FAASM_INSTALL_DIR)
build_dir = join(PROJ_ROOT, "build", "native_tools")
clean_dir(build_dir, clean)
build_cmd = [
"cmake",
"-GNinja",
"-DC... | 44,221 |
def test_global_settings_data():
"""Ensure that GlobalSettingsData objects are properly initialized
per-thread"""
def check_initialized(index):
if index == 0:
sleep(0.1)
with pytest.raises(AttributeError):
_global_settings_data.testing_index # pylint: disable=W0104
... | 44,222 |
def set_client(client):
"""
Set the global HTTP client for sdk.
Returns previous client.
"""
global _global_client
previous = _global_client
_global_client = client
return previous | 44,223 |
def readNetAddress(b, hasStamp):
"""
Reads an encoded NetAddress from b depending on the protocol version and
whether or not the timestamp is included per hasStamp. Some messages like
version do not include the timestamp.
Args:
b (ByteArray): The encoded NetAddress.
hasStamp (bool)... | 44,224 |
def get_all_clouds(session, return_type=None, **kwargs):
"""
Retrieves details for all available storage clouds.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object.
:type return_type: str
:param return_type: If this is set to the string 'json', this... | 44,225 |
def AddTags(resource_id, region, **kwargs):
"""Adds tags to an SoftLayer resource created by PerfKitBenchmarker.
Read existing tags first and add existing tags with new ones
"""
if not kwargs:
return
describe_cmd = SoftLayer_PREFIX + [
'--format',
'json',
'vs',
'detail',
... | 44,226 |
def _get_account_balances_by_regid(user_regid):
"""
returns uw_sws.models.Finance object for a given regid
"""
if user_regid is None:
return None
return get_account_balances_by_regid(user_regid) | 44,227 |
def scrape_meaning(word):
"""
Method to scrape the meaning of a word from google search
"""
# TODO: Add validation checks on the word passed
raw_html_response = fetch_content_from_web(word)
response = parse_html_content(raw_html_response)
return response | 44,228 |
def libname(name):
"""gets 'name' and returns something like libname.cpython-37m-darwin.so"""
filename = build_ext_cmd.get_ext_filename(name)
fn, ext = os.path.splitext(filename)
return build_ext_cmd.shlib_compiler.library_filename(fn, libtype) | 44,229 |
def make_embed(msg_type='', title=None, icon=None, content=None,
msg_colour=None, guild=None, title_url=None,
thumbnail='', image='', fields=None, footer=None,
footer_icon=None, inline=False):
"""Returns a formatted discord embed object.
Define either a type or a co... | 44,230 |
def dynamic_stitch(indices, data):
"""
Args
indices: A list of at least 1 Tensor objects with type int32.
data: A list with the same length as indices of Tensor objects with
the same type.
Returns
A Tensor. Has the same type as data.
"""
dim_0 = int(max([torch.ma... | 44,231 |
def snake(string):
"""snake_case"""
return "_".join(string.split()) | 44,232 |
def parse_standard_metadata():
"""
Gather the standard metadata information from Jenkins and the DBMS.
Returns
-------
The metadata obtained from Jenkins and the DBMS.
Warnings
--------
Underlying implementation is hacky right now.
"""
return {**_parse_jenkins_env_vars(), **_pa... | 44,233 |
def load_resource(api_server):
"""Load a default resource file.
:type api_server: str
:rtype: dict
"""
logger.debug('load_resource({0})...'.format(api_server))
rsrcs = {}
rsrc_files = [
"resources/misc.json.j2",
"resources/api_clients.json.j2",
"resources/api_apps.js... | 44,234 |
def match_all_args(ctx, node, func, args):
"""Call match_args multiple times to find all type errors.
Args:
ctx: The abstract context.
node: The current CFG node.
func: An abstract function
args: An Args object to match against func
Returns:
A tuple of (new_args, errors)
where new_args... | 44,235 |
def samples_from_cpprb(npsamples, device=None):
"""
Convert samples generated by cpprb.ReplayBuffer.sample() into
State, Action, rewards, State.
Return Samples object.
Args:
npsamples (dict of nparrays):
Samples generated by cpprb.ReplayBuffer.sample()
device (optional): ... | 44,236 |
def mini(description, **kwargs):
"""Single notification function
Simple notification function in one line. Has only one required parameter
and attempts to use reasonable defaults for everything else
:param string description: Notification message
"""
kwargs['notifierFactory'] = GrowlNotifier
gntp.notifier.mini(... | 44,237 |
def SplitRosFile(RosFile, fileToData):
""" Input : example.txt file output by pcl_to_windows ros node.
The output is 6 .txt files [x y z r g b] which are then read by function
CreateMatFile().
"""
source = os.path.join('/home','ubuntu','biobot_ros_jtk','src','pcl_to_windows','example.txt')
# Mov... | 44,238 |
def merger(directory='export'):
"""
Run this function after the download is complete to have gdal attempt \
to merge the geoTIFFs. Generally should not used on it's own.
Parameters:
directory (str): The directory to find the unmerged TIF images in. Defaults to 'export'
Returns:... | 44,239 |
def generateKeys():
"""
generates and returns a dictionary containing the original columns names from the
LIDAR file as values and the currently used column names as corresponding keys
ws_1 : Speed Value.1
dir_1 : Direction Value.1
h_1 : Node RT01 Lidar Height
"""
keys = {"ws_0" :... | 44,240 |
def process_line(line):
"""Return the syntax error points of line."""
stack = []
for c in line:
if c in '([{<':
stack.append(c)
elif c != closings[stack.pop()]:
return points[c]
return 0 | 44,241 |
def upgrade():
"""Upgrade database schema and/or data, creating a new revision.
1. Strip every dropdown option of leading and trailing whitespace.
2. Remove duplicate dropdown options in every CAD.
3. Remove empty dropdown options in every CAD (leave one empty dropdown
option if there are no non-empty option... | 44,242 |
def get_uniprot_homologs(rev=False):
"""As above, but exclusively uniprot => mouse uniprot"""
homologs = {}
with open('data/corum_mouse_homologs.txt') as infile:
data = [line.strip().split('\t') for line in infile]
for line in data:
original = line[1].split('|')[1]
uniprot = line... | 44,243 |
def _create_pattern_line(
price_plot: plt.Subplot,
spike_breakdown: List[float],
spike_pattern: models.PotentialPattern,
spike_color: List[float],
) -> None:
"""Create a dashed line on the max price for periods with a potential spike"""
# get highest possible price for each period
first_per... | 44,244 |
def flatten(
value: list,
levels: typing.Optional[int] = None
) -> list:
"""Flatten a list.
.. code-block:: yaml
- vars:
new_list: "{{ [1, 2, [3, [4, 5, [6]], 7]] | flatten }}"
# -> [1, 2, 3, 4, 5, 6, 7]
To flatten only the top level, use the ``levels`` argument:
... | 44,245 |
def GetStage(messages):
"""Returns corresponding GoogleCloudFunctionsV2(alpha|beta)Stage."""
if messages is apis.GetMessagesModule(_API_NAME, _V2_ALPHA):
return messages.GoogleCloudFunctionsV2alphaStage
elif messages is apis.GetMessagesModule(_API_NAME, _V2_BETA):
return messages.GoogleCloudFunctionsV2bet... | 44,246 |
def get_general_case_info(adapter, institute_id=None, slice_query=None):
"""Return general information about cases
Args:
adapter(adapter.MongoAdapter)
institute_id(str)
slice_query(str): Query to filter cases to obtain statistics for.
Returns:
general(dict)
"""
g... | 44,247 |
def test_helper_put(mocker, url, bucket, key):
"""Test helper _put is correctly called."""
mocked_connection = mocker.patch("tentaclio_gs.clients.GSClient._connect")
stream = io.StringIO()
with gs_client.GSClient(url) as client:
client._put(stream, bucket_name=bucket, key_name=key)
connecti... | 44,248 |
def _normalize_ids(arg, atoms={int, long, str, unicode, NewId}):
""" Normalizes the ids argument for ``browse`` (v7 and v8) to a tuple.
Various implementations were tested on the corpus of all browse() calls
performed during a full crawler run (after having installed all website_*
modules) and this one... | 44,249 |
def is_intersection(g, n):
"""
Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
R... | 44,250 |
def AxisRotation(p, ang, inplace=False, deg=True, axis='z'):
""" Rotates points p angle ang (in deg) about an axis """
axis = axis.lower()
# Copy original array to if not inplace
if not inplace:
p = p.copy()
# Convert angle to radians
if deg:
ang *= np.pi / 180
if axis == ... | 44,251 |
def get_dir_list(path: Path)->List[str]:
"""
Return directory list
"""
dir_list = []
paths = Path(path).glob("**/*")
for p in paths:
if p.is_dir():
dir_list.append(str(p))
return dir_list | 44,252 |
def tokenize(data: typing.Union[str, typing.Sequence[str]]) -> list[str]:
"""break up string into tokens, tokens can be separated by commas or spaces
creates separate tokens for:
- "(" or "[" at beginning
- ")" or "]" at end
"""
# break into tokens
if isinstance(data, str):
data = ... | 44,253 |
def git_installed():
"""Interrupt execution of memote if `git` has not been installed."""
LOGGER.info("Checking `git` installation.")
try:
check_output(["git", "--version"])
except CalledProcessError as e:
LOGGER.critical(
"The execution of memote was interrupted since no ins... | 44,254 |
def de_comma(string):
"""Remove any trailing commas
>>> de_comma(',fred,,') == ',fred'
True
"""
return string.rstrip(',') | 44,255 |
def test_approve_translation_basic(translation_a, client_superuser):
"""Check if approve view works properly."""
url = reverse('pontoon.review.approve')
params = {
'translation': translation_a.pk,
'paths': [],
'ignore_warnings': 'true',
}
response = client_superuser.post(url... | 44,256 |
def MakeData(ea, flags, size, tid):
"""
Create a data item at the specified address
@param ea: linear address
@param flags: FF_BYTE..FF_PACKREAL
@param size: size of item in bytes
@param tid: for FF_STRU the structure id
@return: 1-ok, 0-failure
"""
return idaapi.do_data... | 44,257 |
def get_node_network_receive(cluster_id, ip, start, end, bk_biz_id=None):
"""获取网络数据
start, end单位为毫秒,和数据平台保持一致
数据单位KB/s
"""
step = (end - start) // 60
prom_query = f"""
max(rate(node_network_receive_bytes_total{{cluster_id="{cluster_id}",job="node-exporter", instance=~"{ ip }:9100"}}[5m])... | 44,258 |
def verify_vrrpv3_summary(dut,**kwargs):
"""
Author: Raghukumar Rampur
email : raghukumar.thimmareddy@broadcom.com
:param dut:
:param interface:
:type string or list
:param vrid:
:type string or list
:param vip:
:type virtual-ip in string or list
:param state:
:type vrrp ... | 44,259 |
def attributes_restore(node):
"""Restore previously unlocked attributes to their default state.
Args:
node (str): Node to restore attributes
Returns:
bool: False if attribute doesn't exists else True
"""
attr_name = "attributes_state"
base_attr = "{}.{}".format(node, attr_nam... | 44,260 |
def keras_imdb_cnn(num_words=None, maxlen=None, embedding_dim=128):
"""
imdb的cnn评分
:return:
"""
(x_train, y_train), (x_test, y_test) = imdb.load_data(
os.path.join(root_path, "data", "imdb", "imdb.npz"), num_words=num_words)
if not num_words: num_words = max(max([max(x) for x in x_train... | 44,261 |
def get_actual_data(base, n_run, log_path, subfolders):
"""
:param base: the sub folder name right before the _DATE_InstanceNumber
:param n_run: the INSTANCE number in the subfolder name
:param log_path: path to the main log folder containing all the runs of an experiment (e.g. ../data/CH6-14S1G1TNSV/)
... | 44,262 |
async def test_arm_home_success(hass):
"""Test arm home method success."""
responses = [RESPONSE_DISARMED, RESPONSE_ARM_SUCCESS, RESPONSE_ARMED_STAY]
with patch(
"homeassistant.components.totalconnect.TotalConnectClient.TotalConnectClient.request",
side_effect=responses,
):
await... | 44,263 |
def secs_to_str(secs):
"""Given number of seconds returns, e.g., `02h 29m 39s`"""
units = (('s', 60), ('m', 60), ('h', 24), ('d', 7))
out = []
rem = secs
for (unit, cycle) in units:
out.append((rem % cycle, unit))
rem = int(rem / cycle)
if not rem:
break
if re... | 44,264 |
def shuffle(xsets, ysets, seed=None):
"""Shuffle two datasets harmonically
Args:
x, y: datasets, both of them should have same length
Return:
(shuffled_x, shuffled_y): tuple including shuffled x and y
"""
if len(xsets) != len(ysets):
raise ValueError
np.random.seed(seed=s... | 44,265 |
def get_CL_parameters(file_pointer, class_10_100_1000):
""" Function to predict cluster count and mean size by means of clustering
Args:
file_pointer: string with a file path
Returns
tuple with(
clusters: predicted number of clusters
log_mean_rad... | 44,266 |
def test_config_init_property_invalid(mock_get_platform, no_envs):
"""Heavy init raises on invalid property."""
f1 = mock_open(read_data='arb: varb1\narb2: varb2\ndefault_backoff: x')
mock_opens = [
f1.return_value
]
config = Config()
with patch('builtins.open', side_effect=mock_opens... | 44,267 |
def add_known_user(instance: bot, message: trigger) -> None:
"""Add user to known users list."""
username = message.group(3)
if message.group(4):
channel = message.group(4)
elif message.sender[0] == '#':
channel = message.sender
else:
channel = DEFAULT_CHANNEL
if not USE... | 44,268 |
def _nanclean(cube, rejectratio=0.25, boxsz=1):
"""
Detects NaN values in cube and removes them by replacing them with an
interpolation of the nearest neighbors in the data cube. The positions in
the cube are retained in nancube for later remasking.
"""
logger.info('Cleaning NaN values in the c... | 44,269 |
def test_get_user_uid_not_found():
"""Test that get_user() function works even if the current process's
user id does not correspond to a valid user (e.g. running pytest in a
Docker container with 'docker run -u'.
"""
assert get_user() is None | 44,270 |
def parseData(filePath):
"""
Tries to import JSON JobShop PRO file to program
:return machineList itinerariesList
"""
machinesList = []
itinerariesList = []
with open(filePath, 'r', encoding="utf8") as inputfile: # read file from path
importedData = json.loads(inputfile.read())
... | 44,271 |
def curve_fit_log(xdata, ydata, sigma):
"""Fit data to a power law with weights according to a log scale"""
# Weights according to a log scale
# Apply fscalex
xdata_log = np.log10(xdata)
# Apply fscaley
ydata_log = np.log10(ydata)
sigma_log = np.log10(sigma)
# Fit linear
popt_lo... | 44,272 |
def test_rename_methods_logqp(device):
"""Test renaming works with a subset of names when `logqp=True`."""
sde = problems.CustomNamesSDELogqp().to(device)
y0 = torch.ones(batch_size, d, device=device)
ts = torch.linspace(t0, t1, steps=T, device=device)
ans = torchsde.sdeint(sde, y0, ts, dt=dt, names... | 44,273 |
def testWrappedHeart(utest, serviceMaker):
"""Service has a child heart beater"""
opt = dict(config='config',
messages='messages',
freq=5)
test_heart.replaceEnvironment(utest)
masterService = serviceMaker(opt)
service = masterService.getServiceNamed('heart')
test_he... | 44,274 |
def _test_best_ff_hyperparameters(data: SignalDataset) -> None:
"""Use network with best hyperparameters to predict labels for test data.
Produces accuracy and loss graphs for training and validation data, as
well as accuracy and loss values for test data.
"""
hyperparameter_dict = {
'learn... | 44,275 |
def publish(event, actor_id=None, params=None, channels=None):
""" Publish a notification to the given channels, while storing
the parameters and initiating actor for the event. """
assert isinstance(event, Event), event
params = params or {}
outparams = {}
channels = ensure_list(channels)
c... | 44,276 |
def get_computed_response_text_value(response):
"""
extract the text message from the Dialogflow response, fallback: None
"""
try:
if len(response.query_result.fulfillment_text):
return response.query_result.fulfillment_text
elif len(response.query_result.fulfillment_mes... | 44,277 |
def tmpdir_factory(request):
"""Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.
"""
return request.config._tmpdirhandler | 44,278 |
def get_sims(word, language, lemmatized=False, threshold=0.70):
"""Get similar Word2Vec terms from vocabulary or trained model.
TODO: Add option to install corpus if not available.
"""
# Normalize incoming word string
jv_replacer = JVReplacer()
if language == 'latin':
# Note that casefo... | 44,279 |
def collect_ips():
"""Fill IP addresses into people list. Return if all addresses collected or not."""
out, rc, _ = run_cmd('sudo nmap -sn ' + net, log_error=False)
if rc:
print "Error: nmap is required. Run following command:"
print "sudo apt-get -y install nmap"
sys.exit(4)
#... | 44,280 |
def assert_produces_warning(
expected_warning: Optional[Union[Type[Warning], bool]] = Warning,
filter_level="always",
check_stacklevel: bool = True,
raise_on_extra_warnings: bool = True,
match: Optional[str] = None,
):
"""
Context manager for running code expected to either raise a specific
... | 44,281 |
def roles(*role_list):
"""
Decorator defining a list of role names, used to look up host lists.
A role is simply defined as a key in `env` whose value is a list of one or
more host connection strings. For example, the following will ensure that,
barring an override on the command line, ``my_func`` ... | 44,282 |
def check_argument_fpath(fpath):
"""
Check the fpath is valid
"""
if (not isinstance(fpath, bool)) and isinstance(fpath, int):
fpath = str(fpath)
if not isinstance(fpath, str):
print("ERROR: invalid file path [%s], should be a string" % fpath,
file=sys.stderr)
s... | 44,283 |
def pool_tr(
sents: List[str],
# services: List[str] = None,
max_workers: Optional[int] = -1,
from_lang: str = "auto",
to_lang: str = "zh",
timeout: float = 100,
) -> List[Any]:
# fmt: on
""" translate sents.
max_workers: Optional[int] = 10
from_l... | 44,284 |
def main():
"""
The 'main' part of the program. This runs when a GUI is not used.
:return: None
"""
# Some sensible defaults - to pre-populate 'input' statements - saves a lot of typing!
defaults = {}
defaults["HOST"] = input(f"Input Geoserver URL or press ENTER for {DEFAULTS['HOST']} ") o... | 44,285 |
def kcal_plot(df, ax, axis_range=None):
"""
Draw a scatterplot of experimental vs predicted Ki or IC50
:param df: input dataframe
:param ax: matplotlib axis
:param axis_range: range for axes [minX, maxY, minY, maxY]
:return: None
"""
if axis_range is None:
axis_range = [-12, -6, ... | 44,286 |
def stairmaster_mets(setting):
"""
For use in submaximal tests on the StairMaster 4000 PT step ergometer.
Howley, Edward T., Dennis L. Colacino, and Thomas C. Swensen. "Factors Affecting the Oxygen Cost of Stepping on an Electronic Stepping Ergometer." Medicine & Science in Sports & Exercise 24.9 (1992): n... | 44,287 |
def sync(
ctx: typer.Context,
verbose: bool = typer.Option(False, "--verbose", "-v", help="verbose"),
save: bool = typer.Option(False, "--save", "-s", help="save it to InteliJ"),
context: List[str] = typer.Option(
..., "--context", "-c", help="scope/context in InteliJ"
),
ultisnip_file: ... | 44,288 |
def get_uri_for_directory(directory: str,
excludes: Optional[List[str]] = None) -> str:
"""Get a content-addressable URI from a directory's contents.
This function will generate the name of the package by the directory.
It'll go through all the files in the directory and hash the ... | 44,289 |
def clean_cancer_dataset(df_training):
"""
Checks and cleans the dataset of any potential impossible values, e.g. bi-rads columns, the 1st only allows
values in the range of 1-5, ordinal
Age, 2nd column, cannot be negative, integer
Shape, 3rd column, only allows values between 1 and 4, nominal
M... | 44,290 |
def main():
"""Entry point."""
sanity_check()
print("Creating games-features.csv")
with open("games-features.csv", "w") as basefile:
writer = csv.writer(basefile)
writer.writerow(COLUMNS)
count = 0
for game in game_reader():
rec = record(game)
wri... | 44,291 |
def test_local_fetcher_get_fails(tmp_trestle_dir):
"""Test the local fetcher get failure."""
rand_str = ''.join(random.choice(string.ascii_letters) for x in range(16))
catalog_file = pathlib.Path(tmp_trestle_dir.parent / f'{rand_str}.json').__str__()
catalog_data = generators.generate_sample_model(Catal... | 44,292 |
def set_bounds_ex(input_file, model, metab):
"""
Set bounds of the exchange reactions of the selected compounds
If the compounds have to be consumed the bounds of its exchange
reaction it set to (-1000, 0).While it it has to be produced they are
set to (0, 1000)
-------------------------------... | 44,293 |
def str_to_date(date, form=None):
"""
Return Date with datetime format
:param form:
:param date: str date
:return: datetime date
"""
if form is None:
form = get_form(date)
return datetime.datetime.strptime(date, form) | 44,294 |
def get_model_results(corpus, texts, ldamodel=None):
"""function extract model result such as topics, percentage distribution and return it as pandas dataframe
in: corpus : encoded features
in: text : main text
in: ldamodel: the trained model
out: dataframe
"""
topics_df = pd.DataFrame()
... | 44,295 |
def rest_notify():
"""Github rest endpoint."""
sdkid = request.args.get("sdkid")
sdkbase = request.args.get("sdkbase", "master")
sdk_tag = request.args.get("repotag", sdkid.split("/")[-1].lower())
if not sdkid:
return {'message': 'sdkid is a required query parameter'}
rest_bot = RestAP... | 44,296 |
def lib_pt_loc(sys_chars_vals, tolerance = 1e-12):
"""Computes Non-Dimensionalized Libration Points Location for P1-P2 system
Parameters
----------
sys_chars_vals: object
Object of Class sys_char
tolerance: float
convergence tolerance for Newton-Raphson Method
... | 44,297 |
def load():
"""Called by the framework when the extension is 'loaded'."""
if not os.getenv("DRMAA_LIBRARY_PATH"):
LOG.debug("No environment variable $DRMAA_LIBRARY_PATH: loading {} failed".format(__name__))
return
hook.register('post_setup', add_drmaa_option)
hook.register('post_setup', ... | 44,298 |
def max_pool_forward_naive(x, pool_param):
"""
A naive implementation of the forward pass for a max pooling
layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The ... | 44,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.