content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def check_disabled(func):
"""
Decorator to wrap up checking if the Backdrop
connection is set to disabled or not
"""
@wraps(func)
def _check(*args, **kwargs):
if _DISABLED:
return
else:
return func(*args, **kwargs)
return _check | 16,900 |
def debug(message): #pragma: no cover
""" Utility debug function to ease logging. """
_leverage_logger.debug(message) | 16,901 |
def bbox_from_points(points):
"""Construct a numeric list representing a bounding box from polygon coordinates in page representation."""
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
return bbox_from_polygon(xys) | 16,902 |
def return_true():
"""Return True
Simple function used to check liveness of workers.
"""
return True | 16,903 |
def create_list(input_list):
"""Construct the list of items to turn into a table. File and string inputs supported"""
if os.path.isfile(input_list):
with open(input_list, 'r', encoding='UTF-8') as ifile:
return [line.rstrip() for line in ifile]
return input_list.split(',') | 16,904 |
def get_active_test_suite():
"""
Returns the test suite that was last ran
>>> get_active_test_suite()
"Hello"
"""
return TEST_RUNNER_STATE.test_suite | 16,905 |
def go_test(name, library = None, **kwargs):
"""This macro wraps the go_test rule provided by the Bazel Go rules
to silence a deprecation warning for use of the "library" attribute.
It is otherwise equivalent in function to a go_test.
"""
# For internal tests (defined in the same package), we need ... | 16,906 |
def header_from_stream(stream, _magic=None) -> (dict, list, int):
"""
Parse SAM formatted header from stream.
Dict of header values returned is structured as such: {Header tag:[ {Attribute tag: value}, ]}.
Header tags can occur more than once and so each list item represents a different tag line.
:p... | 16,907 |
def walk_binary_file_or_stdin(filepath, buffer_size = 32768):
"""
Yield 'buffer_size' bytes from filepath until EOF, or from
standard input when 'filepath' is '-'.
"""
if filepath == '-':
return walk_binary_stdin(buffer_size)
else:
return walk_binary_file(filepath, buffer_size) | 16,908 |
def register_device() -> device_pb2.DeviceResponse:
"""
Now that the client credentials are set, the device can be registered. The device is
registered by instantiating an OauthService object and using the register() method.
The OauthService requires a Config object and an ISecureCredentialStore object... | 16,909 |
def _sto_to_graph(agent: af.SubTaskOption) -> subgraph.Node:
"""Convert a `SubTaskOption` to a `Graph`."""
node_label = '{},{},{}'.format(agent.name or 'SubTask Option',
agent.subtask.name or 'SubTask',
agent.agent.name or 'Policy')
return subgraph... | 16,910 |
def _hdf5_write_data(filename, data, tablename=None, mode='w', append=False,
header={}, units={}, comments={}, aliases={}, **kwargs):
""" Write table into HDF format
Parameters
----------
filename : file path, or tables.File instance
File to write to. If opened, must be op... | 16,911 |
def filter_input(self, forced=False, context=None):
"""
Passes each hunk (file or code) to the 'input' methods
of the compressor filters.
"""
content = []
for hunk in self.hunks(forced, context=context):
content.append(hunk)
return content | 16,912 |
def create_venn3(df, comparison_triple):
"""
Create a 3 circle venn diagram
Parameters
----------
df: DataFrame
df contains all option ratins for each feature
comparison_pair: list
Three strings. Determines which options to compare.
"""
list_of_dicts = df[compar... | 16,913 |
def delete(request, user):
""" Deletes a poll """
poll_id = request.POST.get('poll_id')
try:
poll = Poll.objects.get(pk=poll_id)
except:
return JsonResponse({'error': 'Invalid poll_id'}, status=404)
if poll.user.id != user.id:
return JsonResponse({'error': 'You cannot delet... | 16,914 |
def get_nodes(collection: str, node_link: Optional[str] = None):
"""Get the Node based on its ID or kind"""
# pylint: disable=too-many-locals,too-many-return-statements,too-many-branches
user_id = to_object_id(g.user._id)
can_view_others_operations = g.user.check_role(IAMPolicies.CAN_VIEW_OTHERS_OPERAT... | 16,915 |
def get_loader(path):
"""Gets the configuration loader for path according to file extension.
Parameters:
path: the path of a configuration file, including the filename
extension.
Returns the loader associated with path's extension within LOADERS.
Throws an UnknownConfigurationExce... | 16,916 |
def mat_stretch(mat, target):
"""
Changes times of `mat` in-place so that it has the same average BPM and
initial time as target.
Returns `mat` changed in-place.
"""
in_times = mat[:, 1:3]
out_times = target[:, 1:3]
# normalize in [0, 1]
in_times -= in_times.min()
in_times /= ... | 16,917 |
def parse_range(cpu_range):
"""Create cpu range object"""
if '-' in cpu_range:
[x, y] = cpu_range.split('-') # pylint: disable=invalid-name
cpus = range(int(x), int(y)+1)
if int(x) >= int(y):
raise ValueError("incorrect cpu range: " + cpu_range)
else:
cpus = [int... | 16,918 |
def causal_parents(node, graph):
"""
Returns the nodes (string names) that are causal parents of the node (have the edge type "causes_or_promotes"), else returns empty list.
Parameters
node - name of the node (string)
graph - networkx graph object
"""
node_causal_parents = []
if list(gra... | 16,919 |
def create_app(settings_override=None):
"""
Create a test application.
:param settings_override: Override settings
:type settings_override: dict
:return: Flask app
"""
app = Flask(__name__)
params = {
'DEBUG': True,
'WEBPACK_MANIFEST_PATH': './build/manifest.json'
}
... | 16,920 |
async def user_me(current_user=Depends(get_current_active_user)):
"""
Get own user
"""
return current_user | 16,921 |
def _check_3dt_version():
"""
The function checks if cluster has diagnostics capability.
:raises: DCOSException if cluster does not have diagnostics capability
"""
cosmos = packagemanager.PackageManager(get_cosmos_url())
if not cosmos.has_capability('SUPPORT_CLUSTER_REPORT'):
raise DCO... | 16,922 |
def get_password_hash(password: str, salt: Optional[str] = None) -> Tuple[str, str]:
"""Get user password hash."""
salt = salt or crypt.mksalt(crypt.METHOD_SHA256)
return salt, crypt.crypt(password, salt) | 16,923 |
def find_iamrole_changes(accounts):
""" Runs watchers/iamrole"""
sm_find_iamrole_changes(accounts) | 16,924 |
def start_at(gra, key):
""" start a v-matrix at a specific atom
Returns the started vmatrix, along with keys to atoms whose neighbors are
missing from it
"""
symb_dct = atom_symbols(gra)
ngb_keys_dct = atoms_sorted_neighbor_atom_keys(
gra, symbs_first=('X', 'C',), symbs_last=('H',), ord... | 16,925 |
def test_scenariooutline_set_rule_on_all_examples(mocker):
"""A ScenarioOutline should forward a set Rule to all its Examples"""
# given
rule_mock = mocker.MagicMock(name="Rule")
scenario = ScenarioOutline(
1, "Scenario Outline", "My ScenarioOutline", [], None, None, [], []
)
first_examp... | 16,926 |
def nested_lookup(key, document):
"""
nested document lookup,
works on dicts and lists
:param key: string of key to lookup
:param document: dict or list to lookup
:return: yields item
"""
if isinstance(document, list):
for d in document:
for result in nested_lookup(ke... | 16,927 |
def test_kubernetes_resource_get_status_value_incomplete():
"""
This test verifies that KubernetesResource.get_status_value() returns None for an undefined resource.
"""
assert KubernetesResource(dict()).get_status_value("replicas") is None | 16,928 |
def associate_kitti(detections,
trackers,
det_cates,
iou_threshold,
velocities,
previous_obs,
vdc_weight):
"""
@param detections:
"""
if (len(trackers) == 0):
return np.empty((... | 16,929 |
def read_app12(imagefile, seg_offset, meta_dict):
"""Read metadata from an APP12 segment and store in dictionary.
1st parameter = file handle for jpeg file, opened as 'rb' read binary
2nd parameter = the offset of the APP12 segment to be processed
3rd parameter = dictionary being created by readmeta();... | 16,930 |
def seat_guest(self, speech, guest, timeout):
"""
Start the view 'seatGuest'
:param speech: the text that will be use by the Local Manager for tablet and vocal
:type speech: dict
:param guest: name of the guest to seat
:type guest: string
:param timeout: maximum time to wait for a reaction ... | 16,931 |
def retreive_retries_and_sqs_handler(task_id):
"""This function retrieve the number of retries and the SQS handler associated to an expired task
Args:
task_id(str): the id of the expired task
Returns:
rtype: dict
Raises:
ClientError: if DynamoDB query failed
"""
try:
... | 16,932 |
def configure_base_bos(assembly):
""" Base configure method for a balance of station cost assembly for coupling models to get a full wind plant balance of station cost estimate. It adds a default balance of station cost aggregator component. """
assembly.add('bos', BaseBOSCostAggregator())
a... | 16,933 |
def test_authorized_rpc_call2(volttron_instance_encrypt):
"""Tests an agent with two capability calling a method that
requires those same two capabilites
"""
agent1, agent2 = build_two_test_agents(volttron_instance_encrypt)
# Add another required capability
agent1.vip.rpc.allow(agent1.foo, 'can... | 16,934 |
def raise_error(config,msg,parser=None):
"""Raise error with specified message, either as parser error (when option passed in via command line),
or ValueError (when option passed in via config file).
Arguments:
----------
config : str
Path to config file.
msg : str
Error messag... | 16,935 |
def update_app_installs():
"""
Update app install counts for all published apps.
We break these into chunks so we can bulk index them. Each chunk will
process the apps in it and reindex them in bulk. After all the chunks are
processed we find records that haven't been updated and purge/reindex thos... | 16,936 |
def decompose(original_weights: torch.Tensor, mask, threshould: float) -> torch.Tensor:
"""
Calculate the scaling matrix. Use before pruning the current layer.
[Inputs]
original_weights: (N[i], N[i+1])
important_weights: (N[i], P[i+1])
[Outputs]
scaling_matrix: (P[i+1], N[i+1])
"""
... | 16,937 |
def calc_Kullback_Leibler_distance(dfi, dfj):
"""
Calculates the Kullback-Leibler distance of the two matrices.
As defined in Aerts et al. (2003). Also called Mutual Information.
Sort will be ascending.
Epsilon is used here to avoid conditional code for checking that neither P nor Q is equal to 0.
... | 16,938 |
def test_python_java_classes():
""" Run Python tests against JPY test classes """
sub_env = {'PYTHONPATH': _build_dir()}
log.info('Executing Python unit tests (against JPY test classes)...')
return jpyutil._execute_python_scripts(python_java_jpy_tests, env=sub_env) | 16,939 |
def trim_datasets_using_par(data, par_indexes):
"""
Removes all the data points needing more fitting parameters than available.
"""
parameters_to_fit = set(par_indexes.keys())
trimmed_data = list()
for data_point in data:
if data_point.get_fitting_parameter_names() <= parameters_to_fi... | 16,940 |
def menu_heading(username, submenu=None):
"""Heading for all menus
:param username: a string containing the username of the authenticated user
:param submenu: a string with the name of submenu
"""
click.clear()
click.secho("===== MAL CLI Application =====", fg="white", bg="blue")
click.echo... | 16,941 |
def _parse_field(field: str) -> Field:
"""
Parse the given string representation of a CSV import field.
:param field: string or string-like field input
:return: a new Field
"""
name, _type = str(field).split(':')
if '(' in _type and _type.endswith(')'):
_type, id_space = _type.split... | 16,942 |
def removeNoise(
audio_clip,
noise_thresh,
mean_freq_noise,
std_freq_noise,
noise_stft_db,
n_grad_freq=2,
n_grad_time=4,
n_fft=2048,
win_length=2048,
hop_length=512,
n_std_thresh=1.5,
prop_decrease=1.0,
verbose=False,
visual=False,
):
"""Remove noise from audi... | 16,943 |
def validate_wra_params(func):
"""Water Risk atlas parameters validation"""
@wraps(func)
def wrapper(*args, **kwargs):
validation_schema = {
'wscheme': {
'required': True
},
'geostore': {
'type': 'string',
'required... | 16,944 |
def handle_request(r):
"""Handle the Simulator request given by the r dictionary
"""
print ("handle_request executed .. ")
print (r)
# Parse request ..
config = SimArgs()
config.machine = r[u'machine']
config.overlay = [r[u'topology']] # List of topologies - just one
config.group = ... | 16,945 |
def number_empty_block(n):
"""Number of empty block"""
L = L4 if n == 4 else L8
i = 0
for x in range(n):
for y in range(n):
if L[x][y] == 0:
i = i + 1
return i | 16,946 |
def test(seconds):
"""
demo
:param seconds:
:return:
"""
time.sleep(seconds) | 16,947 |
def compute_referendum_result_by_regions(referendum_and_areas):
"""Return a table with the absolute count for each region.
The return DataFrame should be indexed by `code_reg` and have columns:
['name_reg', 'Registered', 'Abstentions', 'Null', 'Choice A', 'Choice B']
"""
ans = referendum_and_areas.... | 16,948 |
def fixed_rho_total_legacy(data, rho_p, rho_s, beads_2_M):
"""
*LEGACY*: only returns polycation/cation concentrations. Use updated version
(`fixed_rho_total()`), which returns a dictionary of all concentrations.
Computes the polycation concentration in the
supernatant (I) and coacervate (II) phase... | 16,949 |
def is_valid_file(parser, filename):
"""Check if file exists, and return the filename"""
if not os.path.exists(filename):
parser.error("The file %s does not exist!" % filename)
else:
return filename | 16,950 |
def _check_modality(study: xml.etree.ElementTree.Element, expected_modality: str):
"""Check that the modality of the given study is the expected one."""
series = _parse_series(study)
modality = _check_xml_and_get_text(series[1], "modality")
if modality != expected_modality:
raise ValueError(
... | 16,951 |
def portfolio():
"""Function to render the portfolio page."""
form = PortfolioCreateForm()
if form.validate_on_submit():
try:
portfolio = Portfolio(name=form.data['name'], user_id=session['user_id'])
db.session.add(portfolio)
db.session.commit()
except (D... | 16,952 |
def svn_client_get_simple_provider(*args):
"""svn_client_get_simple_provider(svn_auth_provider_object_t provider, apr_pool_t pool)"""
return apply(_client.svn_client_get_simple_provider, args) | 16,953 |
def svn_client_invoke_get_commit_log(*args):
"""
svn_client_invoke_get_commit_log(svn_client_get_commit_log_t _obj, char log_msg, char tmp_file,
apr_array_header_t commit_items,
void baton, apr_pool_t pool) -> svn_error_t
"""
return apply(_client.svn_client_invoke_get_commit_log, args) | 16,954 |
def enable_ph(module, blade):
"""Enable Phone Hone"""
changed = True
if not module.check_mode:
ph_settings = Support(phonehome_enabled=True)
try:
blade.support.update_support(support=ph_settings)
except Exception:
module.fail_json(msg='Enabling Phone Home fail... | 16,955 |
def find_valid_nodes(node_ids, tree_1, tree_2):
"""
Recursive function for finding a subtree in the second tree
with the same output type of a random subtree in the first tree
Args:
node_ids: List of node ids to search
tree_1: Node containing full tree
tree_2: Node containing f... | 16,956 |
def pytorch_local_average(n, local_lookup, local_tensors):
"""Average the neighborhood tensors.
Parameters
----------
n : {int}
Size of tensor
local_lookup : {dict: int->float}
A dictionary from rank of neighborhood to the weight between two processes
local_tensors : {dict: int-... | 16,957 |
def get_rr_Ux(N, Fmat, psd, x):
"""
Given a rank-reduced decomposition of the Cholesky factor L, calculate L^{T}x
where x is some vector. This way, we don't have to built L, which saves
memory and computational time.
@param N: Vector with the elements of the diagonal matrix N
@param Fmat:... | 16,958 |
def get_poll_options(message: str) -> list:
"""
Turns string into a list of poll options
:param message:
:return:
"""
parts = message.split(CREATE_POLL_EVENT_PATTERN)
if len(parts) > 1:
votes = parts[-1].split(",")
if len(votes) == 1 and votes[0] == ' ':
return []... | 16,959 |
def test_cli_run_basic_ae(cli_args):
"""Test running CLI for an example with default params."""
from pl_bolts.models.autoencoders.basic_ae.basic_ae_module import cli_main
cli_args = cli_args.split(' ') if cli_args else []
with mock.patch("argparse._sys.argv", ["any.py"] + cli_args):
cli_main() | 16,960 |
def get_avg_percent_bonds(bond_list, num_opts, adj_lists, num_trials, break_co_bonds=False):
"""
Given adj_list for a set of options, with repeats for each option, find the avg and std dev of percent of each
bond type
:param bond_list: list of strings representing each bond type
:param num_opts: num... | 16,961 |
def current_fig_image():
"""Takes current figure of matplotlib and returns it as a PIL image.
Also clears the current plot"""
plt.axis('off')
fig = plt.gcf()
buff = StringIO.StringIO()
fig.savefig(buff)
buff.seek(0)
img = Image.open(buff).convert('RGB')
plt.clf()
return img | 16,962 |
def test_oneof_nested_oneof_messages_are_serialized_with_defaults():
"""
Nested messages with oneofs should also be handled
"""
message = Test(
wrapped_nested_message_value=NestedMessage(
id=0, wrapped_message_value=Message(value=0)
)
)
assert (
betterproto.wh... | 16,963 |
def get_bgp_peer(
api_client, endpoint_id, bgp_peer_id, verbose=False, **kwargs
): # noqa: E501
"""Get eBGP peer # noqa: E501
Get eBGP peer details # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> resp... | 16,964 |
def rewrite_elife_funding_awards(json_content, doi):
""" rewrite elife funding awards """
# remove a funding award
if doi == "10.7554/eLife.00801":
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-2":
del json_content[i]
# add fundin... | 16,965 |
def remove_subnet_from_router(router_id, subnet_id):
"""Remove a subnet from the router.
Args:
router_id (str): The router ID.
subnet_id (str): The subnet ID.
"""
return neutron().remove_interface_router(router_id, {
'subnet_id': subnet_id
}) | 16,966 |
def direct_to_template(request, template):
"""Generic template direction view."""
return render_to_response(template, {}, request) | 16,967 |
def validate_metadata(template, size):
"""Validates metadata.
Catch any errors or invalid input that would cause a template with incorrect
information being created and propagated down to instances.
Args:
template: Creation parameters.
size: Size parameters to use.
Returns:
Nothing. The functio... | 16,968 |
def now():
"""Return the current time as date object."""
return datetime.now() | 16,969 |
def is_valid_node_name(name):
"""
Determine if a name is valid for a node.
A node name:
- Cannot be empty
- Cannot start with a number
- Cannot match any blacklisted pattern
:param str name: The name to check.
:return: True if the name is valid. False otherwise.
:rtype: bool
""... | 16,970 |
def trajCalc(setup):
""" Creates trajectory between point A and the ground (B) based off of the initial position and the angle of travel
Arguments:
setup: [Object] ini file parameters
Returns:
A [list] lat/lon/elev of the tail of the trajectory
B [list] lat/lon/elev of the head of the traject... | 16,971 |
async def health() -> Dict[str, str]:
"""Health check function
:return: Health check dict
:rtype: Dict[str: str]
"""
health_response = schemas.Health(name=settings.PROJECT_NAME,
api_version=__version__)
return health_response.dict() | 16,972 |
def projection_v3(v, w):
"""Return the signed length of the projection of vector v on vector w.
For the full vector result, use projection_as_vec_v3().
Since the resulting vector is along the 1st vector, you can get the
full vector result by scaling the 1st vector to the length of the result of
thi... | 16,973 |
def custom_djsettings(settings):
"""Custom django settings to avoid warnings in stdout"""
settings.TEMPLATE_DEBUG = False
settings.DEBUG = False
return settings | 16,974 |
def test_create_pull_requests_no_labels(mock_inquirer_prompt: MockerFixture) -> None:
"""It returns pull request."""
mock_inquirer_prompt.return_value = {
"title": "my title",
"body": "my body",
"labels": "",
"confirmation": True,
"issues_title_query": "issue title",
... | 16,975 |
def bleu(pred_seq, label_seq, k):
"""计算BLEU"""
pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')
len_pred, len_label = len(pred_tokens), len(label_tokens)
score = math.exp(min(0, 1 - len_label / len_pred))
for n in range(1, k + 1):
num_matches, label_subs = 0, collectio... | 16,976 |
def generate_wetbulb_temps(year, directory):
"""Generate puma level hourly time series of wetbulb temperatures for all pumas within a state
:param int year: year of desired dark fractions
:param str directory: path to local root directory for weather data
:export: (*csv*) -- statewide hourly wetbulb t... | 16,977 |
def report_by_name(http_request, agent_name):
"""
A version of report that can look up an agent by its name. This will
generally be slower but it also doesn't expose how the data is stored and
might be easier in some cases.
"""
agent = get_list_or_404(Agent, name=agent_name)[0]
return report... | 16,978 |
def create_application(global_config=None, **local_conf):
"""
Create a configured instance of the WSGI application.
"""
sites, types = load_config(local_conf.get("config"))
return ImageProxy(sites, types) | 16,979 |
def dimensionState(moons,dimension):
"""returns the state for the given dimension"""
result = list()
for moon in moons:
result.append((moon.position[dimension],moon.velocity[dimension]))
return result | 16,980 |
def test_get_local_coordinate_system_no_time_dep(
system_name, reference_name, exp_orientation, exp_coordinates
):
"""Test the ``get_cs`` function without time dependencies.
Have a look into the tests setup section to see which coordinate systems are
defined in the CSM.
Parameters
----------
... | 16,981 |
def login():
"""Log in current user."""
user = get_user()
if user.system_wide_role != 'No Access':
flask_login.login_user(user)
return flask.redirect(common.get_next_url(
flask.request, default_url=flask.url_for('dashboard')))
flask.flash(u'You do not have access. Please contact your administra... | 16,982 |
def test_load_module_recursive_v2_module_depends_on_v1(
local_module_package_index: str, snippetcompiler, preload_v1_module: bool
) -> None:
"""
A V2 module cannot depend on a V1 module. This test case ensure that the load_module_recursive() method
raises an error when a dependency of a V2 module is onl... | 16,983 |
def init_module():
"""
Initialize user's module handler.
:return: wrapper handler.
"""
original_module, module_path, handler_name = import_original_module()
try:
handler = original_module
for name in module_path.split('.')[1:] + [handler_name]:
handler = getattr(handl... | 16,984 |
def daterange(start_date = None, end_date = None):
"""
Loops over date range
"""
if not start_date:
start_date = datetime.datetime(day=1, month=1,year=1950)
if not end_date:
end_date = datetime.datetime.now()
cursor_date = start_date
while cursor_date < end_date:
yi... | 16,985 |
def process(lines: List[str]) -> str:
""" Preprocess a Fortran source file.
Args:
inputLines The input Fortran file.
Returns:
Preprocessed lines of Fortran.
"""
# remove lines that are entirely comments and partial-line comments
lines = [
rm_trailing_comment(line)
... | 16,986 |
def range_atk_params():
"""Range calculations with attack parameters."""
dsc = DamageStatCalc()
attacker = POKEMON_DATA["spinda"]
defender = POKEMON_DATA["spinda"]
move = generate_move(MOVE_DATA["tackle"])
params = {}
params["atk"] = {}
params["atk"]["max_evs"] = True
params["atk"]... | 16,987 |
def _summary(function):
"""
Derive summary information from a function's docstring or name. The summary is the first
sentence of the docstring, ending in a period, or if no dostring is present, the
function's name capitalized.
"""
if not function.__doc__:
return f"{function.__name__.capi... | 16,988 |
def findrun(base,dim,boxsize):
""" find all files associated with run given base directory
and the resolution size and box length """
if not os.path.isdir(base):
print base, 'is not a valid directory'
sys.exit(1)
#retreive all files that match tag and box size
#note this will inclu... | 16,989 |
def sf_rhino_inputs(hull_lis, ten_lines_dic):
"""
create hull_dic to save as rhino input
hull_dic = {hull_ind = [seg1[[pt1][pt2]], seg2[[][]], ...], ...}
saves lines_dic
"""
hull_dic={ind: [] for ind in range(len(hull_lis))}
for ind, hull in enumerate(hull_lis):
for simplex in hull.s... | 16,990 |
def demand_mass_balance_c(host_odemand, class_odemand, avail, host_recapture):
"""Solve Demand Mass Balance equation for class-level
Parameters
----------
host_odemand: int
Observerd host demand
class_odemand: int
Observed class demand
avail: dict
Availability of demand ... | 16,991 |
def test_fetch_methods(mocker: MockerFixture) -> None:
"""
Test ``fetchone``, ``fetchmany``, ``fetchall``.
"""
requests = mocker.patch("datajunction.sql.dbapi.cursor.requests")
requests.post().headers.get.return_value = "application/json"
requests.post().json.return_value = {
"database_i... | 16,992 |
def test_isConnected(web3):
"""
Web3.isConnected() returns True when connected to a node.
"""
assert web3.isConnected() is True | 16,993 |
def record_reaction(reaction):
""" reaction is -1 for cold , 0 for ok, 1 for hot """
ts = datetime.now().isoformat()
th = temphumids.get_current_temphumid()
ot = outside_weather.get_recent_temp()
with open(out_file, 'a') as f:
w = csv.writer(f)
w.writerow([ts, th['temperature'], th['... | 16,994 |
def __iadd__(*args, **kwargs): # real signature unknown
""" a = iadd(a, b) -- Same as a += b. """
pass | 16,995 |
def serve_buffer(
data: bytes,
offered_filename: str = None,
content_type: str = None,
as_attachment: bool = True,
as_inline: bool = False,
default_content_type: Optional[str] = MimeType.FORCE_DOWNLOAD) \
-> HttpResponse:
"""
Serve up binary data from a bu... | 16,996 |
def get_single_image_results(gt_boxes, pred_boxes, iou_thr):
"""Calculates number of true_pos, false_pos, false_neg from single batch of boxes.
Args:
gt_boxes (list of list of floats): list of locations of ground truth
objects as [xmin, ymin, xmax, ymax]
pred_boxes (dict): dict of d... | 16,997 |
def partition(arr, left, right):
"""[summary]
The point of a pivot value is to select a value,
find out where it belongs in the array while moving everything lower than that value
to the left, and everything higher to the right.
Args:
arr ([array]): [Unorderd array]
left ([int]... | 16,998 |
def graphatbottleneck(g,m,shallfp=True):
"""handles the bottleneck transformations for a pure graph ae, return g, compressed, new input, shallfp=True=>convert vector in matrix (with gfromparam), can use redense to add a couple dense layers around the bottleneck (defined by m.redense*)"""
comp=ggoparam(gs=g.s.gs,par... | 16,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.