content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def upload_object(
self, key, body, metadata=None, acl=None, content_type="application/json"
):
"""Upload an arbitrary object to an S3 bucket.
Parameters
----------
S3 key : `str`
The Object's key identifier.
body : `str` or `bytes`
Object data
metadata : `dict`
Head... | 5,346,100 |
def min_ui_count(proteins):
"""
Counts the minimum number of unique identifier peptides across all proteins
in a set
input:
proteins: list of protein sequences as strings ['protein_seq', ...]
output:
minimum number of unique identifier peptides across all proteins in
a set
"""
t... | 5,346,101 |
def check_normalize_py(method):
"""A wrapper that wrap a parameter checker to the original function(normalize operation written in Python)."""
@wraps(method)
def new_method(self, *args, **kwargs):
[mean, std], _ = parse_user_args(method, *args, **kwargs)
check_normalize_py_param(mean, std)
... | 5,346,102 |
def GetOS(build_id, builder_name, step_name, partial_match=False):
# pylint:disable=unused-argument
"""Returns the operating system in the step_metadata.
Args:
build_id (int): Build id of the build.
builder_name (str): Builder name of the build.
step_name (str): The original step name used to get the... | 5,346,103 |
def _list(state, format, filter):
"""Lists the users on the Departing Employees list."""
employee_generator = _get_departing_employees(state.sdk, filter)
list_employees(
employee_generator, format, {"departureDate": "Departure Date"},
) | 5,346,104 |
def __add_registration_args(parser):
"""
keywords defined for image registration
:param parser:
:return:
"""
parser.add_argument(
"--label_normalisation",
metavar='',
help="whether to map unique labels in the training set to "
"consecutive integers (the smal... | 5,346,105 |
def get_catalog_item(catalog_id: Optional[str] = None,
catalog_item_id: Optional[str] = None,
location: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCatalogItemResult:
... | 5,346,106 |
def get_ext_suffix() -> str:
"""Get the extension suffix"""
return get_config_vars()["EXT_SUFFIX"] | 5,346,107 |
def install_nbextension(extension: str,
*flags,
py=True,
sys_prefix=True,
symlink=False,
overwrite=True,
config: str = '',
log_level: Union[int, str] = ... | 5,346,108 |
def confusion_matrix(y_true, y_pred):
"""
Args:
y_true: pd.Series or array or list, ground truth (correct) labels.
y_pred: pd.Series or array or list, predicted labels, as returned by a classifier.
Returns:
Confusion matrix.
"""
t = pd.DataFrame({'actual':y_true, 'predict':y_... | 5,346,109 |
def p_method_arg_optional_array(p):
"""
method_arg_optional_array : method_arg_array method_arg_optional_array
|
"""
if len(p) > 1:
p[0] = '%s%s' % (p[1], p[2])
else:
p[0] = '' | 5,346,110 |
def load_currency_abbreviation_file(path: str) -> List[str]:
"""
Return a list of currency abbreviations present as one value per line in a file.
"""
with open(
os.path.join(__location__, path), "r", encoding="utf-8"
) as _file:
file_content = _file.read()
result = file_conte... | 5,346,111 |
def encode_boxes(boxes, im_shape, encode=True, dim_position=64, wave_length=1000, normalize=False, quantify=-1):
""" modified from PositionalEmbedding in:
Args:
boxes: [bs, num_nodes, 4] or [num_nodes, 4]
im_shape: 2D tensor, [bs, 2] or [2], the size of image is represented as [width, height]
... | 5,346,112 |
def get_docstring_and_version_via_import(target):
"""
Return a tuple like (docstring, version) for the given module,
extracted by importing the module and pulling __doc__ & __version__
from it.
"""
log.debug("Loading module %s", target.file)
sl = SourceFileLoader(target.name, str(target.file... | 5,346,113 |
def plot_t1(times: List[float], contrast: List[float], fname: str = None) -> Figure:
"""
Plot T1 relaxation figure along with laser delay time intervals
:param times: frequencies, unit: ns
:param contrast: contrast, range between 0 and 1
:param fname: if assigned, a '.png' file will be saved
:re... | 5,346,114 |
def init(linter):
"""For each module get `rules` dictionary and visitors. Instantiate each visitor and map it to the
rule class instance using `reports` visitor attribute."""
for module in get_modules(linter.config.ext_rules):
classes = inspect.getmembers(module, inspect.isclass)
module_rule... | 5,346,115 |
def partition_girvan_newman(graph, max_depth):
"""
Use your approximate_betweenness implementation to partition a graph.
Unlike in class, here you will not implement this recursively. Instead,
just remove edges until more than one component is created, then return
those components.
That is, comp... | 5,346,116 |
def start(ctx):
""" Start the API according to the config file
"""
module = ctx.config.get("api", "poloniex")
# unlockWallet
if module == "poloniex":
from .apis import poloniex
poloniex.run(ctx, port=5000)
else:
print_message("Unkown 'api'!", "error") | 5,346,117 |
def inspect_project(dirpath=None):
"""Fetch various information about an already-initialized project"""
if dirpath is None:
dirpath = Path()
else:
dirpath = Path(dirpath)
def exists(*fname):
return Path(dirpath, *fname).exists()
if not exists("pyproject.toml"):
rais... | 5,346,118 |
def test_bidirectional_mode(target_data):
"""
Testing NetGear's Bidirectional Mode with different datatypes
"""
try:
logger.debug('Given Input Data: {}'.format(target_data))
#open strem
stream = VideoGear(source=return_testvideo_path()).start()
#activate bidirectional_mode
options = {'bidirectional_mode'... | 5,346,119 |
def requirements(ctx):
"""Write the `requirements-agent-release.txt` file at the root of the repo
listing all the Agent-based integrations pinned at the version they currently
have in HEAD.
"""
echo_info('Freezing check releases')
checks = get_valid_checks()
checks.remove('stackstate_checks_... | 5,346,120 |
def current_user(request):
"""
Returning the current user with data use of token
"""
serializer = UserSerializer(request.user)
return Response(serializer.data) | 5,346,121 |
def getPercentileLevels(h, frac=[0.5, 0.65, 0.95, 0.975]):
"""
Return image levels that corresponds to given percentiles values
Uses the cumulative distribution of the sorted image density values
Hence this works also for any nd-arrays
inputs:
h array
outputs:
res array containing level values
keywords:
fr... | 5,346,122 |
def test_submission_validate_invalid_no_payload_dict():
"""
Test process_answer.submission_validate function.
"""
submission: dict = {
"xqueue_files": {"student_response.txt": "http://captive.apple.com"},
"xqueue_body": {"student_response": "5", "grader_payload": {"test": "1"}},
}
... | 5,346,123 |
def _rasterize_polygon(lon, lat, i, method):
"""
routine to rasterize polygon
as separate function to allow for parallel operations
"""
global THE_POLYGONS
global THE_MASK
P = THE_POLYGONS[i]
if not isinstance(P, Polygon):
raise ValueError('No Polygon object provided... | 5,346,124 |
def main(argv):
"""
Main entry point of this utility application.
This is simply a function called by the checking of namespace __main__, at
the end of this script (in order to execute only when this script is ran
directly).
Parameters
------
argv: list of str
Arguments receive... | 5,346,125 |
def _ParseSparse(data):
"""Concat sparse tensors together.
Args:
data: A dict of name -> Tensor.
Returns:
A single sparse tensor and a 1-D input spec Tensor.
Raises:
NotImplementedError: Combining dense and sparse tensors is not
supported.
ValueError: If data contains non-string Tensor... | 5,346,126 |
def get_spectra2(X, E_in, p_dict, outputs=None):
"""
Calls get_Efield() to get Electric field, then use Jones matrices
to calculate experimentally useful quantities.
Alias for the get_spectra2 method in libs.spectra.
Inputs:
detuning_range [ numpy 1D array ]
The independent variable and defines the det... | 5,346,127 |
def get_device_components(ralph_device_id):
"""Yields dicts describing all device components to be taken in assets"""
try:
ralph_device = Device.objects.get(id=ralph_device_id)
except Device.DoesNotExist:
raise LookupError('Device not found')
else:
components = ralph_device.get_c... | 5,346,128 |
def clear():
"""Set all LEDS to 0/off"""
all(0) | 5,346,129 |
def resolve_resource_file(res_name, root_path=None, config=None):
"""Convert a resource into an absolute filename.
Resource names are in the form: 'filename.ext'
or 'path/filename.ext'
The system wil look for ~/.mycroft/res_name first, and
if not found will look at /opt/mycroft/res_name,
then ... | 5,346,130 |
def writeDotGraph(taskInfoFile, taskStateFile, workflowClassName) :
"""
write out the current graph state in dot format
"""
addOrder = []
taskInfo = {}
headNodes = set()
tailNodes = set()
# read info file:
for (label, namespace, ptype, _nCores, _memMb, _priority, _isForceLocal, dep... | 5,346,131 |
def _CommonArgs(parser, api_version):
"""A helper function to build args based on different API version."""
messages = apis.GetMessagesModule('compute', api_version)
flags.MakeResourcePolicyArg().AddArgument(parser)
flags.AddCommonArgs(parser)
flags.AddGroupPlacementArgs(parser, messages)
parser.display_inf... | 5,346,132 |
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
Input
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
conte... | 5,346,133 |
def calculate_seat_district(district_deputy_number, parties, votes):
"""
Calculate seats for each party in list of parties for a district
Params:
- district_deputy_number: the number of seats for this district
- parties: list of parties
- votes: list of votes for each party in this... | 5,346,134 |
def dispatch():
"""Run all dispatch tests"""
suite = ServiceTestSuite()
suite.addTest(unittest.makeSuite(TestCase, 'test_dispatch'))
return suite | 5,346,135 |
def get_mask(height, width, grid_size = 10):
"""
Get the location based on the image size corresponding to relu_4_2
and relu_5_1 layer for a desired grid size.
"""
print(height, width)
x_jump = int(width/grid_size)
y_jump = int(height/grid_size)
x_idx = np.linspace(int(x_jump/2),int(widt... | 5,346,136 |
def arrivalTimes2TimeTraceBH(arrivalTimes, binLength):
"""
Convert a list of arrivalTimes to an intensity time trace I(t)
===========================================================================
Input Meaning
---------------------------------------------------------------------------
... | 5,346,137 |
def datetime_to_ts(dt):
"""
convert naive or aware datetime instance to timestamp in second
Args:
dt(datetime): datetime instance
Returns:
int: timestamp in second.
"""
epoch_dt = datetime.datetime.fromtimestamp(0, tz=pytz.utc)
if not hasattr(dt, 'tzinfo') or dt.tzinfo is ... | 5,346,138 |
def peaks(spectra,frequency,number=3,thresh=0.01):
""" Return the peaks from the Fourier transform
Variables:
number: integer. number of peaks to print.
thresh: float. Threshhold intensity for printing.
Returns: Energy (eV), Intensity (depends on type of ... | 5,346,139 |
def load_csv(source_filepath, start_date = None, end_date = None,
timestamp_index = 0,
column_map = {"bidopen": "bidopen",
"bidclose": "bidclose",
"bidhigh": "bidhigh",
"bidlow": "bidlow",
... | 5,346,140 |
def create_kernel(dim0, dim1):
"""Create a two-dimensional LPF kernel, with a half-Hamming window along
the first dimension and a Gaussian along the second.
Parameters
----------
dim0 : int
Half-Hamming window length.
dim1 : int
Gaussian window length.
Returns
-------
... | 5,346,141 |
def generate_fractal_noise_3d(
shape, res, octaves=1, persistence=0.5, lacunarity=2,
tileable=(False, False, False), interpolant=interpolant
):
"""Generate a 3D numpy array of fractal noise.
Args:
shape: The shape of the generated array (tuple of three ints).
This must be a m... | 5,346,142 |
def getDeltaBetweenPosition(data_outVTK, wall_outVTK, cord_choice, x_p0, x_p1, Npts, Uinf=None, Rhoinf=None):
"""
Compute the boundary layer thickness for *Npts* equally distributed between the 2 position
defined thanks to *x_p0*, *x_p1* and *cord_choice*. See the documentation of the function
getDelta... | 5,346,143 |
def get_clean_url(url):
""" Get a url without the language part, if i18n urls are defined
:param url: a string with the url to clean
:return: a string with the cleaned url
"""
url = url.strip('/')
url = '/' if not url else url
return '/'.join(url.split('/')[1:]) | 5,346,144 |
def get_fields_from_url():
"""Returns a list of fields defined in the url as expected by the RESTful standard"""
return request.args.get('fields', '').split(",") | 5,346,145 |
def get_triples_processed(dcids, limit=_MAX_LIMIT):
"""
Generate the GetTriple query and send the request.
The response is processed into as triples strings. This API is used by the
pv tree tool.
"""
url = API_ROOT + API_ENDPOINTS['get_triples']
payload = send_request(url, req_json={'dcids'... | 5,346,146 |
def load_ipython_extension(ip=None):
"""This function is called when the extension is loaded.
It accepts an IPython |ip| instance. We can register the magic
with the :func:`IPython.core.magics.register_magic_function`
method.
Parameters
-----------
ip : |ip|
"""
if ip is None:
... | 5,346,147 |
def cid_to_date(cid):
"""Converts a cid to date string YYYY-MM-DD
Parameters
----------
cid : int
A cid as it is generated by the function ``utils.create_cid()``
Returns
-------
str
A string formated date (e.g. YYYY-MM-DD, 2018-10-01)
"""
return datetime.utcfromtime... | 5,346,148 |
def get_listings(max_pages=10):
"""Returns the listings from the first max_pages of craigslist."""
page = requests.get(URL)
tree = html.fromstring(page.content)
listing_xpath = '//li[@class="result-row"]'
listings = tree.xpath(listing_xpath)
# Get total number of listings
default_lpp = 120 ... | 5,346,149 |
def remove_edge_stochastic_function(G, parameter, prob_func, prob_func_kws={}, random_seed=None, copy=True):
"""
Recieves a Graph and p.
p is function of a defined parameter
Returns a degraded Graph
"""
if random_seed is not None:
random.seed(random_seed)
if copy:... | 5,346,150 |
def find(
_,
ticket_id,
author=False,
sort=None,
reverse=False,
only=None,
permissions=False,
utc=False,
env=None,
releases_only=False,
):
"""
What latest releases/deploys contain commits belonging to this ticket?
"""
# TODO: link these commits back to app release... | 5,346,151 |
def get_sh_type(sh_type):
"""Get the section header type."""
if sh_type == 0:
return 'SHT_NULL'
elif sh_type == 1:
return 'SHT_PROGBITS'
elif sh_type == 2:
return 'SHT_SYMTAB'
elif sh_type == 3:
return 'SHT_STRTAB'
elif sh_type == 4:
return 'SHT_RELA'
... | 5,346,152 |
def run_script():
"""
The main entry point of the script, as called by the client
via the scripting service, passing the required parameters.
"""
client = scripts.client(
'Dataset_Images_To_New_Figure.py',
"""Use Images from a Dataset to replace those in a Figure and
save th... | 5,346,153 |
def model_objectives(model):
"""Return a list of objectives in the model"""
for obj in model.component_map(aml.Objective, active=True).itervalues():
for idx in obj:
yield obj[idx] | 5,346,154 |
def EnsureNoProprietaryMixins(errs, builder_groups, configs, mixins):
"""If we're checking the Chromium config, check that the 'chromium' bots
which build public artifacts do not include the chrome_with_codecs mixin.
"""
if 'chromium' in builder_groups:
for builder in builder_groups['chromium']:
confi... | 5,346,155 |
def show_warn_message(text:str, *args:str) -> str:
"""
Show a warning message.
"""
return _base("showWarningMessage", text, *args) | 5,346,156 |
def read_gmpe_file(resid_file, period):
"""
Reads the gmpe residuals file and returns all the data
"""
gmpe_data = []
# Read residuals file and get information we need
input_file = open(resid_file, 'r')
# Look over header and figure out which column contains the period
# we need to plot... | 5,346,157 |
def remove_sep(path, new_sep='--'):
"""Convert a real path into pseudo-path."""
return path.replace(os.sep, new_sep) | 5,346,158 |
def correct_colors(im1, im2, landmarks1):
"""
Towards perceptual satisfaction of splicing donor image into recipient.
The color of images is argubly the strongest perceptual attribute, which is ameliorated here.
Note: Further work will improve on geometric distortion (cylindrical, spherical, etc.) and image intrins... | 5,346,159 |
def git_commit(message, cwd):
"""Commit files to git server."""
cmd = ['git', 'commit', '-m', message]
subprocess.check_call(cmd, cwd=cwd)
return | 5,346,160 |
def default_loggingfcn(log, time, entity):
"""
Default function used to log snapshots of agents' states.
"""
for name in entity._names:
log[name].append( copy(getattr(entity, name)) ) | 5,346,161 |
def get_types(name=None):
"""Retrieves the list of device types in the system.
Note that we actually use the "GET device-families" endpoint, as this returns a complete list in one request.
"""
all_types = []
all_families = get_families(name=None, includeTypes=True)
for family in all_families:
... | 5,346,162 |
def read_socket(sock, buf_len, echo=True):
""" Read data from socket and return it in JSON format """
reply = sock.recv(buf_len).decode()
try:
ret = json.loads(reply)
except json.JSONDecodeError:
print("Error in reply: ", reply)
sock.close()
raise
if echo:
pri... | 5,346,163 |
def do_monitor_media_list(client, args):
"""List media"""
kwargs = {'user_id': args.userid}
medias = client.media.list(**kwargs)
utils.print_list(medias) | 5,346,164 |
def temperature_source_function(
rho,
district,
norm,
density: xr.DataArray,
etemp: xr.DataArray,
itemp: xr.DataArray,
density_source: xr.DataArray,
source_strength,
source_centre=0.3,
source_width=0.3,
):
"""
Smooth-step core power injection, mimicking Ohmic power deposi... | 5,346,165 |
def mock_dbt_cloud_response(
monkeypatch: MonkeyPatch,
dbt_manifest_file: Path,
dbt_run_results_file: Path,
) -> None:
"""
Mock the dbt cloud response.
Parameters
----------
monkeypatch : MonkeyPatch
The monkey patch fixture.
dbt_manifest_file : Path
The path to the ... | 5,346,166 |
async def model_copy(request, model_id):
""" route for copy item per row """
request_params = {elem: request.form[elem][0] for elem in request.form}
base_obj_id = utils.extract_obj_id_from_query(request_params["_id"])
try:
new_obj_key = await create_object_copy(
model_id, base_obj_id... | 5,346,167 |
def _write_pyserini_corpus(pyserini_index_file, corpus):
"""Writes the in-memory corpus to disk in the Pyserini format."""
with open(pyserini_index_file, 'w', encoding='utf-8') as fOut:
for doc_id, document in corpus.items():
data = {
'id': doc_id,
'title': d... | 5,346,168 |
def load_pr(fname):
"""Loads predicted tracks in tabular format."""
try:
data = np.loadtxt(fname, delimiter=',', dtype=np.float64, ndmin=2)
except (ValueError, IndexError):
# Try using whitespace delim (default).
data = np.loadtxt(fname, delimiter=None, dtype=np.float64, ndmin=2)
# If category is no... | 5,346,169 |
def CheckPsenac(lamada, w, k):
"""Check the validation of parameter lamada, w and k.
"""
try:
if not isinstance(lamada, int) or lamada <= 0:
raise ValueError(
"Error, parameter lamada must be an int type and larger than and equal to 0."
)
elif w > 1 or... | 5,346,170 |
def build_affine(rotation, scale, origin):
"""
Compute affine matrix given rotation, scaling, and origin.
Parameters
----------
rotation : np.array
rotation
scale : np.array
scale factor
Returns
-------
aff : np.array [4x4]
affine matrix
"""
aff = n... | 5,346,171 |
def sample_per_group(data, group_by, ratio = None, n = None):
"""
:type data: DataFrame
:type group_by: list of str
:type ratio: float
:type num_rows: int
:return:
"""
# group the data
data = data.copy()
"""
:type data: DataFrame
"""
data['__order1'] = data.index
grouped = data.groupby(by = group_by)
... | 5,346,172 |
def test_mbo_cell_capa_update_pmf(dev, apdev):
"""MBO cellular data capability update with PMF required"""
ssid = "test-wnm-mbo"
passphrase = "12345678"
params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
params["ieee80211w"] = "2"
params[... | 5,346,173 |
def print_all_models() -> None:
"""
Print description of every model in this module.
"""
model_desc = _get_all_subclasses_from_superclass(
_NonTrainableUnivariateDetector
)
# model_desc.update(
# _get_all_subclasses_from_superclass(_NonTrainableMultivariateDetector)
# )
model... | 5,346,174 |
def get_base64_column(metadata_df: pd.DataFrame) -> pd.DataFrame:
"""
Get accession json base64 str
:return:
"""
# Get accession json object as base64 string
metadata_df['accession_json_base64_str'] = metadata_df[METADATA_PAYLOAD_COLUMNS].\
apply(lambda x: b64encode(bytes(x.to_json(), en... | 5,346,175 |
def bible_studies_view(request):
"""Bible studies view."""
auth = False
try:
auth = request.cookies['auth_tkt']
auth_tools = request.dbsession.query(
MyModel
).filter(MyModel.category == 'admin').all()
except KeyError:
auth_tools = []
query = request.dbses... | 5,346,176 |
def get_num_channels(inputs):
""" Get number of channels in one tensor. """
return inputs.shape[1] | 5,346,177 |
def single_face_marker():
"""
Face marker with a single value.
"""
return np.zeros((2, 3)).astype(int) | 5,346,178 |
def check_qmc(fname=None, archive=False, xflags=(), eqlb=(1,), reblk=(2,20,2),
eqlb_flags=(), reblk_flags=(), quiet_stdout=0, force_raw=0):
"""Checks the QMC results (INFO file) using my stand-alone QMC inspect tools.
x is the extra flags to be passed on to check_* tools."""
if fname == None:
i... | 5,346,179 |
def skew(arr, angle, dx=None, dy=None, fwd=True, fill_min=True):
"""
Skew the origin of successive lines by a specified angle
A skew with angle of 30 degrees causes the following transformation:
+-----------+ +---------------+
| | |000/ /|
| input ... | 5,346,180 |
def websocket_call(configuration, _method, url, **kwargs):
"""An internal function to be called in api-client when a websocket
connection is required. method, url, and kwargs are the parameters of
apiClient.request method."""
url = get_websocket_url(url, kwargs.get("query_params"))
headers = kwargs... | 5,346,181 |
def compute_metrics(feats, pids, camids, num_query):
""" Compute CMC and mAP metrics """
# query
qf = feats[:num_query]
q_pids = np.asarray(pids[:num_query])
q_camids = np.asarray(camids[:num_query])
# gallery
gf = feats[num_query:]
g_pids = np.asarray(pids[num_query:])
g_camids = np... | 5,346,182 |
def parse_date(string_date: str) -> datetime.datetime:
"""
Parses input string of format 'MMM-yyyy' to datetime.
:param str string_date: Date in string format 'MMM-yyyy'
:return: datetime.datetime: parsed datetime
"""
return datetime.datetime.strptime(string_date, '%b-%Y') | 5,346,183 |
def dpr_json_reader(file_to_read):
"""A simple streaming json reader. It assumes the file is well formated,
which is the case of Facebook DPR data, but it cannot be used as a generic
JSON stream reader, where blocks start/end at arbitrary positions
(unlike Facebook DPR data).
:param file_t... | 5,346,184 |
def test_cytoband_by_chrom(real_populated_database):
"""Test function that returns cytobands by chromosome dictionary"""
test_cytobands = [
{
"_id": "7d3c64026fd1a3ae032f9715a82eac46",
"band": "p36.31",
"chrom": "1",
"start": "5400000",
"stop"... | 5,346,185 |
def round_vzeros(v,d=10) :
"""Returns input vector with rounded to zero components
which precision less than requested number of digits.
"""
prec = pow(10,-d)
vx = v[0] if math.fabs(v[0]) > prec else 0.0
vy = v[1] if math.fabs(v[1]) > prec else 0.0
vz = v[2] if math.fabs(v[2]) > prec else... | 5,346,186 |
async def test_fossil_energy_consumption_hole(hass, hass_ws_client):
"""Test fossil_energy_consumption when some data points lack sum."""
now = dt_util.utcnow()
later = dt_util.as_utc(dt_util.parse_datetime("2022-09-01 00:00:00"))
await hass.async_add_executor_job(init_recorder_component, hass)
awa... | 5,346,187 |
def calculation_test():
"""check that the shapiro-wilk test statistic is correctly calculated because p-value should be > 0.05"""
norm_values = np.random.normal(5, 2, 100)
assert shapiro_wilk(norm_values)[1] > 0.05 | 5,346,188 |
def euclidean_distance_loss(params, params_prev):
"""
Euclidean distance loss
https://en.wikipedia.org/wiki/Euclidean_distance
:param params: the current model parameters
:param params_prev: previous model parameters
:return: float
"""
return K.sqrt(K.sum(K.square(params - params_prev), ... | 5,346,189 |
def read_cloudflare_api_file(prog, file, state):
"""Read the input file for Cloudflare login details.
Args:
prog (State): modified if errors encountered in opening or reading
the file.
file (str): the file to read.
state (ConfigState): to record config file syntax errors.
... | 5,346,190 |
def hash_msg(key, msg):
"""Return SHA1 hash from key and msg"""
return b64encode(hmac.new(key, msg, sha1).digest()) | 5,346,191 |
def remove_tex_axis(ax, xtick_fmt='%d', ytick_fmt='%d', axis_remove='both'):
"""
Makes axes normal font in matplotlib.
Parameters
---------------
xtick_fmt : A string, defining the format of the x-axis
ytick_fmt : A string, defining the format of the y-axis
axis_remove : A string, which axi... | 5,346,192 |
def insert_pattern(base, pattern, offset=None): #optional!
"""
Takes a base simulation field and places a given pattern with an offset
onto it. When offset is None, the object is placed into the middle
Parameters
----------
base : numpy.ndarray
The base simulation field. Can already hol... | 5,346,193 |
def get_specific_label_dfs(raw_df, label_loc):
"""
Purpose: Split the instances of data in raw_df based on specific labels/classes
and load them to a dictionary structured -> label : Pandas Dataframe
Params: 1. raw_df (Pandas Dataframe):
- The df containing data
... | 5,346,194 |
def update_figure(df1, n, autoscale=False, ax=None, axis=0, grayed=None, j=0, kind=None, rx=None, ry=None,
start=0, title=None):
""" update_figure.
Recalculates the whole plot for frame n.
:param df1: pandas dataframe, required
:param n: frame to render, required
:param autoscale... | 5,346,195 |
def run(_):
"""
Meant for running/parallelizing training data preparation
:param _: Not used
:return: Runs prep() function
"""
return prep() | 5,346,196 |
def extract_hcs():
"""
Extract HyperCube shuffle and output hypercube shuffle only plans
"""
with open("q4.json") as jf:
q4 = json.load(jf)
assert q4["language"] == 'MyriaL'
# get fragments
fragments = q4["plan"]["fragments"]
assert len(fragments) == 9
# store operators... | 5,346,197 |
def test_parse_timeframe():
"""
Tests the `parse_timeframe()` method in `Rule`.
"""
tf_minutes = {'minutes?': False, 'm': True}
tf_hours = {'hours?': False, 'h': True}
tf_days = {'days?': False, 'd': True}
tf_weeks = {'weeks?': False, 'w': True}
tf_months = {'months?': False, 'M': True}
... | 5,346,198 |
def includeme(config):
"""Bind to the db engine specifed in ``config.registry.settings``."""
# Bind the engine.
settings = config.get_settings()
engine_kwargs_factory = settings.pop("sqlalchemy.engine_kwargs_factory", None)
if engine_kwargs_factory:
kwargs_factory = config.maybe_dotted(engin... | 5,346,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.