content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def scored_ngrams(
docs: Documents,
n: int = 2,
metric: str = "pmi",
tokenizer: Tokenizer = DEFAULT_TOKENIZER,
preprocessor: CallableOnStr = None,
stopwords: Union[str, Collection[str]] = None,
min_freq: int = 0,
fuse_tuples: bool = False,
sep: str = " ",
) -> Series:
"""Get Seri... | 32,700 |
def parse_command_line_arguments() -> argparse.Namespace:
"""Specifies the command line parser and returns a
:class:`argparse.Namespace` containing the arguments."""
parser = argparse.ArgumentParser(
description=f"supreme-pancake v{__version__}")
parser.add_argument(
"-c",
"--cre... | 32,701 |
def imurl(image_url, return_as_array = False , **kwargs):
"""
Read image from url and convert to bytes or ndarray
Paramters
---------
image_url: http / https url of image
return_as_array: Convert image directly to numpy array
default: False
kwargs:
Keyword argu... | 32,702 |
def generate_command(config, work_dir, output_analysis_id_dir, errors, warnings):
"""Build the main command line command to run.
Args:
config (GearToolkitContext.config): run-time options from config.json
work_dir (path): scratch directory where non-saved files can be put
output_analysi... | 32,703 |
def ip(
context,
api_client,
api_key,
input_file,
output_file,
output_format,
verbose,
ip_address,
):
"""Query GreyNoise for all information on a given IP."""
ip_addresses = get_ip_addresses(context, input_file, ip_address)
results = [api_client.ip(ip_address=ip_address) for ... | 32,704 |
def test_start_end_attack(asset_address, raiden_chain, deposit):
""" An attacker can try to steal assets from a hub or the last node in a
path.
The attacker needs to use two addresses (A1 and A2) and connect both to the
hub H, once connected a mediated transfer is initialized from A1 to A2
through ... | 32,705 |
def get_layer(neurons, neuron_loc, depth=None, return_closest: bool=False):
"""Obtain the layer of neurons corresponding to layer number or specific depth."""
layers = np.unique(neuron_loc[2, :])
if depth is not None:
if depth in layers:
pass
elif return_closest:
de... | 32,706 |
def train_single_env(
algo: AlgoProtocol,
env: gym.Env,
buffer: Buffer,
explorer: Optional[Explorer] = None,
n_steps: int = 1000000,
n_steps_per_epoch: int = 10000,
update_interval: int = 1,
update_start_step: int = 0,
random_steps: int = 0,
eval_env: Optional[gym.Env] = None,
... | 32,707 |
async def test_init_ignores_tolerance(hass, setup_comp_3):
"""Test if tolerance is ignored on initialization."""
calls = await _setup_switch(hass, True)
_setup_sensor(hass, 39)
await hass.async_block_till_done()
assert 1 == len(calls)
call = calls[0]
assert HASS_DOMAIN == call.domain
ass... | 32,708 |
def apply_wa_title(tree):
"""
Replace page's ``<title>`` contents with a contents of
``<wa-title>`` element and remove ``<wa-title>`` tag.
WebAnnotator > 1.14 allows annotation of ``<title>`` contents;
it is stored after body in ``<wa-title>`` elements.
"""
for wa_title in tree.xpath('//wa-... | 32,709 |
def capacitor_charge_curve():
""" Plots the charging of a capacitor overtime. """
r = 100
c = 10 * Units.u
DURATION = 0.01
ts = irangef(0, DURATION, Config.time_step)
ts = np.array(ts)
# Model
graph = Graph()
node_5 = Node(graph, value=5, fixed=True, source=True)
node_gnd = No... | 32,710 |
def _format_unpack_code_level(message,
signal_names,
variable_lines,
helper_kinds):
"""Format one unpack level in a signal tree.
"""
body_lines = []
muxes_lines = []
for signal_name in signal_names:
... | 32,711 |
def find_phones():
"""
This function broadcasts on the LAN to the Shexter ports, and looks for a reply from a phone.
:return: (IP, Port) tuple representing the phone the user selects. None if no phone found.
"""
sock_sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock_sender.set... | 32,712 |
def fileGDB_schema() -> StructType:
"""Schema for dummy FileGDB."""
return StructType(
[
StructField("id", LongType()),
StructField("category", StringType()),
StructField("geometry", BinaryType()),
]
) | 32,713 |
def set_atom_stereo_parities(sgr, atm_par_dct):
""" set atom parities
"""
atm_dct = mdict.set_by_key_by_position(atoms(sgr), atm_par_dct,
ATM_STE_PAR_POS)
return _create.from_atoms_and_bonds(atm_dct, bonds(sgr)) | 32,714 |
def clean(expr):
"""
cleans up an expression string
Arguments:
expr: string, expression
"""
expr = expr.replace("^", "**")
return expr | 32,715 |
def atom_stereo_keys(sgr):
""" keys to atom stereo-centers
"""
atm_ste_keys = dict_.keys_by_value(_atom_stereo_parities(sgr),
lambda x: x in [True, False])
return atm_ste_keys | 32,716 |
def scale(query, pdfs):
"""Scale PDF files to a given page size."""
try:
for pdf in pdfs:
reader = PdfFileReader(pdf, strict=False)
if reader.isEncrypted:
raise FileEncryptedError
writer = PdfFileWriter()
w, h = [float(i) * 72 for i in q... | 32,717 |
def get_node_rd(graph, k=3):
"""
Get k nodes to defend based on Recalculated Degree (RD) Removal :cite:`holme2002attack`.
:param graph: an undirected NetworkX graph
:param k: number of nodes to defend
:return: a list of nodes to defend
"""
return get_node_rd_attack(graph, k) | 32,718 |
def get_frog():
"""Returns the interface object to frog NLP. (There should only be one
instance, because it spawns a frog process that consumes a lot of RAM.)
"""
global FROG
if FROG is None:
FROG = frog.Frog(frog.FrogOptions(
tok=True, lemma=True, morph=False, daringmorph=False,... | 32,719 |
def fetch(url: str, **kwargs) -> Selector:
"""
Send HTTP request and parse it as a DOM selector.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
... | 32,720 |
def calc_most_populare_per_company(df):
"""Counts the number of the same car ordered by
each company to find the most populare one per company
Arguments:
df {dict} -- A pandas dataframe which is a dict-like container for series.
"""
header_text = "Table 3: Most populare car per company... | 32,721 |
def growth(x, a, b):
""" Growth model. a is the value at t=0. b is the so-called R number.
Doesnt work. FIX IT """
return np.power(a * 0.5, (x / (4 * (math.log(0.5) / math.log(b))))) | 32,722 |
def __to_localdatetime(val):
"""Convert val into a local datetime for tz Europe/Amsterdam."""
try:
# "timestamp": "2019-02-03T19:20:00",
dt = datetime.strptime(val, __DATE_FORMAT)
dt = pytz.timezone(__TIMEZONE).localize(dt)
return dt
except (ValueError, TypeError):
r... | 32,723 |
def skip_pfcwd_test(duthost, trigger_pfcwd):
"""
Skip PFC watchdog tests that may cause fake alerts
PFC watchdog on Broadcom devices use some approximation techniques to detect
PFC storms, which may cause some fake alerts. Therefore, we skip test cases
whose trigger_pfcwd is False for Broadcom devi... | 32,724 |
def imgMinMaxScaler(img, scale_range):
"""
:param img: image to be rescaled
:param scale_range: (tuple) (min, max) of the desired rescaling
"""
warnings.filterwarnings("ignore")
img = img.astype("float64")
img_std = (img - np.min(img)) / (np.max(img) - np.min(img))
img_scaled = img_std *... | 32,725 |
def conditional_vff(Xnew, inducing_variable, kernel, f, *,
full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
- Xnew are the points of the data or minibatch, size N x D (tf.array, 2d)
- feat is an instance of features.InducingFeature that provides `Kuu` and `Kuf` met... | 32,726 |
def compute_stat(a_basedata_dir, a_dir1, a_dir2, a_ptrn="",
a_cmp=BINARY_OVERLAP):
"""Compare markables in two annotation directories.
Args:
a_basedata_dir (str): directory containing basedata for MMAX project
a_dir1 (str): directory containing markables for the first annotator
a_d... | 32,727 |
def gtzan_music_speech_download(dst='gtzan_music_speech'):
"""Download the GTZAN music and speech dataset.
Parameters
----------
dst : str, optional
Location to put the GTZAN music and speech datset.
"""
path = 'http://opihi.cs.uvic.ca/sound/music_speech.tar.gz'
download_and_extract... | 32,728 |
def xor(text, key):
"""Returns the given string XORed with given key."""
while len(key) < len(text): key += key
key = key[:len(text)]
return "".join(chr(ord(a) ^ ord(b)) for (a, b) in zip(text, key)) | 32,729 |
def get_emojis_voc_counts(path):
"""
Generate a value count of words for every emoji present in the csv files
found in the child directories of "path"
Args:
path (str): parent path of the csv files
Return:
em2vocab [dict of dict]: a dict associating each word to its count is mapped... | 32,730 |
async def test_camera_snapshot_connection_closed(driver):
"""Test camera snapshot when the other side closes the connection."""
loop = MagicMock()
transport = MagicMock()
transport.is_closing = Mock(return_value=True)
connections = {}
async def _async_get_snapshot(*_):
return b"fakesnap... | 32,731 |
def test_create_influxdb_sink() -> None:
"""Test create influxdb-sink connector with default configuration."""
runner = CliRunner()
result = runner.invoke(
main, ["create", "influxdb-sink", "--dry-run", "t1"]
)
assert result.exit_code == 0
# This query is built by InfluxConfig.update_inf... | 32,732 |
def write_pic(svg_path, filebuffer, picture_width, picture_height, vbox_h, mcv):
"""Write picture data."""
if os.path.isfile(TEMPLATE_PATH_1):
template_file = TEMPLATE_PATH_1
elif os.path.isfile(TEMPLATE_PATH_2):
template_file = TEMPLATE_PATH_2
else:
sys.exit(f"Error! Cannot loca... | 32,733 |
def test_requisites_watch_any(state, state_tree):
"""
Call sls file containing several require_in and require.
Ensure that some of them are failing and that the order is right.
"""
if salt.utils.platform.is_windows():
cmd_true = "exit"
cmd_false = "exit /B 1"
else:
cmd_t... | 32,734 |
def _as_scalar(res, dtype=None):
"""Return None or a TensorVariable whose type is in T.float_scalar_types"""
if dtype is None:
dtype = config.floatX
if numpy.all(res.type.broadcastable):
while res.owner and isinstance(res.owner.op, T.DimShuffle):
res = res.owner.inputs[0]
... | 32,735 |
def partition_dataset():
""" Partitioning MNIST """
dataset = datasets.MNIST(
'./data',
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307, ), (0.3081, ))
]))
size = dist.get_world_size... | 32,736 |
def add_size_to_nus(demo_graph, pop, time_left):
"""
adds either nu, or [nu0, growth_rate], where nu0 is the size at the beginning of the epoch
use time_left to set nu0 to the size at the beginning of the epoch
"""
if 'nu' in demo_graph.nodes[pop]:
return demo_graph.nodes[pop]['nu']
else... | 32,737 |
def _rand_lognormals(logs, sigma):
"""Mock-point"""
return np.random.lognormal(mean=logs, sigma=sigma, size=logs.shape) | 32,738 |
def hostMicContinuous():
"""
Sample continuous from host mic
"""
import sounddevice as sd
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
sd.default.samplerate = fs
sd.default.channels = 1
threshold = 0.8
mic_data = np.array([], dtype='int16')
net_input = np.array([], dtype='int16')
init =... | 32,739 |
def add_start_end_qualifiers(statement, startVal, endVal):
"""Add start/end qualifiers to a statement if non-None, or return None.
@param statement: The statement to decorate
@type statement: WD.Statement
@param startVal: An ISO date string for the starting point
@type startVal: str, unicode, or No... | 32,740 |
def _CheckFilter(text):
"""CHecks if a string could be a filter.
@rtype: bool
"""
return bool(frozenset(text) & FILTER_DETECTION_CHARS) | 32,741 |
def test_check_axis_angle():
"""Test input validation for axis-angle representation."""
a_list = [1, 0, 0, 0]
a = pr.check_axis_angle(a_list)
assert_array_almost_equal(a_list, a)
assert_equal(type(a), np.ndarray)
assert_equal(a.dtype, np.float64)
random_state = np.random.RandomState(0)
... | 32,742 |
def listProxyServers():
"""return a list of proxy servers as a list of lists.
E.g. [['nodename','proxyname'], ['nodename','proxyname']].
Typical usage:
for (nodename,proxyname) in listProxyServers():
callSomething(nodename,proxyname)
"""
return listServersOfType("PROXY_SERVER") | 32,743 |
def test_blackbody_emission_value_array():
"""Tests the return value given a temperature array."""
emission = blackbody_emission(TEMPERATURE_ARRAY, FREQUENCY)
true_values = np.array([1.82147825366e-15, 3.06550295038e-15, 3.78860400626e-15])
assert emission == pytest.approx(true_values, abs=1e-20) | 32,744 |
def api_version(func):
"""
API版本验证装饰器
:param func:
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
# 验证api版本
verify_result = verify_version(kwargs.get('version'))
if not verify_result:
raise ApiVersionException() #抛出异常,返回结果状态码400, message:api versi... | 32,745 |
def test_prewitt_h_horizontal():
"""Horizontal prewitt on an edge should be a horizontal line."""
i, j = np.mgrid[-5:6, -5:6]
image = (i >= 0).astype(float)
result = filters.prewitt_h(image)
# Check if result match transform direction
assert (np.all(result[i == 0] == 1))
assert_allclose(resu... | 32,746 |
def count_words(filename):
"""Count the approximate number of words in a file."""
try:
with open(filename, 'r', encoding='utf-8') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
... | 32,747 |
def is_prefix(a: List[Union[int, str]], b: List[Union[int, str]]):
"""Check if `a` is a prefix of `b`."""
if len(a) >= len(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
return False
return True | 32,748 |
def shm_data_find(ifo, ldr_type, start, stride, directory='.', verbose=False):
"""a routine to automate discovery of frames within /dev/shm
"""
end = start+stride
frames = []
for frame in sorted(glob.glob(shm_glob_tmp%(directory, ifo, ifo, ldr_type))):
s, d = utils.extract_start_dur(frame,... | 32,749 |
def backward_inference(protocol, subsys_x, t_x, subsys_y, t_y, silent=True):
"""
Forward inference answers the question:
Given a measurement result of 'subsys_y' at the end of the protocol,
what can I say about the result an Agent would have received had she done
a measurement of 'subsys_x' before t... | 32,750 |
def rainfall_interception_hbv(Rainfall, PotEvaporation, Cmax, InterceptionStorage):
"""
Returns:
TF, Interception, IntEvap,InterceptionStorage
"""
Interception = pcr.min(
Rainfall, Cmax - InterceptionStorage
) #: Interception in mm/timestep
InterceptionStorage = (
Intercept... | 32,751 |
def learn_mspn(
data,
ds_context,
cols="rdc",
rows="kmeans",
min_instances_slice=200,
threshold=0.3,
max_sampling_threshold_cols=10000,
max_sampling_threshold_rows=100000,
ohe=False,
leaves=None,
memory=None,
ran... | 32,752 |
def _sanitize_filename(dfile, no_symlink=True):
"""Check and sanitize 'dfile' for use as a target file.
"""
dirname, basename = os.path.split(dfile)
dirname = os.path.abspath(dirname)
dfile = os.path.join(dirname, basename)
if no_symlink:
if os.path.islink(dfile):
msg = ('{}... | 32,753 |
def _get_replies(
base_path: Path, message: Dict[str, Any], channel_id: str, channel_info: str
) -> None:
"""
リプライメッセージを取得
Parameters
----------
base_path : Path
出力先のBaseとなるPath
message : Dict[str, Any]
メッセージ情報
channel_id : str
チャンネルID
channel_info : str
... | 32,754 |
def generate_image_anim(img, interval=200, save_path=None):
"""
Given CT img, return an animation across axial slice
img: [D,H,W] or [D,H,W,3]
interval: interval between each slice, default 200
save_path: path to save the animation if not None, default None
return: matplotlib.animation.Animatio... | 32,755 |
def get_routes(config, prefix=None, group_by=None):
"""Executes the helper script that extracts the routes out of the
pyramid app."""
python = sys.executable
script = os.path.join(os.path.dirname(__file__), "extract.py")
config = os.path.expanduser(config)
args = [python, script, config]
if ... | 32,756 |
def square_root(s):
""" Function to compute square roots using the Babylonian method
"""
x = s/2
while True:
temp = x
x = (1/2) * ( x + (s/x) )
if temp == x:
return x
# Como la convergencia se alcanza rápidamente, llega un momento en que el error
# e... | 32,757 |
def quisort(uslist, lo=None, hi=None):
"""Sort in-place an unsorted list or slice of a list
lo and hi correspond to the start and stop indices for the list slice"""
if hi is None:
hi = len(uslist) - 1
if lo is None:
lo = 0
def partition(uslist, lo, hi):
"""Compare and swap... | 32,758 |
def datetime_range(datetime_start, datetime_end, step_timedelta):
"""Yield a datetime range, in the range [datetime_start; datetime_end[,
with step step_timedelta."""
assert_is_utc_datetime(datetime_start)
assert_is_utc_datetime(datetime_end)
ras(isinstance(step_timedelta, datetime.timedelta))
r... | 32,759 |
def is_generator(f):
"""Return True if a function is a generator."""
isgen = (f.__code__.co_flags & CO_GENERATOR) != 0
return isgen | 32,760 |
def reward(sample_solution, use_cuda=True, name='reward'):
"""
Args:
sample_solution seq_len of [batch_size]
"""
'''
if 'TSP' in name:
batch_size = sample_solution[0].size(0)
n = len(sample_solution)
tour_len = Variable(torch.zeros([batch_size]))
i... | 32,761 |
def addRegionEntry(Id: int, parentId: int, name: str, RegionType: RegionType, alias=''):
"""
添加自定义地址信息
:param Id: 地址的ID
:param parentId: 地址的父ID, 必须存在
:param name: 地址的名称
:param RegionType: 地址类型,RegionType,
:param alias: 地址的别名, default=''
:return:
"""
geocoding = jpype.JClass('io.... | 32,762 |
def check_movement(pagination):
"""Check for ability to navigate backward or forward between pages."""
pagination_movements = pagination.find_element_by_xpath(
'.//div[@class="search_pagination_right"]'
).find_elements_by_class_name("pagebtn")
# Check for ability to move back
try:
mo... | 32,763 |
def glint_correct_image(imarr, glintarr, nir_band=7):
"""
Apply the sunglint removal algorithm from section III of Lyzenga et al.
2006 to a multispectral image array.
Parameters
----------
imarr : numpy array (RxCxBands shape)
The multispectral image array. See `OpticalRS.RasterDS` for ... | 32,764 |
def draw_reconstructions(ins, outs, states, shape_in, shape_state, Nh):
"""Vizualizacija ulaza i pripadajucih rekonstrkcija i stanja skrivenog sloja
ins -- ualzni vektori
outs -- rekonstruirani vektori
states -- vektori stanja skrivenog sloja
shape_in -- dimezije ulaznih slika npr. (28,28)
shape... | 32,765 |
def get_named_game(id):
"""Get specific game from GB API."""
query_uri = f"{GB_GAME_URL}{id}?format=json&api_key={API_KEY}"
return query_for_goty(query_uri, expect_list=False, always_return_something=False) | 32,766 |
def isoweek_datetime(year, week, timezone='UTC', naive=False):
"""
Returns a datetime matching the starting point of a specified ISO week
in the specified timezone (default UTC). Returns a naive datetime in
UTC if requested (default False).
>>> isoweek_datetime(2017, 1)
datetime.datetime(2017, ... | 32,767 |
def mkdirs(path, filepath=None):
"""
mkdirs(path)
Make directory tree for path. If path is a file with an extention, only the folders are created.
Parameters
----------
path: str
Full path as directory tree or file
filepath: bool
Force to think of path as a file (happens al... | 32,768 |
def map_new_program_rest_to_new_control_rest(request):
"""Map Control to Program object via REST API return response from server.
"""
yield _common_fixtures(request.fixturename) | 32,769 |
def test_config_check(global_integration_cli_args, local_config):
"""
:type global_integration_cli_args: tuple[str]
:type local_config: datacube.config.LocalConfig
"""
# This is not a very thorough check, we just check to see that
# it prints something vaguely related and does not error-out.
... | 32,770 |
def returned(n):
"""Generate a random walk and return True if the walker has returned to
the origin after taking `n` steps.
"""
## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk
for pos in randwalk() >> drop(1) >> takei(xrange(n-1)):
if pos == Origin:
return True
return... | 32,771 |
def test_trie_can_insert_str(trie):
"""Test if we can insert str into tree."""
trie.insert('hello')
assert trie.contains('hello') | 32,772 |
def get_ego_as_agent(frame: np.ndarray) -> np.ndarray:
"""Get a valid agent with information from the AV. Ford Fusion extent is used.
:param frame: The frame from which the Ego states are extracted
:return: An agent numpy array of the Ego states
"""
ego_agent = np.zeros(1, dtype=AGENT_DTYPE)
eg... | 32,773 |
def _handle_get_api_stream(handler, path_match, data):
""" Provide a streaming interface for the event bus. """
gracefully_closed = False
hass = handler.server.hass
wfile = handler.wfile
write_lock = threading.Lock()
block = threading.Event()
restrict = data.get('restrict')
if restrict:... | 32,774 |
def import_dir(path):
"""
imports all XML files in the given directory
"""
# to speed up the import, we disable indexing during the import and only
# rebuild the index at afterwards
os.environ['DISABLE_INDEXING_DURING_IMPORT'] = 'True'
_files = os.listdir(path)
for _file in _files:
... | 32,775 |
def load_users(dir="private/users"):
"""load_users will load up all of the user json files in the dir."""
files = get_files_in_dir(dir)
dict = {}
for filename in files:
user = {}
filepath = join(dir, filename)
with open(filepath) as file:
try:
user = j... | 32,776 |
def _scale_annots_dict(annot, new_sz, ann_im_sz):
"""Scale annotations to the new_sz, provided the original ann_im_sz.
:param annot: bounding box in dict format
:param new_sz: new size of image (after linear transforms like resize)
:param ann_im_sz: original size of image for which the bounding boxes we... | 32,777 |
def test_process_children(cbcsdk_mock, get_summary_response, guid, expected_num_children):
"""Testing Process.children property."""
# mock the search validation
cbcsdk_mock.mock_request("GET", "/api/investigate/v1/orgs/test/processes/search_validation",
GET_PROCESS_VALIDATION_RE... | 32,778 |
def get_handlers_in_instance(inst: Any) -> Tuple[List[Handler], List[Handler]]:
"""Get all handlers from the members of an instance.
Args:
inst: Instance to get handlers from.
Returns:
2-tuple containing the list of all registration and all subscription
handlers.
Raises:
... | 32,779 |
def list(show_deleted: bool, verbose: bool):
"""
List submitted jobs.
Note that, in the non-verbose output, `Last Result` is reporting according to
whether Automate could successfully submit the job. It's possible for Transfer
to run into errors attempting to run your submission, which timer/Automa... | 32,780 |
def django_op_to_flag(op):
"""
Converts a django admin operation string to the matching
grainy permission flag
Arguments:
- op <str>
Returns:
- int
"""
return DJANGO_OP_TO_FLAG.get(op, 0) | 32,781 |
def rgb2gray(images):
"""将RGB图像转为灰度图"""
# Y' = 0.299 R + 0.587 G + 0.114 B
# https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
return np.dot(images[..., :3], [0.299, 0.587, 0.114]) | 32,782 |
def suppress_tensorflow_warnings():
"""
Suppresses tensorflow warnings
"""
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "1"
_tf = _minimal_package_import_check("tensorflow.compat.v1")
_tf.logging.set_verbosity(_tf.logging.ERROR)
_tf.debugging.set_log_device_placement(False) | 32,783 |
def wav2vec2_local(ckpt, *args, **kwargs):
"""
The model from local ckpt
ckpt (str): PATH
"""
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs) | 32,784 |
def mIou(y_true, y_pred, n_classes):
"""
Mean Intersect over Union metric.
Computes the one versus all IoU for each class and returns the average.
Classes that do not appear in the provided set are not counted in the average.
Args:
y_true (1D-array): True labels
y_pred (1D-array): Pr... | 32,785 |
def drop_last(iterable, n=1):
"""Drops the last item of iterable"""
t1, t2 = tee(iterable)
return map(operator.itemgetter(0), zip(t1, islice(t2, n, None))) | 32,786 |
def assert_called_once_with(mocked, *args, **kwargs):
"""Safe convenient methods for mock asserts"""
assert_called_once(mocked)
assert mocked.call_args == mock.call(*args, **kwargs) | 32,787 |
def density(height: float) -> float:
"""
Returns the air density in slug/ft^3 based on altitude
Equations from https://www.grc.nasa.gov/www/k-12/rocket/atmos.html
:param height: Altitude in feet
:return: Density in slugs/ft^3
"""
if height < 36152.0:
temp = 59 - 0.00356 * height
... | 32,788 |
def parse(opts):
"""
Entry point for XML Schema parsing into an OME Model.
"""
# The following two statements are required to "prime" the generateDS
# code and ensure we have reasonable namespace support.
filenames = opts.args
namespace = opts.namespace
schemas = dict()
logging.deb... | 32,789 |
async def test_sensor(hass, stream_reader_writer):
"""Test that sensor works."""
with patch("asyncio.StreamWriter.close", return_value=None), patch(
"asyncio.open_connection",
return_value=stream_reader_writer,
), patch(
"FoldingAtHomeControl.serialconnection.SerialConnection.send_as... | 32,790 |
def has_paired_before() -> bool:
"""Simple check for whether a device has previously been paired.
This does not verify that the pairing information is valid or up to date.
The assumption being - if it's previously paired, then it has previously
connected to the internet.
"""
identity = Identity... | 32,791 |
def caller_linkedin(user_input: dict) -> dict:
"""
Call LinkedIn scraping methods to get info about found and potential subjects.
Args:
`user_input`: user input represented as a dictionary.
Returns:
`dict`: the dictionary with information about found or potential subjects.
"""
r... | 32,792 |
def service_request_eqf(stub_response):
"""
Return a function to be used as the value matching a ServiceRequest in
:class:`EQFDispatcher`.
"""
def resolve_service_request(service_request_intent):
eff = concretize_service_request(
authenticator=object(),
log=object(),
... | 32,793 |
def ScheduleTestPlanCronJob(test_plan_id):
"""Schedules a cron job for a test plan.
If the test plan is not for cron, no cron job will be scheduled.
Args:
test_plan_id: a test plan ID.
"""
test_plan_kicker.ScheduleCronKick(test_plan_id) | 32,794 |
def get_nearest_point_distance(points, wire1, wire2):
"""
>>> get_nearest_point_distance([(0, 0), (158, -12), (146, 46), (155, 4), (155, 11)], [((0, 0), (75, 0)), ((75, 0), (75, -30)), ((75, -30), (158, -30)), ((158, -30), (158, 53)), ((158, 53), (146, 53)), ((146, 53), (146, 4)), ((146, 4), (217, 4)), ((217, 4... | 32,795 |
def sample_hyperparameters():
"""
Yield possible hyperparameter choices.
"""
while True:
yield {
"rnn_size": np.random.choice([64, 128, 256]).item(),
"learning_schedule": np.random.choice(["RMSprop", "adagrad", "adam"]).item(),
"grad_clip": np.random.uniform(... | 32,796 |
def strip_tokens(tokenized: str) -> str:
"""Replaces all tokens with the token's arguments."""
result = []
pos = 0
match = RX_TOKEN.search(tokenized, pos)
while match:
start, end = match.span()
result.append(tokenized[pos:start])
result.append(match.groupdict()['argument'])
... | 32,797 |
def test_check_orders_new_order_above_our(worker, other_orders):
""" Someone put order above ours, own order must be moved
"""
worker2 = other_orders
worker.place_orders()
own_buy_orders = worker.get_own_buy_orders()
own_sell_orders = worker.get_own_sell_orders()
log.debug('KOTH orders: {}'... | 32,798 |
def circular(P=365, K=0.1, T=0, gamma=0, t=None):
"""
circular() simulates the radial velocity signal of a planet in a
circular orbit around a star.
The algorithm needs improvements.
Parameters:
P = period in days
K = semi-amplitude of the signal
T = velocity at zero phase... | 32,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.