content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def limit_vals(input_value, low_limit, high_limit):
"""
Apply limits to an input value.
Parameters
----------
input_value : float
Input value.
low_limit : float
Low limit. If value falls below this limit it will be set to this value.
high_limit : float
High limit. If... | 4520da27c81338631ea0d35651c7e3170de0524c | 3,616,900 |
def reformat_remove_leading_zeros(x, pos):
"""Format 1 as 1, 0 as 0, and all values whose absolute values is between
0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 is
formatted as -.4)."""
val_str = '{:g}'.format(x)
if 0 < np.abs(x) < 1:
return val_str.replace("0", "... | 29788f14482eba5ba29f2dbb93db25314f3dbffa | 3,616,901 |
from bs4 import BeautifulSoup
def getFormData(page):
"""
Finds form data required to post request for
next page. Returns tuple with data
"""
soup = BeautifulSoup(page, 'html.parser')
viewstate = soup.find('input', {'id': '__VIEWSTATE' })['value']
generator = soup.find('input', {... | 0f4ceb3a82d2a2dcad4125445e9803b358e0ada1 | 3,616,902 |
import torch
def get_mask(
ref,
sub,
pyg=False
):
"""
Get the mask for a reference list based on a subset list.
Args:
ref: reference list
sub: subset list
pyg: boolean; whether to return torch tensor for PyG
Return:
mask: list or torch.BoolTensor
"""... | 07e4b092b5becaaec8bc070990259701bc3a00b7 | 3,616,903 |
def round_m(x):
"""Round meters to an accuracy that avoids machine error."""
return np.around(x, decimals=6) | 323447a17715f1bbf525f371e7f5770311f4d592 | 3,616,904 |
def get_merged_overlapping_coords(start_end):
"""merges overlapping spans, assumes sorted by start"""
result = [start_end[0]]
prev_end = result[0][-1]
for i in range(1, len(start_end)):
curr_start, curr_end = start_end[i]
# if we're beyond previous, add and continue
if curr_start... | 22220778a66e069d98d1129b32f024e61fde1859 | 3,616,905 |
def create_prime_node():
"""
Return a prime node with no children
OUTPUT:
A node object with node_type set as NodeType.PRIME
EXAMPLES::
sage: from sage.graphs.graph_decompositions.modular_decomposition import create_prime_node
sage: node = create_prime_node()
sage: node
... | 43879b9b68418565301cedc121d33c40e6ad86b3 | 3,616,906 |
def u_from_psi(head, psi):
"""Calculate u_calc from non dimensional psi.
Parameters
----------
head : pint.Quantity, float
Polytropic head.
psi : pint.Quantity, float
Head coefficient.
Returns
-------
u_calc : pint.Quantity, float
Impeller tip speed.
"""
... | 2f4f1b772decd008e0e52b8fd9e8975feb40b450 | 3,616,907 |
def collapse_objlist(object_list, keyword, suffix='', doarray = False):
""" Given a LIST of identical objects, collapse the objects to form a
list of only a single keyword.
::
aplist = nsdata.getirafap('ap1')
cenlist = nsdata.collapse_objlist(aplist, 'keyword')
If yo... | 32afbf75b7fe7d06cb89a1ebb0a2f34666e8d732 | 3,616,908 |
def make_deprecate(meth, old_name):
"""TODO Add Docs
"""
new_name = meth.__name__
def deprecated_init(*args, **kwargs):
warn("autogluon.{} is now deprecated in favor of autogluon.{}."
.format(old_name, new_name), AutoGluonWarning)
return meth(*args, **kwargs)
deprecated... | 33a8f7f0e1dda1b3f648373051f3f9446ffd06ab | 3,616,909 |
def add_gmail(t=None, u=None, p=None):
"""
Adds server GMail to instance
Adds GMail settings to vim /var/lib/geonode/rogue_geonode/geoshape/local_settings.py
"""
address = _request_input("User", u, True)+'@gmail.com'
host = 'smtp.gmail.com'
return _run_task(_add_email, args=None, kwargs={... | 64e7778b3010981ca31e079d728a1368abffd0c3 | 3,616,910 |
def unpack_mac(sixbytes):
"""Converts a mac address given in a six byte string in network
byte order to a string in colon delimited notation.
>>> unpack_mac(b"012345")
'30:31:32:33:34:35'
>>> unpack_mac(b"bad")
Traceback (most recent call last):
...
ValueError: given buffer is not exactly six bytes long
@typ... | d9504ac1f99229cff1a870ff500808cd6d7174d2 | 3,616,911 |
def create_obs_stacker(environment, history_size=4):
"""Creates an observation stacker.
Args:
environment: environment object.
history_size: int, number of steps to stack.
Returns:
An observation stacker object.
"""
return ObservationStacker(history_size,
environment.vectorized_observation_sha... | 0955e75841247fd2bd8a27f4b695fbfffbd5dbd7 | 3,616,912 |
def s3_name(request):
"""[summary]
Args:
request ([type]): [description]
Returns:
[type]: [description]
"""
bucket_name = "test.bucket"
mock = mock_s3()
mock.start()
conn = boto3.resource("s3", region_name="us-east-1")
conn.create_bucket(Bucket=bucket_name)
requ... | 3e3f4c5a2a9249e8376eb4743632ba9a00f4aad1 | 3,616,913 |
def git_repo(pip_url_kwargs):
"""Create an git repository for tests. Return repo."""
git_repo = create_repo_from_pip_url(**pip_url_kwargs)
git_repo.obtain()
return git_repo | 21bf065c5b226453897c67b93693274201ea51cb | 3,616,914 |
from typing import Dict
import logging
def build_asset_update(
src_asset: Asset, dst_asset: Asset, src_id_dst_map: Dict[int, int], project_src: str, runtime: int, depth: int
) -> Asset:
"""
Makes an updated version of the destination asset based on the corresponding source asset.
Args:
src_as... | 4acb464c8df660f59944eb1903174812cc677ec6 | 3,616,915 |
def test_markdown_code_block():
"""We test that
- A code blocks are supported. Sort of. BUT THE INDENTATION IS CURRENTLY LOST!
- Indented markdown test from editors is supported. The Panel Markdown does not support this.
"""
code_block = """
This is not indented
```python
print("Hello Awesome Pane... | 84f47665265e0c6e5b8137361dd748ca14ac824c | 3,616,916 |
def euclidean_distance(mov_data, joint1, joint2):
"""Calculate the euclidean distance between the 2 given joints for all the frames of the grasping movement.
Args:
mov_data (pd.DataFrame): A pd.DataFrame containing the skeletal data of the grasping movement and of 9 frames before the beginning of the m... | 9f2eedcf3346d3a1cd3126a1e8ddc3e33b8c823d | 3,616,917 |
def ta_iter_SWS(*args):
"""
Function to be optimized for free protons, calls Bohrium version if required
Parameters
----------
mask
Mask indicating which cells to include / exclude from calculation
x
Free protons
k1
k2
k1p
k2p
k3p
st
ks
kf
ft... | 3673f94ae163fbef2ec9809c454a7b3be0edd841 | 3,616,918 |
def get_integer_attribute(attribute_list, name, default_value=None):
"""Returns the integer value of an attribute, if any, or default_value.
Arguments:
attribute_list: A list of attributes to search.
name: The name of the desired attribute.
default_value: A value to return if name is not found in... | ef364f78dbe8ce5cef70651ddab8057a45540e0f | 3,616,919 |
import logging
from pathlib import Path
def init_logger(log_file=None, log_file_level=logging.NOTSET):
"""
Example:
init_logger(log_file)
logger.info("abc'")
"""
if isinstance(log_file, Path):
log_file = str(log_file)
log_format = logging.Formatter(fmt='%(asctime)s - %(leve... | 65df2b9377062aa562b88eadd334447b14c100d3 | 3,616,920 |
def add_news():
"""新闻编辑详情页"""
if not g.user.is_admin:
return redirect('/')
if request.method == 'GET':
# 查询分类的数据
categories = []
try:
categories = Category.query.all()
except Exception as e:
current_app.logger.error(e)
categories_li ... | f079b9cbb321b2971a6fa5b1ae98dfb5cdbc4379 | 3,616,921 |
import tempfile
import shutil
import os
import sys
import io
def get_diag(code, command):
""" Generate diagramm and return data """
code = code + u"\n"
try:
tmpdir = tempfile.mkdtemp()
fd, diag_name = tempfile.mkstemp(dir=tmpdir)
f = os.fdopen(fd, "w")
f.write(code.encod... | e80d88db73604e7471b1c8dd0d1796e438ccf824 | 3,616,922 |
def get_address(tag_name, region, client):
"""
Collects the addresses of the aws instances being used for the estimation
:param tag_name: aws 'Name' tag of the instances
:param region: aws region
:param client: aws client
:return: list with aws instance addresses
"""
ec2 = boto3.Session(... | 565acb98b0cd79a566ed231a3b1cde362cfefa82 | 3,616,923 |
def generate_instances_for_appliances_by_dataids(
schema, tables, appliances, dataids, sample_rate=None):
"""
Returns instances for a list of appliances across a set of dataids
"""
#TODO probably a more efficient way to do this
instances = [generate_appliances_instances(schema, tables, appli... | e56fe7d0a12ebab77af1dd8bac0c13c4eb9d6e90 | 3,616,924 |
def SearchableField(**kw):
# type: (**Any) -> Dict[str, Any]
"""Configure a searchable text field for an Azure Search Index
:param name: Required. The name of the field, which must be unique within the fields collection
of the index or parent field.
:type name: str
:param type: Required. The d... | 5cdfd9aabd6d92f38ee681448546d7dd4976bf3b | 3,616,925 |
def geometry_factor_trace(trace, gap, thickness):
"""Return the kinetic inductance geometry factor for the central conducting trace of a CPW.
If the kinetic inductance of the central trace is L_k, its kinetic inductance contribution per unit length is
L = g_c L_k,
where g_c is the geometry factor ret... | ec4aad344c152d526f0009d26e90181512e6d7d2 | 3,616,926 |
def list_dir(conn=None):
"""
:param conn:
:return: <list>
"""
available = RBF.filter({PART_FIELD: False}).pluck(PRIMARY_FIELD).run(conn)
return [x[PRIMARY_FIELD] for x in available] | 0be9d248fbefe6e22a64863841a601b40daeb5dd | 3,616,927 |
def get_location_in_distance(actor, distance):
"""
Obtain a location in a given distance from the current actor's location.
Note: Search is stopped on first intersection.
@return obtained location and the traveled distance
"""
waypoint = CarlaDataProvider.get_map().get_waypoint(actor.get_locati... | 8dd439b681d94ed74bbfb89225d7710708ad436a | 3,616,928 |
def read_arrays_and_return():
"""
Reads the prepared numpy arrays
# Returns: the read np arrays
"""
X_train = np.load('arrays/X_train_w2v.npy')
y_train = np.load('arrays/y_train_w2v.npy')
X_test = np.load('arrays/X_test_w2v.npy')
y_test = np.load('arrays/y_test_w2v.npy')
retu... | 4aa5f036d3c0002f14a07e09d5c0062f07a35348 | 3,616,929 |
def HtmlRenderer(tooltip):
"""
A renderer that implements all tooltip features
in html.
"""
ret = []
USE_STYLE = True
lineTpl = '<div style="%s">%s</div>'
sideTpl = '<span style="%s">%s</span>'
for idx, line in enumerate(tooltip):
lineHtml = []
lineStyle = []
if idx == 0:
lineStyle.append("font-size... | fc4cbd326138085f39ee339973279e73be5f2af8 | 3,616,930 |
def linear_v2n(inputs, output_size, bias, w_x_inp, params, concat=False,
dtype=None, scope=None, d2=False):
"""
Linear layer
:param inputs: A Tensor or a list of Tensors with shape [batch, input_size]
:param output_size: An integer specify the output size
:param bias: a boolean value ... | c58092c21bdceeb901ce37b6a36586be2ae68025 | 3,616,931 |
def two_opt_with_cycle(orderedPoseListe):
"""
returns an optimised list from an orderedpose using the 2-opt algo with creating a Hamilton cycle
"""
improve = True #we iterate in the list as long as we find improvements
while improve == True:
improve = False
for i in range(len(ordered... | 3d303220fbcb6e9f9832a68ae0580f27247acc5c | 3,616,932 |
def html_to_spreadsheet_cell(html_element):
""" Parse HTML elmement, like <a href=www.google.com>Google</a> to =HYPERLINK(www.google.com, Google) """
link = html_element.find("a")
if link:
return '=HYPERLINK("{}", "{}")'.format(link['href'], link.contents[0])
else:
return html_element.te... | f0c797f59ed55d1ce6aab32ff8c40cf83577ee27 | 3,616,933 |
def get_bucket(bucket_name):
"""
Established a connection and gets s3 bucket
"""
if '.' in bucket_name:
s3 = boto.connect_s3(calling_format=OrdinaryCallingFormat())
else:
s3 = boto.connect_s3()
return s3.get_bucket(bucket_name) | 02cc01b9bf70864fdd3a0e80525e6d7a34536ab6 | 3,616,934 |
def _get_class(canonical_name: str):
"""
Gets a class by it's canonical name. Mind that this can only work with classes that does not require
any argument during instantiation.
:param canonical_name: the canonical name of the class to load dynamically, e.g. x.y.Module.Class
:returns: the instance ... | 289630cf65fcb915da4f4b49baa650d2e27e7a7c | 3,616,935 |
def build_tcp_flags() -> int:
"""
Assembles TCP flags.
"""
flags = 0
for flag in (
TCP_CWR, TCP_ECE, TCP_URG, TCP_ACK,
TCP_PSH, TCP_RST, TCP_SYN, TCP_FIN
):
flags <<= 1
flags |= flag
return flags | c4e04fc9c6201782c242636fc7aca284447ccb84 | 3,616,936 |
import requests
import json
def send_to_slack_channel(url, text):
"""Sending messages to Slack channels."""
payload = {
"text": text
}
if settings.DEBUG:
print(text)
else:
requests.post(url=url, data=json.dumps(payload))
return True | f8d97d1be8c4d6316bc404858ba01a95aa2fb124 | 3,616,937 |
from typing import Tuple
def parseOptionWithArgs(plugin: str) -> Tuple[str, str]:
"""Parse the plugin name into name and parameter
@type plugin: str
@param plugin: The plugin argument
@returns tuple[str, str]: The plugin name and parameter
"""
if '=' in plugin:
plugin, param = plugin.... | 0e1f85f2e31349bf7ddcdc2d35b9ba815a61ec06 | 3,616,938 |
def spm_warp_to_mni(wf_name="spm_warp_to_mni"):
""" Run Gunzip and SPM Normalize12 to the list of files input and outputs the list of warped files.
It does:
- Warp each individual input image to the standard SPM template
Parameters
----------
wf_name: str
Name of the workflow.
Nip... | 5e497c7f34f6349b21807c30e169d7c26e1bc359 | 3,616,939 |
def build_insert_ddl(table_name: TableName, column_list, query_stmt) -> str:
"""Assemble the statement to insert data based on a query."""
columns = join_with_double_quotes(column_list, sep=",\n ")
insert_stmt = """
-- arthur.insert: {table.identifier}
INSERT INTO {table} (
... | 8feab467cb650052f772e5e54680432c06468d0a | 3,616,940 |
import sys
def get_user_password(args):
"""
Allows the user to print the credential for a particular keyring entry
to the screen
"""
username = '%s:%s' % (args.env, args.parameter)
warnstring = colors.rwrap("__ WARNING ".ljust(80, '_'))
print("""
%s
If this operation is successful, the c... | ee4285f5f36e9e909638d05d7abc5e260518ec81 | 3,616,941 |
import functools
import warnings
def silent_nan_np(f):
"""Decorator that silences np errors and returns nan if undefined.
The np.nanmax and other numpy functions will log RuntimeErrors when the
input is only nan (e.g. All-NaN axis encountered). This decorator silences
these messages.
Args:
... | 25a861f4304dab03913995a992c0cd710d0e5c7c | 3,616,942 |
from typing import List
def evaluate_non_measured_estimation_tasks(
estimation_tasks: List[EstimationTask],
) -> List[ExpectationValues]:
"""This function evaluates a list of EstimationTask that are not
measured, and either contain only a constant term or require 0 shot.
Non-constant EstimationTask wi... | bd07ffd48362fc0ed9c5dc66699bea7b6ee0affb | 3,616,943 |
def knapsack(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, lis... | 484ae09e663c834e42a9e05d684138d4fb6ddf08 | 3,616,944 |
def identity(n, dtype='d', format=None):
"""Identity matrix in sparse format
Returns an identity matrix with shape (n,n) using a given
sparse format and dtype.
Parameters
----------
n : integer
Shape of the identity matrix.
dtype :
Data type of the matrix
format : strin... | ff459b04e3876f03cd1bd1d8a060c0a70d8190ea | 3,616,945 |
from datetime import datetime
def d2s(d):
"""
Date to string in friendly format, without time.
"""
return datetime.datetime.strftime(d, '%B %d, %Y') | a4fa2791d602c7bce4642d492818f9b8c1c9182e | 3,616,946 |
def refresh_content(username, password):
"""
Refresh the annoucements and resources for a user
Args:
username (String) : a UQ username to sign into blackboard and scrape
password (String) : the password for the UQ username's blackboard
Returns:
courses
"""
scraper = UQ... | 68f5b5c837625803b9f4ba28870741bd97e9c35e | 3,616,947 |
def adresa_inceput(netmask, ip):
"""
Ia un netmask si un IP si determina adresa de inceput
a retelei
:param (str) netmask:
:param (str) ip:
:return adresa_inceput (str):
"""
netmask_nums = netmask.split(".")
ip_nums = ip.split(".")
adresa_inceput = ""
for i in range(0, 4):
... | dcbe18f68b216d6772fcad01e43829bc33de43c9 | 3,616,948 |
import json
def get_all_features(after_time_added=None):
"""
Args:
after_time_added: get all features that were added to the db after this date.
Returns:
"""
features = []
if after_time_added:
for feature in Feature.objects.exclude(feature_added_time__lt=after_time_added):
... | 19d1bc06ee252ed9c0b5718f548ab8f79ad8f650 | 3,616,949 |
def ASBII(ATcur_P, ATxyz_P, ATxyz_K):
"""
| X | Astr. Azimuth , Zenith , Slope
| Y | ---------------+-------> from P to K distance distance
| Z |AT_P | (Apk) (Bpk) (Spk)
... | 01ac0a6dc8509ee6a0aaf4787268356fb8af2e5e | 3,616,950 |
import socket
def auto_build_socket(address):
"""Auto build a socket.socket instance from address"""
address_type = get_address_type(address)
if address_type == 'tcp':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
elif address_type == 'uds':
sock = socket.socket(socket.... | 676246e4468ea914fa0d72041e0fbd880ce30168 | 3,616,951 |
def get_usage_data_labels(usage_data):
"""Return dict with human readable labels for each of the groups in each of the given usage data timeframes."""
labels = {}
timeframe_formats = {"day": "%H", "week": "%b %d", "month": "%b %d", "year": "%b %Y"}
for timeframe, timeframe_data in usage_data.items():
... | 7c8610a7feb8a3a4a6454f508bfb9c95ccba55ff | 3,616,952 |
def has_same_disk_several_positions(board):
"""
Check if the same disk appears multiple times on the same board
Returns True is there is one or are multiple appearances, False if not
"""
used_disks = list(board.values())
for pos in range(len(used_disks) - 1, -1, -1):
if used_dis... | b184e5c8bfb34c9819e4ffb146c4159c4d247a4c | 3,616,953 |
def _get_temporal_props(ds: xr.Dataset) -> dict:
"""
Get temporal boundaries, resolution and duration of the given dataset. If
the 'bounds' are explicitly defined, these will be used for calculation,
otherwise it will rest on information gathered from the 'time' dimension
itself.
:param ds: Dat... | 662c6f777f86395c6cd6e53888b7bc2e9913fcf2 | 3,616,954 |
def draft_file_resource():
"""Draft file resource."""
return DraftFileResource(
config=DraftFileResourceConfig,
service=Service(config=ServiceConfig)
) | 964c884beb60ac097d93ea4cb9822aba24be2ee7 | 3,616,955 |
import logging
def make_models():
"""build all the models based on the arguments provided via absl
Returns: encoder_model, decoder_model, discriminator_model
"""
if FLAGS.model == "default" and FLAGS.training_method == "adaptive_st" or FLAGS.model == "adaptive_st":
logging.info("define adapt... | 165a840b8802c102d25660da3804c58b4063c558 | 3,616,956 |
def get_expression_parser(_: Environment) -> ExpressionParser:
"""Return an expression parser for the given environment."""
# Future proofing.
return STANDARD_EXPRESSION_PARSER | d7edf3cb6b58da851985f40da8d6bad33c68a2b6 | 3,616,957 |
async def _setup(hass, hass_ws_client, properties_data):
"""Set up tests."""
ws_client = await hass_ws_client(hass)
devices = MockDevices()
await devices.async_load()
devices.fill_properties("33.33.33", properties_data)
async_load_api(hass)
return ws_client, devices | 846716470b62c823e60256e6fff55e06344c2c33 | 3,616,958 |
def filter(function, iterable) -> object:
"""filter."""
if function is None:
return (item for item in iterable if item)
return (item for item in iterable if function(item)) | 36bfce957476f934a18c2bb3a24e994ec2799973 | 3,616,959 |
def red_car(red,lat):
"""
Convert reduced coordinates to cartesian
"""
return np.array(map( lambda coord: coord[0]*lat[0]+coord[1]*lat[1]+coord[2]*lat[2], red)) | 182cf99a6bb3d519d2a2674d12d4ac5ae738fe47 | 3,616,960 |
def _define_collect(batch_env, ppo_hparams, scope, frame_stack_size, eval_phase,
sampling_temp, force_beginning_resets):
"""Collect trajectories.
Args:
batch_env: Batch environment.
ppo_hparams: PPO hparams, defined in tensor2tensor.models.research.rl.
scope: var scope.
frame_st... | 920fb9e62d9cc8075c29ad6f6d6b06b25eeb6059 | 3,616,961 |
def byte_at_a_time_ecb_decryption_harder(encryption_oracle):
"""Performs the byte-at-a-time ECB decryption attack to discover the secret padding used by the oracle."""
# Find the block length
block_length = find_block_length(encryption_oracle)
# To detect if the oracle encrypts with ECB mode, we can e... | 6b45a4674fa796cfcba3f0d6b7c45c8f5aa78284 | 3,616,962 |
import os
def cmk_arn_value():
"""Retrieves the target CMK ARN from environment variable."""
arn = os.environ.get(AWS_KMS_KEY_ID, None)
if arn is None:
raise ValueError(
'Environment variable "{}" must be set to a valid KMS CMK ARN for integration tests to run'.format(
... | 5e775a5f0851f9cf7679844b23fa88656e937f0e | 3,616,963 |
from typing import Optional
from typing import List
from typing import Union
def data_cleaning(
data: pd.DataFrame,
drop_threshold_cols: float = 0.9,
drop_threshold_rows: float = 0.9,
drop_duplicates: bool = True,
convert_dtypes: bool = True,
col_exclude: Optional[List[str]] = None,
catego... | 868c47ec1c1ed9827bfe7c009656eb8e14d04e2e | 3,616,964 |
def _pmf_doc_name(doc):
"""Helper to generate document name for a ProceedingsMaterialFactory LazyAttribute"""
return 'proceedings-{number}-{slug}'.format(
number=doc.factory_parent.meeting.number,
slug=xslugify(doc.factory_parent.type.slug).replace("_", "-")[:128]
) | e3a327ac418a6207e7148621593898ab2190ccbc | 3,616,965 |
def isWanted(client, date):
"""Check if the page of a date contains free time slots."""
loadDate(client, date)
times = getAvailableTimes(client.html)
ret = len(times) > 0
print('\tinspecting date', date, ', result =', 'available!!' if ret else 'full')
return ret | 8a115513a23b5cde7a85737864f16036d8c32190 | 3,616,966 |
import typing
def _get_counter_one(store: typing.Callable, item_key: ItemKey) -> int:
"""Returns count under exactly matched key.
"""
count = store.get(item_key.key)
return 0 if count is None else int(count) | 92b26c65f2abeb0aa7fedd5dfd9e4e626f150892 | 3,616,967 |
def wait_loading():
"""
Wait for selenium page to be ready
"""
return driver.execute_script('return document.readyState;') != 'complete' | 186233548abc55747fa8a46e8eeb19b05f35c608 | 3,616,968 |
def tril(m, k=0):
"""
Returns a lower triangle of an array.
Returns a copy of an array with elements above the k-th diagonal zeroed.
Args:
m(array_like): The shape and data-type of a define these same
attributes of the returned array.
k(int, optional): Diagonal above which ... | 13f1ca4437d8b9084251fcea2910f45fec9808ff | 3,616,969 |
def distance(request):
"""
Compute the Euclidean distance using our package. Check that multithreading has no
effect on the result.
"""
kwargs = request.param
kwargs.update(DATASET_1)
return g.distance_pairwise(**kwargs) | bf60a32584ee2627d6cacd6647468055af2ad6dd | 3,616,970 |
def modify_primer_file( infile, outfile ):
"""! @brief add subfix number to all primers """
counter = 0
mapping_table = {}
with open( outfile, "w" ) as out:
with open( infile, "r" ) as f:
line = f.readline()
while line:
if line[0] == ">":
if counter % 2 == 0:
name = line.strip()
out.w... | 20802c5578adceddafa6c7584a2da5c17b80ede6 | 3,616,971 |
def show_interface(dut, interface_name = None, cli_type="klish"):
"""
API to show sflow interface configuration
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:return:
"""
output = list()
if cli_type == "klish":
command = "show sflow interface"
i... | 8b726e237d1531971b29604a93f0891cfc83349b | 3,616,972 |
def format_currency(amount):
"""Convert float to string currency with 2 decimal places."""
str_format = str(amount)
cents = str_format.split('.')[1]
if len(cents) == 1:
str_format += '0'
return '{0} USD'.format(str_format) | b90d064fe6b095227e5c590ad8d175f072e07957 | 3,616,973 |
async def async_setup(hass, config) -> bool:
"""Initialize the Sure Petcare component."""
if DOMAIN not in config:
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=conf... | 85a5bf34af18410cebee5f5fed5d178f2ebbd265 | 3,616,974 |
def _build_module_validity_mat(module_names):
"""
Build a module validity matrix, ensuring that only valid modules will have
non-zero probabilities. A module is only valid to run if there are enough
attentions to be popped from the stack, and have space to push into
(e.g. _Find), so that stack will not underf... | bf064711d6483237e8ca846dc4954d4454abbb37 | 3,616,975 |
def get_plist_text(cf_bundler_identifier, cf_bundle_name=None,
docset_platform_family=None):
"""TODO"""
cf_bundle_name = cf_bundle_name or cf_bundler_identifier.upper()
docset_platform_family = docset_platform_family or cf_bundle_name.upper()
return """
<?xml version="1.0" encoding="UTF-8"?>
... | 783cdf32c69afe678907c52b37d4201561b493c9 | 3,616,976 |
def make_predictions(df):
"""
Uses the pycaret best model to make predictions on data in the df dataframe.
"""
model = load_model('churn_ada')
predictions = predict_model(model, data=df)
predictions.rename({'Label': 'Churn_prediction'}, axis=1, inplace=True)
predictions['Churn_prediction'].r... | 9a1a3914020cfa685f92612b834117a47f722842 | 3,616,977 |
def _audio_to_embeddings_fn(kv, teacher_fn, output_dimension):
"""Map audio to teacher labels."""
samples = kv[SAMPLES_]
teacher_embeddings = teacher_fn(samples)
teacher_embeddings.shape.assert_has_rank(2)
teacher_embeddings.set_shape([None, output_dimension])
return {SAMPLES_: samples, TARGETS_: teacher_em... | 4965bad9bd367bffa82b2ec40a61514870a42907 | 3,616,978 |
def _get_delay_time(session):
"""
Helper function to extract the delay time from the session.
:param session: Pytest session object.
:return: Returns the delay time for each test loop.
"""
return session.config.option.delay | 466ce191962df90ee8cdc1a5f8a004094eb9e79f | 3,616,979 |
def req_send_restore():
"""Отправка сообщения для активации"""
temp = User.find_link(request.get_json())
data = {
'title': 'Восстановление пароля',
'button': 'Изменить',
'login': temp[0],
'link': "http://127.0.0.1:5000/restore/" + get_link(temp[1]),
'color': col[temp[... | 92ef287b01eecbb1f93f01226a5362dc56fe9dbe | 3,616,980 |
def discretize(df, nbins=10, cut=pd.qcut,
verbose=2, drop_useless=True):
"""Discretize columns in {df} to have at most {nbins} categories.
* Categorical columns: take the Top n-1 plus "Other"
* Continuous columns: cut into {nbins} using {cut}.
Returns a new discretized dataframe with... | 70af1343fdd3464f799e08db02672329bd7771f8 | 3,616,981 |
def get_flavor_kind(penalty):
"""
Gets the flavor kind of a penalty.
Parameters
----------
penalty: PenaltyConfig, PenaltyTuner
The penalty whose flavor we want to know.
Output
------
flavor_kind: None, str
The flavor; one of [None, 'adaptive', 'non_convex']
"""
... | 8da150f1958df61ca494193a673189a929d3aa97 | 3,616,982 |
from typing import Sequence
def is_overlapping_lane_seq(lane_seq1: Sequence[int], lane_seq2: Sequence[int]) -> bool:
"""
Check if the 2 lane sequences are overlapping.
Overlapping is defined as::
s1------s2-----------------e1--------e2
Here lane2 starts somewhere on lane 1 and ends after it,... | 155e3a962f3f457a868585798e1ab8d92c9f115f | 3,616,983 |
import os
def get_dataset_from_code(code, batch_size):
""" interface to get function object
Args:
code(str): specific data type
Returns:
(torch.utils.data.DataLoader): train loader
(torch.utils.data.DataLoader): test loader
"""
dataset_root = "./assets/data"
if code ==... | 305c32d1aafcd776f247542e854d5b5fdcff8921 | 3,616,984 |
def make_uniform_edge_dataset(args):
""" Uniform edge-sampled dataset. """
def dataset_fn(graph_data, seed):
neighbours, lengths, offsets = tensorboard_hack(graph_data)
def _fn(s):
return dataset_ops.UniformEdgeDataset(
args.num_edges, neighbours=neighbours, lengths=... | d3075d81fca902b5684d4750ff0756a58ac43f73 | 3,616,985 |
def output_handler(data, context):
"""Post-process TensorFlow Serving output before it is returned to the client.
Args:
data (obj): the TensorFlow serving response
context (Context): an object containing request and configuration details
Returns:
(bytes, string): data to return to cl... | 7d1bbcb2310c4527c5ae9cfcd51be660532555df | 3,616,986 |
def largest_rectangle(h):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/largest-rectangle/problem
Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a
shopping mall in their place. Your task is to find the largest solid area in which th... | 7d7b66929e8416fdf8fe64e080ec5ed288c72d88 | 3,616,987 |
import sys
def get_size(objct, seen=None):
"""Recursively finds size of objects"""
if seen is None:
seen = set()
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
all_objects = [objct]
total_size = 0
while len(all_objects) > ... | f0761b229780f89e8a2f489f6116ab98c6a26561 | 3,616,988 |
import os
def _load_imsitu_file(mode):
"""
Helper fn that loads imsitu file
:param fn:
:return:
"""
if mode not in LISTS:
raise ValueError("Invalid mode {}, must be train val or test".format(mode))
imsitu_ind_to_label = {}
dps = []
with open(LISTS[mode], 'r') as f:
... | 33f5fe205ebf8f1a4db85e5d0c81f6b8270adda2 | 3,616,989 |
def fahr2cel(t):
"""Converts an input temperature in fahrenheit to degrees celsius
Inputs:
t: temperature, in degrees Fahrenheit
Returns:
Temperature, in C
"""
return (t - 32) * 5 / 9 | b55f2405e06b124adf23b7833dedbe42ff9f75ba | 3,616,990 |
def str2tod(timeval=''):
"""Return tod for given string without fail."""
ret = None
if timeval is not None and timeval != '':
try:
ret = tod(timeval)
except:
pass
return ret | 91a787f61051d297e71c45687ae177e6c2855aad | 3,616,991 |
def readFDOUB1(stream):
"""
Read FDOUB1 from given stream
:type stream: FileIO or ByteIO
:param stream: stream to be read
:return: Result.
:rtype: FDOUB1
"""
return FDOUB1(stream) | 1124b0ab96519500cf9e3fffd992fe3e59d4c542 | 3,616,992 |
def _sub_sample(matrix_X, matrix_Y, test_statistic, num_samples, sub_samples, which_test):
"""
Sub samples the data and calculates the sub sampled test statistic
:param matrix_X: is interpreted as a ``[n*p]`` data matrix, a matrix with ``n`` samples in ``p`` dimensions
:type matrix_X: 2D numpy.array
... | eb40ef16a1e53ad7c50553ba9bffc9ad3aa8a66f | 3,616,993 |
from typing import Callable
from typing import Any
import sys
def require_partitions(f: Callable[['MultiDiskBundleStore', Any], Any]):
"""Decorator added to MultiDiskBundleStore methods that require a disk to
be added to the deployment for tasks to succeed. Prints a helpful error
message prompting the use... | d6860e5dbb1dd7973c7df17260ca85481e06cf1b | 3,616,994 |
from functools import reduce
from .model_store import get_model_file
import os
def get_peleenet(model_name=None,
pretrained=False,
root=os.path.join("~", ".tensorflow", "models"),
**kwargs):
"""
Create PeleeNet model with specific parameters.
Parameters:... | 210d37600efaded5f02e9e79713cdf6190d7ccbf | 3,616,995 |
def read_csv(param_name, filepath):
"""read dataframe using pandas.read_csv, but with appropriate types
"""
specs = filemanager.get_specs(param_name)
columndata = specs['columns']
converters = {c: eval(data['type']) for c, data in columndata.items()}
try:
cols = find_cols(filepath, colum... | 141a2edb13bf8056a5c3f459bd837e8b66710793 | 3,616,996 |
def test_custom_action(FormAction):
""" """
def name(self) -> Text:
return "action_recipe_search"
@staticmethod
def required_slots(tracker:Tracker) -> List[Text]:
# returns names of all slots that must be provides
return ["purpose", "diet_type"]
# can define slot_mappi... | 9e2a3c317a61ac947eb90104f22e0eb0050644b0 | 3,616,997 |
import os
def load_fonts():
"""
Load all fonts in the fonts directory
"""
return [os.path.join('fonts1', font) for font in os.listdir('fonts1')] | 96e339324e2a84a55bef1a307cb0d46343b7f1f6 | 3,616,998 |
def reshape_data(state_trajectory, control_inputs, numstates):
"""
Reshapes the data of get_sampled_traj_and_ctrls
"""
traj = np.array(state_trajectory)
len_traj = len(state_trajectory)
traj = traj.reshape(len_traj, numstates)
ctrl = np.array(control_inputs)
return [traj, ctrl] | d9057e71c8e27644c85ec81664b4432c5c21bcd6 | 3,616,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.