file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
Chevron.test.tsx | /**
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Chevron from './Chevron';
describe('<Chevron />', () => {
describe('default', () => {
it('renders correctly', () => {
const { container, rerender } = render(<Chevron direction="down" />);
const chevron = container.firstChild as HTMLElement;
expect(chevron.tagName.toLowerCase()).toBe('svg');
expect(chevron.classList.contains('chevron')).toBe(true);
rerender(<Chevron direction="up" />);
expect(chevron.classList.contains('chevron_up')).toBe(true);
rerender(<Chevron direction="left" />);
expect(chevron.classList.contains('chevron_left')).toBe(true);
rerender(<Chevron direction="right" />);
expect(chevron.classList.contains('chevron_right')).toBe(true);
rerender(<Chevron direction="down" animate={true} />);
expect(chevron.classList.contains('chevron_animated')).toBe(true);
});
});
describe('with wrapper', () => {
it('renders correctly', () => {
const wrapperClass = 'this_is_wrapper_class';
const iconClass = 'this_is_icon_class';
const { container } = render(
<Chevron
direction="down"
classNames={{ wrapper: wrapperClass, svg: iconClass }}
/>
); | expect(chevron.tagName.toLowerCase()).toBe('svg');
expect(chevronWrapper.classList.contains(wrapperClass)).toBe(true);
expect(chevron.classList.contains(iconClass)).toBe(true);
});
});
describe('as a button', () => {
it('renders correctly', () => {
const wrapperClass = 'this_is_wrapper_class';
const iconClass = 'this_is_icon_class';
const { container } = render(
<Chevron
direction="down"
onClick={jest.fn()}
classNames={{ wrapper: wrapperClass, svg: iconClass }}
/>
);
const chevronButton = container.firstChild as HTMLElement;
const chevron = chevronButton.firstChild as HTMLElement;
expect(chevronButton.tagName.toLowerCase()).toBe('button');
expect(chevron.tagName.toLowerCase()).toBe('svg');
expect(chevronButton.classList.contains(wrapperClass)).toBe(true);
expect(chevron.classList.contains(iconClass)).toBe(true);
});
it('registers clicks', () => {
const clickHandler = jest.fn();
const { container } = render(
<Chevron direction="down" onClick={clickHandler} />
);
const chevronButton = container.firstChild as HTMLElement;
userEvent.click(chevronButton);
expect(clickHandler).toHaveBeenCalledTimes(1);
});
});
}); | const chevronWrapper = container.firstChild as HTMLElement;
const chevron = chevronWrapper.firstChild as HTMLElement;
expect(chevronWrapper.tagName.toLowerCase()).toBe('span'); |
unit.rs | use cranelift_wasm::DefinedFuncIndex;
use failure::Error;
use std::collections::HashMap;
use wasmtime_environ::{ModuleVmctxInfo, ValueLabelsRanges};
use gimli;
use gimli::{AttributeValue, DebuggingInformationEntry, Unit, UnitOffset};
use gimli::write;
use super::address_transform::AddressTransform;
use super::attr::{clone_die_attributes, FileAttributeContext};
use super::expression::{compile_expression, CompiledExpression, FunctionFrameInfo};
use super::line_program::clone_line_program;
use super::range_info_builder::RangeInfoBuilder;
use super::{DebugInputContext, Reader, TransformError};
pub(crate) type PendingDieRef = (write::UnitEntryId, gimli::DwAt, UnitOffset);
struct InheritedAttr<T> {
stack: Vec<(usize, T)>,
}
impl<T> InheritedAttr<T> {
fn new() -> Self |
fn update(&mut self, depth: usize) {
while !self.stack.is_empty() && self.stack.last().unwrap().0 >= depth {
self.stack.pop();
}
}
fn push(&mut self, depth: usize, value: T) {
self.stack.push((depth, value));
}
fn top(&self) -> Option<&T> {
self.stack.last().map(|entry| &entry.1)
}
fn is_empty(&self) -> bool {
self.stack.is_empty()
}
}
fn get_function_frame_info<'a, 'b, 'c>(
module_info: &'b ModuleVmctxInfo,
func_index: DefinedFuncIndex,
value_ranges: &'c ValueLabelsRanges,
) -> Option<FunctionFrameInfo<'a>>
where
'b: 'a,
'c: 'a,
{
if let Some(value_ranges) = value_ranges.get(func_index) {
let frame_info = FunctionFrameInfo {
value_ranges,
memory_offset: module_info.memory_offset,
stack_slots: &module_info.stack_slots[func_index],
};
Some(frame_info)
} else {
None
}
}
fn add_internal_types(
comp_unit: &mut write::Unit,
root_id: write::UnitEntryId,
out_strings: &mut write::StringTable,
module_info: &ModuleVmctxInfo,
) -> (write::UnitEntryId, write::UnitEntryId) {
let wp_die_id = comp_unit.add(root_id, gimli::DW_TAG_base_type);
let wp_die = comp_unit.get_mut(wp_die_id);
wp_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("WebAssemblyPtr")),
);
wp_die.set(gimli::DW_AT_byte_size, write::AttributeValue::Data1(4));
wp_die.set(
gimli::DW_AT_encoding,
write::AttributeValue::Encoding(gimli::DW_ATE_unsigned),
);
let memory_byte_die_id = comp_unit.add(root_id, gimli::DW_TAG_base_type);
let memory_byte_die = comp_unit.get_mut(memory_byte_die_id);
memory_byte_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("u8")),
);
memory_byte_die.set(
gimli::DW_AT_encoding,
write::AttributeValue::Encoding(gimli::DW_ATE_unsigned),
);
memory_byte_die.set(gimli::DW_AT_byte_size, write::AttributeValue::Data1(1));
let memory_bytes_die_id = comp_unit.add(root_id, gimli::DW_TAG_pointer_type);
let memory_bytes_die = comp_unit.get_mut(memory_bytes_die_id);
memory_bytes_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("u8*")),
);
memory_bytes_die.set(
gimli::DW_AT_type,
write::AttributeValue::ThisUnitEntryRef(memory_byte_die_id),
);
let memory_offset = module_info.memory_offset;
let vmctx_die_id = comp_unit.add(root_id, gimli::DW_TAG_structure_type);
let vmctx_die = comp_unit.get_mut(vmctx_die_id);
vmctx_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("WasmtimeVMContext")),
);
vmctx_die.set(
gimli::DW_AT_byte_size,
write::AttributeValue::Data4(memory_offset as u32 + 8),
);
let m_die_id = comp_unit.add(vmctx_die_id, gimli::DW_TAG_member);
let m_die = comp_unit.get_mut(m_die_id);
m_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("memory")),
);
m_die.set(
gimli::DW_AT_type,
write::AttributeValue::ThisUnitEntryRef(memory_bytes_die_id),
);
m_die.set(
gimli::DW_AT_data_member_location,
write::AttributeValue::Udata(memory_offset as u64),
);
let vmctx_ptr_die_id = comp_unit.add(root_id, gimli::DW_TAG_pointer_type);
let vmctx_ptr_die = comp_unit.get_mut(vmctx_ptr_die_id);
vmctx_ptr_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("WasmtimeVMContext*")),
);
vmctx_ptr_die.set(
gimli::DW_AT_type,
write::AttributeValue::ThisUnitEntryRef(vmctx_die_id),
);
(wp_die_id, vmctx_ptr_die_id)
}
fn get_base_type_name<R>(
type_entry: &DebuggingInformationEntry<R>,
unit: &Unit<R, R::Offset>,
context: &DebugInputContext<R>,
) -> Result<String, Error>
where
R: Reader,
{
// FIXME remove recursion.
match type_entry.attr_value(gimli::DW_AT_type)? {
Some(AttributeValue::UnitRef(ref offset)) => {
let mut entries = unit.entries_at_offset(*offset)?;
entries.next_entry()?;
if let Some(die) = entries.current() {
if let Some(AttributeValue::DebugStrRef(str_offset)) =
die.attr_value(gimli::DW_AT_name)?
{
return Ok(String::from(
context.debug_str.get_str(str_offset)?.to_string()?,
));
}
match die.tag() {
gimli::DW_TAG_const_type => {
return Ok(format!("const {}", get_base_type_name(die, unit, context)?));
}
gimli::DW_TAG_pointer_type => {
return Ok(format!("{}*", get_base_type_name(die, unit, context)?));
}
gimli::DW_TAG_reference_type => {
return Ok(format!("{}&", get_base_type_name(die, unit, context)?));
}
gimli::DW_TAG_array_type => {
return Ok(format!("{}[]", get_base_type_name(die, unit, context)?));
}
_ => (),
}
}
}
_ => (),
};
Ok(String::from("??"))
}
fn replace_pointer_type<R>(
parent_id: write::UnitEntryId,
comp_unit: &mut write::Unit,
wp_die_id: write::UnitEntryId,
entry: &DebuggingInformationEntry<R>,
unit: &Unit<R, R::Offset>,
context: &DebugInputContext<R>,
out_strings: &mut write::StringTable,
pending_die_refs: &mut Vec<(write::UnitEntryId, gimli::DwAt, UnitOffset)>,
) -> Result<write::UnitEntryId, Error>
where
R: Reader,
{
let die_id = comp_unit.add(parent_id, gimli::DW_TAG_structure_type);
let die = comp_unit.get_mut(die_id);
let name = format!(
"WebAssemblyPtrWrapper<{}>",
get_base_type_name(entry, unit, context)?
);
die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add(name.as_str())),
);
die.set(gimli::DW_AT_byte_size, write::AttributeValue::Data1(4));
let p_die_id = comp_unit.add(die_id, gimli::DW_TAG_template_type_parameter);
let p_die = comp_unit.get_mut(p_die_id);
p_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("T")),
);
p_die.set(
gimli::DW_AT_type,
write::AttributeValue::ThisUnitEntryRef(wp_die_id),
);
match entry.attr_value(gimli::DW_AT_type)? {
Some(AttributeValue::UnitRef(ref offset)) => {
pending_die_refs.push((p_die_id, gimli::DW_AT_type, *offset))
}
_ => (),
}
let m_die_id = comp_unit.add(die_id, gimli::DW_TAG_member);
let m_die = comp_unit.get_mut(m_die_id);
m_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("__ptr")),
);
m_die.set(
gimli::DW_AT_type,
write::AttributeValue::ThisUnitEntryRef(wp_die_id),
);
m_die.set(
gimli::DW_AT_data_member_location,
write::AttributeValue::Data1(0),
);
Ok(die_id)
}
fn append_vmctx_info(
comp_unit: &mut write::Unit,
parent_id: write::UnitEntryId,
vmctx_die_id: write::UnitEntryId,
addr_tr: &AddressTransform,
frame_info: Option<&FunctionFrameInfo>,
scope_ranges: &[(u64, u64)],
out_strings: &mut write::StringTable,
) -> Result<(), Error> {
let loc = {
let endian = gimli::RunTimeEndian::Little;
let expr = CompiledExpression::vmctx();
let mut locs = Vec::new();
for (begin, length, data) in
expr.build_with_locals(scope_ranges, addr_tr, frame_info, endian)
{
locs.push(write::Location::StartLength {
begin,
length,
data,
});
}
let list_id = comp_unit.locations.add(write::LocationList(locs));
write::AttributeValue::LocationListRef(list_id)
};
let var_die_id = comp_unit.add(parent_id, gimli::DW_TAG_variable);
let var_die = comp_unit.get_mut(var_die_id);
var_die.set(
gimli::DW_AT_name,
write::AttributeValue::StringRef(out_strings.add("__vmctx")),
);
var_die.set(
gimli::DW_AT_type,
write::AttributeValue::ThisUnitEntryRef(vmctx_die_id),
);
var_die.set(gimli::DW_AT_location, loc);
Ok(())
}
pub(crate) fn clone_unit<'a, R>(
unit: Unit<R, R::Offset>,
context: &DebugInputContext<R>,
addr_tr: &'a AddressTransform,
value_ranges: &'a ValueLabelsRanges,
out_encoding: &gimli::Encoding,
module_info: &ModuleVmctxInfo,
out_units: &mut write::UnitTable,
out_strings: &mut write::StringTable,
) -> Result<(), Error>
where
R: Reader,
{
let mut die_ref_map = HashMap::new();
let mut pending_die_refs = Vec::new();
let mut stack = Vec::new();
// Iterate over all of this compilation unit's entries.
let mut entries = unit.entries();
let (mut comp_unit, file_map, cu_low_pc, wp_die_id, vmctx_die_id) =
if let Some((depth_delta, entry)) = entries.next_dfs()? {
assert!(depth_delta == 0);
let (out_line_program, debug_line_offset, file_map) = clone_line_program(
&unit,
entry,
addr_tr,
out_encoding,
context.debug_str,
context.debug_line,
out_strings,
)?;
if entry.tag() == gimli::DW_TAG_compile_unit {
let unit_id = out_units.add(write::Unit::new(*out_encoding, out_line_program));
let comp_unit = out_units.get_mut(unit_id);
let root_id = comp_unit.root();
die_ref_map.insert(entry.offset(), root_id);
let cu_low_pc = if let Some(AttributeValue::Addr(addr)) =
entry.attr_value(gimli::DW_AT_low_pc)?
{
addr
} else {
// FIXME? return Err(TransformError("No low_pc for unit header").into());
0
};
clone_die_attributes(
entry,
context,
addr_tr,
None,
&unit.encoding(),
comp_unit,
root_id,
None,
None,
cu_low_pc,
out_strings,
&die_ref_map,
&mut pending_die_refs,
FileAttributeContext::Root(Some(debug_line_offset)),
)?;
let (wp_die_id, vmctx_die_id) =
add_internal_types(comp_unit, root_id, out_strings, module_info);
stack.push(root_id);
(comp_unit, file_map, cu_low_pc, wp_die_id, vmctx_die_id)
} else {
return Err(TransformError("Unexpected unit header").into());
}
} else {
return Ok(()); // empty
};
let mut skip_at_depth = None;
let mut current_frame_base = InheritedAttr::new();
let mut current_value_range = InheritedAttr::new();
let mut current_scope_ranges = InheritedAttr::new();
while let Some((depth_delta, entry)) = entries.next_dfs()? {
let depth_delta = if let Some((depth, cached)) = skip_at_depth {
let new_depth = depth + depth_delta;
if new_depth > 0 {
skip_at_depth = Some((new_depth, cached));
continue;
}
skip_at_depth = None;
new_depth + cached
} else {
depth_delta
};
if !context
.reachable
.contains(&entry.offset().to_unit_section_offset(&unit))
{
// entry is not reachable: discarding all its info.
skip_at_depth = Some((0, depth_delta));
continue;
}
let new_stack_len = stack.len().wrapping_add(depth_delta as usize);
current_frame_base.update(new_stack_len);
current_scope_ranges.update(new_stack_len);
current_value_range.update(new_stack_len);
let range_builder = if entry.tag() == gimli::DW_TAG_subprogram {
let range_builder = RangeInfoBuilder::from_subprogram_die(
entry,
context,
&unit.encoding(),
addr_tr,
cu_low_pc,
)?;
if let RangeInfoBuilder::Function(func_index) = range_builder {
if let Some(frame_info) =
get_function_frame_info(module_info, func_index, value_ranges)
{
current_value_range.push(new_stack_len, frame_info);
}
current_scope_ranges.push(new_stack_len, range_builder.get_ranges(addr_tr));
Some(range_builder)
} else {
// FIXME current_scope_ranges.push()
None
}
} else {
let high_pc = entry.attr_value(gimli::DW_AT_high_pc)?;
let ranges = entry.attr_value(gimli::DW_AT_ranges)?;
if high_pc.is_some() || ranges.is_some() {
let range_builder =
RangeInfoBuilder::from(entry, context, &unit.encoding(), cu_low_pc)?;
current_scope_ranges.push(new_stack_len, range_builder.get_ranges(addr_tr));
Some(range_builder)
} else {
None
}
};
if depth_delta <= 0 {
for _ in depth_delta..1 {
stack.pop();
}
} else {
assert!(depth_delta == 1);
}
if let Some(AttributeValue::Exprloc(expr)) = entry.attr_value(gimli::DW_AT_frame_base)? {
if let Some(expr) = compile_expression(&expr, &unit.encoding(), None)? {
current_frame_base.push(new_stack_len, expr);
}
}
let parent = stack.last().unwrap();
if entry.tag() == gimli::DW_TAG_pointer_type {
// Wrap pointer types.
// TODO reference types?
let die_id = replace_pointer_type(
*parent,
comp_unit,
wp_die_id,
entry,
&unit,
context,
out_strings,
&mut pending_die_refs,
)?;
stack.push(die_id);
assert!(stack.len() == new_stack_len);
die_ref_map.insert(entry.offset(), die_id);
continue;
}
let die_id = comp_unit.add(*parent, entry.tag());
stack.push(die_id);
assert!(stack.len() == new_stack_len);
die_ref_map.insert(entry.offset(), die_id);
clone_die_attributes(
entry,
context,
addr_tr,
current_value_range.top(),
&unit.encoding(),
&mut comp_unit,
die_id,
range_builder,
current_scope_ranges.top(),
cu_low_pc,
out_strings,
&die_ref_map,
&mut pending_die_refs,
FileAttributeContext::Children(&file_map, current_frame_base.top()),
)?;
if entry.tag() == gimli::DW_TAG_subprogram && !current_scope_ranges.is_empty() {
append_vmctx_info(
comp_unit,
die_id,
vmctx_die_id,
addr_tr,
current_value_range.top(),
current_scope_ranges.top().expect("range"),
out_strings,
)?;
}
}
for (die_id, attr_name, offset) in pending_die_refs {
let die = comp_unit.get_mut(die_id);
if let Some(unit_id) = die_ref_map.get(&offset) {
die.set(attr_name, write::AttributeValue::ThisUnitEntryRef(*unit_id));
} else {
// TODO check why loosing DIEs
}
}
Ok(())
}
| {
InheritedAttr { stack: Vec::new() }
} |
blame_opt.py | #!/usr/bin/python3
###############################################################################
#
# Copyright (c) 2015-2020, Intel Corporation
# Copyright (c) 2019-2020, University of Utah
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
###############################################################################
"""
Experimental script for automatic sorting of errors, basing on failed optimization phase
"""
###############################################################################
import logging
import os
import re
import common
import gen_test_makefile
import run_gen
icc_blame_opts = ["-from_rtn=0 -to_rtn=", "-num_opt=", "-num-case="]
icc_opt_patterns = ["\(\d+\)", "\(\d+\)\s*\n", "DO ANOTHER.*\(\d+\)"]
icc_opt_name_prefix = "DOING\s*\[\w*\]\s*"
icc_opt_name_suffix = "\s*\(\d*\)\s*\(last opt\)"
icx_blame_opts = ["-mllvm -opt-bisect-limit="]
icx_opt_patterns = ["BISECT: running pass \(\d+\)"]
icx_opt_name_prefix = "BISECT: running pass \(\d+\) "
icx_opt_name_suffix = " \(.*\)"
clang_blame_opts = ["-mllvm -opt-bisect-limit="]
clang_opt_patterns = ["BISECT: running pass \(\d+\)"]
clang_opt_name_prefix = "BISECT: running pass \(\d+\) "
clang_opt_name_suffix = " \(.*\)"
dpcpp_gpu_blame_opts = ["IGC_ShaderDumpEnableAll=1 IGC_ShaderDisableOptPassesAfter="]
dpcpp_gpu_patterns = ["Skipping optimization pass: .* (threshold: \(\d+\))."]
dpcpp_gpu_opt_name_prefix = "Skipping optimization pass: '"
dpcpp_gpu_opt_name_suffix = "' \(.*\)."
compilers_blame_opts = {"icc": icc_blame_opts, "icx": icx_blame_opts, "clang": clang_blame_opts, "dpcpp": dpcpp_gpu_blame_opts}
compilers_blame_patterns = {"icc": icc_opt_patterns, "icx": icx_opt_patterns, "clang": clang_opt_patterns, "dpcpp": dpcpp_gpu_patterns}
compilers_opt_name_cutter = {"icc": [icc_opt_name_prefix, icc_opt_name_suffix], \
"icx": [icx_opt_name_prefix, icx_opt_name_suffix], \
"clang": [clang_opt_name_prefix, clang_opt_name_suffix], \
"dpcpp": [dpcpp_gpu_opt_name_prefix, dpcpp_gpu_opt_name_suffix]}
blame_test_makefile_name = "Blame_Makefile"
###############################################################################
def get_next_step(start, end, current, fail_flag):
if fail_flag:
next_start = start
next_current = (current - start) // 2 + start
next_end = current
else:
next_start = current
next_current = (end - current) // 2 + current
next_end = end
return next_start, next_end, next_current
def dump_exec_output(msg, ret_code, output, err_output, time_expired, num):
common.log_msg(logging.DEBUG, msg + " (process " + str(num) + ")")
common.log_msg(logging.DEBUG, "Ret code: " + str(ret_code) + " | process " + str(num))
common.log_msg(logging.DEBUG, "Time exp: " + str(time_expired) + " | process " + str(num))
common.log_msg(logging.DEBUG, "Output: " + str(output, "utf-8") + " | process " + str(num))
common.log_msg(logging.DEBUG, "Err output: " + str(err_output, "utf-8") + " | process " + str(num))
def execute_blame_phase(valid_res, fail_target, inject_str, num, phase_num):
gen_test_makefile.gen_makefile(
out_file_name = blame_test_makefile_name,
force = True,
config_file = None,
only_target = fail_target,
inject_blame_opt = inject_str + "-1" if fail_target.specs.name != "dpcpp" else None,
inject_blame_env = inject_str + "1" if fail_target.specs.name == "dpcpp" else None)
ret_code, output, err_output, time_expired, elapsed_time = \
common.run_cmd(["make", "-f", blame_test_makefile_name, fail_target.name], run_gen.compiler_timeout, num)
if fail_target.specs.name == "dpcpp":
ret_code, output, err_output, time_expired, elapsed_time = \
common.run_cmd(["make", "-f", blame_test_makefile_name, "run_" + fail_target.name], run_gen.compiler_timeout, num)
opt_num_regex = re.compile(compilers_blame_patterns[fail_target.specs.name][phase_num])
try:
if fail_target.specs.name == "dpcpp":
max_opt_num = 250
else:
matches = opt_num_regex.findall(str(err_output, "utf-8"))
# Some icc phases may not support going to phase "2", i.e. drilling down to num_case level,
# in this case we are done.
if phase_num == 2 and not matches:
return str(-1)
max_opt_num_str = matches[-1]
remove_brackets_pattern = re.compile("\d+")
max_opt_num = int(remove_brackets_pattern.findall(max_opt_num_str)[-1])
common.log_msg(logging.DEBUG, "Max opt num (process " + str(num) + "): " + str(max_opt_num))
except IndexError:
common.log_msg(logging.ERROR, "Can't decode max opt number using \"" + compilers_blame_patterns[fail_target.specs.name][phase_num]
+ "\" regexp (phase " + str(phase_num) + ") in the following output:\n" + str(err_output, "utf-8")
+ " (process " + str(num) + "): ")
raise
start_opt = 0
end_opt = max_opt_num
cur_opt = max_opt_num
failed_flag = True
time_to_finish = False
while not time_to_finish:
start_opt, end_opt, cur_opt = get_next_step(start_opt, end_opt, cur_opt, failed_flag)
common.log_msg(logging.DEBUG, "Previous failed (process " + str(num) + "): " + str(failed_flag))
failed_flag = False
eff = ((start_opt + 1) >= cur_opt) # Earliest fail was found
common.log_msg(logging.DEBUG, "Trying opt (process " + str(num) + "): " + str(start_opt) + "/" + str(cur_opt) + "/" + str(end_opt))
gen_test_makefile.gen_makefile(
out_file_name = blame_test_makefile_name,
force = True,
config_file = None,
only_target = fail_target,
inject_blame_opt = inject_str + str(cur_opt) if fail_target.specs.name != "dpcpp" else None,
inject_blame_env = inject_str + str(cur_opt) if fail_target.specs.name == "dpcpp" else None)
ret_code, output, err_output, time_expired, elapsed_time = \
common.run_cmd(["make", "-f", blame_test_makefile_name, fail_target.name], run_gen.compiler_timeout, num)
if time_expired or ret_code != 0:
dump_exec_output("Compilation failed", ret_code, output, err_output, time_expired, num)
failed_flag = True
if not eff:
continue
else:
break
ret_code, output, err_output, time_expired, elapsed_time = \
common.run_cmd(["make", "-f", blame_test_makefile_name, "run_" + fail_target.name], run_gen.run_timeout, num)
if time_expired or ret_code != 0:
dump_exec_output("Execution failed", ret_code, output, err_output, time_expired, num)
failed_flag = True
if not eff:
continue
else:
break
if str(output, "utf-8").split()[-1] != valid_res:
common.log_msg(logging.DEBUG, "Output differs (process " + str(num) + "): " + str(output, "utf-8").split()[-1] + " vs " + valid_res + " (expected)")
failed_flag = True
if not eff:
continue
else:
break
| time_to_finish = (eff and failed_flag) or (eff and not failed_flag and (cur_opt == (end_opt - 1)))
common.log_msg(logging.DEBUG, "Time to finish (process " + str(num) + "): " + str(time_to_finish))
if not failed_flag:
common.log_msg(logging.DEBUG, "Swapping current and end opt (process " + str(num) + ")")
cur_opt = end_opt
common.log_msg(logging.DEBUG, "Finished blame phase, result: " + str(inject_str) + str(cur_opt) + " (process " + str(num) + ")")
return cur_opt
def blame(fail_dir, valid_res, fail_target, out_dir, lock, num, inplace):
blame_str = ""
stdout = stderr = b""
if not re.search("-O0", fail_target.args):
blame_opts = compilers_blame_opts[fail_target.specs.name]
phase_num = 0
blame_phase_num = 0
# Do blaming
try:
for i in blame_opts:
blame_str += i
blame_phase_num = execute_blame_phase(valid_res, fail_target, blame_str, num, phase_num)
if fail_target.specs.name == "dpcpp":
# Special case becasue triagging mechanism is different and there's only one level of triagging.
blame_str += str(blame_phase_num-1)
else:
blame_str += str(blame_phase_num)
blame_str += " "
phase_num += 1
except:
common.log_msg(logging.ERROR, "Something went wrong while executing blame_opt.py on " + str(fail_dir))
return False
# Wrap up results
gen_test_makefile.gen_makefile(
out_file_name = blame_test_makefile_name,
force = True,
config_file = None,
only_target = fail_target,
inject_blame_opt = blame_str if fail_target.specs.name != "dpcpp" else None,
inject_blame_env = blame_str if fail_target.specs.name == "dpcpp" else None)
ret_code, stdout, stderr, time_expired, elapsed_time = \
common.run_cmd(["make", "-f", blame_test_makefile_name, fail_target.name], run_gen.compiler_timeout, num)
if fail_target.specs.name == "dpcpp":
ret_code, stdout, stderr, time_expired, elapsed_time = \
common.run_cmd(["make", "-f", blame_test_makefile_name, "run_" + fail_target.name], run_gen.compiler_timeout, num)
if fail_target.specs.name != "dpcpp":
opt_name_pattern = re.compile(compilers_opt_name_cutter[fail_target.specs.name][0] + ".*" +
compilers_opt_name_cutter[fail_target.specs.name][1])
opt_name = opt_name_pattern.findall(str(stderr, "utf-8"))[-1]
opt_name = re.sub(compilers_opt_name_cutter[fail_target.specs.name][0], "", opt_name)
opt_name = re.sub(compilers_opt_name_cutter[fail_target.specs.name][1], "", opt_name)
real_opt_name = opt_name
opt_name = opt_name.replace(" ", "_")
else:
if blame_phase_num == 1:
# It's special case for DPC++. 1 means that triagging failed, no specific phase can be blamed.
real_opt_name = opt_name = "FailedToBlame"
else:
opt_name_pattern = re.compile(compilers_opt_name_cutter[fail_target.specs.name][0] + ".*" +
compilers_opt_name_cutter[fail_target.specs.name][1])
opt_name = opt_name_pattern.findall(str(stderr, "utf-8"))[0]
opt_name = re.sub(compilers_opt_name_cutter[fail_target.specs.name][0], "", opt_name)
opt_name = re.sub(compilers_opt_name_cutter[fail_target.specs.name][1], "", opt_name)
real_opt_name = opt_name
opt_name = opt_name.replace(" ", "_")
else:
real_opt_name = opt_name = "O0_bug"
common.run_cmd(["make", "-f", blame_test_makefile_name, "clean"], run_gen.compiler_timeout, num)
seed_dir = os.path.basename(os.path.normpath(fail_dir))
# Create log files in different places depending on "inplace" switch.
if not inplace:
full_out_path = os.path.join(os.path.join(out_dir, opt_name), seed_dir)
common.copy_test_to_out(fail_dir, full_out_path, lock)
else:
full_out_path = "."
# Write to log
with open(os.path.join(full_out_path, "log.txt"), "a") as log_file:
log_file.write("\nBlaming for " + fail_target.name + " optset was done.\n")
log_file.write("Optimization to blame: " + real_opt_name + "\n")
log_file.write("Blame opts: " + blame_str + "\n\n")
log_file.write("Details of blaming run:\n")
log_file.write("=== Compiler log ==================================================\n")
log_file.write(str(stdout, "utf-8"))
log_file.write("=== Compiler err ==================================================\n")
log_file.write(str(stderr, "utf-8"))
log_file.write("=== Compiler end ==================================================\n")
common.log_msg(logging.DEBUG, "Done blaming")
# Inplace mode require blaming string to be communicated back to the caller
if not inplace:
return True
else:
return real_opt_name
def prepare_env_and_blame(fail_dir, valid_res, fail_target, out_dir, lock, num, inplace=False):
common.log_msg(logging.DEBUG, "Blaming target: " + fail_target.name + " | " + fail_target.specs.name)
os.chdir(fail_dir)
if fail_target.specs.name not in compilers_blame_opts:
common.log_msg(logging.DEBUG, "We can't blame " + fail_target.name + " (process " + str(num) + ")")
return False
return blame(fail_dir, valid_res, fail_target, out_dir, lock, num, inplace) | |
api_op_DescribePortal.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package iotsitewise
import (
"context"
"fmt"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/iotsitewise/types"
"github.com/awslabs/smithy-go/middleware"
smithyhttp "github.com/awslabs/smithy-go/transport/http"
"time"
)
// Retrieves information about a portal.
func (c *Client) DescribePortal(ctx context.Context, params *DescribePortalInput, optFns ...func(*Options)) (*DescribePortalOutput, error) {
if params == nil {
params = &DescribePortalInput{}
}
result, metadata, err := c.invokeOperation(ctx, "DescribePortal", params, optFns, addOperationDescribePortalMiddlewares)
if err != nil {
return nil, err
}
out := result.(*DescribePortalOutput)
out.ResultMetadata = metadata
return out, nil
}
type DescribePortalInput struct {
// The ID of the portal.
//
// This member is required.
PortalId *string
}
type DescribePortalOutput struct {
// The ARN
// (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of
// the portal, which has the following format.
// arn:${Partition}:iotsitewise:${Region}:${Account}:portal/${PortalId}
//
// This member is required.
PortalArn *string
// The AWS SSO application generated client ID (used with AWS SSO APIs). AWS IoT
// SiteWise includes portalClientId for only portals that use AWS SSO to
// authenticate users.
//
// This member is required.
PortalClientId *string
// The AWS administrator's contact email address.
//
// This member is required.
PortalContactEmail *string
// The date the portal was created, in Unix epoch time.
//
// This member is required.
PortalCreationDate *time.Time
// The ID of the portal.
//
// This member is required.
PortalId *string
// The date the portal was last updated, in Unix epoch time.
//
// This member is required.
PortalLastUpdateDate *time.Time
// The name of the portal.
//
// This member is required.
PortalName *string
// The URL for the AWS IoT SiteWise Monitor portal. You can use this URL to access
// portals that use AWS SSO for authentication. For portals that use IAM for
// authentication, you must use the CreatePresignedPortalUrl
// (https://docs.aws.amazon.com/AWS IoT SiteWise API
// ReferenceAPI_CreatePresignedPortalUrl.html) operation to create a URL that you
// can use to access the portal.
//
// This member is required.
PortalStartUrl *string
// The current status of the portal, which contains a state and any error message.
//
// This member is required.
PortalStatus *types.PortalStatus
// The service to use to authenticate users to the portal.
PortalAuthMode types.AuthMode
// The portal's description.
PortalDescription *string
// The portal's logo image, which is available at a URL.
PortalLogoImageLocation *types.ImageLocation
// The ARN
// (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) of
// the service role that allows the portal's users to access your AWS IoT SiteWise
// resources on your behalf. For more information, see Using service roles for AWS
// IoT SiteWise Monitor
// (https://docs.aws.amazon.com/iot-sitewise/latest/userguide/monitor-service-role.html)
// in the AWS IoT SiteWise User Guide.
RoleArn *string
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
}
func addOperationDescribePortalMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpDescribePortal{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpDescribePortal{}, middleware.After)
if err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil |
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddAttemptClockSkewMiddleware(stack); err != nil {
return err
}
if err = addClientUserAgent(stack); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addEndpointPrefix_opDescribePortalMiddleware(stack); err != nil {
return err
}
if err = addOpDescribePortalValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribePortal(options.Region), middleware.Before); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
return nil
}
type endpointPrefix_opDescribePortalMiddleware struct {
}
func (*endpointPrefix_opDescribePortalMiddleware) ID() string {
return "EndpointHostPrefix"
}
func (m *endpointPrefix_opDescribePortalMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if smithyhttp.GetHostnameImmutable(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
req.HostPrefix = "monitor."
return next.HandleSerialize(ctx, in)
}
func addEndpointPrefix_opDescribePortalMiddleware(stack *middleware.Stack) error {
return stack.Serialize.Insert(&endpointPrefix_opDescribePortalMiddleware{}, `OperationSerializer`, middleware.Before)
}
func newServiceMetadataMiddleware_opDescribePortal(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "iotsitewise",
OperationName: "DescribePortal",
}
}
| {
return err
} |
QuickSort_test.go | package QuickSort
import (
"testing"
"muse/util/SequenceBuilder"
"muse/util/Sequences"
)
func TestQuickSort(t *testing.T) {
size := 32768
arr := make([]int, size)
SequenceBuilder.PackRandom(arr)
checksum := Sequences.ParityChecksum(arr)
Sort(arr)
if Sequences.ParityChecksum(arr) != checksum |
if !Sequences.IsSorted(arr) {
t.FailNow()
}
}
| {
t.FailNow()
} |
job.go | package job
import (
"context"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
shellwords "github.com/mattn/go-shellwords"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/ghodss/yaml"
v1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
// Job has client of kubernetes, current job, command, timeout, and target container information.
type Job struct {
client kubernetes.Interface
// Batch v1 job struct.
CurrentJob *v1.Job
// Command which override the current job struct.
Args []string
// Target container name.
Container string
// If you set 0, timeout is ignored.
Timeout time.Duration
}
// NewJob returns a new Job struct, and initialize kubernetes client.
// It read the job definition yaml file, and unmarshal to batch/v1/Job.
func NewJob(configFile, currentFile, command, container string, timeout time.Duration) (*Job, error) {
if len(configFile) == 0 {
return nil, errors.New("Config file is required")
}
if len(currentFile) == 0 {
return nil, errors.New("Template file is required")
}
if len(container) == 0 {
return nil, errors.New("Container is required")
}
client, err := newClient(os.ExpandEnv(configFile))
if err != nil {
return nil, err
}
downloaded, err := downloadFile(currentFile)
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadFile(downloaded)
if err != nil {
return nil, err
}
var currentJob v1.Job
err = yaml.Unmarshal(bytes, ¤tJob)
if err != nil {
return nil, err
}
currentJob.SetName(generateRandomName(currentJob.Name))
p := shellwords.NewParser()
args, err := p.Parse(command)
log.Info("Received args:")
for _, arg := range args {
log.Info(arg)
}
if err != nil {
return nil, err
}
return &Job{
client,
¤tJob,
args,
container,
timeout,
}, nil
}
func downloadFile(rawurl string) (string, error) {
if !strings.HasPrefix(rawurl, "https://") {
return rawurl, nil
}
req, err := http.NewRequest("GET", rawurl, nil)
if err != nil {
return rawurl, err
}
token := os.Getenv("GITHUB_TOKEN")
if len(token) > 0 {
req.Header.Set("Authorization", "token "+token)
req.Header.Set("Accept", "application/vnd.github.v3.raw")
}
client := new(http.Client)
resp, err := client.Do(req)
if err != nil {
return rawurl, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return rawurl, fmt.Errorf("Could not read template file from %s", rawurl)
}
// Get random string from url.
hasher := md5.New()
hasher.Write([]byte(rawurl))
downloaded := "/tmp/" + hex.EncodeToString(hasher.Sum(nil)) + ".yml"
out, err := os.Create(downloaded)
if err != nil {
return rawurl, err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
return downloaded, err
}
func generateRandomName(name string) string {
return fmt.Sprintf("%s-%s", name, secureRandomStr(16))
}
// secureRandomStr is generate random string.
func secureRandomStr(b int) string {
k := make([]byte, b)
if _, err := rand.Read(k); err != nil {
panic(err)
}
return fmt.Sprintf("%x", k)
}
// Validate checks job templates before run the job.
func (j *Job) Validate() error {
_, err := findContainerIndex(j.CurrentJob, j.Container)
return err
}
// RunJob is run a kubernetes job, and returns the job information.
func (j *Job) RunJob() (*v1.Job, error) {
ctx := context.Background()
currentJob := j.CurrentJob.DeepCopy()
index, err := findContainerIndex(currentJob, j.Container)
if err != nil {
return nil, err
}
if len(j.Args) > 0 {
currentJob.Spec.Template.Spec.Containers[index].Args = j.Args
}
resultJob, err := j.client.BatchV1().Jobs(j.CurrentJob.Namespace).Create(ctx, currentJob, metav1.CreateOptions{})
if err != nil {
return nil, err
}
return resultJob, nil
}
// findContainerIndex finds target container from job definition.
func findContainerIndex(job *v1.Job, containerName string) (int, error) {
for index, container := range job.Spec.Template.Spec.Containers {
if container.Name == containerName {
return index, nil
}
}
return 0, fmt.Errorf("Specified container %s does not exist in the template", containerName)
}
// WaitJob waits response of the job.
func (j *Job) WaitJob(ctx context.Context, job *v1.Job, ignoreSidecar bool) error {
log.Info("Waiting for running job...")
errCh := make(chan error, 1)
done := make(chan struct{}, 1)
go func() {
err := j.WaitJobComplete(ctx, job, ignoreSidecar)
if err != nil {
errCh <- err
}
close(done)
}()
select {
case err := <-errCh:
if err != nil {
return err
}
case <-done:
log.Info("Job is succeeded")
case <-ctx.Done():
return errors.New("process timeout")
}
return nil
}
// WaitJobComplete waits the completion of the job.
// If the job is failed, this function returns error.
// If the job is succeeded, this function returns nil.
func (j *Job) WaitJobComplete(ctx context.Context, job *v1.Job, ignoreSidecar bool) error {
retry:
for {
time.Sleep(3 * time.Second)
running, err := j.client.BatchV1().Jobs(job.Namespace).Get(ctx, job.Name, metav1.GetOptions{})
if err != nil {
return err
}
if running.Status.Active == 0 {
return checkJobConditions(running.Status.Conditions)
}
if ignoreSidecar {
pods, err := j.FindPods(ctx, running)
if err != nil {
return err
}
finished, err := checkPodConditions(pods, j.Container)
if finished {
log.Warn("Pod is still running, but specified container is completed, so job will be terminated")
return err
}
}
continue retry
}
}
// FindPods finds pod in the job.
func (j *Job) FindPods(ctx context.Context, job *v1.Job) ([]corev1.Pod, error) {
labels := parseLabels(job.Spec.Template.Labels)
listOptions := metav1.ListOptions{
LabelSelector: labels,
}
podList, err := j.client.CoreV1().Pods(job.Namespace).List(ctx, listOptions)
if err != nil {
return []corev1.Pod{}, err
}
return podList.Items, err
}
// checkJobConditions checks conditions of all jobs.
// If any job is failed, returns error.
func checkJobConditions(conditions []v1.JobCondition) error {
for _, condition := range conditions {
if condition.Type == v1.JobFailed {
return fmt.Errorf("Job is failed: %s", condition.Reason)
}
}
return nil
}
// checkPodConditions check all pods related a job.
// Returns true, if all containers in the pods which are matched container name is completed.
func checkPodConditions(pods []corev1.Pod, containerName string) (bool, error) {
results := []bool{}
errs := []error{}
for _, pod := range pods {
if podIncludeContainer(pod, containerName) {
finished, err := containerIsCompleted(pod, containerName)
results = append(results, finished)
errs = append(errs, err)
}
}
if len(results) == 0 {
return false, nil
}
for _, r := range results {
if !r {
return false, nil
}
}
var err error
for _, e := range errs {
if e != nil {
err = e
}
}
return true, err
}
func podIncludeContainer(pod corev1.Pod, containerName string) bool {
for _, container := range pod.Spec.Containers {
if container.Name == containerName {
return true
}
}
return false
}
func | (pod corev1.Pod, containerName string) (bool, error) {
if pod.Status.Phase == corev1.PodSucceeded {
return true, nil
}
if pod.Status.Phase == corev1.PodFailed {
return true, fmt.Errorf("%s Pod is failed", pod.Name)
}
if pod.Status.Phase == corev1.PodPending {
return false, nil
}
for _, status := range pod.Status.ContainerStatuses {
if status.Name == containerName && status.State.Terminated != nil {
if status.State.Terminated.ExitCode == 0 {
return true, nil
}
return true, fmt.Errorf("Container is failed: %s", status.State.Terminated.Reason)
}
}
return false, nil
}
// Cleanup removes the job from the kubernetes cluster.
func (j *Job) Cleanup() error {
ctx := context.Background()
log.Infof("Removing the job: %s", j.CurrentJob.Name)
options := metav1.DeleteOptions{}
err := j.client.BatchV1().Jobs(j.CurrentJob.Namespace).Delete(ctx, j.CurrentJob.Name, options)
if err != nil {
return err
}
return j.removePods(ctx)
}
func (j *Job) removePods(ctx context.Context) error {
// Use job-name to find pods which are related the job.
labels := "job-name=" + j.CurrentJob.Name
log.Infof("Remove related pods which labels is: %s", labels)
listOptions := metav1.ListOptions{
LabelSelector: labels,
}
options := metav1.DeleteOptions{
GracePeriodSeconds: nil, // Use default grace period seconds.
}
return j.client.CoreV1().Pods(j.CurrentJob.Namespace).DeleteCollection(ctx, options, listOptions)
}
| containerIsCompleted |
async.rs | //! Example 02. Asynchronous scene loading.
//!
//! Difficulty: Medium.
//!
//! This example shows how to load scene in separate thread and how create standard
//! loading screen which will show progress.
extern crate rg3d;
pub mod shared;
use rg3d::{
animation::Animation,
core::{color::Color, pool::Handle},
engine::resource_manager::ResourceManager,
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
gui::{
grid::{Column, GridBuilder, Row},
message::{MessageDirection, ProgressBarMessage, TextMessage, WidgetMessage},
node::StubNode,
progress_bar::ProgressBarBuilder,
text::TextBuilder,
widget::WidgetBuilder,
HorizontalAlignment, Thickness, VerticalAlignment,
},
scene::{node::Node, Scene},
utils::translate_event,
};
use std::{
sync::{Arc, Mutex},
time::Instant,
};
use crate::shared::create_camera;
use rg3d::core::algebra::{UnitQuaternion, Vector2, Vector3};
// Create our own engine type aliases. These specializations are needed
// because engine provides a way to extend UI with custom nodes and messages.
type GameEngine = rg3d::engine::Engine<(), StubNode>;
type UiNode = rg3d::gui::node::UINode<(), StubNode>;
type BuildContext<'a> = rg3d::gui::BuildContext<'a, (), StubNode>;
struct Interface {
root: Handle<UiNode>,
debug_text: Handle<UiNode>,
progress_bar: Handle<UiNode>,
progress_text: Handle<UiNode>,
}
fn create_ui(ctx: &mut BuildContext, screen_size: Vector2<f32>) -> Interface {
let debug_text;
let progress_bar;
let progress_text;
let root = GridBuilder::new(
WidgetBuilder::new()
.with_width(screen_size.x)
.with_height(screen_size.y)
.with_child({
debug_text =
TextBuilder::new(WidgetBuilder::new().on_row(0).on_column(0)).build(ctx);
debug_text
})
.with_child({
progress_bar =
ProgressBarBuilder::new(WidgetBuilder::new().on_row(1).on_column(1)).build(ctx);
progress_bar
})
.with_child({
progress_text = TextBuilder::new(
WidgetBuilder::new()
.on_column(1)
.on_row(0)
.with_margin(Thickness::bottom(20.0))
.with_vertical_alignment(VerticalAlignment::Bottom),
)
.with_horizontal_text_alignment(HorizontalAlignment::Center)
.build(ctx);
progress_text
}),
)
.add_row(Row::stretch())
.add_row(Row::strict(30.0))
.add_row(Row::stretch())
.add_column(Column::stretch())
.add_column(Column::strict(200.0))
.add_column(Column::stretch())
.build(ctx);
Interface {
root,
debug_text,
progress_bar,
progress_text,
}
}
struct GameScene {
scene: Scene,
model_handle: Handle<Node>,
walk_animation: Handle<Animation>,
}
struct SceneLoadContext {
data: Option<GameScene>,
message: String,
progress: f32,
}
impl SceneLoadContext {
pub fn report_progress(&mut self, progress: f32, message: &str) {
self.progress = progress;
self.message = message.to_owned();
println!("Loading progress: {}% - {}", progress * 100.0, message);
}
}
fn create_scene_async(resource_manager: ResourceManager) -> Arc<Mutex<SceneLoadContext>> {
// Create load context - it will be shared with caller and loader threads.
let context = Arc::new(Mutex::new(SceneLoadContext {
data: None,
message: "Starting..".to_string(),
progress: 0.0,
}));
let result = context.clone();
// Spawn separate thread which will create scene by loading various assets.
std::thread::spawn(move || {
futures::executor::block_on(async move {
let mut scene = Scene::new();
// It is important to lock context for short period of time so other thread can
// read data from it as soon as possible - not when everything was loaded.
context
.lock()
.unwrap()
.report_progress(0.0, "Creating camera...");
// Camera is our eyes in the world - you won't see anything without it.
let camera =
create_camera(resource_manager.clone(), Vector3::new(0.0, 6.0, -12.0)).await;
scene.graph.add_node(Node::Camera(camera));
context
.lock()
.unwrap()
.report_progress(0.33, "Loading model...");
// Load model resource. Is does *not* adds anything to our scene - it just loads a
// resource then can be used later on to instantiate models from it on scene. Why
// loading of resource is separated from instantiation? Because there it is too
// inefficient to load a resource every time you trying to create instance of it -
// much more efficient is to load it one and then make copies of it. In case of
// models it is very efficient because single vertex and index buffer can be used
// for all models instances, so memory footprint on GPU will be lower.
let model_resource = resource_manager
.request_model("examples/data/mutant.FBX")
.await
.unwrap();
// Instantiate model on scene - but only geometry, without any animations.
// Instantiation is a process of embedding model resource data in desired scene.
let model_handle = model_resource.instantiate_geometry(&mut scene);
// Now we have whole sub-graph instantiated, we can start modifying model instance.
scene.graph[model_handle]
.local_transform_mut()
// Our model is too big, fix it by scale.
.set_scale(Vector3::new(0.05, 0.05, 0.05));
context
.lock()
.unwrap()
.report_progress(0.66, "Loading animation...");
// Add simple animation for our model. Animations are loaded from model resources -
// this is because animation is a set of skeleton bones with their own transforms.
let walk_animation_resource = resource_manager
.request_model("examples/data/walk.fbx")
.await
.unwrap();
// Once animation resource is loaded it must be re-targeted to our model instance.
// Why? Because animation in *resource* uses information about *resource* bones,
// not model instance bones, retarget_animations maps animations of each bone on
// model instance so animation will know about nodes it should operate on.
let walk_animation = *walk_animation_resource
.retarget_animations(model_handle, &mut scene)
.get(0)
.unwrap();
context.lock().unwrap().report_progress(1.0, "Done");
context.lock().unwrap().data = Some(GameScene {
scene,
model_handle,
walk_animation,
})
})
});
// Immediately return shared context.
result
}
struct InputController {
rotate_left: bool,
rotate_right: bool,
}
fn | () {
let event_loop = EventLoop::new();
let window_builder = rg3d::window::WindowBuilder::new()
.with_title("Example - Asynchronous Scene Loading")
.with_resizable(true);
let mut engine = GameEngine::new(window_builder, &event_loop).unwrap();
// Prepare resource manager - it must be notified where to search textures. When engine
// loads model resource it automatically tries to load textures it uses. But since most
// model formats store absolute paths, we can't use them as direct path to load texture
// instead we telling engine to search textures in given folder.
engine
.resource_manager
.state()
.set_textures_path("examples/data");
// Create simple user interface that will show some useful info.
let window = engine.get_window();
let screen_size = window.inner_size().to_logical(window.scale_factor());
let interface = create_ui(
&mut engine.user_interface.build_ctx(),
Vector2::new(screen_size.width, screen_size.height),
);
// Create scene asynchronously - this method immediately returns empty load context
// which will be filled with data over time.
let game_scene = create_scene_async(engine.resource_manager.clone());
// Initially these handles are None, once scene is loaded they'll be assigned.
let mut scene_handle = Handle::NONE;
let mut model_handle = Handle::NONE;
let mut walk_animation = Handle::NONE;
// Set ambient light.
engine
.renderer
.set_ambient_color(Color::opaque(200, 200, 200));
let clock = Instant::now();
let fixed_timestep = 1.0 / 60.0;
let mut elapsed_time = 0.0;
// We will rotate model using keyboard input.
let mut model_angle = 180.0f32.to_radians();
// Create input controller - it will hold information about needed actions.
let mut input_controller = InputController {
rotate_left: false,
rotate_right: false,
};
// Finally run our event loop which will respond to OS and window events and update
// engine state accordingly. Engine lets you to decide which event should be handled,
// this is minimal working example if how it should be.
event_loop.run(move |event, _, control_flow| {
match event {
Event::MainEventsCleared => {
// This main game loop - it has fixed time step which means that game
// code will run at fixed speed even if renderer can't give you desired
// 60 fps.
let mut dt = clock.elapsed().as_secs_f32() - elapsed_time;
while dt >= fixed_timestep {
dt -= fixed_timestep;
elapsed_time += fixed_timestep;
// ************************
// Put your game logic here.
// ************************
// Check each frame if our scene is created - here we just trying to lock context
// without blocking, it is important for main thread to be functional while other
// thread still loading data.
if let Ok(mut load_context) = game_scene.try_lock() {
if let Some(game_scene) = load_context.data.take() {
// Add scene to engine - engine will take ownership over scene and will return
// you a handle to scene which can be used later on to borrow it and do some
// actions you need.
scene_handle = engine.scenes.add(game_scene.scene);
model_handle = game_scene.model_handle;
walk_animation = game_scene.walk_animation;
// Once scene is loaded, we should hide progress bar and text.
engine.user_interface.send_message(WidgetMessage::visibility(interface.progress_bar, MessageDirection::ToWidget,false));
engine.user_interface.send_message(WidgetMessage::visibility(interface.progress_text,MessageDirection::ToWidget, false));
}
// Report progress in UI.
engine.user_interface.send_message(ProgressBarMessage::progress(interface.progress_bar, MessageDirection::ToWidget,load_context.progress));
engine.user_interface.send_message(
TextMessage::text(interface.progress_text,MessageDirection::ToWidget,
format!("Loading scene: {}%\n{}", load_context.progress * 100.0, load_context.message)));
}
// Update scene only if it is loaded.
if scene_handle.is_some() {
// Use stored scene handle to borrow a mutable reference of scene in
// engine.
let scene = &mut engine.scenes[scene_handle];
// Our animation must be applied to scene explicitly, otherwise
// it will have no effect.
scene.animations
.get_mut(walk_animation)
.get_pose()
.apply(&mut scene.graph);
// Rotate model according to input controller state.
if input_controller.rotate_left {
model_angle -= 5.0f32.to_radians();
} else if input_controller.rotate_right {
model_angle += 5.0f32.to_radians();
}
scene.graph[model_handle]
.local_transform_mut()
.set_rotation(UnitQuaternion::from_axis_angle(&Vector3::y_axis(), model_angle));
}
// While scene is loading, we will update progress bar.
let fps = engine.renderer.get_statistics().frames_per_second;
let debug_text = format!("Example 02 - Asynchronous Scene Loading\nUse [A][D] keys to rotate model.\nFPS: {}", fps);
engine.user_interface.send_message(TextMessage::text(interface.debug_text, MessageDirection::ToWidget,debug_text));
// It is very important to "pump" messages from UI. Even if don't need to
// respond to such message, you should call this method, otherwise UI
// might behave very weird.
while let Some(_ui_event) = engine.user_interface.poll_message() {
// ************************
// Put your data model synchronization code here. It should
// take message and update data in your game according to
// changes in UI.
// ************************
}
engine.update(fixed_timestep);
}
// Rendering must be explicitly requested and handled after RedrawRequested event is received.
engine.get_window().request_redraw();
}
Event::RedrawRequested(_) => {
// Run renderer at max speed - it is not tied to game code.
engine.render(fixed_timestep).unwrap();
}
Event::WindowEvent { event, .. } => {
match event {
WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit
}
WindowEvent::Resized(size) => {
// It is very important to handle Resized event from window, because
// renderer knows nothing about window size - it must be notified
// directly when window size has changed.
engine.renderer.set_frame_size(size.into());
// Root UI node should be resized too, otherwise progress bar will stay
// in wrong position after resize.
let size = size.to_logical(engine.get_window().scale_factor());
engine.user_interface.send_message(WidgetMessage::width(interface.root, MessageDirection::ToWidget,size.width));
engine.user_interface.send_message(WidgetMessage::height(interface.root, MessageDirection::ToWidget,size.height));
}
WindowEvent::KeyboardInput { input, ..} => {
// Handle key input events via `WindowEvent`, not via `DeviceEvent` (#32)
if let Some(key_code) = input.virtual_keycode {
match key_code {
VirtualKeyCode::A => input_controller.rotate_left = input.state == ElementState::Pressed,
VirtualKeyCode::D => input_controller.rotate_right = input.state == ElementState::Pressed,
_ => ()
}
}
}
_ => ()
}
// It is very important to "feed" user interface (UI) with events coming
// from main window, otherwise UI won't respond to mouse, keyboard, or any
// other event.
if let Some(os_event) = translate_event(&event) {
engine.user_interface.process_os_event(&os_event);
}
}
Event::DeviceEvent { .. } => {
// Handle key input events via `WindowEvent`, not via `DeviceEvent` (#32)
}
_ => *control_flow = ControlFlow::Poll,
}
});
}
| main |
server.js | var webpack = require("webpack")
var WebpackDevServer = require("webpack-dev-server")
var config = require("./webpack.config")
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(5000, "localhost", function (err, result) {
if (err) {
console.log(err)
}
console.log("\nListening at localhost: 5000\n")
})
var WebSocketServer = require("ws").Server
var wss = new WebSocketServer({ port: 5001 })
var connections = {}
wss.on("connection", function connection(ws) {
var uuid = "" + Math.random()
connections[uuid] = ws
ws.on("message", function incoming(message) {
message.sender = ws.uuid
broadcast(uuid, message)
})
})
function | (sender, message) {
console.log("\n" + message)
for (var key in connections)
if (key !== sender) {
try {
connections[key].send(message)
} catch (e) {
delete connections[key]
}
}
}
| broadcast |
arrow.js | import { $, createSVG, animateSVG } from './svg_utils';
export default class | {
constructor(gantt, from_task, to_task) {
this.gantt = gantt;
this.from_task = from_task;
this.to_task = to_task;
this.calculate_path();
this.draw();
}
calculate_path() {
let start_x =
this.from_task.$bar.getX() + this.from_task.$bar.getWidth() - 5;
const condition = () =>
this.to_task.$bar.getX() < start_x + this.gantt.options.padding &&
start_x > this.from_task.$bar.getX() + this.gantt.options.padding;
while (condition()) {
start_x -= 10;
}
const start_y =
this.gantt.options.header_height +
this.gantt.options.bar_height +
(this.gantt.options.padding + this.gantt.options.bar_height) *
this.from_task.task._index +
this.gantt.options.padding;
const end_x = this.to_task.$bar.getX() - this.gantt.options.padding / 2;
const end_y =
this.gantt.options.header_height +
this.gantt.options.bar_height / 2 +
(this.gantt.options.padding + this.gantt.options.bar_height) *
this.to_task.task._index +
this.gantt.options.padding;
const from_is_below_to =
this.from_task.task._index > this.to_task.task._index;
const curve = this.gantt.options.arrow_curve;
const clockwise = from_is_below_to ? 1 : 0;
const curve_y = from_is_below_to ? -curve : curve;
const offset = from_is_below_to
? end_y + this.gantt.options.arrow_curve
: end_y - this.gantt.options.arrow_curve;
this.path = `M ${start_x}` + ' ' + `${start_y}` + ' ' +
`V ${offset}` + ' ' +
`a ${curve}` + ' ' + `${curve}` + ' ' + `0` + ' ' + `0` + ' ' + `${clockwise}` + ' ' + `${curve}` + ' ' + `${curve_y}` + ' ' +
`L ${end_x}` + ' ' + `${end_y}` + ' ' +
`m -5` + ' ' + `-5` + ' ' +
`l 5` + ' ' + `5` + ' ' +
`l -5` + ' ' + `5`;
if (
this.to_task.$bar.getX() <
this.from_task.$bar.getX() + this.gantt.options.padding + 10
) {
const down_1 = this.gantt.options.padding / 2 - curve;
const down_2 =
this.to_task.$bar.getY() +
this.to_task.$bar.getHeight() / 2 -
curve_y;
const left = this.to_task.$bar.getX() - this.gantt.options.padding;
this.path = `M ${start_x}` + ' ' + `${start_y}` + ' ' +
`v ${down_1}` + ' ' +
`a ${curve}` + ' ' + `${curve}` + ' ' + `0` + ' ' + `0` + ' ' + `1` + ' ' + `-${curve}` + ' ' + `${curve}` + ' ' +
`H ${left}` + ' ' +
`a ${curve}` + ' ' + `${curve}` + ' ' + `0` + ' ' + `0` + ' ' + `${clockwise}` + ' ' + `-${curve}` + ' ' + `${curve_y}` + ' ' +
`V ${down_2}` + ' ' +
`a ${curve}` + ' ' + `${curve}` + ' ' + `0` + ' ' + `0` + ' ' + `${clockwise}` + ' ' + `${curve}` + ' ' + `${curve_y}` + ' ' +
`L ${end_x}` + ' ' + `${end_y}` + ' ' +
`m -5` + ' ' + `-5` + ' ' +
`l 5` + ' ' + `5` + ' ' +
`l -5` + ' ' + `5`;
}
}
draw() {
this.element = createSVG('path', {
d: this.path,
'data-from': this.from_task.task.id,
'data-to': this.to_task.task.id
});
if (this.to_task.task.animate) {
animateSVG(this.element, 'opacity', 0, 0, '0.8s', '0s');
animateSVG(this.element, 'opacity', 0, 1, '0.4s', '0.8s');
}
}
update() {
this.calculate_path();
this.element.setAttribute('d', this.path);
}
}
| Arrow |
http.ts | import * as http from 'http';
import * as stream from 'stream';
import * as url from 'url';
import * as net from 'net';
// http Server
{
function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {}
let server: http.Server = new http.Server();
class MyIncomingMessage extends http.IncomingMessage {
foo: number;
}
class MyServerResponse extends http.ServerResponse {
foo: string;
}
server = new http.Server({ IncomingMessage: MyIncomingMessage});
server = new http.Server({
IncomingMessage: MyIncomingMessage,
ServerResponse: MyServerResponse
}, reqListener);
server = http.createServer(reqListener);
server = http.createServer({ IncomingMessage: MyIncomingMessage });
server = http.createServer({ ServerResponse: MyServerResponse }, reqListener);
server = http.createServer({ insecureHTTPParser: true }, reqListener);
// test public props
const maxHeadersCount: number | null = server.maxHeadersCount;
const headersTimeout: number = server.headersTimeout;
const timeout: number = server.timeout;
const listening: boolean = server.listening;
const keepAliveTimeout: number = server.keepAliveTimeout;
const requestTimeout: number = server.requestTimeout;
server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {});
}
// http IncomingMessage
// http ServerResponse
{
// incoming
const incoming: http.IncomingMessage = new http.IncomingMessage(new net.Socket());
incoming.setEncoding('utf8');
incoming.setTimeout(1000).setTimeout(100, () => {});
// stream
incoming.pause();
incoming.resume();
// response
const res: http.ServerResponse = new http.ServerResponse(incoming);
// test headers
res.setHeader('Content-Type', 'text/plain')
.setHeader('Return-Type', 'this');
const bool: boolean = res.hasHeader('Content-Type');
const headers: string[] = res.getHeaderNames();
// trailers
res.addTrailers([
['x-fOo', 'xOxOxOx'],
['x-foO', 'OxOxOxO'],
['X-fOo', 'xOxOxOx'],
['X-foO', 'OxOxOxO']
] as ReadonlyArray<[string, string]>);
res.addTrailers({ 'x-foo': 'bar' });
// writeHead
res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n').end();
res.writeHead(200, { 'Transfer-Encoding': 'chunked' });
res.writeHead(200, ['Transfer-Encoding', 'chunked']);
res.writeHead(200);
// writeProcessing
res.writeProcessing();
// write string
res.write('Part of my res.');
// write buffer
const chunk = Buffer.alloc(16390, 'Й');
res.write(chunk);
res.write(chunk, 'hex');
// end
res.end("end msg");
// without msg
res.end();
// flush
res.flushHeaders();
res.req; // $ExpectType IncomingMessage
}
// http ClientRequest
{
let req: http.ClientRequest = new http.ClientRequest("https://www.google.com");
req = new http.ClientRequest(new url.URL("https://www.google.com"));
req = new http.ClientRequest({ path: 'http://0.0.0.0' });
req = new http.ClientRequest({ setHost: false });
// header
req.setHeader('Content-Type', 'text/plain');
const bool: boolean = req.hasHeader('Content-Type');
const headers: string[] = req.getHeaderNames();
req.removeHeader('Date');
// write
const chunk = Buffer.alloc(16390, 'Й');
req.write(chunk);
req.write('a');
req.end();
// abort
req.abort();
// connection
if (req.connection) {
req.connection.on('pause', () => { });
}
if (req.socket) {
req.socket.on("connect", () => {});
}
// event
req.on('data', () => { });
// path
const path: string = req.path;
req.path = '/';
// method
const method: string = req.method;
const rawHeaderNames: string[] = req.getRawHeaderNames();
}
{
// Status codes
let codeMessage: string = http.STATUS_CODES['400']!;
codeMessage = http.STATUS_CODES[400]!;
}
{
let agent: http.Agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 10000,
maxSockets: Infinity,
maxTotalSockets: Infinity,
maxFreeSockets: 256,
timeout: 15000,
scheduling: 'lifo',
});
agent = http.globalAgent;
let sockets: NodeJS.ReadOnlyDict<net.Socket[]> = agent.sockets;
sockets = agent.freeSockets;
http.request({ agent: false });
http.request({ agent });
http.request({ agent: undefined });
// ensure compatibility with url.parse()
http.request(url.parse("http://www.example.org/xyz"));
}
{
http.get('http://www.example.com/xyz');
http.request('http://www.example.com/xyz');
http.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {});
http.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {});
http.get(new url.URL('http://www.example.com/xyz'));
http.request(new url.URL('http://www.example.com/xyz'));
http.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {});
http.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {});
const opts: http.RequestOptions = {
path: '"/some/path'
};
http.get(new url.URL('http://www.example.com'), opts);
http.request(new url.URL('http://www.example.com'), opts);
http.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {});
http.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {});
}
{
// Make sure .listen() and .close() return a Server instance
http.createServer().listen(0).close().address();
net.createServer().listen(0).close().address();
}
{
const request = http.request({ path: 'http://0.0.0.0' });
request.once('error', () => { });
request.setNoDelay(true);
request.abort();
}
// http request options
{
const requestOpts: http.RequestOptions = {
abort: new AbortSignal(),
timeout: 30000
};
const clientArgs: http.ClientRequestArgs = {
abort: new AbortSignal(),
timeout: 30000
};
}
// http headers
{
const headers: http.IncomingHttpHeaders = {
'content-type': 'application/json',
'set-cookie': [ 'type=ninja', 'language=javascript' ]
};
headers["access-control-request-headers"] = "content-type, x-custom-header";
headers["access-control-request-method"] = "PUT";
headers.origin = "https://example.com";
}
// statics
{
const maxHeaderSize = http.maxHeaderSize;
}
{
const opts: http.RequestOptions = http.urlToHttpOptions(new url.URL('test.com'));
}
// net server events
{
let server = new http.Server();
let _socket = new net.Socket();
let _err = new Error();
let _bool = true;
server = server.addListener("close", () => {});
server = server.addListener("connection", (socket) => {
_socket = socket;
});
server = server.addListener("error", (err) => {
_err = err;
});
server = server.addListener("listening", () => {});
_bool = server.emit("close");
_bool = server.emit("connection", _socket);
_bool = server.emit("error", _err);
_bool = server.emit("listening");
server = server.on("close", () => {});
server = server.on("connection", (socket) => {
_socket = socket;
});
server = server.on("error", (err) => {
_err = err;
});
server = server.on("listening", () => {});
server = server.once("close", () => {});
server = server.once("connection", (socket) => {
_socket = socket;
});
server = server.once("error", (err) => {
_err = err;
});
server = server.once("listening", () => {});
server = server.prependListener("close", () => {});
server = server.prependListener("connection", (socket) => {
_socket = socket;
});
server = server.prependListener("error", (err) => {
_err = err;
});
server = server.prependListener("listening", () => {}); | });
server = server.prependOnceListener("error", (err) => {
_err = err;
});
server = server.prependOnceListener("listening", () => {});
}
// http server events
{
let server = new http.Server();
let _socket = new stream.Duplex();
let _req = new http.IncomingMessage(new net.Socket());
let _res = new http.ServerResponse(_req);
let _err = new Error();
let _head = Buffer.from("");
let _bool = true;
server = server.addListener("checkContinue", (req, res) => {
_req = req;
_res = res;
});
server = server.addListener("checkExpectation", (req, res) => {
_req = req;
_res = res;
});
server = server.addListener("clientError", (err, socket) => {
_err = err;
_socket = socket;
});
server = server.addListener("connect", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
server = server.addListener("request", (req, res) => {
_req = req;
_res = res;
});
server = server.addListener("upgrade", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
_bool = server.emit("checkContinue", _req, _res);
_bool = server.emit("checkExpectation", _req, _res);
_bool = server.emit("clientError", _err, _socket);
_bool = server.emit("connect", _req, _socket, _head);
_bool = server.emit("request", _req, _res);
_bool = server.emit("upgrade", _req, _socket, _head);
server = server.on("checkContinue", (req, res) => {
_req = req;
_res = res;
});
server = server.on("checkExpectation", (req, res) => {
_req = req;
_res = res;
});
server = server.on("clientError", (err, socket) => {
_err = err;
_socket = socket;
});
server = server.on("connect", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
server = server.on("request", (req, res) => {
_req = req;
_res = res;
});
server = server.on("upgrade", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
server = server.once("checkContinue", (req, res) => {
_req = req;
_res = res;
});
server = server.once("checkExpectation", (req, res) => {
_req = req;
_res = res;
});
server = server.once("clientError", (err, socket) => {
_err = err;
_socket = socket;
});
server = server.once("connect", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
server = server.once("request", (req, res) => {
_req = req;
_res = res;
});
server = server.once("upgrade", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
server = server.prependListener("checkContinue", (req, res) => {
_req = req;
_res = res;
});
server = server.prependListener("checkExpectation", (req, res) => {
_req = req;
_res = res;
});
server = server.prependListener("clientError", (err, socket) => {
_err = err;
_socket = socket;
});
server = server.prependListener("connect", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
server = server.prependListener("request", (req, res) => {
_req = req;
_res = res;
});
server = server.prependListener("upgrade", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
server = server.prependOnceListener("checkContinue", (req, res) => {
_req = req;
_res = res;
});
server = server.prependOnceListener("checkExpectation", (req, res) => {
_req = req;
_res = res;
});
server = server.prependOnceListener("clientError", (err, socket) => {
_err = err;
_socket = socket;
});
server = server.prependOnceListener("connect", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
server = server.prependOnceListener("request", (req, res) => {
_req = req;
_res = res;
});
server = server.prependOnceListener("upgrade", (req, socket, head) => {
_req = req;
_socket = socket;
_head = head;
});
} |
server = server.prependOnceListener("close", () => {});
server = server.prependOnceListener("connection", (socket) => {
_socket = socket; |
application.py | # coding=utf-8
# Copyright (C) 2020 NumS Development Team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import List
import numpy as np
from nums.core.array.blockarray import BlockArray, Block
from nums.core.array import utils as array_utils
from nums.core.storage.storage import ArrayGrid, StoredArray, StoredArrayS3
# TODO(hme): Remove dependence on specific system and scheduler implementations.
from nums.core.systems.systems import System, RaySystem, SerialSystem
from nums.core.systems.gpu_systems import CupyParallelSystem
from nums.core.systems.schedulers import BlockCyclicScheduler
from nums.core.systems import utils as systems_utils
from nums.core.systems.filesystem import FileSystem
from nums.core.array.random import NumsRandomState
# pylint: disable = too-many-lines
class ArrayApplication(object):
def __init__(self, system: System, filesystem: FileSystem):
self.system: System = system
self._filesystem: FileSystem = filesystem
self._array_grids: (str, ArrayGrid) = {}
self.random = self.random_state()
self.one_half = self.scalar(.5)
self.two = self.scalar(2.0)
self.one = self.scalar(1.0)
self.zero = self.scalar(0.0)
self._block_shape_map = {}
def num_cores_total(self):
if isinstance(self.system, RaySystem):
system: RaySystem = self.system
nodes = system.nodes()
num_cores = sum(map(lambda n: n["Resources"]["CPU"], nodes))
elif isinstance(self.system, CupyParallelSystem):
system: CupyParallelSystem = self.system
num_cores = system.num_gpus
else:
assert isinstance(self.system, SerialSystem)
num_cores = systems_utils.get_num_cores()
return int(num_cores)
def compute_block_shape(self,
shape: tuple,
dtype: np.dtype,
cluster_shape=None,
num_cores=None):
# TODO (hme): Add support for downstream optimizer to decide block shape.
if dtype in (np.float32, np.float64, float):
dtype = np.finfo(dtype).dtype
elif dtype in (np.int32, np.int64, int):
dtype = np.iinfo(dtype).dtype
elif dtype in (bool, np.bool_):
dtype = np.dtype(np.bool_)
else:
raise ValueError("dtype %s not supported" % str(dtype))
nbytes = dtype.alignment
size = np.product(shape) * nbytes
# If the object is less than 100 megabytes, there's not much value in constructing
# a block tensor.
if size < 10 ** 8:
block_shape = shape
return block_shape
if num_cores is not None:
pass
else:
num_cores = self.num_cores_total()
if cluster_shape is not None:
pass
elif isinstance(self.system, RaySystem) \
and isinstance(self.system.scheduler, BlockCyclicScheduler):
# This configuration is the default.
cluster_shape = self.system.scheduler.cluster_shape
elif isinstance(self.system, CupyParallelSystem):
cluster_shape = self.system.cluster_shape
else:
assert isinstance(self.system, SerialSystem)
cluster_shape = (1, 1)
if len(shape) < len(cluster_shape):
cluster_shape = cluster_shape[:len(shape)]
elif len(shape) > len(cluster_shape):
cluster_shape = list(cluster_shape)
for axis in range(len(shape)):
if axis >= len(cluster_shape):
cluster_shape.append(1)
cluster_shape = tuple(cluster_shape)
shape_np = np.array(shape, dtype=np.int)
# Softmax on cluster shape gives strong preference to larger dimensions.
cluster_weights = np.exp(np.array(cluster_shape)) / np.sum(np.exp(cluster_shape))
shape_fracs = np.array(shape) / np.sum(shape)
# cluster_weights weight the proportion of cores available along each axis,
# and shape_fracs is the proportion of data along each axis.
weighted_shape_fracs = cluster_weights * shape_fracs
weighted_shape_fracs = weighted_shape_fracs / np.sum(weighted_shape_fracs)
# Compute dimensions of grid shape
# so that the number of blocks are close to the number of cores.
grid_shape_frac = num_cores ** weighted_shape_fracs
grid_shape = np.floor(grid_shape_frac)
# Put remainder on largest axis.
remaining = np.sum(grid_shape_frac - grid_shape)
grid_shape[np.argmax(shape)] += remaining
grid_shape = np.ceil(grid_shape).astype(np.int)
# We use ceiling of floating block shape
# so that resulting grid shape is <= to what we compute above.
block_shape = tuple((shape_np + grid_shape - 1) // grid_shape)
return block_shape
def get_block_shape(self, shape, dtype: np.dtype):
# Simple way to ensure shape compatibility for basic linear algebra operations.
block_shape = self.compute_block_shape(shape, dtype)
final_block_shape = []
for axis in range(len(shape)):
shape_dim = shape[axis]
block_shape_dim = block_shape[axis]
if shape_dim not in self._block_shape_map:
self._block_shape_map[shape_dim] = block_shape_dim
final_block_shape.append(self._block_shape_map[shape_dim])
return tuple(final_block_shape)
def _get_array_grid(self, filename: str, stored_array_cls) -> ArrayGrid:
if filename not in self._array_grids:
store_inst: StoredArray = stored_array_cls(filename)
self._array_grids[filename] = store_inst.get_grid()
return self._array_grids[filename]
######################################
# Filesystem API
######################################
def write_fs(self, ba: BlockArray, filename: str):
res = self._write(ba, filename, self._filesystem.write_block_fs)
self._filesystem.write_meta_fs(ba, filename)
return res
def | (self, filename: str):
meta = self._filesystem.read_meta_fs(filename)
addresses = meta["addresses"]
grid_meta = meta["grid_meta"]
grid = ArrayGrid.from_meta(grid_meta)
ba: BlockArray = BlockArray(grid, self.system)
for grid_entry in addresses:
node_address = addresses[grid_entry]
options = {"resources": {node_address: 1.0 / 10 ** 4}}
ba.blocks[grid_entry].oid = self._filesystem.read_block_fs(filename,
grid_entry,
grid_meta,
options=options)
return ba
def delete_fs(self, filename: str):
meta = self._filesystem.read_meta_fs(filename)
addresses = meta["addresses"]
grid_meta = meta["grid_meta"]
grid = ArrayGrid.from_meta(grid_meta)
result_grid = ArrayGrid(grid.grid_shape,
tuple(np.ones_like(grid.shape, dtype=np.int)),
dtype=dict.__name__)
rarr = BlockArray(result_grid, self.system)
for grid_entry in addresses:
node_address = addresses[grid_entry]
options = {"resources": {node_address: 1.0 / 10 ** 4}}
rarr.blocks[grid_entry].oid = self._filesystem.delete_block_fs(filename,
grid_entry,
grid_meta,
options=options)
self._filesystem.delete_meta_fs(filename)
return rarr
def write_s3(self, ba: BlockArray, filename: str):
grid_entry = tuple(np.zeros_like(ba.shape, dtype=np.int))
result = self._filesystem.write_meta_s3(filename,
grid_meta=ba.grid.to_meta(),
syskwargs={
"grid_entry": grid_entry,
"grid_shape": ba.grid.grid_shape
})
assert "ETag" in self.system.get(result).item(), "Metadata write failed."
return self._write(ba, filename, self._filesystem.write_block_s3)
def _write(self, ba: BlockArray, filename, remote_func):
grid = ba.grid
result_grid = ArrayGrid(grid.grid_shape,
tuple(np.ones_like(grid.shape, dtype=np.int)),
dtype=dict.__name__)
rarr = BlockArray(result_grid, self.system)
for grid_entry in grid.get_entry_iterator():
rarr.blocks[grid_entry].oid = remote_func(ba.blocks[grid_entry].oid,
filename,
grid_entry,
grid.to_meta(),
syskwargs={
"grid_entry": grid_entry,
"grid_shape": grid.grid_shape
})
return rarr
def read_s3(self, filename: str):
store_cls, remote_func = StoredArrayS3, self._filesystem.read_block_s3
grid = self._get_array_grid(filename, store_cls)
grid_meta = grid.to_meta()
grid_entry_iterator = grid.get_entry_iterator()
rarr = BlockArray(grid, self.system)
for grid_entry in grid_entry_iterator:
rarr.blocks[grid_entry].oid = remote_func(filename, grid_entry, grid_meta,
syskwargs={
"grid_entry": grid_entry,
"grid_shape": grid.grid_shape
})
return rarr
def delete_s3(self, filename: str):
grid = self._get_array_grid(filename, StoredArrayS3)
grid_entry = tuple(np.zeros_like(grid.shape, dtype=np.int))
result = self._filesystem.delete_meta_s3(filename,
syskwargs={
"grid_entry": grid_entry,
"grid_shape": grid.grid_shape
})
deleted_key = self.system.get(result).item()["Deleted"][0]["Key"]
assert deleted_key == StoredArrayS3(filename, grid).get_meta_key()
results: BlockArray = self._delete(filename,
StoredArrayS3,
self._filesystem.delete_block_s3)
return results
def _delete(self, filename, store_cls, remote_func):
grid = self._get_array_grid(filename, store_cls)
result_grid = ArrayGrid(grid.grid_shape,
tuple(np.ones_like(grid.shape, dtype=np.int)),
dtype=dict.__name__)
rarr = BlockArray(result_grid, self.system)
for grid_entry in grid.get_entry_iterator():
rarr.blocks[grid_entry].oid = remote_func(filename, grid_entry, grid.to_meta(),
syskwargs={
"grid_entry": grid_entry,
"grid_shape": grid.grid_shape
})
return rarr
def read_csv(self, filename, dtype=np.float, delimiter=',', has_header=False, num_workers=None):
if num_workers is None:
num_workers = self.num_cores_total()
arrays: list = self._filesystem.read_csv(filename, dtype, delimiter, has_header,
num_workers)
shape = np.zeros(len(arrays[0].shape), dtype=int)
for array in arrays:
shape += np.array(array.shape, dtype=int)
shape = tuple(shape)
block_shape = self.get_block_shape(shape, dtype)
result = self.concatenate(arrays, axis=0, axis_block_size=block_shape[0])
# Release references immediately, in case we need to do another reshape.
del arrays
if result.block_shape[1] != block_shape[1]:
result = result.reshape(block_shape=block_shape)
return result
def loadtxt(self, fname, dtype=float, comments='# ', delimiter=' ',
converters=None, skiprows=0, usecols=None, unpack=False,
ndmin=0, encoding='bytes', max_rows=None, num_workers=None) -> BlockArray:
if num_workers is None:
num_workers = self.num_cores_total()
return self._filesystem.loadtxt(
fname, dtype=dtype, comments=comments, delimiter=delimiter,
converters=converters, skiprows=skiprows,
usecols=usecols, unpack=unpack, ndmin=ndmin,
encoding=encoding, max_rows=max_rows, num_workers=num_workers)
######################################
# Array Operations API
######################################
def scalar(self, value):
return BlockArray.from_scalar(value, self.system)
def array(self, array: np.ndarray, block_shape: tuple = None):
assert len(array.shape) == len(block_shape)
return BlockArray.from_np(array,
block_shape=block_shape,
copy=False,
system=self.system)
def zeros(self, shape: tuple, block_shape: tuple, dtype: np.dtype = None):
return self._new_array("zeros", shape, block_shape, dtype)
def ones(self, shape: tuple, block_shape: tuple, dtype: np.dtype = None):
return self._new_array("ones", shape, block_shape, dtype)
def empty(self, shape: tuple, block_shape: tuple, dtype: np.dtype = None):
return self._new_array("empty", shape, block_shape, dtype)
def _new_array(self, op_name: str, shape: tuple, block_shape: tuple, dtype: np.dtype = None):
assert len(shape) == len(block_shape)
if dtype is None:
dtype = np.float64
grid = ArrayGrid(shape, block_shape, dtype.__name__)
grid_meta = grid.to_meta()
rarr = BlockArray(grid, self.system)
for grid_entry in grid.get_entry_iterator():
rarr.blocks[grid_entry].oid = self.system.new_block(op_name,
grid_entry,
grid_meta,
syskwargs={
"grid_entry": grid_entry,
"grid_shape": grid.grid_shape
})
return rarr
def concatenate(self, arrays: List, axis: int, axis_block_size: int = None):
num_arrs = len(arrays)
assert num_arrs > 1
first_arr: BlockArray = arrays[0]
num_axes = len(first_arr.shape)
# Check assumptions and define result shapes and block shapes.
for i in range(num_arrs):
curr_ba: BlockArray = arrays[i]
assert num_axes == len(curr_ba.shape), "Unequal num axes."
assert curr_ba.dtype == first_arr.dtype, "Incompatible dtypes " \
"%s, %s" % (curr_ba.dtype, first_arr.dtype)
for curr_axis in range(num_axes):
first_block_size = first_arr.block_shape[curr_axis]
block_size = curr_ba.block_shape[curr_axis]
if first_block_size == block_size:
continue
elif axis == curr_axis:
assert axis_block_size is not None, "block axis size is required " \
"when block shapes are neq."
else:
raise ValueError("Other axis shapes and block shapes must be equal.")
# Compute result shapes.
result_shape = []
result_block_shape = []
for curr_axis in range(num_axes):
if curr_axis == axis:
if axis_block_size is None:
# They are all equal.
axis_block_size = first_arr.block_shape[curr_axis]
result_block_size = axis_block_size
result_size = 0
for i in range(num_arrs):
curr_ba: BlockArray = arrays[i]
size = curr_ba.shape[curr_axis]
result_size += size
else:
result_size = first_arr.shape[curr_axis]
result_block_size = first_arr.block_shape[curr_axis]
result_shape.append(result_size)
result_block_shape.append(result_block_size)
result_shape, result_block_shape = tuple(result_shape), tuple(result_block_shape)
result_ba = self.empty(result_shape, result_block_shape, first_arr.dtype)
# Write result blocks.
# TODO (hme): This can be optimized by updating blocks directly.
pos = 0
for arr in arrays:
delta = arr.shape[axis]
axis_slice = slice(pos, pos+delta)
result_selector = tuple([slice(None, None) for _ in range(axis)] + [axis_slice, ...])
result_ba[result_selector] = arr
pos += delta
return result_ba
def eye(self, shape: tuple, block_shape: tuple, dtype: np.dtype = None):
assert len(shape) == len(block_shape) == 2
if dtype is None:
dtype = np.float64
grid = ArrayGrid(shape, block_shape, dtype.__name__)
grid_meta = grid.to_meta()
rarr = BlockArray(grid, self.system)
for grid_entry in grid.get_entry_iterator():
syskwargs = {"grid_entry": grid_entry, "grid_shape": grid.grid_shape}
if np.all(np.diff(grid_entry) == 0):
# This is a diagonal block.
rarr.blocks[grid_entry].oid = self.system.new_block("eye",
grid_entry,
grid_meta,
syskwargs=syskwargs)
else:
rarr.blocks[grid_entry].oid = self.system.new_block("zeros",
grid_entry,
grid_meta,
syskwargs=syskwargs)
return rarr
def diag(self, X: BlockArray) -> BlockArray:
if len(X.shape) == 1:
shape = X.shape[0], X.shape[0]
block_shape = X.block_shape[0], X.block_shape[0]
grid = ArrayGrid(shape, block_shape, X.dtype.__name__)
grid_meta = grid.to_meta()
rarr = BlockArray(grid, self.system)
for grid_entry in grid.get_entry_iterator():
syskwargs = {"grid_entry": grid_entry, "grid_shape": grid.grid_shape}
if np.all(np.diff(grid_entry) == 0):
# This is a diagonal block.
rarr.blocks[grid_entry].oid = self.system.diag(X.blocks[grid_entry[0]].oid,
syskwargs=syskwargs)
else:
rarr.blocks[grid_entry].oid = self.system.new_block("zeros",
grid_entry,
grid_meta,
syskwargs=syskwargs)
elif len(X.shape) == 2:
assert X.shape[0] == X.shape[1]
assert X.block_shape[0] == X.block_shape[1]
shape = X.shape[0],
block_shape = X.block_shape[0],
grid = ArrayGrid(shape, block_shape, X.dtype.__name__)
rarr = BlockArray(grid, self.system)
for grid_entry in X.grid.get_entry_iterator():
out_grid_entry = grid_entry[:1]
out_grid_shape = grid.grid_shape[:1]
syskwargs = {"grid_entry": out_grid_entry, "grid_shape": out_grid_shape}
if np.all(np.diff(grid_entry) == 0):
# This is a diagonal block.
rarr.blocks[out_grid_entry].oid = self.system.diag(X.blocks[grid_entry].oid,
syskwargs=syskwargs)
else:
raise ValueError("X must have 1 or 2 axes.")
return rarr
def arange(self, shape, block_shape, step=1, dtype=np.int64) -> BlockArray:
assert step == 1
# Generate ranges per block.
grid = ArrayGrid(shape, block_shape, dtype.__name__)
rarr = BlockArray(grid, self.system)
for _, grid_entry in enumerate(grid.get_entry_iterator()):
syskwargs = {"grid_entry": grid_entry, "grid_shape": grid.grid_shape}
start = block_shape[0] * grid_entry[0]
entry_shape = grid.get_block_shape(grid_entry)
stop = start + entry_shape[0]
rarr.blocks[grid_entry].oid = self.system.arange(start,
stop,
step,
dtype,
syskwargs=syskwargs)
return rarr
def linspace(self, start, stop, shape, block_shape, endpoint, retstep, dtype, axis):
assert axis == 0
assert endpoint is True
assert retstep is False
step_size = (stop - start) / (shape[0]-1)
result = self.arange(shape, block_shape)
result = start + result * step_size
if dtype is not None and dtype != result.dtype:
result = result.astype(dtype)
return result
def log(self, X: BlockArray):
return X.ufunc("log")
def exp(self, X: BlockArray):
return X.ufunc("exp")
def abs(self, X: BlockArray):
return X.ufunc("abs")
def min(self, X: BlockArray, axis=None, keepdims=False):
return self.reduce("min", X, axis, keepdims)
def max(self, X: BlockArray, axis=None, keepdims=False):
return self.reduce("max", X, axis, keepdims)
def argmin(self, X: BlockArray, axis=None):
pass
def sum(self, X: BlockArray, axis=None, keepdims=False, dtype=None):
return self.reduce("sum", X, axis, keepdims, dtype)
def reduce(self, op_name: str, X: BlockArray, axis=None, keepdims=False, dtype=None):
res = X.reduce_axis(op_name, axis, keepdims=keepdims)
if dtype is not None:
res = res.astype(dtype)
return res
def mean(self, X: BlockArray, axis=None, keepdims=False, dtype=None):
if X.dtype not in (float, np.float32, np.float64):
X = X.astype(np.float64)
num_summed = np.product(X.shape) if axis is None else X.shape[axis]
res = self.sum(X, axis=axis, keepdims=keepdims) / num_summed
if dtype is not None:
res = res.astype(dtype)
return res
def var(self, X: BlockArray, axis=None, ddof=0, keepdims=False, dtype=None):
mean = self.mean(X, axis=axis, keepdims=True)
ss = self.sum((X - mean)**self.two, axis=axis, keepdims=keepdims)
num_summed = (np.product(X.shape) if axis is None else X.shape[axis]) - ddof
res = ss / num_summed
if dtype is not None:
res = res.astype(dtype)
return res
def std(self, X: BlockArray, axis=None, ddof=0, keepdims=False, dtype=None):
res = self.sqrt(self.var(X, axis, ddof, keepdims))
if dtype is not None:
res = res.astype(dtype)
return res
def argop(self, op_name: str, arr: BlockArray, axis=None):
if len(arr.shape) > 1:
raise NotImplementedError("%s currently supports one-dimensional arrays." % op_name)
if axis is None:
axis = 0
assert axis == 0
grid = ArrayGrid(shape=(), block_shape=(), dtype=np.int64.__name__)
result = BlockArray(grid, self.system)
reduction_result = None, None
for grid_entry in arr.grid.get_entry_iterator():
block_slice: slice = arr.grid.get_slice(grid_entry)[0]
block: Block = arr.blocks[grid_entry]
syskwargs = {
"grid_entry": grid_entry,
"grid_shape": arr.grid.grid_shape,
"options": {"num_returns": 2},
}
reduction_result = self.system.arg_op(op_name,
block.oid,
block_slice,
*reduction_result,
syskwargs=syskwargs)
argoptima, _ = reduction_result
result.blocks[()].oid = argoptima
return result
def sqrt(self, X):
if X.dtype not in (float, np.float32, np.float64):
X = X.astype(np.float64)
return X.ufunc("sqrt")
def norm(self, X):
return self.sqrt(X.T @ X)
def xlogy(self, x: BlockArray, y: BlockArray) -> BlockArray:
if x.dtype not in (float, np.float32, np.float64):
x = x.astype(np.float64)
if x.dtype not in (float, np.float32, np.float64):
y = y.astype(np.float64)
return self.map_bop("xlogy", x, y)
def where(self, condition: BlockArray, x=None, y=None):
result_oids = []
shape_oids = []
num_axes = max(1, len(condition.shape))
# Stronger constraint than necessary, but no reason for anything stronger.
if x is not None or y is not None:
assert x is not None and y is not None
assert condition.shape == x.shape == y.shape
assert condition.block_shape == x.block_shape == y.block_shape
for grid_entry in condition.grid.get_entry_iterator():
block: Block = condition.blocks[grid_entry]
block_slice_tuples = condition.grid.get_slice_tuples(grid_entry)
roids = self.system.where(block.oid, x, y,
block_slice_tuples,
syskwargs={
"grid_entry": grid_entry,
"grid_shape": condition.grid.grid_shape,
"options": {"num_returns": num_axes+1}
})
block_oids, shape_oid = roids[:-1], roids[-1]
shape_oids.append(shape_oid)
result_oids.append(block_oids)
shapes = self.system.get(shape_oids)
result_shape = (np.sum(shapes),)
if result_shape == (0,):
return (self.array(np.array([], dtype=np.int64), block_shape=(0,)),)
# Remove empty shapes.
result_shape_pair = []
for i, shape in enumerate(shapes):
if np.sum(shape) > 0:
result_shape_pair.append((result_oids[i], shape))
result_block_shape = self.compute_block_shape(result_shape, np.int64)
result_arrays = []
for axis in range(num_axes):
block_arrays = []
for i in range(len(result_oids)):
if shapes[i] == (0,):
continue
block_arrays.append(BlockArray.from_oid(result_oids[i][axis],
shapes[i],
np.int64,
self.system))
if len(block_arrays) == 1:
axis_result = block_arrays[0]
else:
axis_result = self.concatenate(block_arrays, 0, result_block_shape[0])
result_arrays.append(axis_result)
return tuple(result_arrays)
def map_uop(self,
op_name: str,
arr: BlockArray,
out: BlockArray = None,
where=True,
args=None,
kwargs=None) -> BlockArray:
"""
A map, for unary operators, that applies to every entry of an array.
:param op_name: An element-wise unary operator.
:param arr: A BlockArray.
:param out: A BlockArray to which the result is written.
:param where: An indicator specifying the indices to which op is applied.
:param args: Args provided to op.
:param kwargs: Keyword args provided to op.
:return: A BlockArray.
"""
if where is not True:
raise NotImplementedError("'where' argument is not yet supported.")
args = () if args is None else args
kwargs = {} if kwargs is None else kwargs
shape = arr.shape
block_shape = arr.block_shape
dtype = array_utils.get_uop_output_type(op_name, arr.dtype)
assert len(shape) == len(block_shape)
if out is None:
grid = ArrayGrid(shape, block_shape, dtype.__name__)
rarr = BlockArray(grid, self.system)
else:
rarr = out
grid = rarr.grid
assert rarr.shape == arr.shape and rarr.block_shape == arr.block_shape
for grid_entry in grid.get_entry_iterator():
# TODO(hme): Faster to create ndarray first,
# and instantiate block array on return
# to avoid instantiating blocks on BlockArray initialization.
rarr.blocks[grid_entry] = arr.blocks[grid_entry].uop_map(op_name,
args=args,
kwargs=kwargs)
return rarr
def matmul(self,
arr_1: BlockArray,
arr_2: BlockArray) -> BlockArray:
return arr_1 @ arr_2
def tensordot(self,
arr_1: BlockArray,
arr_2: BlockArray,
axes: int = 2) -> BlockArray:
return arr_1.tensordot(arr_2, axes)
def map_bop(self,
op_name: str,
arr_1: BlockArray,
arr_2: BlockArray,
out: BlockArray = None,
where=True,
args=None,
kwargs=None) -> BlockArray:
# TODO (hme): Move this into BlockArray, and invoke on operator implementations.
"""
A map, for binary operators, that applies element-wise to every entry of the input arrays.
:param op_name: An element-wise binary operator.
:param arr_1: A BlockArray.
:param arr_2: A BlockArray.
:param out: A BlockArray to which the result is written.
:param where: An indicator specifying the indices to which op is applied.
:param args: Args provided to op.
:param kwargs: Keyword args provided to op.
:return: A BlockArray.
"""
if where is not True:
raise NotImplementedError("'where' argument is not yet supported.")
if args is not None:
raise NotImplementedError("'args' is not yet supported.")
if not (kwargs is None or len(kwargs) == 0):
raise NotImplementedError("'kwargs' is not yet supported.")
try:
ufunc = np.__getattribute__(op_name)
if (op_name.endswith("max") or op_name == "maximum"
or op_name.endswith("min") or op_name == "minimum"
or op_name.startswith("logical")):
rarr = self._broadcast_bop(op_name, arr_1, arr_2)
else:
result_blocks: np.ndarray = ufunc(arr_1.blocks, arr_2.blocks)
rarr = BlockArray.from_blocks(result_blocks,
result_shape=None,
system=self.system)
except Exception as _:
rarr = self._broadcast_bop(op_name, arr_1, arr_2)
if out is not None:
assert out.grid.grid_shape == rarr.grid.grid_shape
assert out.shape == rarr.shape
assert out.block_shape == rarr.block_shape
out.blocks[:] = rarr.blocks[:]
rarr = out
return rarr
def _broadcast_bop(self, op_name, arr_1, arr_2) -> BlockArray:
"""
We want to avoid invoking this op whenever possible; NumPy's imp is faster.
:param op_name: Name of binary operation.
:param arr_1: A BlockArray.
:param arr_2: A BlockArray.
:return: A BlockArray.
"""
if arr_1.shape != arr_2.shape:
output_grid_shape = array_utils.broadcast_shape(arr_1.grid.grid_shape,
arr_2.grid.grid_shape)
arr_1 = arr_1.broadcast_to(output_grid_shape)
arr_2 = arr_2.broadcast_to(output_grid_shape)
dtype = array_utils.get_bop_output_type(op_name,
arr_1.dtype,
arr_2.dtype)
grid = ArrayGrid(arr_1.shape, arr_1.block_shape, dtype.__name__)
rarr = BlockArray(grid, self.system)
for grid_entry in rarr.grid.get_entry_iterator():
block_1: Block = arr_1.blocks[grid_entry]
block_2: Block = arr_2.blocks[grid_entry]
rarr.blocks[grid_entry] = block_1.bop(op_name, block_2, {})
return rarr
def get(self, *arrs):
if len(arrs) == 1:
if isinstance(arrs[0], BlockArray):
return arrs[0].get()
else:
return arrs[0]
else:
r = []
for item in arrs:
if isinstance(item, BlockArray):
r.append(item.get())
else:
r.append(item)
return r
def allclose(self, a: BlockArray, b: BlockArray, rtol=1.e-5, atol=1.e-8):
assert a.shape == b.shape and a.block_shape == b.block_shape
bool_list = []
grid_shape = a.grid.grid_shape
for grid_entry in a.grid.get_entry_iterator():
a_block, b_block = a.blocks[grid_entry].oid, b.blocks[grid_entry].oid
bool_list.append(self.system.allclose(a_block, b_block, rtol, atol,
syskwargs={
"grid_entry": grid_entry,
"grid_shape": grid_shape
}))
oid = self.system.logical_and(*bool_list,
syskwargs={"grid_entry": (0, 0), "grid_shape": (1, 1)})
return BlockArray.from_oid(oid, (), np.bool, self.system)
def qr(self, X: BlockArray):
return self.indirect_tsqr(X)
def indirect_tsr(self, X: BlockArray, reshape_output=True):
assert len(X.shape) == 2
# TODO (hme): This assertion is temporary and ensures returned
# shape of qr of block is correct.
assert X.block_shape[0] >= X.shape[1]
# Compute R for each block.
grid = X.grid
grid_shape = grid.grid_shape
shape = X.shape
block_shape = X.block_shape
R_oids = []
# Assume no blocking along second dim.
for i in range(grid_shape[0]):
# Select a row according to block_shape.
row = []
for j in range(grid_shape[1]):
row.append(X.blocks[i, j].oid)
R_oids.append(self.system.qr(*row,
mode="r",
axis=1,
syskwargs={
"grid_entry": (i, 0),
"grid_shape": (grid_shape[0], 1),
"options": {"num_returns": 1}
})
)
# Construct R by summing over R blocks.
# TODO (hme): Communication may be inefficient due to redundancy of data.
R_shape = (shape[1], shape[1])
R_block_shape = (block_shape[1], block_shape[1])
tsR = BlockArray(ArrayGrid(shape=R_shape,
block_shape=R_shape,
dtype=X.dtype.__name__),
self.system)
tsR.blocks[0, 0].oid = self.system.qr(*R_oids,
mode="r",
axis=0,
syskwargs={
"grid_entry": (0, 0),
"grid_shape": (1, 1),
"options": {"num_returns": 1}
})
# If blocking is "tall-skinny," then we're done.
if R_shape != R_block_shape:
if reshape_output:
R = tsR.reshape(shape=R_shape, block_shape=R_block_shape)
else:
R = tsR
else:
R = tsR
return R
def indirect_tsqr(self, X: BlockArray, reshape_output=True):
shape = X.shape
block_shape = X.block_shape
R_shape = (shape[1], shape[1])
R_block_shape = (block_shape[1], block_shape[1])
tsR = self.indirect_tsr(X, reshape_output=False)
# Compute inverse of R.
tsR_inverse = self.inv(tsR)
# If blocking is "tall-skinny," then we're done.
if R_shape != R_block_shape:
R_inverse = tsR_inverse.reshape(shape=R_shape, block_shape=R_block_shape)
if reshape_output:
R = tsR.reshape(shape=R_shape, block_shape=R_block_shape)
else:
R = tsR
else:
R_inverse = tsR_inverse
R = tsR
Q = X @ R_inverse
return Q, R
def direct_tsqr(self, X, reshape_output=True):
assert len(X.shape) == 2
# Compute R for each block.
shape = X.shape
grid = X.grid
grid_shape = grid.grid_shape
block_shape = X.block_shape
Q_oids = []
R_oids = []
QR_dims = []
Q2_shape = [0, shape[1]]
for i in range(grid_shape[0]):
# Select a row according to block_shape.
row = []
for j in range(grid_shape[1]):
row.append(X.blocks[i, j].oid)
# We invoke "reduced", so q, r is returned with dimensions (M, K), (K, N), K = min(M, N)
M = grid.get_block_shape((i, 0))[0]
N = shape[1]
K = min(M, N)
QR_dims.append(((M, K), (K, N)))
Q2_shape[0] += K
# Run each row on separate nodes along first axis.
# This maintains some data locality.
Q_oid, R_oid = self.system.qr(*row,
mode="reduced",
axis=1,
syskwargs={
"grid_entry": (i, 0),
"grid_shape": (grid_shape[0], 1),
"options": {"num_returns": 2}
})
R_oids.append(R_oid)
Q_oids.append(Q_oid)
# TODO (hme): This pulls several order N^2 R matrices on a single node.
# A solution is the recursive extension to direct TSQR.
Q2_oid, R2_oid = self.system.qr(*R_oids,
mode="reduced",
axis=0,
syskwargs={
"grid_entry": (0, 0),
"grid_shape": (1, 1),
"options": {"num_returns": 2}
})
Q2_shape = tuple(Q2_shape)
Q2_block_shape = (QR_dims[0][1][0], shape[1])
Q2 = self._vec_from_oids([Q2_oid],
shape=Q2_shape,
block_shape=Q2_block_shape,
dtype=X.dtype)
# The resulting Q's from this operation are N^2 (same size as above R's).
Q2_oids = list(map(lambda block: block.oid, Q2.blocks.flatten()))
# Construct Q.
Q = self.zeros(shape=shape,
block_shape=(block_shape[0], shape[1]),
dtype=X.dtype)
for i, grid_entry in enumerate(Q.grid.get_entry_iterator()):
Q_dims, R_dims = QR_dims[i]
Q1_block_shape = Q_dims
Q2_block_shape = R_dims
Q.blocks[grid_entry].oid = self.system.bop("tensordot", Q_oids[i], Q2_oids[i],
a1_shape=Q1_block_shape,
a2_shape=Q2_block_shape,
a1_T=False, a2_T=False, axes=1,
syskwargs={"grid_entry": grid_entry,
"grid_shape": Q.grid.grid_shape})
# Construct R.
shape = X.shape
R_shape = (shape[1], shape[1])
R_block_shape = (block_shape[1], block_shape[1])
tsR = self._vec_from_oids([R2_oid], shape=R_shape, block_shape=R_shape, dtype=X.dtype)
# If blocking is "tall-skinny," then we're done.
if R_shape == R_block_shape or not reshape_output:
R = tsR
else:
R = tsR.reshape(shape=R_shape, block_shape=R_block_shape)
if Q.shape != block_shape or not reshape_output:
Q = Q.reshape(shape=shape, block_shape=block_shape)
return Q, R
def svd(self, X):
# TODO(hme): Optimize by merging with direct qr to compute U directly,
# to avoid wasting space storing intermediate Q.
# This may not really help until we have operator fusion.
assert len(X.shape) == 2
block_shape = X.block_shape
shape = X.shape
R_shape = (shape[1], shape[1])
R_block_shape = (block_shape[1], block_shape[1])
Q, R = self.direct_tsqr(X, reshape_output=False)
assert R.shape == R.block_shape
R_U, S, VT = self.system.svd(R.blocks[(0, 0)].oid,
syskwargs={"grid_entry": (0, 0),
"grid_shape": (1, 1)})
R_U: BlockArray = self._vec_from_oids([R_U], R_shape, R_block_shape, X.dtype)
S: BlockArray = self._vec_from_oids([S], R_shape[:1], R_block_shape[:1], X.dtype)
VT = self._vec_from_oids([VT], R_shape, R_block_shape, X.dtype)
U = Q @ R_U
return U, S, VT
def inv(self, X: BlockArray):
return self._inv(self.system.inv, {}, X)
def _inv(self, remote_func, kwargs, X: BlockArray):
# TODO (hme): Implement scalable version.
block_shape = X.block_shape
assert len(X.shape) == 2
assert X.shape[0] == X.shape[1]
single_block = X.shape[0] == X.block_shape[0] and X.shape[1] == X.block_shape[1]
if single_block:
result = X.copy()
else:
result = X.reshape(block_shape=X.shape)
result.blocks[0, 0].oid = remote_func(result.blocks[0, 0].oid,
**kwargs,
syskwargs={
"grid_entry": (0, 0),
"grid_shape": (1, 1)
})
if not single_block:
result = result.reshape(block_shape=block_shape)
return result
def cholesky(self, X: BlockArray):
# TODO (hme): Implement scalable version.
# Note:
# A = Q, R
# A.T @ A = R.T @ R
# A.T @ A = L @ L.T
# => R == L.T
block_shape = X.block_shape
assert len(X.shape) == 2
assert X.shape[0] == X.shape[1]
single_block = X.shape[0] == X.block_shape[0] and X.shape[1] == X.block_shape[1]
if single_block:
result = X.copy()
else:
result = X.reshape(block_shape=X.shape)
result.blocks[0, 0].oid = self.system.cholesky(result.blocks[0, 0].oid,
syskwargs={
"grid_entry": (0, 0),
"grid_shape": (1, 1)
})
if not single_block:
result = result.reshape(block_shape=block_shape)
return result
def fast_linear_regression(self, X: BlockArray, y: BlockArray):
assert len(X.shape) == 2
assert len(y.shape) == 1
block_shape = X.block_shape
shape = X.shape
R_shape = (shape[1], shape[1])
R_block_shape = (block_shape[1], block_shape[1])
Q, R = self.indirect_tsqr(X, reshape_output=False)
R_inv = self.inv(R)
if R_shape != R_block_shape:
R_inv = R_inv.reshape(shape=R_shape, block_shape=R_block_shape)
theta = R_inv @ (Q.T @ y)
return theta
def linear_regression(self, X: BlockArray, y: BlockArray):
assert len(X.shape) == 2
assert len(y.shape) == 1
block_shape = X.block_shape
shape = X.shape
R_shape = (shape[1], shape[1])
R_block_shape = (block_shape[1], block_shape[1])
Q, R = self.direct_tsqr(X, reshape_output=False)
# Invert R.
R_inv = self.inv(R)
if R_shape != R_block_shape:
R_inv = R_inv.reshape(shape=R_shape, block_shape=R_block_shape)
theta = R_inv @ (Q.T @ y)
return theta
def ridge_regression(self, X: BlockArray, y: BlockArray, lamb: float):
assert len(X.shape) == 2
assert len(y.shape) == 1
assert lamb >= 0
block_shape = X.block_shape
shape = X.shape
R_shape = (shape[1], shape[1])
R_block_shape = (block_shape[1], block_shape[1])
R = self.indirect_tsr(X)
lamb_vec = self.array(lamb*np.eye(R_shape[0]), block_shape=R_block_shape)
# TODO (hme): A better solution exists, which inverts R by augmenting X and y.
# See Murphy 7.5.2.
theta = self.inv(lamb_vec + R.T @ R) @ (X.T @ y)
return theta
def _vec_from_oids(self, oids, shape, block_shape, dtype):
arr = BlockArray(ArrayGrid(shape=shape,
block_shape=shape,
dtype=dtype.__name__),
self.system)
# Make sure resulting grid shape is a vector (1 dimensional).
assert np.sum(arr.grid.grid_shape) == (max(arr.grid.grid_shape)
+ len(arr.grid.grid_shape) - 1)
for i, grid_entry in enumerate(arr.grid.get_entry_iterator()):
arr.blocks[grid_entry].oid = oids[i]
if block_shape != shape:
return arr.reshape(block_shape=block_shape)
return arr
def random_state(self, seed=None):
return NumsRandomState(self.system, seed)
| read_fs |
babylonjs.materials.min.js | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("babylonjs")):"function"==typeof define&&define.amd?define("babylonjs-materials",["babylonjs"],t):"object"==typeof exports?exports["babylonjs-materials"]=t(require("babylonjs")):e.MATERIALS=t(e.BABYLON)}("undefined"!=typeof self?self:"undefined"!=typeof global?global:this,function(e){return function(e){var t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(n,r,function(t){return e[t]}.bind(null,r));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=19)}([function(t,i){t.exports=e},function(e,t,i){"use strict";i.d(t,"b",function(){return r}),i.d(t,"a",function(){return o});
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved. | Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)};function r(e,t){function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function o(e,t,i,n){var r,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,i,a):r(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}},function(e,t){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch(e){"object"==typeof window&&(i=window)}e.exports=i},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef BUMP\nvarying vec2 vNormalUV;\nvarying vec2 vNormalUV2;\nuniform sampler2D normalSampler;\nuniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;\nuniform sampler2D reflectionSampler;\n\nconst float LOG2=1.442695;\nuniform vec3 cameraPosition;\nuniform vec4 waterColor;\nuniform float colorBlendFactor;\nuniform vec4 waterColor2;\nuniform float colorBlendFactor2;\nuniform float bumpHeight;\nuniform float time;\n\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvarying vec3 vPosition;\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));\nif (normalW.y<0.0) {\nnormalW.y=-normalW.y;\n}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\nvec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\n\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);\nfloat IfresnelTerm=1.0-fresnelTerm;\nrefractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;\nreflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;\nbaseColor=combinedColor;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else\n#ifdef REFLECTION\n\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=max(dot(viewDirectionW,upVector),0.0);\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);\nbaseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#elif defined(IMAGEPROCESSING)\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n}\n";r.Effect.ShadersStore.waterPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;\nuniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<logDepthDeclaration>\n\nuniform mat4 worldReflectionViewProjection;\nuniform vec2 windDirection;\nuniform float waveLength;\nuniform float time;\nuniform float windForce;\nuniform float waveHeight;\nuniform float waveSpeed;\n\nvarying vec3 vPosition;\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x == 0.)\n{\nvNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{\nvNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\nvec3 p=position;\nfloat newY=(sin(((p.x/0.05)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+(cos(((p.z/0.05)+time*waveSpeed))*waveHeight*windDirection.y*5.0);\np.y+=abs(newY);\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#ifdef REFLECTION\nworldPos=viewProjection*finalWorld*vec4(p,1.0);\n\nvPosition=position;\nvRefractionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvRefractionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvRefractionMapTexCoord.z=worldPos.w;\nworldPos=worldReflectionViewProjection*vec4(position,1.0);\nvReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include<logDepthVertex>\n}\n";r.Effect.ShadersStore.waterVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.BUMP=!1,t.REFLECTION=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.SPECULARTERM=!1,t.LOGARITHMICDEPTH=!1,t.FRESNELSEPARATE=!1,t.BUMPSUPERIMPOSE=!1,t.BUMPAFFECTSREFLECTION=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.EXPOSURE=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i,n){void 0===n&&(n=new r.Vector2(512,512));var o=e.call(this,t,i)||this;return o.renderTargetSize=n,o.diffuseColor=new r.Color3(1,1,1),o.specularColor=new r.Color3(0,0,0),o.specularPower=64,o._disableLighting=!1,o._maxSimultaneousLights=4,o.windForce=6,o.windDirection=new r.Vector2(0,1),o.waveHeight=.4,o.bumpHeight=.4,o._bumpSuperimpose=!1,o._fresnelSeparate=!1,o._bumpAffectsReflection=!1,o.waterColor=new r.Color3(.1,.1,.6),o.colorBlendFactor=.2,o.waterColor2=new r.Color3(.1,.1,.6),o.colorBlendFactor2=.2,o.waveLength=.1,o.waveSpeed=1,o.disableClipPlane=!1,o._renderTargets=new r.SmartArray(16),o._mesh=null,o._reflectionTransform=r.Matrix.Zero(),o._lastTime=0,o._lastDeltaTime=0,o._createRenderTargets(i,n),o.getRenderTargetTextures=function(){return o._renderTargets.reset(),o._renderTargets.push(o._reflectionRTT),o._renderTargets.push(o._refractionRTT),o._renderTargets},o._imageProcessingConfiguration=o.getScene().imageProcessingConfiguration,o._imageProcessingConfiguration&&(o._imageProcessingObserver=o._imageProcessingConfiguration.onUpdateParameters.add(function(){o._markAllSubMeshesAsImageProcessingDirty()})),o}return Object(n.b)(t,e),Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"refractionTexture",{get:function(){return this._refractionRTT},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"reflectionTexture",{get:function(){return this._reflectionRTT},enumerable:!0,configurable:!0}),t.prototype.addToRenderList=function(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)},t.prototype.enableRenderTargets=function(e){var t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)},t.prototype.getRenderList=function(){return this._refractionRTT?this._refractionRTT.renderList:[]},Object.defineProperty(t.prototype,"renderTargetsEnabled",{get:function(){return!(this._refractionRTT&&0===this._refractionRTT.refreshRate)},enumerable:!0,configurable:!0}),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,o.texturesEnabled)){if(this.bumpTexture&&r.MaterialFlags.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;n._needUVs=!0,n.BUMP=!0}r.MaterialFlags.ReflectionTextureEnabled&&(n.REFLECTION=!0)}if(r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForMisc(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._areMiscDirty&&(this._fresnelSeparate&&(n.FRESNELSEPARATE=!0),this._bumpSuperimpose&&(n.BUMPSUPERIMPOSE=!0),this._bumpAffectsReflection&&(n.BUMPAFFECTSREFLECTION=!0)),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!0,this._maxSimultaneousLights,this._disableLighting),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),this._mesh=e,this._waitingRenderList){for(var f=0;f<this._waitingRenderList.length;f++)this.addToRenderList(o.getNodeByID(this._waitingRenderList[f]));this._waitingRenderList=null}if(n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var l=new r.EffectFallbacks;n.FOG&&l.addFallback(1,"FOG"),n.LOGARITHMICDEPTH&&l.addFallback(0,"LOGARITHMICDEPTH"),r.MaterialHelper.HandleFallbacksForShadows(n,l,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&l.addCPUSkinningFallback(0,e);var u=[r.VertexBuffer.PositionKind];n.NORMAL&&u.push(r.VertexBuffer.NormalKind),n.UV1&&u.push(r.VertexBuffer.UVKind),n.UV2&&u.push(r.VertexBuffer.UV2Kind),n.VERTEXCOLOR&&u.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(u,e,n,l),r.MaterialHelper.PrepareAttributesForInstances(u,n);var c=n.toString(),d=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","normalMatrix","logarithmicDepthConstant","worldReflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed"],p=["normalSampler","refractionSampler","reflectionSampler"],h=new Array;r.ImageProcessingConfiguration&&(r.ImageProcessingConfiguration.PrepareUniforms(d,n),r.ImageProcessingConfiguration.PrepareSamplers(p,n)),r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:h,samplers:p,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(o.getEngine().createEffect("water",{attributes:u,uniformsNames:d,uniformBuffersNames:h,samplers:p,defines:c,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;if(a&&this._mesh){this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,a)&&(this.bumpTexture&&r.MaterialFlags.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),r.MaterialHelper.BindLogDepth(o,this._activeEffect,n),r.MaterialFlags.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));var s=this._mesh.getWorldMatrix().multiply(this._reflectionTransform).multiply(n.getProjectionMatrix()),f=n.getEngine().getDeltaTime();f!==this._lastDeltaTime&&(this._lastDeltaTime=f,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("worldReflectionViewProjection",s),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect)}}},t.prototype._createRenderTargets=function(e,t){var i,n=this;this._refractionRTT=new r.RenderTargetTexture(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=r.Constants.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=r.Constants.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0,this._reflectionRTT=new r.RenderTargetTexture(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=r.Constants.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=r.Constants.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;var o,a=null,s=r.Matrix.Zero();this._refractionRTT.onBeforeRender=function(){if(n._mesh&&(i=n._mesh.isVisible,n._mesh.isVisible=!1),!n.disableClipPlane){a=e.clipPlane;var t=n._mesh?n._mesh.position.y:0;e.clipPlane=r.Plane.FromPositionAndNormal(new r.Vector3(0,t+.05,0),new r.Vector3(0,1,0))}},this._refractionRTT.onAfterRender=function(){n._mesh&&(n._mesh.isVisible=i),n.disableClipPlane||(e.clipPlane=a)},this._reflectionRTT.onBeforeRender=function(){if(n._mesh&&(i=n._mesh.isVisible,n._mesh.isVisible=!1),!n.disableClipPlane){a=e.clipPlane;var t=n._mesh?n._mesh.position.y:0;e.clipPlane=r.Plane.FromPositionAndNormal(new r.Vector3(0,t-.05,0),new r.Vector3(0,-1,0)),r.Matrix.ReflectionToRef(e.clipPlane,s)}o=e.getViewMatrix(),s.multiplyToRef(o,n._reflectionTransform),e.setTransformMatrix(n._reflectionTransform,e.getProjectionMatrix()),e.getEngine().cullBackFaces=!1,e._mirroredCameraPosition=r.Vector3.TransformCoordinates(e.activeCamera.position,s)},this._reflectionRTT.onAfterRender=function(){n._mesh&&(n._mesh.isVisible=i),e.clipPlane=a,e.setTransformMatrix(o,e.getProjectionMatrix()),e.getEngine().cullBackFaces=!0,e._mirroredCameraPosition=null}},t.prototype.getAnimatables=function(){var e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._bumpTexture&&t.push(this._bumpTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||this._bumpTexture===t},t.prototype.dispose=function(t){this.bumpTexture&&this.bumpTexture.dispose();var i=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=i&&this.getScene().customRenderTargets.splice(i,1),i=-1,-1!=(i=this.getScene().customRenderTargets.indexOf(this._reflectionRTT))&&this.getScene().customRenderTargets.splice(i,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(var t=0;t<this._refractionRTT.renderList.length;t++)e.renderList.push(this._refractionRTT.renderList[t].id);return e},t.prototype.getClassName=function(){return"WaterMaterial"},t.Parse=function(e,i,n){var o=r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n);return o._waitingRenderList=e.renderList,o},t.CreateDefaultMesh=function(e,t){return r.Mesh.CreateGround(e,512,512,32,t,!1)},Object(n.a)([Object(r.serializeAsTexture)("bumpTexture")],t.prototype,"_bumpTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"specularColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"specularPower",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"windForce",void 0),Object(n.a)([Object(r.serializeAsVector2)()],t.prototype,"windDirection",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"waveHeight",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"bumpHeight",void 0),Object(n.a)([Object(r.serialize)("bumpSuperimpose")],t.prototype,"_bumpSuperimpose",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsMiscDirty")],t.prototype,"bumpSuperimpose",void 0),Object(n.a)([Object(r.serialize)("fresnelSeparate")],t.prototype,"_fresnelSeparate",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsMiscDirty")],t.prototype,"fresnelSeparate",void 0),Object(n.a)([Object(r.serialize)("bumpAffectsReflection")],t.prototype,"_bumpAffectsReflection",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsMiscDirty")],t.prototype,"bumpAffectsReflection",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"waterColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"colorBlendFactor",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"waterColor2",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"colorBlendFactor2",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"waveLength",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"waveSpeed",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"disableClipPlane",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"useLogarithmicDepth",null),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.WaterMaterial"]=f,i.d(t,"WaterMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\nuniform vec3 cameraPosition;\nuniform vec3 cameraOffset;\nuniform float luminance;\nuniform float turbidity;\nuniform float rayleigh;\nuniform float mieCoefficient;\nuniform float mieDirectionalG;\nuniform vec3 sunPosition;\n\n#include<fogFragmentDeclaration>\n\nconst float e=2.71828182845904523536028747135266249775724709369995957;\nconst float pi=3.141592653589793238462643383279502884197169;\nconst float n=1.0003;\nconst float N=2.545E25;\nconst float pn=0.035;\nconst vec3 lambda=vec3(680E-9,550E-9,450E-9);\nconst vec3 K=vec3(0.686,0.678,0.666);\nconst float v=4.0;\nconst float rayleighZenithLength=8.4E3;\nconst float mieZenithLength=1.25E3;\nconst vec3 up=vec3(0.0,1.0,0.0);\nconst float EE=1000.0;\nconst float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;\nconst float cutoffAngle=pi/1.95;\nconst float steepness=1.5;\nvec3 totalRayleigh(vec3 lambda)\n{\nreturn (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));\n}\nvec3 simplifiedRayleigh()\n{\nreturn 0.0005/vec3(94,40,18);\n}\nfloat rayleighPhase(float cosTheta)\n{\nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));\n}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{\nfloat c=(0.2*T )*10E-18;\nreturn 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;\n}\nfloat hgPhase(float cosTheta,float g)\n{\nreturn (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));\n}\nfloat sunIntensity(float zenithAngleCos)\n{\nreturn EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));\n}\nfloat A=0.15;\nfloat B=0.50;\nfloat C=0.10;\nfloat D=0.20;\nfloat EEE=0.02;\nfloat F=0.30;\nfloat W=1000.0;\nvec3 Uncharted2Tonemap(vec3 x)\n{\nreturn ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\n\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);\nfloat rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));\nvec3 sunDirection=normalize(sunPosition);\nfloat sunE=sunIntensity(dot(sunDirection,up));\nvec3 betaR=simplifiedRayleigh()*rayleighCoefficient;\nvec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;\nfloat zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));\nfloat sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nfloat sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nvec3 Fex=exp(-(betaR*sR+betaM*sM));\nfloat cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);\nfloat rPhase=rayleighPhase(cosTheta*0.5+0.5);\nvec3 betaRTheta=betaR*rPhase;\nfloat mPhase=hgPhase(cosTheta,mieDirectionalG);\nvec3 betaMTheta=betaM*mPhase;\nvec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));\nLin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));\nvec3 direction=normalize(vPositionW-cameraPosition);\nfloat theta=acos(direction.y);\nfloat phi=atan(direction.z,direction.x);\nvec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);\nvec3 L0=vec3(0.1)*Fex;\nfloat sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);\nL0+=(sunE*19000.0*Fex)*sundisk;\nvec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));\nvec3 texColor=(Lin+L0);\ntexColor*=0.04 ;\ntexColor+=vec3(0.0,0.001,0.0025)*0.3;\nfloat g_fMaxLuminance=1.0;\nfloat fLumScaled=0.1/luminance;\nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled);\nfloat ExposureBias=fLumCompressed;\nvec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);\n\n\n\nvec3 retColor=curr*whiteScale;\n\n\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n\n#include<fogFragment>\ngl_FragColor=color;\n}\n";r.Effect.ShadersStore.skyPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\nvoid main(void) {\ngl_Position=viewProjection*world*vec4(position,1.0);\nvec4 worldPos=world*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.skyVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.POINTSIZE=!1,t.FOG=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.luminance=1,n.turbidity=10,n.rayleigh=2,n.mieCoefficient=.005,n.mieDirectionalG=.8,n.distance=500,n.inclination=.49,n.azimuth=.25,n.sunPosition=new r.Vector3(0,100,0),n.useSunPosition=!1,n.cameraOffset=r.Vector3.Zero(),n._cameraPosition=r.Vector3.Zero(),n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;if(r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,!1,n),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!1),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var a=new r.EffectFallbacks;n.FOG&&a.addFallback(1,"FOG");var f=[r.VertexBuffer.PositionKind];n.VERTEXCOLOR&&f.push(r.VertexBuffer.ColorKind);var l=n.toString();t.setEffect(o.getEngine().createEffect("sky",f,["world","viewProjection","view","vFogInfos","vFogColor","pointSize","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset"],[],l,a,this.onCompiled,this.onError),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene();if(i._materialDefines){var o=i.effect;if(o){this._activeEffect=o,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),this._mustRebind(n,o)&&(r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize)),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect);var a=n.activeCamera;if(a){var s=a.getWorldMatrix();this._cameraPosition.x=s.m[12],this._cameraPosition.y=s.m[13],this._cameraPosition.z=s.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){var f=Math.PI*(this.inclination-.5),l=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(l),this.sunPosition.y=this.distance*Math.sin(l)*Math.sin(f),this.sunPosition.z=this.distance*Math.sin(l)*Math.cos(f)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect)}}},t.prototype.getAnimatables=function(){return[]},t.prototype.dispose=function(t){e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.SkyMaterial",e},t.prototype.getClassName=function(){return"SkyMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serialize)()],t.prototype,"luminance",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"turbidity",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"rayleigh",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"mieCoefficient",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"mieDirectionalG",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"distance",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"inclination",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"azimuth",void 0),Object(n.a)([Object(r.serializeAsVector3)()],t.prototype,"sunPosition",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"useSunPosition",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"cameraOffset",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.SkyMaterial"]=f,i.d(t,"SkyMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\nuniform sampler2D distortionSampler;\nuniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;\nvarying vec2 vDistortionCoords2;\nvarying vec2 vDistortionCoords3;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvec4 bx2(vec4 x)\n{\nreturn vec4(2.0)*x-vec4(1.0);\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\n\nfloat alpha=1.0;\n#ifdef DIFFUSE\n\nconst float distortionAmount0=0.092;\nconst float distortionAmount1=0.092;\nconst float distortionAmount2=0.092;\nvec2 heightAttenuation=vec2(0.3,0.39);\nvec4 noise0=texture2D(distortionSampler,vDistortionCoords1);\nvec4 noise1=texture2D(distortionSampler,vDistortionCoords2);\nvec4 noise2=texture2D(distortionSampler,vDistortionCoords3);\nvec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;\nvec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);\nvec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;\nbaseColor*=opacityColor;\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=vec4(baseColor.rgb,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";r.Effect.ShadersStore.firePixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n\nuniform float time;\nuniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;\nvarying vec2 vDistortionCoords2;\nvarying vec2 vDistortionCoords3;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n\n#ifdef DIFFUSE\nvDiffuseUV=uv;\nvDiffuseUV.y-=0.2;\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\n\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;\nvDistortionCoords1.x=uv.x;\nvDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;\nvDistortionCoords2.x=uv.x;\nvDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;\nvDistortionCoords3.x=uv.x;\nvDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n}\n";r.Effect.ShadersStore.fireVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.UV1=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.BonesPerMesh=0,t.NUM_BONE_INFLUENCERS=0,t.INSTANCES=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.diffuseColor=new r.Color3(1,1,1),n.speed=1,n._scaledDiffuse=new r.Color3,n._lastTime=0,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return!1},t.prototype.needAlphaTesting=function(){return!0},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(n.ALPHATEST=!!this._opacityTexture,n._areMiscDirty&&(n.POINTSIZE=this.pointsCloud||o.forcePointsCloud,n.FOG=o.fogEnabled&&e.applyFog&&o.fogMode!==r.Scene.FOGMODE_NONE&&this.fogEnabled),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!1,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.UV1&&l.push(r.VertexBuffer.UVKind),n.VERTEXCOLOR&&l.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString();t.setEffect(o.getEngine().createEffect("fire",{attributes:l,uniformsNames:["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix","time","speed"],uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene();if(i._materialDefines){var o=i.effect;o&&(this._activeEffect=o,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,o)&&(this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(o,n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._lastTime+=n.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),this._distortionTexture&&t.push(this._distortionTexture),this._opacityTexture&&t.push(this._opacityTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._diffuseTexture===t||(this._distortionTexture===t||this._opacityTexture===t))},t.prototype.getClassName=function(){return"FireMaterial"},t.prototype.dispose=function(t){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.customType="BABYLON.FireMaterial",t.diffuseColor=this.diffuseColor.asArray(),t.speed=this.speed,this._diffuseTexture&&(t._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(t._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(t._opacityTexture=this._opacityTexture.serialize()),t},t.Parse=function(e,i,n){var o=new t(e.name,i);return o.diffuseColor=r.Color3.FromArray(e.diffuseColor),o.speed=e.speed,o.alpha=e.alpha,o.id=e.id,r.Tags.AddTagsTo(o,e.tags),o.backFaceCulling=e.backFaceCulling,o.wireframe=e.wireframe,e._diffuseTexture&&(o._diffuseTexture=r.Texture.Parse(e._diffuseTexture,i,n)),e._distortionTexture&&(o._distortionTexture=r.Texture.Parse(e._distortionTexture,i,n)),e._opacityTexture&&(o._opacityTexture=r.Texture.Parse(e._opacityTexture,i,n)),o},Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),Object(n.a)([Object(r.serializeAsTexture)("distortionTexture")],t.prototype,"_distortionTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"distortionTexture",void 0),Object(n.a)([Object(r.serializeAsTexture)("opacityTexture")],t.prototype,"_opacityTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"opacityTexture",void 0),Object(n.a)([Object(r.serializeAsColor3)("diffuse")],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"speed",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.FireMaterial"]=f,i.d(t,"FireMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\nuniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\nuniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\nuniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(0.,0.,0.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);\nnormalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";r.Effect.ShadersStore.triplanarPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\n\nvec3 xtan=vec3(0,0,1);\nvec3 xbin=vec3(0,1,0);\nvec3 ytan=vec3(1,0,0);\nvec3 ybin=vec3(0,0,1);\nvec3 ztan=vec3(1,0,0);\nvec3 zbin=vec3(0,1,0);\nvec3 normalizedNormal=normalize(normal);\nnormalizedNormal*=normalizedNormal;\nvec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);\nvec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);\nworldTangent=(world*vec4(worldTangent,1.0)).xyz;\nworldBinormal=(world*vec4(worldBinormal,1.0)).xyz;\nvec3 worldNormal=normalize(cross(worldTangent,worldBinormal));\ntangentSpace[0]=worldTangent;\ntangentSpace[1]=worldBinormal;\ntangentSpace[2]=worldNormal;\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.triplanarVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSEX=!1,t.DIFFUSEY=!1,t.DIFFUSEZ=!1,t.BUMPX=!1,t.BUMPY=!1,t.BUMPZ=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.SPECULARTERM=!1,t.NORMAL=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.tileSize=1,n.diffuseColor=new r.Color3(1,1,1),n.specularColor=new r.Color3(.2,.2,.2),n.specularPower=64,n._disableLighting=!1,n._maxSimultaneousLights=4,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(n._areTexturesDirty&&o.texturesEnabled){if(r.MaterialFlags.DiffuseTextureEnabled)for(var f=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],l=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"],u=0;u<f.length;u++)if(f[u]){if(!f[u].isReady())return!1;n[l[u]]=!0}if(r.MaterialFlags.BumpTextureEnabled)for(f=[this.normalTextureX,this.normalTextureY,this.normalTextureZ],l=["BUMPX","BUMPY","BUMPZ"],u=0;u<f.length;u++)if(f[u]){if(!f[u].isReady())return!1;n[l[u]]=!0}}if(r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var c=new r.EffectFallbacks;n.FOG&&c.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,c,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&c.addCPUSkinningFallback(0,e);var d=[r.VertexBuffer.PositionKind];n.NORMAL&&d.push(r.VertexBuffer.NormalKind),n.VERTEXCOLOR&&d.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(d,e,n,c),r.MaterialHelper.PrepareAttributesForInstances(d,n);var p=n.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","tileSize"],v=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ"],m=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:m,samplers:v,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(o.getEngine().createEffect("triplanar",{attributes:d,uniformsNames:h,uniformBuffersNames:m,samplers:v,defines:p,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),n.getCachedMaterial()!==this&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTextureX&&t.push(this._diffuseTextureX),this._diffuseTextureY&&t.push(this._diffuseTextureY),this._diffuseTextureZ&&t.push(this._diffuseTextureZ),this._normalTextureX&&t.push(this._normalTextureX),this._normalTextureY&&t.push(this._normalTextureY),this._normalTextureZ&&t.push(this._normalTextureZ),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._diffuseTextureX===t||(this._diffuseTextureY===t||(this._diffuseTextureZ===t||(this._normalTextureX===t||(this._normalTextureY===t||this._normalTextureZ===t)))))},t.prototype.dispose=function(t){this.mixTexture&&this.mixTexture.dispose(),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.TriPlanarMaterial",e},t.prototype.getClassName=function(){return"TriPlanarMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serializeAsTexture)()],t.prototype,"mixTexture",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTextureX")],t.prototype,"_diffuseTextureX",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTextureX",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexturY")],t.prototype,"_diffuseTextureY",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTextureY",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTextureZ")],t.prototype,"_diffuseTextureZ",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTextureZ",void 0),Object(n.a)([Object(r.serializeAsTexture)("normalTextureX")],t.prototype,"_normalTextureX",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"normalTextureX",void 0),Object(n.a)([Object(r.serializeAsTexture)("normalTextureY")],t.prototype,"_normalTextureY",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"normalTextureY",void 0),Object(n.a)([Object(r.serializeAsTexture)("normalTextureZ")],t.prototype,"_normalTextureZ",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"normalTextureZ",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"tileSize",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"specularColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"specularPower",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.TriPlanarMaterial"]=f,i.d(t,"TriPlanarMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nuniform vec4 furColor;\nuniform float furLength;\nvarying vec3 vPositionW;\nvarying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef HIGHLEVEL\nuniform float furOffset;\nuniform float furOcclusion;\nuniform sampler2D furTexture;\nvarying vec2 vFurUV;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<fogFragmentDeclaration>\n#include<clipPlaneFragmentDeclaration>\nfloat Rand(vec3 rv) {\nfloat x=dot(rv,vec3(12.9898,78.233,24.65487));\nreturn fract(sin(x)*43758.5453);\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=furColor;\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\n\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));\nif (furTextureColor.a<=0.0 || furTextureColor.g<furOffset) {\ndiscard;\n}\nfloat occlusion=mix(0.0,furTextureColor.b*1.2,furOffset);\nbaseColor=vec4(baseColor.xyz*max(occlusion,furOcclusion),1.1-furOffset);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;\nvec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include<fogFragment>\ngl_FragColor=color;\n}";r.Effect.ShadersStore.furPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform float furLength;\nuniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;\nuniform vec3 furGravity;\nuniform float furTime;\nuniform float furSpacing;\nuniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {\nfloat x=dot(rv,vec3(12.9898,78.233,24.65487));\nreturn fract(sin(x)*43758.5453);\n}\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\n\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else\nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);\nvec3 tangent2=vec3(-normal.z,0,normal.x);\nr=Rand(tangent1*r);\nfloat J=(2.0+4.0*r);\nr=Rand(tangent2*r);\nfloat K=(2.0+2.0*r);\ntangent1=tangent1*J+tangent2*K;\ntangent1=normalize(tangent1);\nvec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\n\nvec3 forceDirection=vec3(0.0,0.0,0.0);\nforceDirection.x=sin(furTime+position.x*0.05)*0.2;\nforceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;\nforceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;\nvec3 displacement=vec3(0.0,0.0,0.0);\ndisplacement=furGravity+forceDirection;\nfloat displacementFactor=pow(furOffset,3.0);\nvec3 aNormal=normal;\naNormal.xyz+=displacement*displacementFactor;\nnewPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);\nvec4 worldPos=finalWorld*vec4(newPosition,1.0);\nvPositionW=vec3(worldPos);\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.furVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.HEIGHTMAP=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.HIGHLEVEL=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.diffuseColor=new r.Color3(1,1,1),n.furLength=1,n.furAngle=0,n.furColor=new r.Color3(.44,.21,.02),n.furOffset=0,n.furSpacing=12,n.furGravity=new r.Vector3(0,0,0),n.furSpeed=100,n.furDensity=20,n.furOcclusion=0,n._disableLighting=!1,n._maxSimultaneousLights=4,n.highLevelFur=!0,n._furTime=0,n}return Object(n.b)(t,e),Object.defineProperty(t.prototype,"furTime",{get:function(){return this._furTime},set:function(e){this._furTime=e},enumerable:!0,configurable:!0}),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.updateFur=function(){for(var e=1;e<this._meshes.length;e++){var t=this._meshes[e].material;t.furLength=this.furLength,t.furAngle=this.furAngle,t.furGravity=this.furGravity,t.furSpacing=this.furSpacing,t.furSpeed=this.furSpeed,t.furColor=this.furColor,t.diffuseTexture=this.diffuseTexture,t.furTexture=this.furTexture,t.highLevelFur=this.highLevelFur,t.furTime=this.furTime,t.furDensity=this.furDensity}},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(n._areTexturesDirty&&o.texturesEnabled){if(this.diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(this.heightTexture&&a.getCaps().maxVertexTextureImageUnits){if(!this.heightTexture.isReady())return!1;n._needUVs=!0,n.HEIGHTMAP=!0}}if(this.highLevelFur!==n.HIGHLEVEL&&(n.HIGHLEVEL=!0,n.markAsUnprocessed()),r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,f,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.NORMAL&&l.push(r.VertexBuffer.NormalKind),n.UV1&&l.push(r.VertexBuffer.UVKind),n.UV2&&l.push(r.VertexBuffer.UV2Kind),n.VERTEXCOLOR&&l.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"],d=["diffuseSampler","heightTexture","furTexture"],p=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(o.getEngine().createEffect("fur",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),n.getCachedMaterial()!==this&&(this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),this._heightTexture&&t.push(this._heightTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this.diffuseTexture===t||this._heightTexture===t)},t.prototype.dispose=function(t){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(var i=1;i<this._meshes.length;i++){var n=this._meshes[i].material;n&&n.dispose(t),this._meshes[i].dispose()}e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e},t.prototype.getClassName=function(){return"FurMaterial"},t.Parse=function(e,i,n){var o=r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n);return e.sourceMeshName&&o.highLevelFur&&i.executeWhenReady(function(){var n=i.getMeshByName(e.sourceMeshName);if(n){var r=t.GenerateTexture("Fur Texture",i);o.furTexture=r,t.FurifyMesh(n,e.quality)}}),o},t.GenerateTexture=function(e,t){for(var i=new r.DynamicTexture("FurTexture "+e,256,t,!0),n=i.getContext(),o=0;o<2e4;++o)n.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",n.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=r.Texture.WRAP_ADDRESSMODE,i.wrapV=r.Texture.WRAP_ADDRESSMODE,i},t.FurifyMesh=function(e,i){var n,o=[e],a=e.material;if(!(a instanceof t))throw"The material of the source mesh must be a Fur Material";for(n=1;n<i;n++){var s=new t(a.name+n,e.getScene());e.getScene().materials.pop(),r.Tags.EnableFor(s),r.Tags.AddTagsTo(s,"furShellMaterial"),s.furLength=a.furLength,s.furAngle=a.furAngle,s.furGravity=a.furGravity,s.furSpacing=a.furSpacing,s.furSpeed=a.furSpeed,s.furColor=a.furColor,s.diffuseTexture=a.diffuseTexture,s.furOffset=n/i,s.furTexture=a.furTexture,s.highLevelFur=a.highLevelFur,s.furTime=a.furTime,s.furDensity=a.furDensity;var f=e.clone(e.name+n);f.material=s,f.skeleton=e.skeleton,f.position=r.Vector3.Zero(),o.push(f)}for(n=1;n<o.length;n++)o[n].parent=e;return e.material._meshes=o,o},Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),Object(n.a)([Object(r.serializeAsTexture)("heightTexture")],t.prototype,"_heightTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"heightTexture",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"furLength",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"furAngle",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"furColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"furOffset",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"furSpacing",void 0),Object(n.a)([Object(r.serializeAsVector3)()],t.prototype,"furGravity",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"furSpeed",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"furDensity",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"furOcclusion",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"highLevelFur",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"furTime",null),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.FurMaterial"]=f,i.d(t,"FurMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform sampler2D textureSampler;\nuniform vec2 vTextureInfos;\nuniform sampler2D diffuse1Sampler;\nuniform sampler2D diffuse2Sampler;\nuniform sampler2D diffuse3Sampler;\nuniform vec2 diffuse1Infos;\nuniform vec2 diffuse2Infos;\nuniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;\nuniform sampler2D bump2Sampler;\nuniform sampler2D bump3Sampler;\n#endif\n\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{\nvec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;\nvec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;\nvec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;\nbump1Color.rgb*=mixColor.r;\nbump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);\nvec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);\nmap=map*255./127.-128./127.;\nmat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);\nreturn normalize(TBN*map);\n}\n#endif\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vTextureInfos.y;\nvec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);\nvec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);\nvec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);\ndiffuse1Color.rgb*=baseColor.r;\ndiffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);\nbaseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";r.Effect.ShadersStore.terrainPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform mat4 textureMatrix;\nuniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x == 0.)\n{\nvTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.terrainVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.BUMP=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.SPECULARTERM=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.diffuseColor=new r.Color3(1,1,1),n.specularColor=new r.Color3(0,0,0),n.specularPower=64,n._disableLighting=!1,n._maxSimultaneousLights=4,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(o.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(n._needUVs=!0,r.MaterialFlags.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady())return!1;if(!this.diffuseTexture2||!this.diffuseTexture2.isReady())return!1;if(!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;n.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&r.MaterialFlags.BumpTextureEnabled){if(!this.bumpTexture1.isReady())return!1;if(!this.bumpTexture2.isReady())return!1;if(!this.bumpTexture3.isReady())return!1;n._needNormals=!0,n.BUMP=!0}}if(r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,f,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.NORMAL&&l.push(r.VertexBuffer.NormalKind),n.UV1&&l.push(r.VertexBuffer.UVKind),n.UV2&&l.push(r.VertexBuffer.UV2Kind),n.VERTEXCOLOR&&l.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],d=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler"],p=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(o.getEngine().createEffect("terrain",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,a)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),r.MaterialFlags.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),r.MaterialFlags.BumpTextureEnabled&&n.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._mixTexture&&t.push(this._mixTexture),this._diffuseTexture1&&t.push(this._diffuseTexture1),this._diffuseTexture2&&t.push(this._diffuseTexture2),this._diffuseTexture3&&t.push(this._diffuseTexture3),this._bumpTexture1&&t.push(this._bumpTexture1),this._bumpTexture2&&t.push(this._bumpTexture2),this._bumpTexture3&&t.push(this._bumpTexture3),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._mixTexture===t||(this._diffuseTexture1===t||(this._diffuseTexture2===t||(this._diffuseTexture3===t||(this._bumpTexture1===t||(this._bumpTexture2===t||this._bumpTexture3===t))))))},t.prototype.dispose=function(t){this.mixTexture&&this.mixTexture.dispose(),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.TerrainMaterial",e},t.prototype.getClassName=function(){return"TerrainMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serializeAsTexture)("mixTexture")],t.prototype,"_mixTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"mixTexture",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture1")],t.prototype,"_diffuseTexture1",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture1",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture2")],t.prototype,"_diffuseTexture2",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture2",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture3")],t.prototype,"_diffuseTexture3",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture3",void 0),Object(n.a)([Object(r.serializeAsTexture)("bumpTexture1")],t.prototype,"_bumpTexture1",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture1",void 0),Object(n.a)([Object(r.serializeAsTexture)("bumpTexture2")],t.prototype,"_bumpTexture2",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture2",void 0),Object(n.a)([Object(r.serializeAsTexture)("bumpTexture3")],t.prototype,"_bumpTexture3",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture3",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"specularColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"specularPower",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.TerrainMaterial"]=f,i.d(t,"TerrainMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\n\nuniform vec4 topColor;\nuniform vec4 bottomColor;\nuniform float offset;\nuniform float scale;\nuniform float smoothness;\n\nvarying vec3 vPositionW;\nvarying vec3 vPosition;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\nfloat h=vPosition.y*scale+offset;\nfloat mysmoothness=clamp(smoothness,0.01,max(smoothness,10.));\nvec4 baseColor=mix(bottomColor,topColor,max(pow(max(h,0.0),mysmoothness),0.0));\n\nvec3 diffuseColor=baseColor.rgb;\n\nfloat alpha=baseColor.a;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\n#ifdef EMISSIVE\nvec3 diffuseBase=baseColor.rgb;\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";r.Effect.ShadersStore.gradientPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vPosition;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvPosition=position;\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.gradientVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.EMISSIVE=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n._maxSimultaneousLights=4,n.topColor=new r.Color3(1,0,0),n.topColorAlpha=1,n.bottomColor=new r.Color3(0,0,1),n.bottomColorAlpha=1,n.offset=0,n.scale=1,n.smoothness=1,n._disableLighting=!1,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1||this.topColorAlpha<1||this.bottomColorAlpha<1},t.prototype.needAlphaTesting=function(){return!0},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),n.EMISSIVE=this._disableLighting,r.MaterialHelper.PrepareDefinesForAttributes(e,n,!1,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,f),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.NORMAL&&l.push(r.VertexBuffer.NormalKind),n.UV1&&l.push(r.VertexBuffer.UVKind),n.UV2&&l.push(r.VertexBuffer.UV2Kind),n.VERTEXCOLOR&&l.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","topColor","bottomColor","offset","smoothness","scale"],d=[],p=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:4}),t.setEffect(o.getEngine().createEffect("gradient",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,a),this._mustRebind(n,a)&&(r.MaterialHelper.BindClipPlane(a,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){return[]},t.prototype.dispose=function(t){e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.GradientMaterial",e},t.prototype.getClassName=function(){return"GradientMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"topColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"topColorAlpha",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"bottomColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"bottomColorAlpha",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"offset",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"scale",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"smoothness",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.GradientMaterial"]=f,i.d(t,"GradientMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{\ndiffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;\nif (info.ndl<0.5)\nlevel=0.5;\ndiffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];\nToonThresholds[0]=0.95;\nToonThresholds[1]=0.5;\nToonThresholds[2]=0.2;\nToonThresholds[3]=0.03;\nfloat ToonBrightnessLevels[5];\nToonBrightnessLevels[0]=1.0;\nToonBrightnessLevels[1]=0.8;\nToonBrightnessLevels[2]=0.6;\nToonBrightnessLevels[3]=0.35;\nToonBrightnessLevels[4]=0.2;\nif (info.ndl>ToonThresholds[0])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[0];\n}\nelse if (info.ndl>ToonThresholds[1])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[1];\n}\nelse if (info.ndl>ToonThresholds[2])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[2];\n}\nelse if (info.ndl>ToonThresholds[3])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[3];\n}\nelse\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[4];\n}\n#endif\nreturn max(diffuseBase,vec3(0.2));\n}\nvoid main(void)\n{\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nlightingInfo info;\nvec3 diffuseBase=vec3(0.,0.,0.);\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";r.Effect.ShadersStore.cellPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.cellVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.NDOTL=!0,t.CUSTOMUSERLIGHTING=!0,t.CELLBASIC=!0,t.DEPTHPREPASS=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.diffuseColor=new r.Color3(1,1,1),n._computeHighLevel=!1,n._disableLighting=!1,n._maxSimultaneousLights=4,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,o.texturesEnabled&&this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(n.CELLBASIC=!this.computeHighLevel,r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,f,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.NORMAL&&l.push(r.VertexBuffer.NormalKind),n.UV1&&l.push(r.VertexBuffer.UVKind),n.UV2&&l.push(r.VertexBuffer.UV2Kind),n.VERTEXCOLOR&&l.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix"],d=["diffuseSampler"],p=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(o.getEngine().createEffect("cell",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,a)&&(this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,this._maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||this._diffuseTexture===t},t.prototype.dispose=function(t){this._diffuseTexture&&this._diffuseTexture.dispose(),e.prototype.dispose.call(this,t)},t.prototype.getClassName=function(){return"CellMaterial"},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.CellMaterial",e},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),Object(n.a)([Object(r.serializeAsColor3)("diffuse")],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serialize)("computeHighLevel")],t.prototype,"_computeHighLevel",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"computeHighLevel",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.CellMaterial"]=f,i.d(t,"CellMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n}\nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5);\nfractionPartOfPosition/=differentialLength;\nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI);\nreturn result;\n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2;\n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset.xyz)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\nfloat opacity=1.0;\n#ifdef TRANSPARENT\nopacity=clamp(grid,0.08,gridControl.w*grid);\n#endif\n#ifdef OPACITY\nopacity*=texture2D(opacitySampler,vOpacityUV).a;\n#endif\n\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef TRANSPARENT\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n#endif\n}";r.Effect.ShadersStore.gridPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#include<instancesDeclaration>\n\nuniform mat4 projection;\nuniform mat4 view;\n\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#ifdef FOG\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=view*finalWorld*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef OPACITY\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\nvPosition=position;\nvNormal=normal;\n}";r.Effect.ShadersStore.gridVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.OPACITY=!1,t.TRANSPARENT=!1,t.FOG=!1,t.PREMULTIPLYALPHA=!1,t.UV1=!1,t.UV2=!1,t.INSTANCES=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.mainColor=r.Color3.Black(),n.lineColor=r.Color3.Teal(),n.gridRatio=1,n.gridOffset=r.Vector3.Zero(),n.majorUnitFrequency=10,n.minorUnitVisibility=.33,n.opacity=1,n.preMultiplyAlpha=!1,n._gridControl=new r.Vector4(n.gridRatio,n.majorUnitFrequency,n.minorUnitVisibility,n.opacity),n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()},t.prototype.needAlphaBlendingForMesh=function(e){return this.needAlphaBlending()},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;if(n.TRANSPARENT!==this.opacity<1&&(n.TRANSPARENT=!n.TRANSPARENT,n.markAsUnprocessed()),n.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(n.PREMULTIPLYALPHA=!n.PREMULTIPLYALPHA,n.markAsUnprocessed()),n._areTexturesDirty&&(n._needUVs=!1,o.texturesEnabled&&this._opacityTexture&&r.MaterialFlags.OpacityTextureEnabled)){if(!this._opacityTexture.isReady())return!1;n._needUVs=!0,n.OPACITY=!0}if(r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,!1,this.fogEnabled,!1,n),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,o.getEngine(),n,!!i),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial(),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!1,!1);var a=[r.VertexBuffer.PositionKind,r.VertexBuffer.NormalKind];n.UV1&&a.push(r.VertexBuffer.UVKind),n.UV2&&a.push(r.VertexBuffer.UV2Kind),r.MaterialHelper.PrepareAttributesForInstances(a,n);var f=n.toString();t.setEffect(o.getEngine().createEffect("grid",a,["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos"],["opacitySampler"],f,void 0,this.onCompiled,this.onError),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,o.INSTANCES||this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",n.getViewMatrix()),this._activeEffect.setMatrix("projection",n.getProjectionMatrix()),this._mustRebind(n,a)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&r.MaterialFlags.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix()))),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},t.prototype.dispose=function(t){e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.GridMaterial",e},t.prototype.getClassName=function(){return"GridMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"mainColor",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"lineColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"gridRatio",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"gridOffset",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"majorUnitFrequency",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"minorUnitVisibility",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"opacity",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"preMultiplyAlpha",void 0),Object(n.a)([Object(r.serializeAsTexture)("opacityTexture")],t.prototype,"_opacityTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"opacityTexture",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.GridMaterial"]=f,i.d(t,"GridMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";r.Effect.ShadersStore.simplePixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.simpleVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.diffuseColor=new r.Color3(1,1,1),n._disableLighting=!1,n._maxSimultaneousLights=4,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,o.texturesEnabled&&this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,f,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.NORMAL&&l.push(r.VertexBuffer.NormalKind),n.UV1&&l.push(r.VertexBuffer.UVKind),n.UV2&&l.push(r.VertexBuffer.UV2Kind),n.VERTEXCOLOR&&l.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix"],d=["diffuseSampler"],p=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(o.getEngine().createEffect("simple",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,a)&&(this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||this.diffuseTexture===t},t.prototype.dispose=function(t){this._diffuseTexture&&this._diffuseTexture.dispose(),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.SimpleMaterial",e},t.prototype.getClassName=function(){return"SimpleMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),Object(n.a)([Object(r.serializeAsColor3)("diffuse")],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.SimpleMaterial"]=f,i.d(t,"SimpleMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n\nuniform float time;\nuniform float speed;\nuniform float movingSpeed;\nuniform vec3 fogColor;\nuniform sampler2D noiseTexture;\nuniform float fogDensity;\n\nvarying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nfloat random( vec3 scale,float seed ){\nreturn fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;\n}\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\n\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );\nvec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time*0.02;\nvec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;\nT1.x+=noiseTex.x*2.0;\nT1.y+=noiseTex.y*2.0;\nT2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;\nT2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;\nfloat p=texture2D( noiseTexture,T1*3.0 ).a;\nvec4 lavaColor=texture2D( diffuseSampler,T2*4.0);\nvec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );\nbaseColor=temp;\nfloat depth=gl_FragCoord.z*4.0;\nconst float LOG2=1.442695;\nfloat fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );\nfogFactor=1.0-clamp( fogFactor,0.0,1.0 );\nbaseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );\ndiffuseColor=baseColor.rgb;\n\n\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";r.Effect.ShadersStore.lavaPixelShader=o;var a="precision highp float;\n\nuniform float time;\nuniform float lowFrequencySpeed;\n\nvarying float noise;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n\n\nvec3 mod289(vec3 x)\n{\nreturn x-floor(x*(1.0/289.0))*289.0;\n}\nvec4 mod289(vec4 x)\n{\nreturn x-floor(x*(1.0/289.0))*289.0;\n}\nvec4 permute(vec4 x)\n{\nreturn mod289(((x*34.0)+1.0)*x);\n}\nvec4 taylorInvSqrt(vec4 r)\n{\nreturn 1.79284291400159-0.85373472095314*r;\n}\nvec3 fade(vec3 t) {\nreturn t*t*t*(t*(t*6.0-15.0)+10.0);\n}\n\nfloat pnoise(vec3 P,vec3 rep)\n{\nvec3 Pi0=mod(floor(P),rep);\nvec3 Pi1=mod(Pi0+vec3(1.0),rep);\nPi0=mod289(Pi0);\nPi1=mod289(Pi1);\nvec3 Pf0=fract(P);\nvec3 Pf1=Pf0-vec3(1.0);\nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);\nvec4 iy=vec4(Pi0.yy,Pi1.yy);\nvec4 iz0=Pi0.zzzz;\nvec4 iz1=Pi1.zzzz;\nvec4 ixy=permute(permute(ix)+iy);\nvec4 ixy0=permute(ixy+iz0);\nvec4 ixy1=permute(ixy+iz1);\nvec4 gx0=ixy0*(1.0/7.0);\nvec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;\ngx0=fract(gx0);\nvec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);\nvec4 sz0=step(gz0,vec4(0.0));\ngx0-=sz0*(step(0.0,gx0)-0.5);\ngy0-=sz0*(step(0.0,gy0)-0.5);\nvec4 gx1=ixy1*(1.0/7.0);\nvec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;\ngx1=fract(gx1);\nvec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);\nvec4 sz1=step(gz1,vec4(0.0));\ngx1-=sz1*(step(0.0,gx1)-0.5);\ngy1-=sz1*(step(0.0,gy1)-0.5);\nvec3 g000=vec3(gx0.x,gy0.x,gz0.x);\nvec3 g100=vec3(gx0.y,gy0.y,gz0.y);\nvec3 g010=vec3(gx0.z,gy0.z,gz0.z);\nvec3 g110=vec3(gx0.w,gy0.w,gz0.w);\nvec3 g001=vec3(gx1.x,gy1.x,gz1.x);\nvec3 g101=vec3(gx1.y,gy1.y,gz1.y);\nvec3 g011=vec3(gx1.z,gy1.z,gz1.z);\nvec3 g111=vec3(gx1.w,gy1.w,gz1.w);\nvec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));\ng000*=norm0.x;\ng010*=norm0.y;\ng100*=norm0.z;\ng110*=norm0.w;\nvec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));\ng001*=norm1.x;\ng011*=norm1.y;\ng101*=norm1.z;\ng111*=norm1.w;\nfloat n000=dot(g000,Pf0);\nfloat n100=dot(g100,vec3(Pf1.x,Pf0.yz));\nfloat n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));\nfloat n110=dot(g110,vec3(Pf1.xy,Pf0.z));\nfloat n001=dot(g001,vec3(Pf0.xy,Pf1.z));\nfloat n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));\nfloat n011=dot(g011,vec3(Pf0.x,Pf1.yz));\nfloat n111=dot(g111,Pf1);\nvec3 fade_xyz=fade(Pf0);\nvec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);\nvec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);\nfloat n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);\nreturn 2.2*n_xyz;\n}\n\nfloat turbulence( vec3 p ) {\nfloat w=100.0;\nfloat t=-.5;\nfor (float f=1.0 ; f<=10.0 ; f++ ){\nfloat power=pow( 2.0,f );\nt+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );\n}\nreturn t;\n}\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef NORMAL\n\nnoise=10.0*-.10*turbulence( .5*normal+time*1.15 );\n\nfloat b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );\n\nfloat displacement =-1.5*noise+b;\n\nvec3 newPosition=position+normal*displacement;\ngl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );\nvec4 worldPos=finalWorld*vec4(newPosition,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}";r.Effect.ShadersStore.lavaVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.LIGHT0=!1,t.LIGHT1=!1,t.LIGHT2=!1,t.LIGHT3=!1,t.SPOTLIGHT0=!1,t.SPOTLIGHT1=!1,t.SPOTLIGHT2=!1,t.SPOTLIGHT3=!1,t.HEMILIGHT0=!1,t.HEMILIGHT1=!1,t.HEMILIGHT2=!1,t.HEMILIGHT3=!1,t.DIRLIGHT0=!1,t.DIRLIGHT1=!1,t.DIRLIGHT2=!1,t.DIRLIGHT3=!1,t.POINTLIGHT0=!1,t.POINTLIGHT1=!1,t.POINTLIGHT2=!1,t.POINTLIGHT3=!1,t.SHADOW0=!1,t.SHADOW1=!1,t.SHADOW2=!1,t.SHADOW3=!1,t.SHADOWS=!1,t.SHADOWESM0=!1,t.SHADOWESM1=!1,t.SHADOWESM2=!1,t.SHADOWESM3=!1,t.SHADOWPOISSON0=!1,t.SHADOWPOISSON1=!1,t.SHADOWPOISSON2=!1,t.SHADOWPOISSON3=!1,t.SHADOWPCF0=!1,t.SHADOWPCF1=!1,t.SHADOWPCF2=!1,t.SHADOWPCF3=!1,t.SHADOWPCSS0=!1,t.SHADOWPCSS1=!1,t.SHADOWPCSS2=!1,t.SHADOWPCSS3=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.UNLIT=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.speed=1,n.movingSpeed=1,n.lowFrequencySpeed=1,n.fogDensity=.15,n._lastTime=0,n.diffuseColor=new r.Color3(1,1,1),n._disableLighting=!1,n._unlit=!1,n._maxSimultaneousLights=4,n._scaledDiffuse=new r.Color3,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,o.texturesEnabled&&this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=!0,r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,f),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.NORMAL&&l.push(r.VertexBuffer.NormalKind),n.UV1&&l.push(r.VertexBuffer.UVKind),n.UV2&&l.push(r.VertexBuffer.UV2Kind),n.VERTEXCOLOR&&l.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"],d=["diffuseSampler","noiseTexture"],p=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(o.getEngine().createEffect("lava",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,o.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,a)&&(this.diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._lastTime+=n.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=r.Color3.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||this.diffuseTexture===t},t.prototype.dispose=function(t){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.LavaMaterial",e},t.prototype.getClassName=function(){return"LavaMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),Object(n.a)([Object(r.serializeAsTexture)()],t.prototype,"noiseTexture",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"fogColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"speed",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"movingSpeed",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"lowFrequencySpeed",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"fogDensity",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("unlit")],t.prototype,"_unlit",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"unlit",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.LavaMaterial"]=f,i.d(t,"LavaMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform float alpha;\nuniform vec3 shadowColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0..1]\n\nvec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";r.Effect.ShadersStore.shadowOnlyPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.shadowOnlyVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.shadowColor=r.Color3.Black(),n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return!0},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},Object.defineProperty(t.prototype,"activeLight",{get:function(){return this._activeLight},set:function(e){this._activeLight=e},enumerable:!0,configurable:!0}),t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(this._activeLight)for(var f=0,l=e.lightSources;f<l.length;f++){var u=l[f];if(u.shadowEnabled){if(this._activeLight===u)break;var c=e.lightSources.indexOf(this._activeLight);-1!==c&&(e.lightSources.splice(c,1),e.lightSources.splice(0,0,this._activeLight));break}}if(r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,1),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!1,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var d=new r.EffectFallbacks;n.FOG&&d.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,d,1),n.NUM_BONE_INFLUENCERS>0&&d.addCPUSkinningFallback(0,e);var p=[r.VertexBuffer.PositionKind];n.NORMAL&&p.push(r.VertexBuffer.NormalKind),r.MaterialHelper.PrepareAttributesForBones(p,e,n,d),r.MaterialHelper.PrepareAttributesForInstances(p,n);var h=n.toString(),v=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6"],m=new Array,g=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:v,uniformBuffersNames:g,samplers:m,defines:n,maxSimultaneousLights:1}),t.setEffect(o.getEngine().createEffect("shadowOnly",{attributes:p,uniformsNames:v,uniformBuffersNames:g,samplers:m,defines:h,fallbacks:d,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,a)&&(r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),r.MaterialHelper.BindEyePosition(a,n)),n.lightsEnabled&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,1),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.ShadowOnlyMaterial",e},t.prototype.getClassName=function(){return"ShadowOnlyMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.ShadowOnlyMaterial"]=f,i.d(t,"ShadowOnlyMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform sampler2D mixMap1Sampler;\nuniform vec2 vTextureInfos;\n#ifdef MIXMAP2\nuniform sampler2D mixMap2Sampler;\n#endif\nuniform sampler2D diffuse1Sampler;\nuniform sampler2D diffuse2Sampler;\nuniform sampler2D diffuse3Sampler;\nuniform sampler2D diffuse4Sampler;\nuniform vec2 diffuse1Infos;\nuniform vec2 diffuse2Infos;\nuniform vec2 diffuse3Infos;\nuniform vec2 diffuse4Infos;\n#ifdef MIXMAP2\nuniform sampler2D diffuse5Sampler;\nuniform sampler2D diffuse6Sampler;\nuniform sampler2D diffuse7Sampler;\nuniform sampler2D diffuse8Sampler;\nuniform vec2 diffuse5Infos;\nuniform vec2 diffuse6Infos;\nuniform vec2 diffuse7Infos;\nuniform vec2 diffuse8Infos;\n#endif\n#endif\n\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 finalMixColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef MIXMAP2\nvec4 mixColor2=vec4(1.,1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec4 mixColor=texture2D(mixMap1Sampler,vTextureUV);\n#include<depthPrePass>\nmixColor.rgb*=vTextureInfos.y;\nvec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);\nvec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);\nvec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);\nvec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);\ndiffuse1Color.rgb*=mixColor.r;\ndiffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);\ndiffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);\nfinalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a);\n#ifdef MIXMAP2\nmixColor=texture2D(mixMap2Sampler,vTextureUV);\nmixColor.rgb*=vTextureInfos.y;\nvec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);\nvec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);\nvec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);\nvec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);\ndiffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);\ndiffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);\ndiffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);\nfinalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a);\n#endif\n#endif\n#ifdef VERTEXCOLOR\nfinalMixColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";r.Effect.ShadersStore.mixPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform mat4 textureMatrix;\nuniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x == 0.)\n{\nvTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.mixVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.SPECULARTERM=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.VERTEXCOLOR=!1,t.VERTEXALPHA=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.MIXMAP2=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.diffuseColor=new r.Color3(1,1,1),n.specularColor=new r.Color3(0,0,0),n.specularPower=64,n._disableLighting=!1,n._maxSimultaneousLights=4,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(o.texturesEnabled){if(!this._mixTexture1||!this._mixTexture1.isReady())return!1;if(n._needUVs=!0,r.MaterialFlags.DiffuseTextureEnabled){if(!this._diffuseTexture1||!this._diffuseTexture1.isReady())return!1;if(n.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())return!1;if(!this._diffuseTexture3||!this._diffuseTexture3.isReady())return!1;if(!this._diffuseTexture4||!this._diffuseTexture4.isReady())return!1;if(this._mixTexture2){if(!this._mixTexture2.isReady())return!1;if(n.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())return!1;if(!this._diffuseTexture6||!this._diffuseTexture6.isReady())return!1;if(!this._diffuseTexture7||!this._diffuseTexture7.isReady())return!1;if(!this._diffuseTexture8||!this._diffuseTexture8.isReady())return!1}}}if(r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,f,this.maxSimultaneousLights),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.NORMAL&&l.push(r.VertexBuffer.NormalKind),n.UV1&&l.push(r.VertexBuffer.UVKind),n.UV2&&l.push(r.VertexBuffer.UV2Kind),n.VERTEXCOLOR&&l.push(r.VertexBuffer.ColorKind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],d=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],p=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(o.getEngine().createEffect("mix",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,a)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),r.MaterialFlags.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),r.MaterialFlags.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o,this.maxSimultaneousLights),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._mixTexture1&&t.push(this._mixTexture1),this._diffuseTexture1&&t.push(this._diffuseTexture1),this._diffuseTexture2&&t.push(this._diffuseTexture2),this._diffuseTexture3&&t.push(this._diffuseTexture3),this._diffuseTexture4&&t.push(this._diffuseTexture4),this._mixTexture2&&t.push(this._mixTexture2),this._diffuseTexture5&&t.push(this._diffuseTexture5),this._diffuseTexture6&&t.push(this._diffuseTexture6),this._diffuseTexture7&&t.push(this._diffuseTexture7),this._diffuseTexture8&&t.push(this._diffuseTexture8),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._mixTexture1===t||(this._diffuseTexture1===t||(this._diffuseTexture2===t||(this._diffuseTexture3===t||(this._diffuseTexture4===t||(this._mixTexture2===t||(this._diffuseTexture5===t||(this._diffuseTexture6===t||(this._diffuseTexture7===t||this._diffuseTexture8===t)))))))))},t.prototype.dispose=function(t){this._mixTexture1&&this._mixTexture1.dispose(),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.MixMaterial",e},t.prototype.getClassName=function(){return"MixMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serializeAsTexture)("mixTexture1")],t.prototype,"_mixTexture1",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"mixTexture1",void 0),Object(n.a)([Object(r.serializeAsTexture)("mixTexture2")],t.prototype,"_mixTexture2",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"mixTexture2",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture1")],t.prototype,"_diffuseTexture1",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture1",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture2")],t.prototype,"_diffuseTexture2",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture2",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture3")],t.prototype,"_diffuseTexture3",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture3",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture4")],t.prototype,"_diffuseTexture4",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture4",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture1")],t.prototype,"_diffuseTexture5",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture5",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture2")],t.prototype,"_diffuseTexture6",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture6",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture3")],t.prototype,"_diffuseTexture7",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture7",void 0),Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture4")],t.prototype,"_diffuseTexture8",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture8",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"specularColor",void 0),Object(n.a)([Object(r.serialize)()],t.prototype,"specularPower",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.MixMaterial"]=f,i.d(t,"MixMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef LIGHTING\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\n#ifdef LIGHTING\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=baseColor.rgb;\n#endif\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";r.Effect.ShadersStore.normalPixelShader=o;var a="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";r.Effect.ShadersStore.normalVertexShader=a;var s=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.ALPHATEST=!1,t.DEPTHPREPASS=!1,t.POINTSIZE=!1,t.FOG=!1,t.LIGHT0=!1,t.LIGHT1=!1,t.LIGHT2=!1,t.LIGHT3=!1,t.SPOTLIGHT0=!1,t.SPOTLIGHT1=!1,t.SPOTLIGHT2=!1,t.SPOTLIGHT3=!1,t.HEMILIGHT0=!1,t.HEMILIGHT1=!1,t.HEMILIGHT2=!1,t.HEMILIGHT3=!1,t.DIRLIGHT0=!1,t.DIRLIGHT1=!1,t.DIRLIGHT2=!1,t.DIRLIGHT3=!1,t.POINTLIGHT0=!1,t.POINTLIGHT1=!1,t.POINTLIGHT2=!1,t.POINTLIGHT3=!1,t.SHADOW0=!1,t.SHADOW1=!1,t.SHADOW2=!1,t.SHADOW3=!1,t.SHADOWS=!1,t.SHADOWESM0=!1,t.SHADOWESM1=!1,t.SHADOWESM2=!1,t.SHADOWESM3=!1,t.SHADOWPOISSON0=!1,t.SHADOWPOISSON1=!1,t.SHADOWPOISSON2=!1,t.SHADOWPOISSON3=!1,t.SHADOWPCF0=!1,t.SHADOWPCF1=!1,t.SHADOWPCF2=!1,t.SHADOWPCF3=!1,t.SHADOWPCSS0=!1,t.SHADOWPCSS1=!1,t.SHADOWPCSS2=!1,t.SHADOWPCSS3=!1,t.NORMAL=!1,t.UV1=!1,t.UV2=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.LIGHTING=!1,t.rebuild(),t}return Object(n.b)(t,e),t}(r.MaterialDefines),f=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.diffuseColor=new r.Color3(1,1,1),n._disableLighting=!1,n._maxSimultaneousLights=4,n}return Object(n.b)(t,e),t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaBlendingForMesh=function(e){return this.needAlphaBlending()||e.visibility<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.isReadyForSubMesh=function(e,t,i){if(this.isFrozen&&t.effect&&t.effect._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new s);var n=t._materialDefines,o=this.getScene();if(!this.checkReadyOnEveryCall&&t.effect&&this._renderId===o.getRenderId())return!0;var a=o.getEngine();if(n._areTexturesDirty&&(n._needUVs=!1,o.texturesEnabled&&this._diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;n._needUVs=!0,n.DIFFUSE=!0}if(r.MaterialHelper.PrepareDefinesForMisc(e,o,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),n._needNormals=!0,r.MaterialHelper.PrepareDefinesForLights(o,e,n,!1,this._maxSimultaneousLights,this._disableLighting),r.MaterialHelper.PrepareDefinesForFrameBoundValues(o,a,n,!!i),n.LIGHTING=!this._disableLighting,r.MaterialHelper.PrepareDefinesForAttributes(e,n,!0,!0),n.isDirty){n.markAsProcessed(),o.resetCachedMaterial();var f=new r.EffectFallbacks;n.FOG&&f.addFallback(1,"FOG"),r.MaterialHelper.HandleFallbacksForShadows(n,f),n.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,e);var l=[r.VertexBuffer.PositionKind];n.NORMAL&&l.push(r.VertexBuffer.NormalKind),n.UV1&&l.push(r.VertexBuffer.UVKind),n.UV2&&l.push(r.VertexBuffer.UV2Kind),r.MaterialHelper.PrepareAttributesForBones(l,e,n,f),r.MaterialHelper.PrepareAttributesForInstances(l,n);var u=n.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","vClipPlane5","vClipPlane6","diffuseMatrix"],d=["diffuseSampler"],p=new Array;r.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:n,maxSimultaneousLights:4}),t.setEffect(o.getEngine().createEffect("normal",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},a),n)}return!(!t.effect||!t.effect.isReady())&&(this._renderId=o.getRenderId(),t.effect._wasPreviouslyReady=!0,!0)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),o=i._materialDefines;if(o){var a=i.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",n.getTransformMatrix()),r.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(n,a)&&(this.diffuseTexture&&r.MaterialFlags.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),r.MaterialHelper.BindClipPlane(this._activeEffect,n),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),r.MaterialHelper.BindEyePosition(a,n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),n.lightsEnabled&&!this.disableLighting&&r.MaterialHelper.BindLights(n,t,this._activeEffect,o),n.fogEnabled&&t.applyFog&&n.fogMode!==r.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",n.getViewMatrix()),r.MaterialHelper.BindFogParameters(n,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},t.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||this.diffuseTexture===t},t.prototype.dispose=function(t){this.diffuseTexture&&this.diffuseTexture.dispose(),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return r.SerializationHelper.Clone(function(){return new t(e,i.getScene())},this)},t.prototype.serialize=function(){var e=r.SerializationHelper.Serialize(this);return e.customType="BABYLON.NormalMaterial",e},t.prototype.getClassName=function(){return"NormalMaterial"},t.Parse=function(e,i,n){return r.SerializationHelper.Parse(function(){return new t(e.name,i)},e,i,n)},Object(n.a)([Object(r.serializeAsTexture)("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),Object(n.a)([Object(r.serializeAsColor3)()],t.prototype,"diffuseColor",void 0),Object(n.a)([Object(r.serialize)("disableLighting")],t.prototype,"_disableLighting",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),Object(n.a)([Object(r.serialize)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),Object(n.a)([Object(r.expandToProperty)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),t}(r.PushMaterial);r._TypeStore.RegisteredTypes["BABYLON.NormalMaterial"]=f,i.d(t,"NormalMaterial",function(){return f})},function(e,t,i){"use strict";i.r(t);var n=i(1),r=i(0),o=function(){return function(){}}(),a=function(){return function(){}}(),s=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.CustomParts=new a,n.customShaderNameResolve=n.Builder,n.FragmentShader=r.Effect.ShadersStore.defaultPixelShader,n.VertexShader=r.Effect.ShadersStore.defaultVertexShader,n}return Object(n.b)(t,e),t.prototype.AttachAfterBind=function(e,t){for(var i in this._newUniformInstances){"vec2"==(n=i.toString().split("-"))[0]?t.setVector2(n[1],this._newUniformInstances[i]):"vec3"==n[0]?t.setVector3(n[1],this._newUniformInstances[i]):"vec4"==n[0]?t.setVector4(n[1],this._newUniformInstances[i]):"mat4"==n[0]?t.setMatrix(n[1],this._newUniformInstances[i]):"float"==n[0]&&t.setFloat(n[1],this._newUniformInstances[i])}for(var i in this._newSamplerInstances){var n;"sampler2D"==(n=i.toString().split("-"))[0]&&this._newSamplerInstances[i].isReady&&this._newSamplerInstances[i].isReady()&&t.setTexture(n[1],this._newSamplerInstances[i])}},t.prototype.ReviewUniform=function(e,t){if("uniform"==e)for(var i in this._newUniforms)-1==this._customUniform[i].indexOf("sampler")&&t.push(this._newUniforms[i]);if("sampler"==e)for(var i in this._newUniforms)-1!=this._customUniform[i].indexOf("sampler")&&t.push(this._newUniforms[i]);return t},t.prototype.Builder=function(e,i,n,o,a){var s=this;if(this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,t.ShaderIndexer++;var f="custom_"+t.ShaderIndexer;this.ReviewUniform("uniform",i),this.ReviewUniform("sampler",o);var l=this._afterBind.bind(this);return this._afterBind=function(e,t){if(t){s.AttachAfterBind(e,t);try{l(e,t)}catch(t){}}},r.Effect.ShadersStore[f+"VertexShader"]=this.VertexShader.replace("#define CUSTOM_VERTEX_BEGIN",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#define CUSTOM_VERTEX_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#define CUSTOM_VERTEX_MAIN_BEGIN",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#define CUSTOM_VERTEX_UPDATE_POSITION",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#define CUSTOM_VERTEX_UPDATE_NORMAL",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:"").replace("#define CUSTOM_VERTEX_MAIN_END",this.CustomParts.Vertex_MainEnd?this.CustomParts.Vertex_MainEnd:""),r.Effect.ShadersStore[f+"PixelShader"]=this.FragmentShader.replace("#define CUSTOM_FRAGMENT_BEGIN",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#define CUSTOM_FRAGMENT_MAIN_BEGIN",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#define CUSTOM_FRAGMENT_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE",this.CustomParts.Fragment_Custom_Diffuse?this.CustomParts.Fragment_Custom_Diffuse:"").replace("#define CUSTOM_FRAGMENT_UPDATE_ALPHA",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#define CUSTOM_FRAGMENT_BEFORE_LIGHTS",this.CustomParts.Fragment_Before_Lights?this.CustomParts.Fragment_Before_Lights:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FOG",this.CustomParts.Fragment_Before_Fog?this.CustomParts.Fragment_Before_Fog:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:""),this._isCreatedShader=!0,this._createdShaderName=f,f},t.prototype.AddUniform=function(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances=new Array,this._newUniformInstances=new Array),i&&(t.indexOf("sampler"),this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this},t.prototype.Fragment_Begin=function(e){return this.CustomParts.Fragment_Begin=e,this},t.prototype.Fragment_Definitions=function(e){return this.CustomParts.Fragment_Definitions=e,this},t.prototype.Fragment_MainBegin=function(e){return this.CustomParts.Fragment_MainBegin=e,this},t.prototype.Fragment_Custom_Diffuse=function(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this},t.prototype.Fragment_Custom_Alpha=function(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this},t.prototype.Fragment_Before_Lights=function(e){return this.CustomParts.Fragment_Before_Lights=e,this},t.prototype.Fragment_Before_Fog=function(e){return this.CustomParts.Fragment_Before_Fog=e,this},t.prototype.Fragment_Before_FragColor=function(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this},t.prototype.Vertex_Begin=function(e){return this.CustomParts.Vertex_Begin=e,this},t.prototype.Vertex_Definitions=function(e){return this.CustomParts.Vertex_Definitions=e,this},t.prototype.Vertex_MainBegin=function(e){return this.CustomParts.Vertex_MainBegin=e,this},t.prototype.Vertex_Before_PositionUpdated=function(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this},t.prototype.Vertex_Before_NormalUpdated=function(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this},t.prototype.Vertex_MainEnd=function(e){return this.CustomParts.Vertex_MainEnd=e,this},t.ShaderIndexer=1,t}(r.StandardMaterial);r._TypeStore.RegisteredTypes["BABYLON.CustomMaterial"]=s;var f=function(){return function(){}}(),l=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.CustomParts=new f,n.customShaderNameResolve=n.Builder,n.FragmentShader=r.Effect.ShadersStore.pbrPixelShader,n.VertexShader=r.Effect.ShadersStore.pbrVertexShader,n}return Object(n.b)(t,e),t.prototype.AttachAfterBind=function(e,t){for(var i in this._newUniformInstances){"vec2"==(n=i.toString().split("-"))[0]?t.setVector2(n[1],this._newUniformInstances[i]):"vec3"==n[0]?t.setVector3(n[1],this._newUniformInstances[i]):"vec4"==n[0]?t.setVector4(n[1],this._newUniformInstances[i]):"mat4"==n[0]?t.setMatrix(n[1],this._newUniformInstances[i]):"float"==n[0]&&t.setFloat(n[1],this._newUniformInstances[i])}for(var i in this._newSamplerInstances){var n;"sampler2D"==(n=i.toString().split("-"))[0]&&this._newSamplerInstances[i].isReady&&this._newSamplerInstances[i].isReady()&&t.setTexture(n[1],this._newSamplerInstances[i])}},t.prototype.ReviewUniform=function(e,t){if("uniform"==e)for(var i in this._newUniforms)-1==this._customUniform[i].indexOf("sampler")&&t.push(this._newUniforms[i]);if("sampler"==e)for(var i in this._newUniforms)-1!=this._customUniform[i].indexOf("sampler")&&t.push(this._newUniforms[i]);return t},t.prototype.Builder=function(e,i,n,o,a){var s=this;if(this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,t.ShaderIndexer++;var f="custom_"+t.ShaderIndexer;this.ReviewUniform("uniform",i),this.ReviewUniform("sampler",o);var l=this._afterBind.bind(this);return this._afterBind=function(e,t){if(t){s.AttachAfterBind(e,t);try{l(e,t)}catch(t){}}},r.Effect.ShadersStore[f+"VertexShader"]=this.VertexShader.replace("#define CUSTOM_VERTEX_BEGIN",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#define CUSTOM_VERTEX_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#define CUSTOM_VERTEX_MAIN_BEGIN",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#define CUSTOM_VERTEX_UPDATE_POSITION",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#define CUSTOM_VERTEX_UPDATE_NORMAL",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:"").replace("#define CUSTOM_VERTEX_MAIN_END",this.CustomParts.Vertex_MainEnd?this.CustomParts.Vertex_MainEnd:""),r.Effect.ShadersStore[f+"PixelShader"]=this.FragmentShader.replace("#define CUSTOM_FRAGMENT_BEGIN",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#define CUSTOM_FRAGMENT_MAIN_BEGIN",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#define CUSTOM_FRAGMENT_DEFINITIONS",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#define CUSTOM_FRAGMENT_UPDATE_ALBEDO",this.CustomParts.Fragment_Custom_Albedo?this.CustomParts.Fragment_Custom_Albedo:"").replace("#define CUSTOM_FRAGMENT_UPDATE_ALPHA",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#define CUSTOM_FRAGMENT_BEFORE_LIGHTS",this.CustomParts.Fragment_Before_Lights?this.CustomParts.Fragment_Before_Lights:"").replace("#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS",this.CustomParts.Fragment_Custom_MetallicRoughness?this.CustomParts.Fragment_Custom_MetallicRoughness:"").replace("#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE",this.CustomParts.Fragment_Custom_MicroSurface?this.CustomParts.Fragment_Custom_MicroSurface:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FOG",this.CustomParts.Fragment_Before_Fog?this.CustomParts.Fragment_Before_Fog:"").replace("#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:""),this._isCreatedShader=!0,this._createdShaderName=f,f},t.prototype.AddUniform=function(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances=new Array,this._newUniformInstances=new Array),i&&(t.indexOf("sampler"),this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this},t.prototype.Fragment_Begin=function(e){return this.CustomParts.Fragment_Begin=e,this},t.prototype.Fragment_Definitions=function(e){return this.CustomParts.Fragment_Definitions=e,this},t.prototype.Fragment_MainBegin=function(e){return this.CustomParts.Fragment_MainBegin=e,this},t.prototype.Fragment_Custom_Albedo=function(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this},t.prototype.Fragment_Custom_Alpha=function(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this},t.prototype.Fragment_Before_Lights=function(e){return this.CustomParts.Fragment_Before_Lights=e,this},t.prototype.Fragment_Custom_MetallicRoughness=function(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this},t.prototype.Fragment_Custom_MicroSurface=function(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this},t.prototype.Fragment_Before_Fog=function(e){return this.CustomParts.Fragment_Before_Fog=e,this},t.prototype.Fragment_Before_FragColor=function(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this},t.prototype.Vertex_Begin=function(e){return this.CustomParts.Vertex_Begin=e,this},t.prototype.Vertex_Definitions=function(e){return this.CustomParts.Vertex_Definitions=e,this},t.prototype.Vertex_MainBegin=function(e){return this.CustomParts.Vertex_MainBegin=e,this},t.prototype.Vertex_Before_PositionUpdated=function(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this},t.prototype.Vertex_Before_NormalUpdated=function(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this},t.prototype.Vertex_MainEnd=function(e){return this.CustomParts.Vertex_MainEnd=e,this},t.ShaderIndexer=1,t}(r.PBRMaterial);r._TypeStore.RegisteredTypes["BABYLON.PBRCustomMaterial"]=l,i.d(t,"CustomShaderStructure",function(){return o}),i.d(t,"ShaderSpecialParts",function(){return a}),i.d(t,"CustomMaterial",function(){return s}),i.d(t,"ShaderAlebdoParts",function(){return f}),i.d(t,"PBRCustomMaterial",function(){return l})},function(e,t,i){"use strict";i.r(t);var n=i(10);i.d(t,"CellMaterial",function(){return n.CellMaterial});var r=i(17);i.d(t,"CustomShaderStructure",function(){return r.CustomShaderStructure}),i.d(t,"ShaderSpecialParts",function(){return r.ShaderSpecialParts}),i.d(t,"CustomMaterial",function(){return r.CustomMaterial}),i.d(t,"ShaderAlebdoParts",function(){return r.ShaderAlebdoParts}),i.d(t,"PBRCustomMaterial",function(){return r.PBRCustomMaterial});var o=i(5);i.d(t,"FireMaterial",function(){return o.FireMaterial});var a=i(7);i.d(t,"FurMaterial",function(){return a.FurMaterial});var s=i(9);i.d(t,"GradientMaterial",function(){return s.GradientMaterial});var f=i(11);i.d(t,"GridMaterial",function(){return f.GridMaterial});var l=i(13);i.d(t,"LavaMaterial",function(){return l.LavaMaterial});var u=i(15);i.d(t,"MixMaterial",function(){return u.MixMaterial});var c=i(16);i.d(t,"NormalMaterial",function(){return c.NormalMaterial});var d=i(14);i.d(t,"ShadowOnlyMaterial",function(){return d.ShadowOnlyMaterial});var p=i(12);i.d(t,"SimpleMaterial",function(){return p.SimpleMaterial});var h=i(4);i.d(t,"SkyMaterial",function(){return h.SkyMaterial});var v=i(8);i.d(t,"TerrainMaterial",function(){return v.TerrainMaterial});var m=i(6);i.d(t,"TriPlanarMaterial",function(){return m.TriPlanarMaterial});var g=i(3);i.d(t,"WaterMaterial",function(){return g.WaterMaterial})},function(e,t,i){"use strict";i.r(t),function(e){var n=i(18);i.d(t,"CellMaterial",function(){return n.CellMaterial}),i.d(t,"CustomShaderStructure",function(){return n.CustomShaderStructure}),i.d(t,"ShaderSpecialParts",function(){return n.ShaderSpecialParts}),i.d(t,"CustomMaterial",function(){return n.CustomMaterial}),i.d(t,"ShaderAlebdoParts",function(){return n.ShaderAlebdoParts}),i.d(t,"PBRCustomMaterial",function(){return n.PBRCustomMaterial}),i.d(t,"FireMaterial",function(){return n.FireMaterial}),i.d(t,"FurMaterial",function(){return n.FurMaterial}),i.d(t,"GradientMaterial",function(){return n.GradientMaterial}),i.d(t,"GridMaterial",function(){return n.GridMaterial}),i.d(t,"LavaMaterial",function(){return n.LavaMaterial}),i.d(t,"MixMaterial",function(){return n.MixMaterial}),i.d(t,"NormalMaterial",function(){return n.NormalMaterial}),i.d(t,"ShadowOnlyMaterial",function(){return n.ShadowOnlyMaterial}),i.d(t,"SimpleMaterial",function(){return n.SimpleMaterial}),i.d(t,"SkyMaterial",function(){return n.SkyMaterial}),i.d(t,"TerrainMaterial",function(){return n.TerrainMaterial}),i.d(t,"TriPlanarMaterial",function(){return n.TriPlanarMaterial}),i.d(t,"WaterMaterial",function(){return n.WaterMaterial});var r=void 0!==e?e:"undefined"!=typeof window?window:void 0;if(void 0!==r)for(var o in r.BABYLON=r.BABYLON||{},n)r.BABYLON[o]=n[o]}.call(this,i(2))}])}); | |
88_Merge_Sorted_Array.py | """
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
"""
class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing | def merge(self, A, m, B, n):
i = m - 1
j = n - 1
x = m + n - 1
while i>=0 and j>=0:
if A[i] > B[j]:
A[x] = A[i]
i -= 1
else:
A[x] = B[j]
j -= 1
x -= 1
while j>=0:
A[x] = B[j]
x -= 1
j -= 1
# Focus on detail!!! | |
jinja_common.py | # -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2022. All Rights Reserved.
import calendar
import logging
import json
import os
import time
from resilient_circuits.template_functions import render_json, environment
LOG = logging.getLogger(__name__)
class JinjaEnvironment():
def __init__(self):
# Add the timestamp-parse function to the global JINJA environment
env = environment()
env.globals.update({
"resilient_datetimeformat": jinja_resilient_datetimeformat,
"resilient_substitute": jinja_resilient_substitute,
"resilient_splitpart": jinja_resilient_splitpart
})
env.filters.update({
"resilient_datetimeformat": jinja_resilient_datetimeformat,
"resilient_substitute": jinja_resilient_substitute,
"resilient_splitpart": jinja_resilient_splitpart
})
def make_payload_from_template(self, template_override, default_template, payload):
"""convert a payload into a newformat based on a specified template
Args:
template_override ([str]): [/path/to/template.jinja]
default_template ([str]): [/path/to/template.jinja]
payload ([dict]): [data to convert]
Returns:
[dict]: [converted payload]
"""
template_data = self.get_template(template_override, default_template)
# Render the template.
rendered_payload = render_json(template_data, payload)
LOG.debug(rendered_payload)
return rendered_payload
def get_template(self, specified_template, default_template):
"""return the contents of a jinja template, either from the default or a customer specified
custom path
Args:
specified_template ([str]): [customer specified template path]
default_template ([str]): [default template location]
Returns:
[str]: [contents of template]
"""
template_file_path = specified_template
if template_file_path:
if not (os.path.exists(template_file_path) and os.path.isfile(template_file_path)):
LOG.error(u"Template file: %s doesn't exist, using default template",
template_file_path)
template_file_path = None
if not template_file_path:
# using default template
template_file_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
default_template
)
LOG.debug(u"Incident template file: %s", template_file_path)
with open(template_file_path, "r") as definition:
return definition.read()
def jinja_resilient_datetimeformat(value, date_format="%Y-%m-%dT%H:%M:%S"):
"""custom jinja filter to convert UTC dates to epoch format
Args:
value ([str]): [jinja provided field value]
date_format (str, optional): [conversion format]. Defaults to "%Y-%m-%dT%H:%M:%S".
Returns:
[int]: [epoch value of datetime, in milliseconds]
"""
if not value:
return value
utc_time = time.strptime(value[:value.rfind('.')], date_format)
return calendar.timegm(utc_time)*1000
def jinja_resilient_substitute(value, json_str):
"""jinja custom filter to replace values based on a lookup dictionary
Args:
value ([str]): [original value]
json_str ([str]): [string encoded json lookup values]
Returns:
[str]: [replacement value or original value if no replacement found]
"""
replace_dict = json.loads(json_str)
if value in replace_dict:
return replace_dict[value]
# use a default value if specific match is missing
if 'DEFAULT' in replace_dict:
return replace_dict['DEFAULT']
return value | """[split a string and return the index]
Args:
value ([str]): [string to split]
index ([int]): [index to return]
split_chars (str, optional): [split characters]. Defaults to ' - '.
Returns:
[str]: [index of string. if index is out of bounds, the original string is returned]
"""
splits = value.split(split_chars)
if len(splits) > index:
return splits[index]
else:
return value |
def jinja_resilient_splitpart (value, index, split_chars=' - '): |
dialog-donate.component.spec.ts | import { ComponentFixture, TestBed } from '@angular/core/testing'; |
import { DialogDonateComponent } from './dialog-donate.component';
describe('DialogDonateComponent', () => {
let component: DialogDonateComponent;
let fixture: ComponentFixture<DialogDonateComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ DialogDonateComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(DialogDonateComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
}); | |
StudioMicrophone.d.ts | /// <reference types="react" /> | }) => JSX.Element;
export default StudioMicrophone; | declare const StudioMicrophone: ({ size, rem }: {
size: number | string;
rem?: boolean | undefined; |
main.rs | use std::net::IpAddr;
use std::path::PathBuf;
use std::str::FromStr;
use bytes::Bytes;
use destream::de::FromStream;
use futures::{future, stream, TryFutureExt};
use structopt::StructOpt;
use tokio::time::Duration;
use tc_error::*;
use tc_transact::{Transact, TxnId};
use tc_value::{LinkHost, LinkProtocol};
use tinychain::gateway::Gateway;
use tinychain::object::InstanceClass;
use tinychain::*;
type TokioError = Box<dyn std::error::Error + Send + Sync + 'static>;
const MIN_CACHE_SIZE: usize = 5000;
fn data_size(flag: &str) -> TCResult<u64> {
const ERR: &str = "unable to parse data size";
if flag.is_empty() || flag == "0" {
return Ok(0);
}
let size = u64::from_str_radix(&flag[0..flag.len() - 1], 10)
.map_err(|_| TCError::bad_request(ERR, flag))?;
if flag.ends_with('K') {
Ok(size * 1000)
} else if flag.ends_with('M') {
Ok(size * 1_000_000)
} else if flag.ends_with('G') {
Ok(size * 1_000_000_000)
} else {
Err(TCError::bad_request(ERR, flag))
}
}
fn duration(flag: &str) -> TCResult<Duration> {
u64::from_str(flag)
.map(Duration::from_secs)
.map_err(|_| TCError::bad_request("invalid duration", flag))
}
#[derive(Clone, StructOpt)]
struct Config {
#[structopt(
long = "address",
default_value = "0.0.0.0",
about = "The IP address to bind"
)]
pub address: IpAddr,
#[structopt(long = "log_level", default_value = "warn")]
pub log_level: String,
#[structopt(
long = "workspace",
default_value = "/tmp/tc/tmp",
about = "workspace directory"
)]
pub workspace: PathBuf,
#[structopt(long = "cache_size", default_value = "1G", parse(try_from_str = data_size))]
pub cache_size: u64,
#[structopt(
long = "data_dir",
about = "data directory (required to host a Cluster)"
)]
pub data_dir: Option<PathBuf>,
#[structopt(long = "cluster", about = "path(s) to Cluster config files")]
pub clusters: Vec<PathBuf>,
#[structopt(
long = "request_ttl",
default_value = "30",
parse(try_from_str = duration),
about = "maximum allowed request duration"
)]
pub request_ttl: Duration,
#[structopt(long = "http_port", default_value = "8702")]
pub http_port: u16,
}
impl Config {
fn gateway(&self) -> gateway::Config {
gateway::Config {
addr: self.address,
http_port: self.http_port,
request_ttl: self.request_ttl,
}
}
}
#[tokio::main]
async fn main() -> Result<(), TokioError> {
let config = Config::from_args(); | .init();
if !config.workspace.exists() {
log::info!(
"workspace directory {:?} does not exist, attempting to create it...",
config.workspace
);
std::fs::create_dir_all(&config.workspace)?;
}
let cache_size = config.cache_size as usize;
if cache_size < MIN_CACHE_SIZE {
return Err(TCError::bad_request("the minimum cache size is", MIN_CACHE_SIZE).into());
}
let cache = freqfs::Cache::new(config.cache_size as usize, Duration::from_secs(1), None);
let workspace = cache.clone().load(config.workspace).await?;
let txn_id = TxnId::new(Gateway::time());
let data_dir = if let Some(data_dir) = config.data_dir {
if !data_dir.exists() {
panic!("{:?} does not exist--create it or provide a different path for the --data_dir flag", data_dir);
}
let data_dir = cache.load(data_dir).await?;
tinychain::fs::Dir::load(data_dir, txn_id)
.map_ok(Some)
.await?
} else {
None
};
#[cfg(feature = "tensor")]
{
tc_tensor::print_af_info();
println!();
}
let txn_server = tinychain::txn::TxnServer::new(workspace).await;
let mut clusters = Vec::with_capacity(config.clusters.len());
if !config.clusters.is_empty() {
let txn_server = txn_server.clone();
let kernel = tinychain::Kernel::new(std::iter::empty());
let gateway = Gateway::new(gateway_config.clone(), kernel, txn_server.clone());
let token = gateway.new_token(&txn_id)?;
let txn = txn_server.new_txn(gateway, txn_id, token).await?;
let data_dir = data_dir.ok_or_else(|| {
TCError::internal("the --data_dir option is required to host a Cluster")
})?;
let host = LinkHost::from((
LinkProtocol::HTTP,
config.address.clone(),
Some(config.http_port),
));
for path in config.clusters {
let config = tokio::fs::read(&path)
.await
.expect(&format!("read from {:?}", &path));
let mut decoder = destream_json::de::Decoder::from_stream(stream::once(future::ready(
Ok(Bytes::from(config)),
)));
let cluster = match InstanceClass::from_stream((), &mut decoder).await {
Ok(class) => {
cluster::instantiate(&txn, host.clone(), class, data_dir.clone()).await?
}
Err(cause) => panic!("error parsing cluster config {:?}: {}", path, cause),
};
clusters.push(cluster);
}
data_dir.commit(&txn_id).await;
}
let kernel = tinychain::Kernel::new(clusters);
let gateway = tinychain::gateway::Gateway::new(gateway_config, kernel, txn_server);
log::info!("starting server, cache size is {}", config.cache_size);
gateway.listen().await
} | let gateway_config = config.gateway();
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(config.log_level)) |
json-form-select.tsx | import * as React from 'react';
import { JsonFormFieldProps, JsonFormFieldState } from '@shared/components/json-form/react/json-form.models';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';
import ThingsboardBaseComponent from '@shared/components/json-form/react/json-form-base-component';
interface ThingsboardSelectState extends JsonFormFieldState {
currentValue: any;
}
class ThingsboardSelect extends React.Component<JsonFormFieldProps, ThingsboardSelectState> {
constructor(props) {
super(props);
this.onSelected = this.onSelected.bind(this);
const possibleValue = this.getModelKey(this.props.model, this.props.form.key);
this.state = {
currentValue: this.props.model !== undefined && possibleValue ? possibleValue : this.props.form.titleMap != null ?
this.props.form.titleMap[0].value : ''
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.model && nextProps.form.key) {
this.setState({
currentValue: this.getModelKey(nextProps.model, nextProps.form.key)
|| (nextProps.form.titleMap != null ? nextProps.form.titleMap[0].value : '')
});
}
}
getModelKey(model, key) {
if (Array.isArray(key)) {
return key.reduce((cur, nxt) => (cur[nxt] || {}), model);
} else {
return model[key];
}
}
onSelected(event: React.ChangeEvent<{ name?: string; value: any }>) {
this.setState({
currentValue: event.target.value
});
this.props.onChangeValidate(event);
}
| <MenuItem key={idx}
value={item.value}>{item.name}</MenuItem>
));
return (
<FormControl className={this.props.form.htmlClass}
disabled={this.props.form.readonly}
fullWidth={true}>
<InputLabel htmlFor='select-field'>{this.props.form.title}</InputLabel>
<Select
value={this.state.currentValue}
onChange={this.onSelected}>
{menuItems}
</Select>
</FormControl>
);
}
}
export default ThingsboardBaseComponent(ThingsboardSelect); | render() {
const menuItems = this.props.form.titleMap.map((item, idx) => ( |
hill_system.py | import numpy as np
from scipy.integrate import solve_ivp
def HS_ode(t,y,HS):
rhs = -HS.gamma*y + HS.lambda_value(y)
return rhs
def at_HS_equilibrium(t,y,HS,tol = 1e-3):
val = np.linalg.norm(HS_ode(t,y,HS)) - tol
if val < 0:
return 0
else:
return val
def simulate_HS(x0,HS,max_time,tol = 1e-3):
"""
Simulate the hill system ODE. Terminate simulation if an equilibrium is found.
Input:
x0 - initial condition
HS - HillSystemParameter object
max_time - time at which to terminate the simulation if an equilibrium hasn't been found
Output:
sol - output of solve_ivp
"""
ode = lambda t,y: HS_ode(t,y,HS)
at_equilibrium = lambda t,y: at_HS_equilibrium(t,y,HS,tol)
at_equilibrium.terminal = True
integration_interval = (0,max_time)
sol = solve_ivp(ode,integration_interval,x0,method = 'BDF',events = at_equilibrium)
return sol
def find_equilibrium(x0,HS,max_time,tol = 1e-3):
"""
Simulate the ODE to equilibrium starting from x0
Input:
x0 - initial condition
HS - HillSystemParameter object
max_time - run the ode from time points [0,max_time]. If the solver reaches
max_time before finding an equilibrium, then report that an equilibrium
was not found
Output:
x - value of the equilibrium, if found within max_time. If not found, returns -1
"""
ode = lambda t,y: HS_ode(t,y,HS)
at_equilibrium = lambda t,y: at_HS_equilibrium(t,y,HS,tol)
# def ode(t,y,HS = HS):
# rhs = -HS.gamma*y + HS.lambda_value(y)
# return rhs
# def at_equilibrium(t,y,HS = HS,tol = tol):
# val = np.linalg.norm(ode(t,y)) - tol
# if val < 0: | at_equilibrium.terminal = True
integration_interval = (0,max_time)
sol = solve_ivp(ode,integration_interval,x0,method = 'BDF',events = at_equilibrium)
if sol.status == 1: #at_equilibrium triggered stopping integration
return sol.y[:,-1]
else:
return -1
def find_hill_equilibria_from_FPs(FPs,HS,RS,max_time,tol = 1e-3):
"""
Use DSGRN equilibria as initial conditions for finding Hill equilibria.
Input:
FPs - list of fixed point coordinates computed by DSGRN
HS - HillSystemParameter object
RS - RampSystem object
max_time - maximum time to run the ODE for each equilibrium search attempt.
Output:
eq - list of Nx1 numpy arrays. An entry is -1 if find_equilibrium didn't find an
equilibrium within max_time. len(eq) == len(FPs)
"""
reg_DSGRN_equilibria = RS.reg_equilibria_from_FPs(FPs)
hill_eq = [find_equilibrium(x0.reshape([x0.shape[0]]),HS,max_time,tol = tol) for x0 in reg_DSGRN_equilibria]
return hill_eq
def num_unique_vectors(vectors,tol = 1e-3):
"""
Given a list of vectors, count the number which are unique up to some tolerance
"""
repeat_indices = []
num_unique = 0
for j, vec0 in enumerate(vectors):
if j in repeat_indices:
continue
num_unique += 1
for i, vec1 in enumerate(vectors[j+1:]):
i = i+j+1
if i in repeat_indices:
continue
if np.allclose(vec0,vec1,rtol = tol):
repeat_indices.append(i)
return num_unique
def hill_value(x,hill_parameter):
sign = hill_parameter.sign
theta = hill_parameter.theta
Delta = hill_parameter.Delta
L = hill_parameter.L
n = hill_parameter.n
if sign == 1:
return L + Delta/((theta/x)**n + 1)
if sign == -1:
return L + Delta/((x/theta)**n + 1)
def hill_second_derivative_root(*args):
if len(args) == 1:
hill_parameter = args[0]
theta = hill_parameter.theta
n = hill_parameter.n
elif len(args) == 2:
theta = args[0]
n = args[1]
else:
raise TypeError('hill_second_derivative_root() takes 1 or 2 position arguments\
but {} were given.'.format(len(args)))
return theta*((n-1)/(n+1))**(1/n)
def hill_derivative_magnitude(x,*args):
if len(args) == 1:
hill_parameter = args[0]
sign = hill_parameter.sign
Delta = hill_parameter.Delta
theta = hill_parameter.theta
n = hill_parameter.n
elif len(args) == 4:
sign = args[0]
Delta = args[1]
theta = args[2]
n = args[3]
else:
raise TypeError('hill_derivative() takes 1 or 4 positiional arguments\
but {} were given.'.format(len(args)))
if n == np.inf:
if theta == x:
return np.inf
else:
return 0
return Delta*n/(theta*(theta/x)**(n-1) + 2*x + x*(x/theta)**n)
def make_hill_coefficient_array(Network,n):
"""
Make a hill coefficient array consistent with the network topology with each
hill coefficient equal to n
Input:
Network - DSGRN network object
n - float or integer greater than 1
Output:
numpy array with entry [i,j] equal to n if j->i is an edge and 0 otherwise
"""
N = Network.size()
hill_coefficients = np.zeros([N,N])
for j in range(N):
for i in Network.outputs(j):
hill_coefficients[i,j] = n
return hill_coefficients
def make_sign_from_network(Network):
"""
Make an NxN numpy array describing the interaction sign between edges
Input:
Network - DSGRN network object
Output:
numpy array with 1 if j->i, -1 if j-|i, and 0 otherwise.
"""
N = Network.size()
sign = np.zeros([N,N])
for j in range(N):
for i in Network.outputs(j):
sign[i,j] = 1 if Network.interaction(j,i) else -1
return sign
class HillParameter:
def __init__(self,sign,L,Delta,theta,n):
"""
Input:
sign - either 1 or -1
L,Delta,theta,n - parameters for a hill function
"""
self.sign = sign
self.L = L
self.Delta = Delta
self.theta = theta
self.n = n
def __repr__(self):
sign = self.sign
L = self.L
Delta = self.Delta
theta = self.theta
n = self.n
return 'HillParameter({},{},{},{},{})'.format(sign,L,Delta,theta,n)
def func_value(self,x):
return hill_value(x,self)
def dx_value(self,x):
return self.sign*hill_derivative_magnitude(x,self)
class HillSystemParameter:
def __init__(self,Network,sign,L,Delta,theta,n,gamma):
"""
Input:
gamma - length N lists
sign,L,Delta,theta,n - NxN arrays
"""
self.Network = Network
N = Network.size()
self.sign = np.array(sign)
self.L = np.array(L)
self.Delta = np.array(Delta)
self.theta = np.array(theta)
self.n = np.array(n)
self.gamma = np.array(gamma).reshape([N])
def __eq__(self,other):
if isinstance(other,HillSystemParameter):
return np.array_equal(self.sign,other.sign) and np.array_equal(self.L, other.L) \
and np.array_equal(self.Delta, other.Delta) and np.array_equal(self.theta,other.theta) \
and np.array_equal(self.n, other.n) and np.array_equal(self.gamma,other.gamma)
else:
return False
def hill_parameter(self,i,j):
return HillParameter(self.sign[i,j],self.L[i,j],self.Delta[i,j],self.theta[i,j],self.n[i,j])
def lambda_value(self,x):
Network = self.Network
N = Network.size()
val = np.zeros([N])
for i in range(N):
cur_prod = 1
for source_set in Network.logic(i):
cur_sum = 0
for j in source_set:
cur_param = self.hill_parameter(i,j)
cur_sum += cur_param.func_value(x[j])
cur_prod *= cur_sum
val[i] = cur_prod
return val
def is_equilibrium(self,x,tol = 1e-4):
N = self.Network.size()
x = np.array(x).reshape([N])
return np.allclose(self.lambda_value(x)-self.gamma*x,np.zeros([N]),atol=tol)
def Jacobian(self,x):
N = self.Network.size()
J = np.diag(-self.gamma)
for i in range(N):
for j in self.Network.inputs(i):
cur_prod = 1
for source_set in self.Network.logic(i):
cur_sum = 0
if j in source_set:
cur_sum = self.hill_parameter(i,j).dx_value(x[j])
else:
for k in source_set:
cur_sum += self.hill_parameter(i,k).func_value(x[k])
cur_prod *= cur_sum
J[i,j] += cur_prod
return j
def is_saddle(self,x,tol = 1e-4):
N = self.Network.size()
x = np.array(x).reshape([N,1])
if not self.is_equilibrium(x,tol=tol):
return False
J = self.Jacobian(x)
if np.linalg.matrix_rank(J) == N:
return False
return True | # return 0
# else:
# return val |
selectors.js | import { createSelector } from 'reselect';
import { initialState } from 'containers/SnackMessage/reducer';
const selectSnackMessage = (state) => state.snackMessage || initialState;
const makeSnackMessageSelector = () =>
createSelector(selectSnackMessage, (substate) => substate.message);
const makeSnackMessageTypeSelector = () =>
createSelector(selectSnackMessage, (substate) => substate.type);
const makeIdSelector = () =>
createSelector(selectSnackMessage, (substate) => substate.id);
const makeDurationSelector = () =>
createSelector(selectSnackMessage, (substate) => substate.duration); |
export {
makeTranslateSelector,
makeDurationSelector,
makeIdSelector,
makeSnackMessageSelector,
makeSnackMessageTypeSelector,
}; |
const makeTranslateSelector = () =>
createSelector(selectSnackMessage, (substate) => substate.translate); |
delete.rs | //! Handles delete presentation.
use actix_web::web;
use actix_web::{Error, HttpResponse};
use actix_web_httpauth::extractors::bearer::BearerAuth;
use deadpool_postgres::Client;
use uuid::Uuid;
use crate::auth::auth_payload::AuthPayload;
use crate::database::postgresql::PersistentConnectionPool;
use crate::service_errors::ServiceError;
/// Handler for deleting presentation file.
pub async fn handle_delete_presentation(
pool: web::Data<PersistentConnectionPool>,
meeting_id: web::Data<Uuid>,
auth: BearerAuth,
) -> Result<HttpResponse, Error> {
let client = pool.get().await?;
let user_id = AuthPayload::from_bearer_auth(&auth)?.uuid;
// Only presenter may delete the presentation file.
if !is_presenter(&client, &meeting_id, &user_id).await? {
return Err(ServiceError::Unauthorized(
"Only presenter of meeting session may delete presentation file".to_string(),
)
.into());
}
delete_file(&meeting_id).await?;
Ok(HttpResponse::NoContent().finish())
}
async fn is_presenter(
client: &Client,
meeting_id: &Uuid,
user_id: &Uuid,
) -> Result<bool, ServiceError> {
if let Some((presenter_id, _)) = get_participants(&client, &meeting_id).await? {
Ok(&presenter_id == user_id)
} else {
Ok(false)
}
}
const GET_PARTICIPANTS_QUERY: &str = r#"
SELECT
presenter,
listeners
FROM
meeting_sessions
WHERE
meeting_id = $1::UUID
;
"#;
async fn get_participants(
client: &Client,
meeting_id: &Uuid,
) -> Result<Option<(Uuid, Vec<Uuid>)>, ServiceError> {
let statement = client.prepare(GET_PARTICIPANTS_QUERY).await?;
let rows = client.query(&statement, &[meeting_id]).await?;
if rows.is_empty() {
Ok(None)
} else {
let (presenter, listeners) = (rows[0].get(0), rows[0].get(1));
Ok(Some((presenter, listeners)))
} | }
async fn delete_file(meeting_id: &Uuid) -> Result<(), ServiceError> {
let raw_path = format!("/data/presentations/{}.png", &meeting_id);
let path = std::path::PathBuf::from(&raw_path);
web::block(move || {
if path.exists() {
std::fs::remove_file(&path)
} else {
Ok(())
}
})
.await
.map_err(|e| e.into())
} | |
aperiodic_ean.py | from typing import List
from core.exceptions.data_exceptions import (DataIndexNotFoundException,
DataIllegalEventTypeException,
DataIllegalActivityTypeException)
from core.exceptions.input_exceptions import (InputFormatException,
InputTypeInconsistencyException)
from core.exceptions.graph_exceptions import (GraphEdgeIdMultiplyAssignedException,
GraphIncidentNodeNotFoundException,
GraphNodeIdMultiplyAssignedException)
from core.io.csv import CsvReader, CsvWriter
from core.model.aperiodic_ean import AperiodicEvent, AperiodicActivity
from core.model.graph import Graph
from core.model.impl.simple_dict_graph import SimpleDictGraph
from core.model.periodic_ean import ActivityType, EventType
from core.model.timetable import Timetable
from core.util.config import Config, default_config
class AperiodicEANReader:
"""
Class to process csv-lines, formatted in the LinTim
Activities-expanded.giv, Events-expanded.giv or Timetable-expanded.tim
format. Use a CsvReader with an instance of this class to read periodic
activities, events or timetable files. For convenience, :func:`~core.io.aperiodic_ean.read` is provided, that does
all the necessary work.
"""
def __init__(self, event_file_name: str, activity_file_name: str, aperiodic_timetable_file_name: str,
aperiodic_ean: Graph[AperiodicEvent, AperiodicActivity], timetable: Timetable = None):
"""
Constructor for a PeriodicEANReader for given file names and periodic
EAN. The given names will not influence the read file but the used name
in any error message, so be sure to use the same name in here aswell as
in the CsvReader!
:param activity_file_name source file name for aperiodic
activities
:param event_file_name source file name for aperiodic events.
:param aperiodic_timetable_file_name source file name for aperiodic
timetable.
:param aperiodic_ean aperiodic event activity network.
:param timetable aperiodic timetable
"""
self.aperiodicActivitiesFileName = activity_file_name
self.aperiodicEventsFileName = event_file_name
self.aperiodicTimetableFileName = aperiodic_timetable_file_name
self.aperiodicEAN = aperiodic_ean
self.timetable = timetable
@staticmethod
def parse_event_type(input_type: str, event_id: int) -> EventType:
"""
Parse the given input as an event type. Will raise, if it is not valid.
:param input_type: the input to parse
:param event_id: the event id. Only used for error handling
:return: the parsed event type
"""
if input_type.lower() == "arrival" or input_type.lower() == "\"arrival\"":
result = EventType.ARRIVAL
elif (input_type.lower() == "departure" or
input_type.lower() == "\"departure\""):
result = EventType.DEPARTURE
else:
raise DataIllegalEventTypeException(event_id, input_type)
return result
@staticmethod
def parse_activity_type(input_type: str, activity_id: int) -> ActivityType:
"""
Parse the given input as an activity type. Will raise, if it is not
valid.
:param input_type: the input to parse
:param activity_id: the activity id. Only used for error handling.
:return: the parsed activity type
"""
if input_type.lower() == "drive" or input_type.lower() == "\"drive\"":
result = ActivityType.DRIVE
elif (input_type.lower() == "wait" or
input_type.lower() == "\"wait\""):
result = ActivityType.WAIT
elif (input_type.lower() == "change" or
input_type.lower() == "\"change\""):
result = ActivityType.CHANGE
elif (input_type.lower() == "headway" or
input_type.lower() == "\"headway\""):
result = ActivityType.HEADWAY
elif (input_type.lower() == "turnaround" or
input_type.lower() == "\"turnaround\""):
result = ActivityType.TURNAROUND
else:
raise DataIllegalActivityTypeException(activity_id, input_type)
return result
def process_aperiodic_event(self, args: List[str], line_number: int) -> None:
"""
Process the content of an aperiodic event file.
:param args the content of the line.
:param line_number the line number, used for error handling
:raise exceptions if the line does not contain exactly 6 entries
if the specific types of the entries do not match
the expectations
if ht event type is not defined
if the event cannot be added to the EAN
"""
if len(args) != 6:
raise InputFormatException(self.aperiodicEventsFileName, len(args),
6)
try:
event_id = int(args[0])
except ValueError:
raise InputTypeInconsistencyException(self.aperiodicEventsFileName,
1, line_number, "int",
args[0])
try:
periodic_event_id = int(args[1])
except ValueError:
raise InputTypeInconsistencyException(self.aperiodicEventsFileName,
2, line_number, "int",
args[1])
event_type = AperiodicEANReader.parse_event_type(args[2], event_id)
try:
time = int(args[3])
except ValueError:
raise InputTypeInconsistencyException(self.aperiodicEventsFileName,
4, line_number, "int",
args[3])
try:
passengers = float(args[4])
except ValueError:
raise InputTypeInconsistencyException(self.aperiodicEventsFileName,
5, line_number, "float",
args[4])
try:
stopId = int(args[5])
except ValueError:
raise InputTypeInconsistencyException(self.aperiodicEventsFileName,
6, line_number, "int",
args[5])
aperiodicEvent = AperiodicEvent(event_id, periodic_event_id, stopId,
event_type, time, passengers)
eventAdded = self.aperiodicEAN.addNode(aperiodicEvent)
if not eventAdded:
raise GraphNodeIdMultiplyAssignedException(event_id)
if self.timetable is not None:
self.timetable[aperiodicEvent] = time
def process_aperiodic_activity(self, args: [str], line_number: int) -> None:
"""
Process the content of a periodic activity file.
:param args the content of the line
:param line_number the line number, used for error handling
:raise exceptions if the line does not contain exactly 8 entries
if the specific types of the entries do not match
the expectations
if the activity type is not defined
if the activity cannot be added to the EAN.
"""
if len(args) != 8:
raise InputFormatException(self.aperiodicActivitiesFileName,
len(args), 8)
try:
activityId = int(args[0])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicActivitiesFileName,
1, line_number, "int",
args[0]))
try:
periodicActivityId = int(args[1])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicActivitiesFileName,
2, line_number, "int",
args[1]))
activityType = AperiodicEANReader.parse_activity_type(args[2], activityId)
try:
sourceEventId = int(args[3])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicActivitiesFileName,
4, line_number, "int",
args[3]))
try:
targetEventId = int(args[4])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicActivitiesFileName,
5, line_number, "int",
args[4]))
try:
lowerBound = int(args[5])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicActivitiesFileName,
6, line_number, "int",
args[5]))
try:
upperBound = int(args[6])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicActivitiesFileName,
7, line_number, "int",
args[6]))
try:
passengers = float(args[7])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicActivitiesFileName,
8, line_number, "int",
args[7]))
sourceEvent = self.aperiodicEAN.getNode(sourceEventId)
if not sourceEvent:
raise GraphIncidentNodeNotFoundException(activityId, sourceEventId)
targetEvent = self.aperiodicEAN.getNode(targetEventId)
if not targetEvent:
raise GraphIncidentNodeNotFoundException(activityId, targetEventId)
aperiodicActivity = AperiodicActivity(activityId, periodicActivityId,
activityType, sourceEvent,
targetEvent, lowerBound,
upperBound, passengers)
activityAdded = self.aperiodicEAN.addEdge(aperiodicActivity)
if not activityAdded:
raise GraphEdgeIdMultiplyAssignedException(activityId)
def process_aperiodic_timetable_entry(self, args: [str], line_number) -> None:
"""
Process the content of a timetable file.
:param args the content of the line
:param line_number the line number, used for error handling
:raise exceptions if the line does not exactly contain 2 entries
if the specific types of the entries do not match
the expectations
if the event does not exist
"""
if len(args) != 2:
raise InputFormatException(self.aperiodicTimetableFileName,
len(args), 2)
try:
eventId = int(args[0])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicTimetableFileName,
1, line_number, "int",
args[0]))
try:
time = int(args[1])
except ValueError:
raise(InputTypeInconsistencyException(self.aperiodicTimetableFileName,
2, line_number, "int",
args[1]))
event = self.aperiodicEAN.getNode(eventId)
if not event:
raise DataIndexNotFoundException("Aperiodic event", eventId)
event.setTime(time)
if self.timetable is not None:
self.timetable[event] = time
@staticmethod
def read(read_events: bool=True, read_activities: bool=True, read_seperate_timetable: bool=False,
read_disposition_timetable: bool=False, config: Config=default_config, event_file_name: str = "",
activity_file_name: str = "", timetable_file_name: str = "",
ean: Graph[AperiodicEvent, AperiodicActivity] = None, timetable: Timetable = None,
time_units_per_minute: int=0) -> (Graph[AperiodicEvent, AperiodicActivity], Timetable):
""""
Read the aperiodic EAN defined by the given file names. Will read the
timetable, if a file name is given. The data will be appended to the
fivfiven EAN and timetable object, if they are given. Otherwie, a new
EAN will be created.
:param read_events:
:param read_activities:
:param read_seperate_timetable:
:param read_disposition_timetable:
:param config:
:param time_units_per_minute:
:param event_file_name the file name to read the events
:param activity_file_name the file name to read the activities
:param timetable_file_name the file name to read the timetable
:param ean the aperiodic ean to store the read values in
:param timetable the aperiodic timetable to store the read
timetable in.
"""
if not ean:
ean = SimpleDictGraph()
if time_units_per_minute == 0:
time_units_per_minute = config.getIntegerValue("time_units_per_minute")
if not timetable:
timetable = Timetable(time_units_per_minute)
if read_events and not event_file_name:
event_file_name = config.getStringValue("default_events_expanded_file")
if read_activities and not activity_file_name:
activity_file_name = config.getStringValue("default_activities_expanded_file")
if read_disposition_timetable and not timetable_file_name:
timetable_file_name = config.getStringValue("default_disposition_timetable_file")
elif read_seperate_timetable and not timetable_file_name:
timetable_file_name = config.getStringValue("default_timetable_expanded_file")
reader = AperiodicEANReader(activity_file_name, event_file_name, timetable_file_name,
ean, timetable)
if read_events:
CsvReader.readCsv(event_file_name,
reader.process_aperiodic_event)
if read_activities:
CsvReader.readCsv(activity_file_name,
reader.process_aperiodic_activity)
if read_disposition_timetable or read_seperate_timetable:
CsvReader.readCsv(timetable_file_name,
reader.process_aperiodic_timetable_entry)
return ean, timetable
class AperiodicEANWriter:
"""
Implementation of an aperiodic EAN writer as a static method. Just call
writeEAN.
"""
@staticmethod
def write(ean: Graph[AperiodicEvent, AperiodicActivity], timetable: Timetable = None,
config: Config = default_config, write_events: bool = True, events_file_name: str = "",
events_header: str = None, write_activities: bool = False, activities_file_name: str = "",
activities_header: str = "", write_timetable: bool=False, write_disposition_timetable: bool=False,
timetable_file_name: str="", timetable_header: str="") -> None:
"""
Write the given ean. Which data should be written can be controlled
with writeEvents, writeActivities and writeAperiodicTimetable. If no
filenames or headers are given for a datatype and it should be written,
the corresponding values are read from the given config (or the
default config, if none is given). For the timetable, the data will be
read from the events, if no timetable object is given.
:param write_timetable:
:param write_disposition_timetable:
:param timetable_file_name:
:param timetable_header:
:param ean: the ean to write
:param config: the config to read from, if necessary values are not given
:param write_events: whether to write the events
:param aperiodicEventsFileName the file name to write the events to
:param events_header: the header to write in the event file
:param write_activities: whether to write the activities
:param activities_file_name the file name to write the activities to
:param activities_header: the header to write in the activities file
:param timetable
:param events_file_name
"""
if write_events:
if not events_file_name:
events_file_name = config.getStringValue("default_events_expanded_file")
if not events_header:
events_header = config.getStringValue("events_header")
CsvWriter.writeListStatic(events_file_name, ean.getNodes(), lambda e: e.toCsvStrings(None),
header=events_header)
if write_activities:
if not activities_file_name:
activities_file_name = config.getStringValue("default_activities_expanded_file")
if not activities_header:
activities_header = config.getStringValue("activities_header")
CsvWriter.writeListStatic(activities_file_name, ean.getEdges(), AperiodicActivity.toCsvStrings,
header=activities_header)
if write_disposition_timetable:
if not timetable_file_name:
timetable_file_name = config.getStringValue("default_disposition_timetable_file")
if not timetable_header:
|
elif write_timetable:
if not timetable_file_name:
timetable_file_name = config.getStringValue("default_timetable_expanded_file")
if not timetable_header:
timetable_header = config.getStringValue("timetable_header")
if write_disposition_timetable or write_timetable:
CsvWriter.writeListStatic(timetable_file_name, ean.getNodes(),
lambda e: e.toCsvStringsForTimetable(timetable), header=timetable_header)
@staticmethod
def setEventTimesFromTimetable(ean: Graph[AperiodicEvent, AperiodicActivity], timetable: Timetable) -> None:
"""
Set the time members in the aperiodic events according to the values
mapped to by the given timetable object.
:param ean the EAN in which the event times are to be updated.
:param timetable the timetable object from which the updated times
shall be taken.
"""
for event in ean.getNodes():
try:
event.setTime(timetable[event])
except ValueError:
#Ignore this. For events, that are not in the timetable, we dont want to set a new time.
pass
| timetable_header = config.getStringValue("timetable_header_disposition") |
submit_request_utility.py | import logging
import json
import time
import os
import config.config as pconfig
import env
from avalon_sdk.connector.direct.jrpc.jrpc_worker_registry import \
JRPCWorkerRegistryImpl
from avalon_sdk.connector.direct.jrpc.jrpc_work_order import \
JRPCWorkOrderImpl
from avalon_sdk.worker.worker_details import \
WorkerType, WorkerStatus
from avalon_sdk.connector.direct.jrpc.jrpc_work_order_receipt \
import JRPCWorkOrderReceiptImpl
from avalon_sdk.connector.blockchains.fabric.fabric_worker_registry \
import FabricWorkerRegistryImpl
from avalon_sdk.connector.blockchains.fabric.fabric_work_order \
import FabricWorkOrderImpl
from avalon_sdk.connector.blockchains.ethereum.ethereum_worker_registry \
import EthereumWorkerRegistryImpl
from avalon_sdk.connector.blockchains.ethereum.ethereum_work_order \
import EthereumWorkOrderProxyImpl
import avalon_sdk.worker.worker_details as worker_details
logger = logging.getLogger(__name__)
TCFHOME = os.environ.get("TCF_HOME", "../../")
def | ():
config = pconfig.parse_configuration_files(
env.conffiles, env.confpaths)
logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])
config["tcf"]["json_rpc_uri"] = env.uri_client_sdk
return config
def _create_worker_registry_instance(blockchain_type, config):
# create worker registry instance for direct/proxy model
if env.proxy_mode and blockchain_type == 'fabric':
return FabricWorkerRegistryImpl(config)
elif env.proxy_mode and blockchain_type == 'ethereum':
return EthereumWorkerRegistryImpl(config)
else:
logger.info("Direct SDK code path\n")
return JRPCWorkerRegistryImpl(config)
def _create_work_order_instance(blockchain_type, config):
# create work order instance for direct/proxy model
if env.proxy_mode and blockchain_type == 'fabric':
return FabricWorkOrderImpl(config)
elif env.proxy_mode and blockchain_type == 'ethereum':
return EthereumWorkOrderProxyImpl(config)
else:
logger.info("Direct SDK code path\n")
return JRPCWorkOrderImpl(config)
def _create_work_order_receipt_instance(blockchain_type, config):
# create work order receipt instance for direct/proxy model
if env.proxy_mode and blockchain_type == 'fabric':
return None
elif env.proxy_mode and blockchain_type == 'ethereum':
# TODO need to implement
return None
else:
logger.info("Direct SDK code path\n")
return JRPCWorkOrderReceiptImpl(config)
def submit_request_listener(
uri_client, input_json_str, output_json_file_name):
logger.info("Listener code path\n")
req_time = time.strftime("%Y%m%d_%H%M%S")
request_method = input_json_str["method"]
input_json_str = json.dumps(input_json_str)
# write request to file
signed_input_file = ('./results/' + output_json_file_name + '_' + req_time
+ '_request.json')
with open(signed_input_file, 'w') as req_file:
req_file.write(json.dumps(input_json_str, ensure_ascii=False))
logger.info("in submit listener %s", input_json_str)
if request_method == "WorkOrderGetResult":
logger.info("- Validating WorkOrderGetResult Response-")
response = {}
response_timeout_start = time.time()
response_timeout_multiplier = ((6000 / 3600) + 6) * 3
while "result" not in response:
if "error" in response:
if response["error"]["code"] != 5:
logger.info('WorkOrderGetResult - '
'Response received with error code. ')
err_cd = 1
break
response_timeout_end = time.time()
if ((response_timeout_end - response_timeout_start) >
response_timeout_multiplier):
logger.info('ERROR: WorkOrderGetResult response is not \
received within expected time.')
break
response = uri_client._postmsg(input_json_str)
else:
logger.info('**********Received Request*********\n%s\n', input_json_str)
response = uri_client._postmsg(input_json_str)
logger.info('**********Received Response*********\n%s\n', response)
# write response to file
response_output_file = ('./results/' + output_json_file_name + '_'
+ req_time + '_response.json')
with open(response_output_file, 'w') as resp_file:
resp_file.write(json.dumps(response, ensure_ascii=False))
return response
def workorder_submit_sdk(wo_params, input_json_obj=None):
logger.info("WorkOrderSubmit SDK code path\n")
if input_json_obj is None:
req_id = 3
else:
req_id = input_json_obj["id"]
config = config_file_read()
work_order = _create_work_order_instance(env.blockchain_type, config)
logger.info(" work order id %s \n", wo_params.get_work_order_id())
logger.info(" worker id %s \n", wo_params.get_worker_id())
logger.info(" Requester ID %s \n", wo_params.get_requester_id())
logger.info(" To string %s \n", wo_params.to_string())
logger.info(" worker id %s \n", wo_params.get_worker_id())
logger.info("Work order submit request : %s, \n \n ",
wo_params.to_jrpc_string(req_id))
response = work_order.work_order_submit(
wo_params.get_work_order_id(),
wo_params.get_worker_id(),
wo_params.get_requester_id(),
wo_params.to_string(),
id=req_id
)
if env.proxy_mode and (type(response) != dict):
if response.value == 0:
response = {"error": {"code": 5}}
else:
response = {"error": {"code": response.value}}
response["workOrderId"] = wo_params.get_work_order_id()
logger.info('**********Received Response*********\n%s\n', response)
return response
def worker_lookup_sdk(worker_type, input_json=None):
logger.info("WorkerLookUp SDK code path\n")
if input_json is None:
jrpc_req_id = 3
else:
jrpc_req_id = input_json["id"]
config = config_file_read()
worker_dict = {'SGX': WorkerType.TEE_SGX,
'MPC': WorkerType.MPC, 'ZK': WorkerType.ZK}
worker_registry = _create_worker_registry_instance(env.blockchain_type, config)
if env.blockchain_type == "ethereum":
if worker_type in worker_dict.keys():
worker = WorkerType.TEE_SGX
else:
worker = worker_type
worker_lookup_response = worker_registry.worker_lookup(
worker,
config["WorkerConfig"]["OrganizationId"],
config["WorkerConfig"]["ApplicationTypeId"],
jrpc_req_id
)
else:
worker_lookup_response = worker_registry.worker_lookup(
worker_type=worker_dict.get(worker_type, worker_type), id=jrpc_req_id)
logger.info("\n Worker lookup response: {}\n".format(
json.dumps(worker_lookup_response, indent=4)
))
return worker_lookup_response
def worker_register_sdk(register_params, input_json):
logger.info("WorkerRegister SDK code path\n")
jrpc_req_id = input_json["id"]
if input_json is None:
jrpc_req_id = 3
else:
jrpc_req_id = input_json["id"]
worker_dict = {'SGX': WorkerType.TEE_SGX,
'MPC': WorkerType.MPC, 'ZK': WorkerType.ZK}
config = config_file_read()
worker_registry = _create_worker_registry_instance(env.blockchain_type, config)
if env.proxy_mode and (env.blockchain_type == "ethereum"):
worker_register_result = worker_registry.worker_register(
register_params["worker_id"],
worker_dict[register_params["workerType"]],
register_params["organization_id"],
register_params["application_type_id"],
json.dumps(register_params["details"]))
else:
worker_register_result = worker_registry.worker_register(
register_params["worker_id"],
worker_dict[register_params["workerType"]],
register_params["organization_id"],
register_params["application_type_id"],
json.dumps(register_params["details"]), jrpc_req_id)
logger.info("\n Worker register response: {}\n".format(
json.dumps(worker_register_result, indent=4)))
return worker_register_result
def worker_setstatus_sdk(set_status_params, input_json):
logger.info("WorkerSetStatus SDK code path\n")
logger.info("Worker status params %s \n", set_status_params)
if input_json is None:
jrpc_req_id = 3
else:
jrpc_req_id = input_json["id"]
status_dict = {1: WorkerStatus.ACTIVE, 2: WorkerStatus.OFF_LINE,
3: WorkerStatus.DECOMMISSIONED,
4: WorkerStatus.COMPROMISED}
config = config_file_read()
worker_registry = _create_worker_registry_instance(env.blockchain_type, config)
if env.proxy_mode and (env.blockchain_type == "ethereum"):
worker_setstatus_result = worker_registry.worker_set_status(
set_status_params["worker_id"],
status_dict[set_status_params["status"]])
else:
worker_setstatus_result = worker_registry.worker_set_status(
set_status_params["worker_id"],
status_dict[set_status_params["status"]], jrpc_req_id)
if env.proxy_mode:
result = worker_setstatus_result
worker_setstatus_result = {}
worker_setstatus_result["error"] = {"code" : result.value, "message" : ""}
logger.info("\n Worker setstatus response: {}\n".format(worker_setstatus_result))
return worker_setstatus_result
def worker_retrieve_sdk(worker_id, input_json=None):
logger.info("WorkerRetrieve SDK code path\n")
worker_obj = worker_details.SGXWorkerDetails()
if input_json is None:
jrpc_req_id = 11
else:
jrpc_req_id = input_json["id"]
config = config_file_read()
worker_registry = _create_worker_registry_instance(env.blockchain_type, config)
worker_retrieve_result = worker_registry.worker_retrieve(worker_id, jrpc_req_id)
if env.proxy_mode:
if worker_retrieve_result is None:
worker_retrieve_result = {"error": {"code": '', "message": "Worker Id not found"}}
else:
response = worker_retrieve_result
worker_obj.load_worker(json.loads(response[4]))
worker_retrieve_result = {}
result = {"workerType": response[1],
"organizationId": response[2],
"applicationTypeId": response[3],
"details": json.loads(response[4])}
worker_retrieve_result["result"] = result
if "error" in worker_retrieve_result:
logger.error("Unable to retrieve worker details\n")
return worker_retrieve_result
logger.info("\n Worker retrieve response: {}\n".format(worker_retrieve_result))
worker_obj.worker_id = worker_id
worker_retrieve_result["workerId"] = worker_id
logger.info("\n Worker ID\n%s\n", worker_id)
return worker_retrieve_result
def worker_update_sdk(update_params, input_json=None):
logger.info("WorkerUpdate SDK code path\n")
logger.info("Worker update params %s \n", update_params)
worker_obj = worker_details.SGXWorkerDetails()
# update_params = json.loads(update_params)
if input_json is None:
jrpc_req_id = 11
else:
jrpc_req_id = input_json["id"]
config = config_file_read()
worker_registry = _create_worker_registry_instance(env.blockchain_type, config)
if env.proxy_mode and (env.blockchain_type == "ethereum"):
worker_update_result = worker_registry.worker_update(
update_params["worker_id"],
json.dumps(update_params["details"]))
else:
worker_update_result = worker_registry.worker_update(
update_params["worker_id"],
json.dumps(update_params["details"]), jrpc_req_id)
if env.proxy_mode and (type(worker_update_result) != dict):
response = worker_update_result.value
worker_update_result = {"error": {"code": response, "message" : ""}}
logger.info("\n Worker update response: {}\n".format(worker_update_result))
return worker_update_result
def workorder_receiptcreate_sdk(wo_create_receipt, input_json):
logger.info("WorkerReceiptCreate SDK code path\n")
jrpc_req_id = input_json["id"]
config = config_file_read()
# Create receipt
wo_receipt = _create_work_order_receipt_instance(env.blockchain_type, config)
# Submit work order create receipt jrpc request
wo_receipt_resp = wo_receipt.work_order_receipt_create(
wo_create_receipt["workOrderId"],
wo_create_receipt["workerServiceId"],
wo_create_receipt["workerId"],
wo_create_receipt["requesterId"],
wo_create_receipt["receiptCreateStatus"],
wo_create_receipt["workOrderRequestHash"],
wo_create_receipt["requesterGeneratedNonce"],
wo_create_receipt["requesterSignature"],
wo_create_receipt["signatureRules"],
wo_create_receipt["receiptVerificationKey"],
jrpc_req_id
)
logger.info("Work order create receipt response : {} \n \n ".format(
wo_receipt_resp
))
return wo_receipt_resp
def workorder_receiptretrieve_sdk(workorderId, input_json):
logger.info("ReceiptRetrieve SDK code path\n")
jrpc_req_id = input_json["id"]
config = config_file_read()
# Create receipt
wo_receipt = _create_work_order_receipt_instance(env.blockchain_type, config)
wo_receipt_resp = wo_receipt.work_order_receipt_retrieve(
workorderId, jrpc_req_id)
logger.info("Work order retrieve receipt response : {} \n \n ".format(
wo_receipt_resp
))
# Retrieve last update to receipt by passing 0xFFFFFFFF
jrpc_req_id += 1
receipt_update_retrieve = \
wo_receipt.work_order_receipt_update_retrieve(
workorderId,
None,
1 << 32,
id=jrpc_req_id)
logger.info("\n Last update to receipt receipt is:\n {}".format(
json.dumps(receipt_update_retrieve, indent=4)
))
return receipt_update_retrieve
def workorder_getresult_sdk(workorderId, input_json):
logger.info("WorkOderGetResult SDK code path\n")
jrpc_req_id = input_json["id"]
config = config_file_read()
work_order = _create_work_order_instance(env.blockchain_type, config)
logger.info("----- Validating WorkOrderGetResult Response ------")
get_result_res = work_order.work_order_get_result(
workorderId, jrpc_req_id)
logger.info("****** WorkOrderGetResult Received Response*****\n%s\n", get_result_res)
if env.proxy_mode and (get_result_res is None):
get_result_res = {"error": {"code": -1}}
return get_result_res
def workorder_receiptlookup_sdk(requesterId, input_json):
logger.info("ReceiptRetrieve SDK code path\n")
jrpc_req_id = input_json["id"]
config = config_file_read()
wo_receipt = _create_work_order_receipt_instance(env.blockchain_type, config)
wo_receipt_resp = wo_receipt.work_order_receipt_lookup(
requester_id=requesterId, id=jrpc_req_id)
logger.info("Work order receipt lookup response : {} \n \n ".format(
wo_receipt_resp
))
return wo_receipt_resp
| config_file_read |
main.go | package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"github.com/truestblue/php-transformer/dictionary"
"github.com/truestblue/php-transformer/parser"
"github.com/truestblue/php-transformer/php5"
"github.com/truestblue/php-transformer/php7"
printer2 "github.com/truestblue/php-transformer/printer"
"github.com/truestblue/php-transformer/visitor"
"github.com/yookoala/realpath"
"io"
"strings"
"errors"
)
const (
DIR = iota
CPY = iota
SCR = iota
)
var wg sync.WaitGroup
var usePhp5 *bool
var dump *bool
var replace *bool
var test *bool
var phar *bool
var base = ""
var outFilePath = ""
func main() {
usePhp5 = flag.Bool("php5", false, "use PHP5 parserWorker")
dump = flag.Bool("dump", false, "disable dumping to stdout")
replace = flag.Bool("replace", false, "replace files in place")
test = flag.Bool("test", false, "transform .phpt files")
phar = flag.Bool("phar", false, "transform .inc")
flag.Parse()
pathCh := make(chan string)
resultCh := make(chan parser.Parser)
dictionary.InitMapping()
// run 4 concurrent parserWorkers
for i := 0; i < 4; i++ {
go parserWorker(pathCh, resultCh)
}
// run printer goroutine
go printer(resultCh)
// process files
processPath(flag.Args(), pathCh)
// wait the all files done
wg.Wait()
close(pathCh)
close(resultCh)
}
func processPath(pathList []string, pathCh chan<- string) {
for _, pathCur := range pathList {
real, err := realpath.Realpath(pathCur)
checkErr(err)
parsePathOut(real)
err = filepath.Walk(real, func(pathCur string, f os.FileInfo, err error) error {
if !f.IsDir() && (filepath.Ext(pathCur) == ".php" ||
(*test && filepath.Ext(pathCur) == ".phpt") ||
(*phar && (filepath.Ext(pathCur) == ".inc"))) {
wg.Add(1)
pathCh <- pathCur
} else if f.IsDir() {
printOut(pathCur, DIR)
} else {
printOut(pathCur, CPY)
}
return nil
})
checkErr(err)
}
}
func parserWorker(pathCh <-chan string, result chan<- parser.Parser) {
var parserWorker parser.Parser
for {
path, ok := <-pathCh
if !ok {
return
}
src, _ := os.Open(path)
if *usePhp5 {
parserWorker = php5.NewParser(src, path)
} else {
parserWorker = php7.NewParser(src, path)
}
parserWorker.Parse()
result <- parserWorker
}
}
func printer(result <-chan parser.Parser) {
for {
parserWorker, ok := <-result
if !ok {
return
}
fmt.Printf("==> %s\n", parserWorker.GetPath())
for _, e := range parserWorker.GetErrors() {
fmt.Println(e)
}
if *dump {
nsResolver := visitor.NewNamespaceResolver()
parserWorker.GetRootNode().Walk(nsResolver)
dumper := visitor.Dumper{
Writer: os.Stdout,
Indent: " | ",
Comments: parserWorker.GetComments(),
Positions: parserWorker.GetPositions(),
NsResolver: nsResolver,
}
parserWorker.GetRootNode().Walk(dumper)
}
fileOut := printOut(parserWorker.GetPath(), SCR)
file, err := os.Create(fileOut)
checkErr(err)
p := printer2.NewPrinter(file, " ")
p.Print(parserWorker.GetRootNode())
wg.Done()
}
}
func checkErr(err error) {
if err != nil {
log.Fatal(err)
}
}
func printOut(pathCur string, printType int) string {
sf := strings.SplitAfter(pathCur, base)
if !*replace {
sf[0] = outFilePath
}
fileOut := strings.Join(sf, "/")
switch printType {
case DIR:
os.MkdirAll(fileOut, os.ModePerm)
case CPY:
if !*replace {
copyFile(pathCur, fileOut)
}
case SCR:
//just pass back file name.
default:
//panic
}
return fileOut
}
func | (src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
return out.Close()
}
func parsePathOut(real string) {
f, err := os.Lstat(real)
checkErr(err)
if !f.IsDir() {
err := errors.New("Error-- filenames not accepted, please enter path")
checkErr(err)
}
real = strings.TrimRight(real, "/")
base = real + "/"
if !*replace {
outFilePath = real + "-ps"
os.MkdirAll(outFilePath, os.ModePerm)
}
}
| copyFile |
void_node.rs | use crate::{
ast::node::VoidNode,
crocol::{CrocolNode, LCodegen, LNodeResult},
CrocoError,
};
impl CrocolNode for VoidNode {
fn crocol<'ctx>(
&mut self,
_codegen: &mut LCodegen<'ctx>,
) -> Result<LNodeResult<'ctx>, CrocoError> |
}
| {
Ok(LNodeResult::Void)
} |
test_db.py | # Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import datetime
import inspect
import unittest
from random import choice
from unittest.mock import patch
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_field
from frappe.database import savepoint
from frappe.database.database import Database
from frappe.query_builder import Field
from frappe.query_builder.functions import Concat_ws
from frappe.tests.test_query_builder import db_type_is, run_only_if
from frappe.utils import add_days, cint, now, random_string
from frappe.utils.testutils import clear_custom_fields
class TestDB(unittest.TestCase):
def test_get_value(self):
self.assertEqual(frappe.db.get_value("User", {"name": ["=", "Administrator"]}), "Administrator")
self.assertEqual(frappe.db.get_value("User", {"name": ["like", "Admin%"]}), "Administrator")
self.assertNotEqual(frappe.db.get_value("User", {"name": ["!=", "Guest"]}), "Guest")
self.assertEqual(frappe.db.get_value("User", {"name": ["<", "Adn"]}), "Administrator")
self.assertEqual(frappe.db.get_value("User", {"name": ["<=", "Administrator"]}), "Administrator")
self.assertEqual(
frappe.db.get_value("User", {}, ["Max(name)"], order_by=None),
frappe.db.sql("SELECT Max(name) FROM tabUser")[0][0],
)
self.assertEqual(
frappe.db.get_value("User", {}, "Min(name)", order_by=None),
frappe.db.sql("SELECT Min(name) FROM tabUser")[0][0],
)
self.assertIn(
"for update",
frappe.db.get_value(
"User", Field("name") == "Administrator", for_update=True, run=False
).lower(),
)
user_doctype = frappe.qb.DocType("User")
self.assertEqual(
frappe.qb.from_(user_doctype).select(user_doctype.name, user_doctype.email).run(),
frappe.db.get_values(
user_doctype,
filters={},
fieldname=[user_doctype.name, user_doctype.email],
order_by=None,
),
)
self.assertEqual(
frappe.db.sql("""SELECT name FROM `tabUser` WHERE name > 's' ORDER BY MODIFIED DESC""")[0][0],
frappe.db.get_value("User", {"name": [">", "s"]}),
)
self.assertEqual(
frappe.db.sql("""SELECT name FROM `tabUser` WHERE name >= 't' ORDER BY MODIFIED DESC""")[0][0],
frappe.db.get_value("User", {"name": [">=", "t"]}),
)
self.assertEqual(
frappe.db.get_values(
"User",
filters={"name": "Administrator"},
distinct=True,
fieldname="email",
),
frappe.qb.from_(user_doctype)
.where(user_doctype.name == "Administrator")
.select("email")
.distinct()
.run(),
)
self.assertIn(
"concat_ws",
frappe.db.get_value(
"User",
filters={"name": "Administrator"},
fieldname=Concat_ws(" ", "LastName"),
run=False,
).lower(),
)
self.assertEqual(
frappe.db.sql("select email from tabUser where name='Administrator' order by modified DESC"),
frappe.db.get_values("User", filters=[["name", "=", "Administrator"]], fieldname="email"),
)
def test_get_value_limits(self):
# check both dict and list style filters
filters = [{"enabled": 1}, [["enabled", "=", 1]]]
for filter in filters:
self.assertEqual(1, len(frappe.db.get_values("User", filters=filter, limit=1)))
# count of last touched rows as per DB-API 2.0 https://peps.python.org/pep-0249/#rowcount
self.assertGreaterEqual(1, cint(frappe.db._cursor.rowcount))
self.assertEqual(2, len(frappe.db.get_values("User", filters=filter, limit=2)))
self.assertGreaterEqual(2, cint(frappe.db._cursor.rowcount))
# without limits length == count
self.assertEqual(
len(frappe.db.get_values("User", filters=filter)), frappe.db.count("User", filter)
)
frappe.db.get_value("User", filters=filter)
self.assertGreaterEqual(1, cint(frappe.db._cursor.rowcount))
frappe.db.exists("User", filter)
self.assertGreaterEqual(1, cint(frappe.db._cursor.rowcount))
def test_escape(self):
frappe.db.escape("香港濟生堂製藥有限公司 - IT".encode("utf-8"))
def test_get_single_value(self):
# setup
values_dict = {
"Float": 1.5,
"Int": 1,
"Percent": 55.5,
"Currency": 12.5,
"Data": "Test",
"Date": datetime.datetime.now().date(),
"Datetime": datetime.datetime.now(),
"Time": datetime.timedelta(hours=9, minutes=45, seconds=10),
}
test_inputs = [
{"fieldtype": fieldtype, "value": value} for fieldtype, value in values_dict.items()
]
for fieldtype in values_dict.keys():
create_custom_field(
"Print Settings",
{
"fieldname": f"test_{fieldtype.lower()}",
"label": f"Test {fieldtype}",
"fieldtype": fieldtype,
},
)
# test
for inp in test_inputs:
fieldname = f"test_{inp['fieldtype'].lower()}"
frappe.db.set_value("Print Settings", "Print Settings", fieldname, inp["value"])
self.assertEqual(frappe.db.get_single_value("Print Settings", fieldname), inp["value"])
# teardown
clear_custom_fields("Print Settings")
def test_log_touched_tables(self):
frappe.flags.in_migrate = True
frappe.flags.touched_tables = set()
frappe.db.set_value("System Settings", "System Settings", "backup_limit", 5)
self.assertIn("tabSingles", frappe.flags.touched_tables)
frappe.flags.touched_tables = set()
todo = frappe.get_doc({"doctype": "ToDo", "description": "Random Description"})
todo.save()
self.assertIn("tabToDo", frappe.flags.touched_tables)
frappe.flags.touched_tables = set()
todo.description = "Another Description"
todo.save()
self.assertIn("tabToDo", frappe.flags.touched_tables)
if frappe.db.db_type != "postgres":
frappe.flags.touched_tables = set()
frappe.db.sql("UPDATE tabToDo SET description = 'Updated Description'")
self.assertNotIn("tabToDo SET", frappe.flags.touched_tables)
self.assertIn("tabToDo", frappe.flags.touched_tables)
frappe.flags.touched_tables = set()
todo.delete()
self.assertIn("tabToDo", frappe.flags.touched_tables)
frappe.flags.touched_tables = set()
create_custom_field("ToDo", {"label": "ToDo Custom Field"})
self.assertIn("tabToDo", frappe.flags.touched_tables)
self.assertIn("tabCustom Field", frappe.flags.touched_tables)
frappe.flags.in_migrate = False
frappe.flags.touched_tables.clear()
def test_db_keywords_as_fields(self):
"""Tests if DB keywords work as docfield names. If they're wrapped with grave accents."""
# Using random.choices, picked out a list of 40 keywords for testing
all_keywords = {
"mariadb": [
"CHARACTER",
"DELAYED",
"LINES",
"EXISTS",
"YEAR_MONTH",
"LOCALTIME",
"BOTH",
"MEDIUMINT",
"LEFT",
"BINARY",
"DEFAULT",
"KILL",
"WRITE",
"SQL_SMALL_RESULT",
"CURRENT_TIME",
"CROSS",
"INHERITS",
"SELECT",
"TABLE",
"ALTER",
"CURRENT_TIMESTAMP",
"XOR",
"CASE",
"ALL",
"WHERE",
"INT",
"TO",
"SOME",
"DAY_MINUTE",
"ERRORS",
"OPTIMIZE",
"REPLACE",
"HIGH_PRIORITY",
"VARBINARY",
"HELP",
"IS",
"CHAR",
"DESCRIBE",
"KEY",
],
"postgres": [
"WORK",
"LANCOMPILER",
"REAL",
"HAVING",
"REPEATABLE",
"DATA",
"USING",
"BIT",
"DEALLOCATE",
"SERIALIZABLE",
"CURSOR",
"INHERITS",
"ARRAY",
"TRUE",
"IGNORE",
"PARAMETER_MODE",
"ROW",
"CHECKPOINT",
"SHOW",
"BY",
"SIZE",
"SCALE",
"UNENCRYPTED",
"WITH",
"AND",
"CONVERT",
"FIRST",
"SCOPE",
"WRITE",
"INTERVAL",
"CHARACTER_SET_SCHEMA",
"ADD",
"SCROLL",
"NULL",
"WHEN",
"TRANSACTION_ACTIVE",
"INT",
"FORTRAN",
"STABLE",
],
}
created_docs = []
# edit by rushabh: added [:1]
# don't run every keyword! - if one works, they all do
fields = all_keywords[frappe.conf.db_type][:1]
test_doctype = "ToDo"
def add_custom_field(field):
create_custom_field(
test_doctype,
{
"fieldname": field.lower(),
"label": field.title(),
"fieldtype": "Data",
},
)
# Create custom fields for test_doctype
for field in fields:
add_custom_field(field)
# Create documents under that doctype and query them via ORM
for _ in range(10):
docfields = {key.lower(): random_string(10) for key in fields}
doc = frappe.get_doc({"doctype": test_doctype, "description": random_string(20), **docfields})
doc.insert()
created_docs.append(doc.name)
random_field = choice(fields).lower()
random_doc = choice(created_docs)
random_value = random_string(20)
# Testing read
self.assertEqual(
list(frappe.get_all("ToDo", fields=[random_field], limit=1)[0])[0], random_field
)
self.assertEqual(
list(frappe.get_all("ToDo", fields=[f"`{random_field}` as total"], limit=1)[0])[0], "total"
)
# Testing read for distinct and sql functions
self.assertEqual(
list(
frappe.get_all(
"ToDo",
fields=[f"`{random_field}` as total"],
distinct=True,
limit=1,
)[0]
)[0],
"total",
)
self.assertEqual(
list(
frappe.get_all(
"ToDo",
fields=[f"`{random_field}`"],
distinct=True,
limit=1,
)[0]
)[0],
random_field,
)
self.assertEqual(
list(frappe.get_all("ToDo", fields=[f"count(`{random_field}`)"], limit=1)[0])[0],
"count" if frappe.conf.db_type == "postgres" else f"count(`{random_field}`)",
)
# Testing update
frappe.db.set_value(test_doctype, random_doc, random_field, random_value)
self.assertEqual(frappe.db.get_value(test_doctype, random_doc, random_field), random_value)
# Cleanup - delete records and remove custom fields
for doc in created_docs:
frappe.delete_doc(test_doctype, doc)
clear_custom_fields(test_doctype)
def test_savepoints(self):
frappe.db.rollback()
save_point = "todonope"
created_docs = []
failed_docs = []
for _ in range(5):
frappe.db.savepoint(save_point)
doc_gone = frappe.get_doc(doctype="ToDo", description="nope").save()
failed_docs.append(doc_gone.name)
frappe.db.rollback(save_point=save_point)
doc_kept = frappe.get_doc(doctype="ToDo", description="nope").save()
created_docs.append(doc_kept.name)
frappe.db.commit()
for d in failed_docs:
self.assertFalse(frappe.db.exists("ToDo", d))
for d in created_docs:
self.assertTrue(frappe.db.exists("ToDo", d))
def test_savepoints_wrapper(self):
frappe.db.rollback()
class SpecificExc(Exception):
pass
created_docs = []
failed_docs = []
for _ in range(5):
with savepoint(catch=SpecificExc):
doc_kept = frappe.get_doc(doctype="ToDo", description="nope").save()
created_docs.append(doc_kept.name)
with savepoint(catch=SpecificExc):
doc_gone = frappe.get_doc(doctype="ToDo", description="nope").save()
failed_docs.append(doc_gone.name)
raise SpecificExc
frappe.db.commit()
for d in failed_docs:
self.assertFalse(frappe.db.exists("ToDo", d))
for d in created_docs:
self.assertTrue(frappe.db.exists("ToDo", d))
def test_transaction_writes_error(self):
from frappe.database.database import Database
frappe.db.rollback()
frappe.db.MAX_WRITES_PER_TRANSACTION = 1
note = frappe.get_last_doc("ToDo")
note.description = "changed"
with self.assertRaises(frappe.TooManyWritesError) as tmw:
note.save()
frappe.db.MAX_WRITES_PER_TRANSACTION = Database.MAX_WRITES_PER_TRANSACTION
def test_transaction_write_counting(self):
note = frappe.get_doc(doctype="Note", title="transaction counting").insert()
writes = frappe.db.transaction_writes
frappe.db.set_value("Note", note.name, "content", "abc")
self.assertEqual(1, frappe.db.transaction_writes - writes)
writes = frappe.db.transaction_writes
frappe.db.sql(
"""
update `tabNote`
set content = 'abc'
where name = %s
""",
note.name,
)
self.assertEqual(1, frappe.db.transaction_writes - writes)
def test_pk_collision_ignoring(self):
# note has `name` generated from title
for _ in range(3):
frappe.get_doc(doctype="Note", title="duplicate name").insert(ignore_if_duplicate=True)
with savepoint():
self.assertRaises(
frappe.DuplicateEntryError, frappe.get_doc(doctype="Note", title="duplicate name").insert
)
# recover transaction to continue other tests
raise Exception
def test_exists(self):
dt, dn = "User", "Administrator"
self.assertEqual(frappe.db.exists(dt, dn, cache=True), dn)
self.assertEqual(frappe.db.exists(dt, dn), dn)
self.assertEqual(frappe.db.exists(dt, {"name": ("=", dn)}), dn)
filters = {"doctype": dt, "name": ("like", "Admin%")}
self.assertEqual(frappe.db.exists(filters), dn)
self.assertEqual(filters["doctype"], dt) # make sure that doctype was not removed from filters
self.assertEqual(frappe.db.exists(dt, [["name", "=", dn]]), dn)
@run_only_if(db_type_is.MARIADB)
class TestDDLCommandsMaria(unittest.TestCase):
test_table_name = "TestNotes"
def setUp(self) -> None:
frappe.db.commit()
frappe.db.sql(
f"""
CREATE TABLE `tab{self.test_table_name}` (`id` INT NULL, content TEXT, PRIMARY KEY (`id`));
"""
)
def tearDown(self) -> None:
frappe.db.sql(f"DROP TABLE tab{self.test_table_name};")
self.test_table_name = "TestNotes"
def test_rename(self) -> N | table_name = f"{self.test_table_name}_new"
frappe.db.rename_table(self.test_table_name, new_table_name)
check_exists = frappe.db.sql(
f"""
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'tab{new_table_name}';
"""
)
self.assertGreater(len(check_exists), 0)
self.assertIn(f"tab{new_table_name}", check_exists[0])
# * so this table is deleted after the rename
self.test_table_name = new_table_name
def test_describe(self) -> None:
self.assertEqual(
(
("id", "int(11)", "NO", "PRI", None, ""),
("content", "text", "YES", "", None, ""),
),
frappe.db.describe(self.test_table_name),
)
def test_change_type(self) -> None:
frappe.db.change_column_type("TestNotes", "id", "varchar(255)")
test_table_description = frappe.db.sql(f"DESC tab{self.test_table_name};")
self.assertGreater(len(test_table_description), 0)
self.assertIn("varchar(255)", test_table_description[0])
def test_add_index(self) -> None:
index_name = "test_index"
frappe.db.add_index(self.test_table_name, ["id", "content(50)"], index_name)
indexs_in_table = frappe.db.sql(
f"""
SHOW INDEX FROM tab{self.test_table_name}
WHERE Key_name = '{index_name}';
"""
)
self.assertEqual(len(indexs_in_table), 2)
class TestDBSetValue(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.todo1 = frappe.get_doc(doctype="ToDo", description="test_set_value 1").insert()
cls.todo2 = frappe.get_doc(doctype="ToDo", description="test_set_value 2").insert()
def test_update_single_doctype_field(self):
value = frappe.db.get_single_value("System Settings", "deny_multiple_sessions")
changed_value = not value
frappe.db.set_value(
"System Settings", "System Settings", "deny_multiple_sessions", changed_value
)
current_value = frappe.db.get_single_value("System Settings", "deny_multiple_sessions")
self.assertEqual(current_value, changed_value)
changed_value = not current_value
frappe.db.set_value("System Settings", None, "deny_multiple_sessions", changed_value)
current_value = frappe.db.get_single_value("System Settings", "deny_multiple_sessions")
self.assertEqual(current_value, changed_value)
changed_value = not current_value
frappe.db.set_single_value("System Settings", "deny_multiple_sessions", changed_value)
current_value = frappe.db.get_single_value("System Settings", "deny_multiple_sessions")
self.assertEqual(current_value, changed_value)
def test_update_single_row_single_column(self):
frappe.db.set_value("ToDo", self.todo1.name, "description", "test_set_value change 1")
updated_value = frappe.db.get_value("ToDo", self.todo1.name, "description")
self.assertEqual(updated_value, "test_set_value change 1")
def test_update_single_row_multiple_columns(self):
description, status = "Upated by test_update_single_row_multiple_columns", "Closed"
frappe.db.set_value(
"ToDo",
self.todo1.name,
{
"description": description,
"status": status,
},
update_modified=False,
)
updated_desciption, updated_status = frappe.db.get_value(
"ToDo", filters={"name": self.todo1.name}, fieldname=["description", "status"]
)
self.assertEqual(description, updated_desciption)
self.assertEqual(status, updated_status)
def test_update_multiple_rows_single_column(self):
frappe.db.set_value(
"ToDo", {"description": ("like", "%test_set_value%")}, "description", "change 2"
)
self.assertEqual(frappe.db.get_value("ToDo", self.todo1.name, "description"), "change 2")
self.assertEqual(frappe.db.get_value("ToDo", self.todo2.name, "description"), "change 2")
def test_update_multiple_rows_multiple_columns(self):
todos_to_update = frappe.get_all(
"ToDo",
filters={"description": ("like", "%test_set_value%"), "status": ("!=", "Closed")},
pluck="name",
)
frappe.db.set_value(
"ToDo",
{"description": ("like", "%test_set_value%"), "status": ("!=", "Closed")},
{"status": "Closed", "priority": "High"},
)
test_result = frappe.get_all(
"ToDo", filters={"name": ("in", todos_to_update)}, fields=["status", "priority"]
)
self.assertTrue(all(x for x in test_result if x["status"] == "Closed"))
self.assertTrue(all(x for x in test_result if x["priority"] == "High"))
def test_update_modified_options(self):
self.todo2.reload()
todo = self.todo2
updated_description = f"{todo.description} - by `test_update_modified_options`"
custom_modified = datetime.datetime.fromisoformat(add_days(now(), 10))
custom_modified_by = "[email protected]"
frappe.db.set_value("ToDo", todo.name, "description", updated_description, update_modified=False)
self.assertEqual(updated_description, frappe.db.get_value("ToDo", todo.name, "description"))
self.assertEqual(todo.modified, frappe.db.get_value("ToDo", todo.name, "modified"))
frappe.db.set_value(
"ToDo",
todo.name,
"description",
"test_set_value change 1",
modified=custom_modified,
modified_by=custom_modified_by,
)
self.assertTupleEqual(
(custom_modified, custom_modified_by),
frappe.db.get_value("ToDo", todo.name, ["modified", "modified_by"]),
)
def test_for_update(self):
self.todo1.reload()
with patch.object(Database, "sql") as sql_called:
frappe.db.set_value(
self.todo1.doctype,
self.todo1.name,
"description",
f"{self.todo1.description}-edit by `test_for_update`",
)
first_query = sql_called.call_args_list[0].args[0]
second_query = sql_called.call_args_list[1].args[0]
self.assertTrue(sql_called.call_count == 2)
self.assertTrue("FOR UPDATE" in first_query)
if frappe.conf.db_type == "postgres":
from frappe.database.postgres.database import modify_query
self.assertTrue(modify_query("UPDATE `tabToDo` SET") in second_query)
if frappe.conf.db_type == "mariadb":
self.assertTrue("UPDATE `tabToDo` SET" in second_query)
def test_cleared_cache(self):
self.todo2.reload()
with patch.object(frappe, "clear_document_cache") as clear_cache:
frappe.db.set_value(
self.todo2.doctype,
self.todo2.name,
"description",
f"{self.todo2.description}-edit by `test_cleared_cache`",
)
clear_cache.assert_called()
def test_update_alias(self):
args = (self.todo1.doctype, self.todo1.name, "description", "Updated by `test_update_alias`")
kwargs = {
"for_update": False,
"modified": None,
"modified_by": None,
"update_modified": True,
"debug": False,
}
self.assertTrue("return self.set_value(" in inspect.getsource(frappe.db.update))
with patch.object(Database, "set_value") as set_value:
frappe.db.update(*args, **kwargs)
set_value.assert_called_once()
set_value.assert_called_with(*args, **kwargs)
@classmethod
def tearDownClass(cls):
frappe.db.rollback()
@run_only_if(db_type_is.POSTGRES)
class TestDDLCommandsPost(unittest.TestCase):
test_table_name = "TestNotes"
def setUp(self) -> None:
frappe.db.sql(
f"""
CREATE TABLE "tab{self.test_table_name}" ("id" INT NULL, content text, PRIMARY KEY ("id"))
"""
)
def tearDown(self) -> None:
frappe.db.sql(f'DROP TABLE "tab{self.test_table_name}"')
self.test_table_name = "TestNotes"
def test_rename(self) -> None:
new_table_name = f"{self.test_table_name}_new"
frappe.db.rename_table(self.test_table_name, new_table_name)
check_exists = frappe.db.sql(
f"""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'tab{new_table_name}'
);
"""
)
self.assertTrue(check_exists[0][0])
# * so this table is deleted after the rename
self.test_table_name = new_table_name
def test_describe(self) -> None:
self.assertEqual([("id",), ("content",)], frappe.db.describe(self.test_table_name))
def test_change_type(self) -> None:
frappe.db.change_column_type(self.test_table_name, "id", "varchar(255)")
check_change = frappe.db.sql(
f"""
SELECT
table_name,
column_name,
data_type
FROM
information_schema.columns
WHERE
table_name = 'tab{self.test_table_name}'
"""
)
self.assertGreater(len(check_change), 0)
self.assertIn("character varying", check_change[0])
def test_add_index(self) -> None:
index_name = "test_index"
frappe.db.add_index(self.test_table_name, ["id", "content(50)"], index_name)
indexs_in_table = frappe.db.sql(
f"""
SELECT indexname
FROM pg_indexes
WHERE tablename = 'tab{self.test_table_name}'
AND indexname = '{index_name}' ;
""",
)
self.assertEqual(len(indexs_in_table), 1)
@run_only_if(db_type_is.POSTGRES)
def test_modify_query(self):
from frappe.database.postgres.database import modify_query
query = "select * from `tabtree b` where lft > 13 and rgt <= 16 and name =1.0 and parent = 4134qrsdc and isgroup = 1.00045"
self.assertEqual(
"select * from \"tabtree b\" where lft > '13' and rgt <= '16' and name = '1' and parent = 4134qrsdc and isgroup = 1.00045",
modify_query(query),
)
query = (
'select locate(".io", "frappe.io"), locate("3", cast(3 as varchar)), locate("3", 3::varchar)'
)
self.assertEqual(
'select strpos( "frappe.io", ".io"), strpos( cast(3 as varchar), "3"), strpos( 3::varchar, "3")',
modify_query(query),
)
@run_only_if(db_type_is.POSTGRES)
def test_modify_values(self):
from frappe.database.postgres.database import modify_values
self.assertEqual(
{"abcd": "23", "efgh": "23", "ijkl": 23.0345, "mnop": "wow"},
modify_values({"abcd": 23, "efgh": 23.0, "ijkl": 23.0345, "mnop": "wow"}),
)
self.assertEqual(["23", "23", 23.00004345, "wow"], modify_values((23, 23.0, 23.00004345, "wow")))
def test_sequence_table_creation(self):
from frappe.core.doctype.doctype.test_doctype import new_doctype
dt = new_doctype("autoinc_dt_seq_test", autoname="autoincrement").insert(ignore_permissions=True)
if frappe.db.db_type == "postgres":
self.assertTrue(
frappe.db.sql(
"""select sequence_name FROM information_schema.sequences
where sequence_name ilike 'autoinc_dt_seq_test%'"""
)[0][0]
)
else:
self.assertTrue(
frappe.db.sql(
"""select data_type FROM information_schema.tables
where table_type = 'SEQUENCE' and table_name like 'autoinc_dt_seq_test%'"""
)[0][0]
)
dt.delete(ignore_permissions=True)
| one:
new_ |
conf.py | # -*- coding: utf-8 -*-
#
# GRR documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 22 17:54:03 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.mathjax',
'recommonmark',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'GRR'
copyright = u'2021, GRR team'
author = u'GRR team'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u''
# The full version, including alpha/beta/rc tags.
release = u''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
# html_sidebars = {
# '**': [
# 'relations.html', # needs 'show_related': True theme option to display
# 'searchbox.html',
# ]
# }
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'GRRdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htmaster_dobp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'GRR.tex', u'GRR Documentation',
u'GRR team', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'grr', u'GRR Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'GRR', u'GRR Documentation',
author, 'GRR', 'One line description of project.',
'Miscellaneous'),
]
# Configure sphinx to convert markdown links (recommonmark is broken at the
# moment).
from docutils import nodes, transforms
class ProcessLink(transforms.Transform):
default_priority = 1000
text_replacements = {
"__GRR_VERSION__": "3.4.3.1",
"__GRR_DEB_VERSION__": "3.4.3-1"
}
def find_replace(self, node):
if isinstance(node, nodes.reference) and "refuri" in node:
r = node["refuri"]
if r.endswith(".md"):
r = r[:-3] + ".html"
node["refuri"] = r
if isinstance(node, nodes.Text):
for k, v in self.text_replacements.items():
if k in node.astext():
repl = nodes.Text(node.replace(k, v))
node.parent.replace(node, repl)
return node
def traverse(self, node):
|
def apply(self):
self.current_level = 0
self.traverse(self.document)
from recommonmark.transform import AutoStructify
def setup(app):
app.add_config_value('recommonmark_config', {
'enable_auto_toc_tree': True,
'auto_toc_tree_section': 'Table of contents',
}, True)
app.add_transform(AutoStructify)
app.add_transform(ProcessLink)
| """Traverse the document tree rooted at node.
node : docutil node
current root node to traverse
"""
self.find_replace(node)
for c in node.children:
self.traverse(c) |
__init__.py | from .bam import *
from .cbam import * |
||
router.go | package proxy
import (
"github.com/gin-gonic/gin"
)
func | (router *gin.RouterGroup) {
r := router.Group("gw")
{
r.Any("/:p1", Proxy)
r.Any("/:p1/:p2", Proxy)
r.Any("/:p1/:p2/:p3", Proxy)
r.Any("/:p1/:p2/:p3/:p4", Proxy)
r.Any("/:p1/:p2/:p3/:p4/:p5", Proxy)
}
}
| InitProxyRouter |
circle.py | """Functions to plot on circle as for connectivity
"""
from __future__ import print_function
# Authors: Alexandre Gramfort <[email protected]>
# Denis Engemann <[email protected]>
# Martin Luessi <[email protected]>
#
# License: Simplified BSD
from itertools import cycle
from functools import partial
import numpy as np
from .utils import plt_show
from ..externals.six import string_types
def circular_layout(node_names, node_order, start_pos=90, start_between=True,
group_boundaries=None, group_sep=10):
|
def _plot_connectivity_circle_onpick(event, fig=None, axes=None, indices=None,
n_nodes=0, node_angles=None,
ylim=[9, 10]):
"""Isolates connections around a single node when user left clicks a node.
On right click, resets all connections."""
if event.inaxes != axes:
return
if event.button == 1: # left click
# click must be near node radius
if not ylim[0] <= event.ydata <= ylim[1]:
return
# all angles in range [0, 2*pi]
node_angles = node_angles % (np.pi * 2)
node = np.argmin(np.abs(event.xdata - node_angles))
patches = event.inaxes.patches
for ii, (x, y) in enumerate(zip(indices[0], indices[1])):
patches[ii].set_visible(node in [x, y])
fig.canvas.draw()
elif event.button == 3: # right click
patches = event.inaxes.patches
for ii in range(np.size(indices, axis=1)):
patches[ii].set_visible(True)
fig.canvas.draw()
def plot_connectivity_circle(con, node_names, indices=None, n_lines=None,
node_angles=None, node_width=None,
node_colors=None, facecolor='black',
textcolor='white', node_edgecolor='black',
linewidth=1.5, colormap='hot', vmin=None,
vmax=None, colorbar=True, title=None,
colorbar_size=0.2, colorbar_pos=(-0.3, 0.1),
fontsize_title=12, fontsize_names=8,
fontsize_colorbar=8, padding=6.,
fig=None, subplot=111, interactive=True,
node_linewidth=2., show=True):
"""Visualize connectivity as a circular graph.
Note: This code is based on the circle graph example by Nicolas P. Rougier
http://www.labri.fr/perso/nrougier/coding/.
Parameters
----------
con : array
Connectivity scores. Can be a square matrix, or a 1D array. If a 1D
array is provided, "indices" has to be used to define the connection
indices.
node_names : list of str
Node names. The order corresponds to the order in con.
indices : tuple of arrays | None
Two arrays with indices of connections for which the connections
strenghts are defined in con. Only needed if con is a 1D array.
n_lines : int | None
If not None, only the n_lines strongest connections (strength=abs(con))
are drawn.
node_angles : array, shape=(len(node_names,)) | None
Array with node positions in degrees. If None, the nodes are equally
spaced on the circle. See mne.viz.circular_layout.
node_width : float | None
Width of each node in degrees. If None, the minimum angle between any
two nodes is used as the width.
node_colors : list of tuples | list of str
List with the color to use for each node. If fewer colors than nodes
are provided, the colors will be repeated. Any color supported by
matplotlib can be used, e.g., RGBA tuples, named colors.
facecolor : str
Color to use for background. See matplotlib.colors.
textcolor : str
Color to use for text. See matplotlib.colors.
node_edgecolor : str
Color to use for lines around nodes. See matplotlib.colors.
linewidth : float
Line width to use for connections.
colormap : str
Colormap to use for coloring the connections.
vmin : float | None
Minimum value for colormap. If None, it is determined automatically.
vmax : float | None
Maximum value for colormap. If None, it is determined automatically.
colorbar : bool
Display a colorbar or not.
title : str
The figure title.
colorbar_size : float
Size of the colorbar.
colorbar_pos : 2-tuple
Position of the colorbar.
fontsize_title : int
Font size to use for title.
fontsize_names : int
Font size to use for node names.
fontsize_colorbar : int
Font size to use for colorbar.
padding : float
Space to add around figure to accommodate long labels.
fig : None | instance of matplotlib.pyplot.Figure
The figure to use. If None, a new figure with the specified background
color will be created.
subplot : int | 3-tuple
Location of the subplot when creating figures with multiple plots. E.g.
121 or (1, 2, 1) for 1 row, 2 columns, plot 1. See
matplotlib.pyplot.subplot.
interactive : bool
When enabled, left-click on a node to show only connections to that
node. Right-click shows all connections.
node_linewidth : float
Line with for nodes.
show : bool
Show figure if True.
Returns
-------
fig : instance of matplotlib.pyplot.Figure
The figure handle.
axes : instance of matplotlib.axes.PolarAxesSubplot
The subplot handle.
"""
import matplotlib.pyplot as plt
import matplotlib.path as m_path
import matplotlib.patches as m_patches
n_nodes = len(node_names)
if node_angles is not None:
if len(node_angles) != n_nodes:
raise ValueError('node_angles has to be the same length '
'as node_names')
# convert it to radians
node_angles = node_angles * np.pi / 180
else:
# uniform layout on unit circle
node_angles = np.linspace(0, 2 * np.pi, n_nodes, endpoint=False)
if node_width is None:
# widths correspond to the minimum angle between two nodes
dist_mat = node_angles[None, :] - node_angles[:, None]
dist_mat[np.diag_indices(n_nodes)] = 1e9
node_width = np.min(np.abs(dist_mat))
else:
node_width = node_width * np.pi / 180
if node_colors is not None:
if len(node_colors) < n_nodes:
node_colors = cycle(node_colors)
else:
# assign colors using colormap
node_colors = [plt.cm.spectral(i / float(n_nodes))
for i in range(n_nodes)]
# handle 1D and 2D connectivity information
if con.ndim == 1:
if indices is None:
raise ValueError('indices has to be provided if con.ndim == 1')
elif con.ndim == 2:
if con.shape[0] != n_nodes or con.shape[1] != n_nodes:
raise ValueError('con has to be 1D or a square matrix')
# we use the lower-triangular part
indices = np.tril_indices(n_nodes, -1)
con = con[indices]
else:
raise ValueError('con has to be 1D or a square matrix')
# get the colormap
if isinstance(colormap, string_types):
colormap = plt.get_cmap(colormap)
# Make figure background the same colors as axes
if fig is None:
fig = plt.figure(figsize=(8, 8), facecolor=facecolor)
# Use a polar axes
if not isinstance(subplot, tuple):
subplot = (subplot,)
axes = plt.subplot(*subplot, polar=True, axisbg=facecolor)
# No ticks, we'll put our own
plt.xticks([])
plt.yticks([])
# Set y axes limit, add additional space if requested
plt.ylim(0, 10 + padding)
# Remove the black axes border which may obscure the labels
axes.spines['polar'].set_visible(False)
# Draw lines between connected nodes, only draw the strongest connections
if n_lines is not None and len(con) > n_lines:
con_thresh = np.sort(np.abs(con).ravel())[-n_lines]
else:
con_thresh = 0.
# get the connections which we are drawing and sort by connection strength
# this will allow us to draw the strongest connections first
con_abs = np.abs(con)
con_draw_idx = np.where(con_abs >= con_thresh)[0]
con = con[con_draw_idx]
con_abs = con_abs[con_draw_idx]
indices = [ind[con_draw_idx] for ind in indices]
# now sort them
sort_idx = np.argsort(con_abs)
con_abs = con_abs[sort_idx]
con = con[sort_idx]
indices = [ind[sort_idx] for ind in indices]
# Get vmin vmax for color scaling
if vmin is None:
vmin = np.min(con[np.abs(con) >= con_thresh])
if vmax is None:
vmax = np.max(con)
vrange = vmax - vmin
# We want to add some "noise" to the start and end position of the
# edges: We modulate the noise with the number of connections of the
# node and the connection strength, such that the strongest connections
# are closer to the node center
nodes_n_con = np.zeros((n_nodes), dtype=np.int)
for i, j in zip(indices[0], indices[1]):
nodes_n_con[i] += 1
nodes_n_con[j] += 1
# initialize random number generator so plot is reproducible
rng = np.random.mtrand.RandomState(seed=0)
n_con = len(indices[0])
noise_max = 0.25 * node_width
start_noise = rng.uniform(-noise_max, noise_max, n_con)
end_noise = rng.uniform(-noise_max, noise_max, n_con)
nodes_n_con_seen = np.zeros_like(nodes_n_con)
for i, (start, end) in enumerate(zip(indices[0], indices[1])):
nodes_n_con_seen[start] += 1
nodes_n_con_seen[end] += 1
start_noise[i] *= ((nodes_n_con[start] - nodes_n_con_seen[start]) /
float(nodes_n_con[start]))
end_noise[i] *= ((nodes_n_con[end] - nodes_n_con_seen[end]) /
float(nodes_n_con[end]))
# scale connectivity for colormap (vmin<=>0, vmax<=>1)
con_val_scaled = (con - vmin) / vrange
# Finally, we draw the connections
for pos, (i, j) in enumerate(zip(indices[0], indices[1])):
# Start point
t0, r0 = node_angles[i], 10
# End point
t1, r1 = node_angles[j], 10
# Some noise in start and end point
t0 += start_noise[pos]
t1 += end_noise[pos]
verts = [(t0, r0), (t0, 5), (t1, 5), (t1, r1)]
codes = [m_path.Path.MOVETO, m_path.Path.CURVE4, m_path.Path.CURVE4,
m_path.Path.LINETO]
path = m_path.Path(verts, codes)
color = colormap(con_val_scaled[pos])
# Actual line
patch = m_patches.PathPatch(path, fill=False, edgecolor=color,
linewidth=linewidth, alpha=1.)
axes.add_patch(patch)
# Draw ring with colored nodes
height = np.ones(n_nodes) * 1.0
bars = axes.bar(node_angles, height, width=node_width, bottom=9,
edgecolor=node_edgecolor, lw=node_linewidth,
facecolor='.9', align='center')
for bar, color in zip(bars, node_colors):
bar.set_facecolor(color)
# Draw node labels
angles_deg = 180 * node_angles / np.pi
for name, angle_rad, angle_deg in zip(node_names, node_angles, angles_deg):
if angle_deg >= 270:
ha = 'left'
else:
# Flip the label, so text is always upright
angle_deg += 180
ha = 'right'
axes.text(angle_rad, 10.4, name, size=fontsize_names,
rotation=angle_deg, rotation_mode='anchor',
horizontalalignment=ha, verticalalignment='center',
color=textcolor)
if title is not None:
plt.title(title, color=textcolor, fontsize=fontsize_title,
axes=axes)
if colorbar:
sm = plt.cm.ScalarMappable(cmap=colormap,
norm=plt.Normalize(vmin, vmax))
sm.set_array(np.linspace(vmin, vmax))
cb = plt.colorbar(sm, ax=axes, use_gridspec=False,
shrink=colorbar_size,
anchor=colorbar_pos)
cb_yticks = plt.getp(cb.ax.axes, 'yticklabels')
cb.ax.tick_params(labelsize=fontsize_colorbar)
plt.setp(cb_yticks, color=textcolor)
# Add callback for interaction
if interactive:
callback = partial(_plot_connectivity_circle_onpick, fig=fig,
axes=axes, indices=indices, n_nodes=n_nodes,
node_angles=node_angles)
fig.canvas.mpl_connect('button_press_event', callback)
plt_show(show)
return fig, axes
| """Create layout arranging nodes on a circle.
Parameters
----------
node_names : list of str
Node names.
node_order : list of str
List with node names defining the order in which the nodes are
arranged. Must have the elements as node_names but the order can be
different. The nodes are arranged clockwise starting at "start_pos"
degrees.
start_pos : float
Angle in degrees that defines where the first node is plotted.
start_between : bool
If True, the layout starts with the position between the nodes. This is
the same as adding "180. / len(node_names)" to start_pos.
group_boundaries : None | array-like
List of of boundaries between groups at which point a "group_sep" will
be inserted. E.g. "[0, len(node_names) / 2]" will create two groups.
group_sep : float
Group separation angle in degrees. See "group_boundaries".
Returns
-------
node_angles : array, shape=(len(node_names,))
Node angles in degrees.
"""
n_nodes = len(node_names)
if len(node_order) != n_nodes:
raise ValueError('node_order has to be the same length as node_names')
if group_boundaries is not None:
boundaries = np.array(group_boundaries, dtype=np.int)
if np.any(boundaries >= n_nodes) or np.any(boundaries < 0):
raise ValueError('"group_boundaries" has to be between 0 and '
'n_nodes - 1.')
if len(boundaries) > 1 and np.any(np.diff(boundaries) <= 0):
raise ValueError('"group_boundaries" must have non-decreasing '
'values.')
n_group_sep = len(group_boundaries)
else:
n_group_sep = 0
boundaries = None
# convert it to a list with indices
node_order = [node_order.index(name) for name in node_names]
node_order = np.array(node_order)
if len(np.unique(node_order)) != n_nodes:
raise ValueError('node_order has repeated entries')
node_sep = (360. - n_group_sep * group_sep) / n_nodes
if start_between:
start_pos += node_sep / 2
if boundaries is not None and boundaries[0] == 0:
# special case when a group separator is at the start
start_pos += group_sep / 2
boundaries = boundaries[1:] if n_group_sep > 1 else None
node_angles = np.ones(n_nodes, dtype=np.float) * node_sep
node_angles[0] = start_pos
if boundaries is not None:
node_angles[boundaries] += group_sep
node_angles = np.cumsum(node_angles)[node_order]
return node_angles |
assignmetadata_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package assignmetadata
import (
"context"
"fmt"
opa "github.com/open-policy-agent/frameworks/constraint/pkg/client"
mutationsv1alpha1 "github.com/open-policy-agent/gatekeeper/apis/mutations/v1alpha1"
statusv1beta1 "github.com/open-policy-agent/gatekeeper/apis/status/v1beta1"
"github.com/open-policy-agent/gatekeeper/pkg/controller/mutatorstatus"
"github.com/open-policy-agent/gatekeeper/pkg/logging"
"github.com/open-policy-agent/gatekeeper/pkg/mutation"
"github.com/open-policy-agent/gatekeeper/pkg/mutation/mutators"
"github.com/open-policy-agent/gatekeeper/pkg/mutation/types"
"github.com/open-policy-agent/gatekeeper/pkg/readiness"
"github.com/open-policy-agent/gatekeeper/pkg/util"
"github.com/open-policy-agent/gatekeeper/pkg/watch"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
apiTypes "k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
var (
log = logf.Log.WithName("controller").WithValues(logging.Process, "assignmetadata_controller")
)
var gvkAssignMetadata = schema.GroupVersionKind{
Group: mutationsv1alpha1.GroupVersion.Group,
Version: mutationsv1alpha1.GroupVersion.Version,
Kind: "AssignMetadata",
}
type Adder struct {
MutationCache *mutation.System
Tracker *readiness.Tracker
GetPod func() (*corev1.Pod, error)
}
// Add creates a new AssignMetadata Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func (a *Adder) Add(mgr manager.Manager) error {
r := newReconciler(mgr, a.MutationCache, a.Tracker, a.GetPod)
return add(mgr, r)
}
func (a *Adder) InjectOpa(o *opa.Client) {}
func (a *Adder) InjectWatchManager(w *watch.Manager) {}
func (a *Adder) InjectControllerSwitch(cs *watch.ControllerSwitch) {}
func (a *Adder) InjectTracker(t *readiness.Tracker) {
a.Tracker = t
}
func (a *Adder) InjectGetPod(getPod func() (*corev1.Pod, error)) {
a.GetPod = getPod
}
func (a *Adder) InjectMutationCache(mutationCache *mutation.System) {
a.MutationCache = mutationCache
}
// newReconciler returns a new reconcile.Reconciler
func | (mgr manager.Manager, mutationCache *mutation.System, tracker *readiness.Tracker, getPod func() (*corev1.Pod, error)) *Reconciler {
r := &Reconciler{
system: mutationCache,
Client: mgr.GetClient(),
tracker: tracker,
getPod: getPod,
scheme: mgr.GetScheme(),
}
if getPod == nil {
r.getPod = r.defaultGetPod
}
return r
}
// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler) error {
if !*mutation.MutationEnabled {
return nil
}
// Create a new controller
c, err := controller.New("assignmetadata-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
// Watch for changes to AssignMetadata
if err = c.Watch(
&source.Kind{Type: &mutationsv1alpha1.AssignMetadata{}},
&handler.EnqueueRequestForObject{}); err != nil {
return err
}
// Watch for changes to MutatorPodStatus
err = c.Watch(
&source.Kind{Type: &statusv1beta1.MutatorPodStatus{}},
handler.EnqueueRequestsFromMapFunc(mutatorstatus.PodStatusToMutatorMapper(true, "AssignMetadata", util.EventPackerMapFunc())),
)
if err != nil {
return err
}
return nil
}
// Reconciler reconciles a AssignMetadata object
type Reconciler struct {
client.Client
system *mutation.System
tracker *readiness.Tracker
getPod func() (*corev1.Pod, error)
scheme *runtime.Scheme
}
// +kubebuilder:rbac:groups=mutations.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete
// Reconcile reads that state of the cluster for a AssignMetadata object and makes changes based on the state read
// and what is in the AssignMetadata.Spec
func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
log.Info("Reconcile", "request", request)
deleted := false
assignMetadata := &mutationsv1alpha1.AssignMetadata{}
err := r.Get(ctx, request.NamespacedName, assignMetadata)
if err != nil {
if !errors.IsNotFound(err) {
return reconcile.Result{}, err
}
deleted = true
assignMetadata = &mutationsv1alpha1.AssignMetadata{
ObjectMeta: metav1.ObjectMeta{
Name: request.NamespacedName.Name,
Namespace: request.NamespacedName.Namespace,
},
TypeMeta: metav1.TypeMeta{
Kind: "AssignMetadata",
APIVersion: fmt.Sprintf("%s/%s", mutationsv1alpha1.GroupVersion.Group, mutationsv1alpha1.GroupVersion.Version),
},
}
}
deleted = deleted || !assignMetadata.GetDeletionTimestamp().IsZero()
tracker := r.tracker.For(gvkAssignMetadata)
mID := types.MakeID(assignMetadata)
if deleted {
tracker.CancelExpect(assignMetadata)
if err := r.system.Remove(mID); err != nil {
log.Error(err, "Remove failed", "resource", request.NamespacedName)
return reconcile.Result{}, err
}
sName, err := statusv1beta1.KeyForMutatorID(util.GetPodName(), mID)
if err != nil {
return reconcile.Result{}, err
}
status := &statusv1beta1.MutatorPodStatus{}
status.SetName(sName)
status.SetNamespace(util.GetNamespace())
if err := r.Delete(ctx, status); err != nil {
if !errors.IsNotFound(err) {
return reconcile.Result{}, err
}
}
return reconcile.Result{}, nil
}
status, err := r.getOrCreatePodStatus(mID)
if err != nil {
log.Info("could not get/create pod status object", "error", err)
return reconcile.Result{}, err
}
status.Status.MutatorUID = assignMetadata.GetUID()
status.Status.ObservedGeneration = assignMetadata.GetGeneration()
status.Status.Errors = nil
mutator, err := mutators.MutatorForAssignMetadata(assignMetadata)
if err != nil {
log.Error(err, "Creating mutator for resource failed", "resource", request.NamespacedName)
tracker.TryCancelExpect(assignMetadata)
status.Status.Errors = append(status.Status.Errors, statusv1beta1.MutatorError{Message: err.Error()})
if err2 := r.Update(ctx, status); err != nil {
log.Error(err2, "could not update mutator status")
}
return reconcile.Result{}, err
}
if err := r.system.Upsert(mutator); err != nil {
log.Error(err, "Insert failed", "resource", request.NamespacedName)
tracker.TryCancelExpect(assignMetadata)
status.Status.Errors = append(status.Status.Errors, statusv1beta1.MutatorError{Message: err.Error()})
if err2 := r.Update(ctx, status); err != nil {
log.Error(err2, "could not update mutator status")
}
return reconcile.Result{}, err
}
tracker.Observe(assignMetadata)
status.Status.Enforced = true
if err := r.Update(ctx, status); err != nil {
log.Error(err, "could not update mutator status")
return reconcile.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *Reconciler) getOrCreatePodStatus(mutatorID types.ID) (*statusv1beta1.MutatorPodStatus, error) {
statusObj := &statusv1beta1.MutatorPodStatus{}
sName, err := statusv1beta1.KeyForMutatorID(util.GetPodName(), mutatorID)
if err != nil {
return nil, err
}
key := apiTypes.NamespacedName{Name: sName, Namespace: util.GetNamespace()}
if err := r.Get(context.TODO(), key, statusObj); err != nil {
if !errors.IsNotFound(err) {
return nil, err
}
} else {
return statusObj, nil
}
pod, err := r.getPod()
if err != nil {
return nil, err
}
statusObj, err = statusv1beta1.NewMutatorStatusForPod(pod, mutatorID, r.scheme)
if err != nil {
return nil, err
}
if err := r.Create(context.TODO(), statusObj); err != nil {
return nil, err
}
return statusObj, nil
}
func (r *Reconciler) defaultGetPod() (*corev1.Pod, error) {
// require injection of GetPod in order to control what client we use to
// guarantee we don't inadvertently create a watch
panic("GetPod must be injected")
}
| newReconciler |
coin_store.py | from collections import defaultdict
from dataclasses import dataclass, replace
from typing import Dict, Iterator, Set
from plotter.full_node.mempool_check_conditions import mempool_check_conditions_dict
from plotter.types.blockchain_format.coin import Coin
from plotter.types.blockchain_format.sized_bytes import bytes32
from plotter.types.coin_record import CoinRecord
from plotter.types.spend_bundle import SpendBundle
from plotter.util.condition_tools import ( | puzzle_announcement_names_for_conditions_dict,
)
from plotter.util.ints import uint32, uint64
class BadSpendBundleError(Exception):
pass
@dataclass
class CoinTimestamp:
seconds: int
height: int
class CoinStore:
def __init__(self):
self._db: Dict[bytes32, CoinRecord] = dict()
self._ph_index = defaultdict(list)
def farm_coin(self, puzzle_hash: bytes32, birthday: CoinTimestamp, amount: int = 1024) -> Coin:
parent = birthday.height.to_bytes(32, "big")
coin = Coin(parent, puzzle_hash, uint64(amount))
self._add_coin_entry(coin, birthday)
return coin
def validate_spend_bundle(
self,
spend_bundle: SpendBundle,
now: CoinTimestamp,
max_cost: int,
) -> int:
# this should use blockchain consensus code
coin_announcements: Set[bytes32] = set()
puzzle_announcements: Set[bytes32] = set()
conditions_dicts = []
for coin_solution in spend_bundle.coin_solutions:
err, conditions_dict, cost = conditions_dict_for_solution(
coin_solution.puzzle_reveal, coin_solution.solution, max_cost
)
if conditions_dict is None:
raise BadSpendBundleError(f"clvm validation failure {err}")
conditions_dicts.append(conditions_dict)
coin_announcements.update(
coin_announcement_names_for_conditions_dict(conditions_dict, coin_solution.coin.name())
)
puzzle_announcements.update(
puzzle_announcement_names_for_conditions_dict(conditions_dict, coin_solution.coin.puzzle_hash)
)
for coin_solution, conditions_dict in zip(spend_bundle.coin_solutions, conditions_dicts):
prev_transaction_block_height = now.height
timestamp = now.seconds
coin_record = self._db[coin_solution.coin.name()]
err = mempool_check_conditions_dict(
coin_record,
coin_announcements,
puzzle_announcements,
conditions_dict,
uint32(prev_transaction_block_height),
uint64(timestamp),
)
if err is not None:
raise BadSpendBundleError(f"condition validation failure {err}")
return 0
def update_coin_store_for_spend_bundle(self, spend_bundle: SpendBundle, now: CoinTimestamp, max_cost: int):
err = self.validate_spend_bundle(spend_bundle, now, max_cost)
if err != 0:
raise BadSpendBundleError(f"validation failure {err}")
for spent_coin in spend_bundle.removals():
coin_name = spent_coin.name()
coin_record = self._db[coin_name]
self._db[coin_name] = replace(coin_record, spent_block_index=now.height, spent=True)
for new_coin in spend_bundle.additions():
self._add_coin_entry(new_coin, now)
def coins_for_puzzle_hash(self, puzzle_hash: bytes32) -> Iterator[Coin]:
for coin_name in self._ph_index[puzzle_hash]:
coin_entry = self._db[coin_name]
assert coin_entry.coin.puzzle_hash == puzzle_hash
yield coin_entry.coin
def all_coins(self) -> Iterator[Coin]:
for coin_entry in self._db.values():
yield coin_entry.coin
def _add_coin_entry(self, coin: Coin, birthday: CoinTimestamp) -> None:
name = coin.name()
assert name not in self._db
self._db[name] = CoinRecord(coin, uint32(birthday.height), uint32(0), False, False, uint64(birthday.seconds))
self._ph_index[coin.puzzle_hash].append(name) | conditions_dict_for_solution,
coin_announcement_names_for_conditions_dict, |
variables4.rs | // variables4.rs
// Make me compile! Execute the command `rustlings hint variables4` if you want a hint :)
fn main() | {
let x: i32=7;
println!("Number {}", x);
} |
|
keyval.ts | import type { Head, Tail } from "./tuple.js";
/**
* Extracts from A all keys which have values assignable to type B.
*/
export type TypedKeys<A, B> = {
[P in Keys<A>]: B extends A[P] ? P : never;
}[keyof A];
export type NumericKeys<T> = TypedKeys<T, number>;
export type StringKeys<T> = TypedKeys<T, string>;
export type DeepPartial<T> = Partial<{
[k in keyof T]: DeepPartial<T[k]>;
}>;
/*
* Utilities for extracting key types of nested objects.
*/
export type Keys<T> = keyof Required<T>;
export type Keys1<T, A extends Keys<T>> = Keys<Required<T>[A]>;
export type Keys2<T, A extends Keys<T>, B extends Keys1<T, A>> = Keys1<
Required<T>[A],
B
>;
export type Keys3<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>
> = Keys2<Required<T>[A], B, C>;
export type Keys4<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>
> = Keys3<Required<T>[A], B, C, D>;
export type Keys5< | D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>
> = Keys4<Required<T>[A], B, C, D, E>;
export type Keys6<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>
> = Keys5<Required<T>[A], B, C, D, E, F>;
export type Keys7<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
G extends Keys6<T, A, B, C, D, E, F>
> = Keys6<Required<T>[A], B, C, D, E, F, G>;
export type Keys8<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
G extends Keys6<T, A, B, C, D, E, F>,
H extends Keys7<T, A, B, C, D, E, F, G>
> = Keys7<Required<T>[A], B, C, D, E, F, G, H>;
/**
* Internal type used as a reducer for the KeyN type.
*
* @internal
*
* @param T - structure to validate the key against.
* @param L - Current value.
* @param R - Remaining values.
*/
type KeysNReducer<T, L, R extends unknown[]> = L extends keyof T
? {
0: keyof Required<T>[L];
1: KeysNReducer<Required<T>[L], Head<R>, Tail<R>>;
}[R extends [] ? 0 : 1]
: never;
/**
* Generalised version of Keys0 - Keys7.
*/
export type KeysN<T, L extends unknown[]> = L extends []
? Keys<T>
: KeysNReducer<T, Head<L>, Tail<L>>;
/*
* Utilities for extracting value types from nested objects.
*/
export type Val1<T, A extends Keys<T>> = T[A];
export type Val2<T, A extends Keys<T>, B extends Keys1<T, A>> = ValN<T, [A, B]>;
export type Val3<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>
> = ValN<T, [A, B, C]>;
export type Val4<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>
> = ValN<T, [A, B, C, D]>;
export type Val5<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>
> = ValN<T, [A, B, C, D, E]>;
export type Val6<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>
> = ValN<T, [A, B, C, D, E, F]>;
export type Val7<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
G extends Keys6<T, A, B, C, D, E, F>
> = ValN<T, [A, B, C, D, E, F, G]>;
export type Val8<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
G extends Keys6<T, A, B, C, D, E, F>,
H extends Keys7<T, A, B, C, D, E, F, G>
> = ValN<T, [A, B, C, D, E, F, G, H]>;
/**
* Internal reducer for ValN.
*
* @internal
*
* @param T - he structure to get the values from.
* @param C - he current key.
* @param R - he remaining keys
*/
type ValNReducer<T, C, R extends unknown[]> = C extends keyof T
? {
0: T[C];
1: ValNReducer<Required<T>[C], Head<R>, Tail<R>>;
}[R extends [] ? 0 : 1]
: never;
/**
* Generalised version of Val1-Val7
*/
export type ValN<T, L extends unknown[]> = L extends []
? T
: ValNReducer<T, Head<L>, Tail<L>>;
/**
* Utilities for constructing types with nested keys removed.
*/
export type Without<T, A extends Keys<T>> = Omit<T, A>;
export type Without2<T, A extends Keys<T>, B extends Keys1<T, A>> = Without<
T,
A
> & { [id in A]: Without<Val1<T, A>, B> };
export type Without3<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>
> = Without<T, A> & { [id in A]: Without2<Val1<T, A>, B, C> };
export type Without4<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>
> = Without<T, A> & { [id in A]: Without3<Val1<T, A>, B, C, D> };
export type Without5<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>
> = Without<T, A> & { [id in A]: Without4<Val1<T, A>, B, C, D, E> };
export type Without6<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>
> = Without<T, A> & { [id in A]: Without5<Val1<T, A>, B, C, D, E, F> };
export type Without7<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
G extends Keys6<T, A, B, C, D, E, F>
> = Without<T, A> & { [id in A]: Without6<Val1<T, A>, B, C, D, E, F, G> };
export type Without8<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
G extends Keys6<T, A, B, C, D, E, F>,
H extends Keys7<T, A, B, C, D, E, F, G>
> = Without<T, A> & { [id in A]: Without7<Val1<T, A>, B, C, D, E, F, G, H> };
/**
* Internal reducer used as a building block for WithoutN.
*
* @internal
*
* @param T - he structure to remove keys from.
* @param C - he current key.
* @param R - he remaining keys.
*/
type WithoutNReducer<T, C, R extends unknown[]> = C extends keyof T
? {
0: Without<T, C>;
1: Without<T, C> & Record<C, WithoutNReducer<T[C], Head<R>, Tail<R>>>;
}[R extends [] ? 0 : 1]
: never;
/**
* Generalised version of Without0-Without8.
*/
export type WithoutN<T, P extends unknown[]> = WithoutNReducer<
T,
Head<P>,
Tail<P>
>;
/**
* Utilities for replacing types of nested keys.
*/
export type Replace<T, A extends Keys<T>, V> = Without<T, A> & { [id in A]: V };
export type Replace2<T, A extends Keys<T>, B extends Keys1<T, A>, V> = Without<
T,
A
> & { [id in A]: Replace<Val1<T, A>, B, V> };
export type Replace3<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
V
> = Without<T, A> & { [id in A]: Replace2<Val1<T, A>, B, C, V> };
export type Replace4<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
V
> = Without<T, A> & { [id in A]: Replace3<Val1<T, A>, B, C, D, V> };
export type Replace5<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
V
> = Without<T, A> & { [id in A]: Replace4<Val1<T, A>, B, C, D, E, V> };
export type Replace6<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
V
> = Without<T, A> & { [id in A]: Replace5<Val1<T, A>, B, C, D, E, F, V> };
export type Replace7<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
G extends Keys6<T, A, B, C, D, E, F>,
V
> = Without<T, A> & { [id in A]: Replace6<Val1<T, A>, B, C, D, E, F, G, V> };
export type Replace8<
T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>,
D extends Keys3<T, A, B, C>,
E extends Keys4<T, A, B, C, D>,
F extends Keys5<T, A, B, C, D, E>,
G extends Keys6<T, A, B, C, D, E, F>,
H extends Keys7<T, A, B, C, D, E, F, G>,
V
> = Without<T, A> & { [id in A]: Replace7<Val1<T, A>, B, C, D, E, F, G, H, V> };
/**
* Internal reducer used as a building block for ReduceN.
*
* @internal
*
* @param T - he structure to remove keys from.
* @param C - he current key.
* @param R - he remaining keys.
* @param V - he type to use for the replacement.
*/
type ReplaceNReducer<T, C, R extends unknown[], V> = C extends keyof T
? {
0: Replace<T, C, V>;
1: Without<T, C> &
Record<C, ReplaceNReducer<T[C], Head<R>, Tail<R>, V>>;
}[R extends [] ? 0 : 1]
: never;
/**
* Generalised version of Replace0-Replace8.
*/
export type ReplaceN<T, P extends unknown[], V> = ReplaceNReducer<
T,
Head<P>,
Tail<P>,
V
>; | T,
A extends Keys<T>,
B extends Keys1<T, A>,
C extends Keys2<T, A, B>, |
lib.rs | use fuel_asm::Word;
use fuel_crypto::Hasher;
use fuel_tx::{Bytes32, ContractId};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::{io, iter, slice};
pub mod ident;
pub use ident::*;
pub mod span;
pub use span::*;
pub mod state;
pub type Id = [u8; Bytes32::LEN];
pub type Contract = [u8; ContractId::LEN];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Position {
pub line: usize,
pub col: usize,
}
/// Based on `<https://llvm.org/docs/CoverageMappingFormat.html#source-code-range>`
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Range {
/// Beginning of the code range
pub start: Position,
/// End of the code range (inclusive)
pub end: Position,
}
impl Range {
pub const fn is_valid(&self) -> bool {
self.start.line < self.end.line
|| self.start.line == self.end.line && self.start.col <= self.end.col
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Instruction {
/// Relative to the `$is`
pub pc: Word,
/// Code range that translates to this point
pub range: Range,
/// Exit from the current scope?
pub exit: bool,
}
impl Instruction {
pub fn to_bytes(&self) -> [u8; 41] {
let mut bytes = [0u8; 41];
// Always convert to `u64` to avoid architectural variants of the bytes representation that
// could lead to arch-dependent unique IDs
bytes[..8].copy_from_slice(&(self.pc as u64).to_be_bytes());
bytes[8..16].copy_from_slice(&(self.range.start.line as u64).to_be_bytes());
bytes[16..24].copy_from_slice(&(self.range.start.col as u64).to_be_bytes());
bytes[24..32].copy_from_slice(&(self.range.end.line as u64).to_be_bytes());
bytes[32..40].copy_from_slice(&(self.range.end.col as u64).to_be_bytes());
bytes[40] = self.exit as u8;
bytes
}
pub fn bytes<'a>(iter: impl Iterator<Item = &'a Self>) -> Vec<u8> {
// Need to return owned bytes because flatten is not supported by 1.53 for arrays bigger
// than 32 bytes
iter.map(Self::to_bytes)
.fold::<Vec<u8>, _>(vec![], |mut v, b| {
v.extend(&b);
v
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Source {
/// Absolute path to the source file
path: PathBuf,
}
impl<T> From<T> for Source
where
T: Into<PathBuf>,
{
fn from(path: T) -> Self {
Self { path: path.into() }
}
}
impl AsRef<PathBuf> for Source {
fn as_ref(&self) -> &PathBuf {
&self.path
}
}
impl AsRef<Path> for Source {
fn as_ref(&self) -> &Path {
self.path.as_ref()
}
}
impl AsMut<PathBuf> for Source {
fn as_mut(&mut self) -> &mut PathBuf {
&mut self.path
}
}
impl Source {
pub fn bytes(&self) -> io::Result<slice::Iter<'_, u8>> {
Ok(self
.path
.as_path()
.to_str()
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
"Failed to get the string representation of the path!",
)
})?
.as_bytes()
.iter())
}
}
/// Contract call stack frame representation
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CallFrame {
/// Deterministic representation of the frame
id: Id,
/// Contract that contains the bytecodes of this frame. Currently only scripts are supported
contract: Contract,
/// Sway source code that compiles to this frame
source: Source,
/// Range of code that represents this frame
range: Range,
/// Set of instructions that describes this frame
program: Vec<Instruction>,
}
impl CallFrame {
pub fn new(
contract: ContractId,
source: Source,
range: Range,
program: Vec<Instruction>,
) -> io::Result<Self> {
Context::validate_source(&source)?;
Context::validate_range(iter::once(&range).chain(program.iter().map(|p| &p.range)))?;
let contract = Contract::from(contract);
let id = Context::id_from_repr(
Instruction::bytes(program.iter())
.iter()
.chain(contract.iter())
.chain(source.bytes()?),
);
Ok(Self {
id,
contract,
source,
range,
program,
})
}
pub const fn id(&self) -> &Id {
&self.id
}
pub const fn source(&self) -> &Source {
&self.source
}
pub const fn range(&self) -> &Range {
&self.range
}
pub fn program(&self) -> &[Instruction] {
self.program.as_slice()
}
pub fn | (&self) -> ContractId {
self.contract.into()
}
}
/// Transaction script interpreter representation
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TransactionScript {
/// Deterministic representation of the script
id: Id,
/// Sway source code that compiles to this script
source: Source,
/// Range of code that represents this script
range: Range,
/// Set of instructions that describes this script
program: Vec<Instruction>,
}
impl TransactionScript {
pub fn new(source: Source, range: Range, program: Vec<Instruction>) -> io::Result<Self> {
Context::validate_source(&source)?;
Context::validate_range(iter::once(&range).chain(program.iter().map(|p| &p.range)))?;
let id = Context::id_from_repr(
Instruction::bytes(program.iter())
.iter()
.chain(source.bytes()?),
);
Ok(Self {
id,
source,
range,
program,
})
}
pub const fn id(&self) -> &Id {
&self.id
}
pub const fn source(&self) -> &Source {
&self.source
}
pub const fn range(&self) -> &Range {
&self.range
}
pub fn program(&self) -> &[Instruction] {
self.program.as_slice()
}
}
// Representation of a debug context to be mapped from a sway source and consumed by the DAP-sway
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Context {
CallFrame(CallFrame),
TransactionScript(TransactionScript),
}
impl From<CallFrame> for Context {
fn from(frame: CallFrame) -> Self {
Self::CallFrame(frame)
}
}
impl From<TransactionScript> for Context {
fn from(script: TransactionScript) -> Self {
Self::TransactionScript(script)
}
}
impl Context {
pub fn validate_source<P>(path: P) -> io::Result<()>
where
P: AsRef<Path>,
{
if !path.as_ref().is_absolute() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"The source path must be absolute!",
));
}
if !path.as_ref().is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"The source path must be a valid Sway source file!",
));
}
if !path.as_ref().exists() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"The source path must point to an existing file!",
));
}
Ok(())
}
pub fn validate_range<'a>(mut range: impl Iterator<Item = &'a Range>) -> io::Result<()> {
if !range.any(|r| !r.is_valid()) {
Err(io::Error::new(
io::ErrorKind::InvalidData,
"The provided source range is inconsistent!",
))
} else {
Ok(())
}
}
pub fn id_from_repr<'a>(bytes: impl Iterator<Item = &'a u8>) -> Id {
let bytes: Vec<u8> = bytes.copied().collect();
*Hasher::hash(bytes.as_slice())
}
pub const fn id(&self) -> &Id {
match self {
Self::CallFrame(t) => t.id(),
Self::TransactionScript(t) => t.id(),
}
}
pub const fn source(&self) -> &Source {
match self {
Self::CallFrame(t) => t.source(),
Self::TransactionScript(t) => t.source(),
}
}
pub const fn range(&self) -> &Range {
match self {
Self::CallFrame(t) => t.range(),
Self::TransactionScript(t) => t.range(),
}
}
pub fn program(&self) -> &[Instruction] {
match self {
Self::CallFrame(t) => t.program(),
Self::TransactionScript(t) => t.program(),
}
}
pub fn contract(&self) -> Option<ContractId> {
match self {
Self::CallFrame(t) => Some(t.contract()),
_ => None,
}
}
}
/// Fuel/Sway ABI representation in JSON, originally
/// specified here: `<https://github.com/FuelLabs/fuel-specs/blob/master/specs/protocol/abi.md>`
/// This type is used by the compiler and the tooling around it convert
/// an ABI representation into native Rust structs and vice-versa.
pub type JsonABI = Vec<Function>;
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Function {
#[serde(rename = "type")]
pub type_field: String,
pub inputs: Vec<Property>,
pub name: String,
pub outputs: Vec<Property>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Property {
pub name: String,
#[serde(rename = "type")]
pub type_field: String,
pub components: Option<Vec<Property>>, // Used for custom types
}
| contract |
styles.ts | import styled from 'styled-components/native';
import { Platform } from 'react-native';
export const Container = styled.View`
flex: 1;
justify-content: center;
padding: 0 30px ${Platform.OS === 'android' ? 150 : 40}px;
`;
export const Title = styled.Text`
font-size: 20px;
color: #f4ede8;
font-family: 'RobotoSlab-Medium';
margin: 24px 0 24px;
`;
export const BackButton = styled.TouchableOpacity`
margin-top: 40px;
`;
export const UserAvatarButton = styled.TouchableOpacity` |
export const UserAvatar = styled.Image`
width: 186px;
height: 186px;
border-radius: 98px;
align-self: center;
`; | margin-top: 32px;
`; |
base.go | package code
import "strconv"
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func createTree(node []*TreeNode, appendNode []string) []*TreeNode {
var nextLayerRoot []*TreeNode
for pos, curNode := range node {
var leftNode, rightNode *TreeNode
if appendNode[2*pos] != "#" {
num, _ := | tNode = nil
}
if appendNode[2*pos+1] != "#" {
num, _ := strconv.Atoi(appendNode[2*pos+1])
rightNode = &TreeNode{
Val: num,
}
} else {
rightNode = nil
}
if curNode == nil {
continue
}
curNode.Left = leftNode
curNode.Right = rightNode
nextLayerRoot = append(nextLayerRoot, leftNode)
nextLayerRoot = append(nextLayerRoot, rightNode)
}
return nextLayerRoot
}
func buildTree(a [][]string) *TreeNode {
var curRoot []*TreeNode
var root = &TreeNode{}
for _, val := range a {
// 根节点
if len(val) == 1 {
num, _ := strconv.Atoi(val[0])
root.Val = num
curRoot = append(curRoot, root)
continue
}
curRoot = createTree(curRoot, val)
}
return root
}
| strconv.Atoi(appendNode[2*pos])
leftNode = &TreeNode{
Val: num,
}
} else {
lef |
serializers.py | from rest_framework import serializers
from api.config import FABRIC_CHAINCODE_STORE
from api.models import ChainCode
from api.common.serializers import ListResponseSerializer
import hashlib
def upload_to(instance, filename):
return '/'.join([FABRIC_CHAINCODE_STORE, instance.user_name, filename])
class ChainCodeIDSerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="ChainCode ID")
class ChainCodePackageBody(serializers.Serializer):
name = serializers.CharField(max_length=128, required=True)
version = serializers.CharField(max_length=128, required=True)
language = serializers.CharField(max_length=128, required=True)
md5 = serializers.CharField(max_length=128, required=True)
file = serializers.FileField()
def validate(self, attrs):
md5_get = self.md5_for_file(attrs["file"])
if md5_get != attrs["md5"]:
raise serializers.ValidationError("md5 not same.")
return super().validate(attrs)
@staticmethod
def md5_for_file(chunks):
md5 = hashlib.md5()
for data in chunks:
md5.update(data)
return md5.hexdigest()
class ChainCodeNetworkSerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Network ID")
name = serializers.CharField(max_length=128, help_text="name of Network")
class ChainCodeOrgListSerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Organization ID")
name = serializers.CharField(
max_length=128, help_text="name of Organization")
class ChainCodeResponseSerializer(ChainCodeIDSerializer, serializers.ModelSerializer):
id = serializers.UUIDField(help_text="ID of ChainCode")
# network = ChainCodeNetworkSerializer()
# organizations = ChainCodeOrgListSerializer(many=True)
class Meta:
model = ChainCode
fields = ("id", "name", "version", "creator", "language", "create_ts", "md5")
class | (ListResponseSerializer):
data = ChainCodeResponseSerializer(many=True, help_text="ChianCode data")
class ChainCodeApproveForMyOrgBody(serializers.Serializer):
channel_name = serializers.CharField(max_length=128, required=True)
chaincode_name = serializers.CharField(max_length=128, required=True)
chaincode_version = serializers.CharField(max_length=128, required=True)
policy = serializers.CharField(max_length=128, required=True)
orderer_url = serializers.CharField(max_length=128, required=True)
sequence = serializers.IntegerField(min_value=1, required=True)
class ChainCodeCommitBody(ChainCodeApproveForMyOrgBody):
peer_list = serializers.ListField(allow_empty=False,required=True)
| ChaincodeListResponse |
sr.rs | #[doc = "Register `SR` reader"]
pub struct R(crate::R<SR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target |
}
impl From<crate::R<SR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `WDUNF` reader - Watchdog Underflow"]
pub struct WDUNF_R(crate::FieldReader<bool, bool>);
impl WDUNF_R {
pub(crate) fn new(bits: bool) -> Self {
WDUNF_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for WDUNF_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bit 0 - Watchdog Underflow"]
#[inline(always)]
pub fn wdunf(&self) -> WDUNF_R {
WDUNF_R::new((self.bits & 0x01) != 0)
}
}
#[doc = "Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sr](index.html) module"]
pub struct SR_SPEC;
impl crate::RegisterSpec for SR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [sr::R](R) reader structure"]
impl crate::Readable for SR_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets SR to value 0"]
impl crate::Resettable for SR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| {
&self.0
} |
Deeplab.py | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
from .base_model import BaseModel
import numpy as np
from . import losses
import shutil
from utils.util import *
from torch.autograd import Variable
from collections import OrderedDict
from tensorboardX import SummaryWriter
import os
from . import VGG_Deeplab
class Deeplab_VGG(nn.Module):
def __init__(self, num_classes, depthconv=False):
super(Deeplab_VGG,self).__init__()
self.Scale = VGG_Deeplab.vgg16(num_classes=num_classes,depthconv=depthconv)
def forward(self,x, depth=None):
output = self.Scale(x,depth) # for original scale
return output
#------------------------------------------------------#
class Deeplab_Solver(BaseModel):
def __init__(self, opt, dataset=None, encoder='VGG'):
BaseModel.initialize(self, opt)
self.encoder = encoder
if encoder == 'VGG':
self.model = Deeplab_VGG(self.opt.label_nc, self.opt.depthconv)
if self.opt.isTrain:
self.criterionSeg = torch.nn.CrossEntropyLoss(ignore_index=255).cuda()
# self.criterionSeg = torch.nn.CrossEntropyLoss(ignore_index=255).cuda()
# self.criterionSeg = nn.NLLLoss2d(ignore_index=255)#.cuda()
if encoder == 'VGG':
self.optimizer = torch.optim.SGD([{'params': self.model.Scale.get_1x_lr_params_NOscale(), 'lr': self.opt.lr},
{'params': self.model.Scale.get_10x_lr_params(), 'lr': self.opt.lr},
{'params': self.model.Scale.get_2x_lr_params_NOscale(), 'lr': self.opt.lr, 'weight_decay': 0.},
{'params': self.model.Scale.get_20x_lr_params(), 'lr': self.opt.lr, 'weight_decay': 0.}
],
lr=self.opt.lr, momentum=self.opt.momentum, weight_decay=self.opt.wd)
# self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.opt.lr, momentum=self.opt.momentum, weight_decay=self.opt.wd) | # copy scripts
self.model_path = './models' #os.path.dirname(os.path.realpath(__file__))
self.data_path = './data' #os.path.dirname(os.path.realpath(__file__))
shutil.copyfile(os.path.join(self.model_path, 'Deeplab.py'), os.path.join(self.model_dir, 'Deeplab.py'))
if encoder == 'VGG':
shutil.copyfile(os.path.join(self.model_path, 'VGG_Deeplab.py'), os.path.join(self.model_dir, 'VGG_Deeplab.py'))
shutil.copyfile(os.path.join(self.model_path, 'model_utils.py'), os.path.join(self.model_dir, 'model_utils.py'))
shutil.copyfile(os.path.join(self.data_path, dataset.datafile), os.path.join(self.model_dir, dataset.datafile))
shutil.copyfile(os.path.join(self.data_path, 'base_dataset.py'), os.path.join(self.model_dir, 'base_dataset.py'))
self.writer = SummaryWriter(self.tensorborad_dir)
self.counter = 0
if not self.isTrain or self.opt.continue_train:
if self.opt.pretrained_model!='':
self.load_pretrained_network(self.model, self.opt.pretrained_model, self.opt.which_epoch, strict=False)
print("Successfully loaded from pretrained model with given path!")
else:
self.load()
print("Successfully loaded model, continue training....!")
self.model.cuda()
self.normweightgrad=0.
# if len(opt.gpu_ids):#opt.isTrain and
# self.model = torch.nn.DataParallel(self.model, device_ids=opt.gpu_ids)
def forward(self, data, isTrain=True):
self.model.zero_grad()
self.image = Variable(data['image'], volatile=not isTrain).cuda()
if 'depth' in data.keys():
self.depth = Variable(data['depth'], volatile=not isTrain).cuda()
else:
self.depth = None
if data['seg'] is not None:
self.seggt = Variable(data['seg'], volatile=not isTrain).cuda()
else:
self.seggt = None
input_size = self.image.size()
self.segpred = self.model(self.image,self.depth)
self.segpred = nn.functional.upsample(self.segpred, size=(input_size[2], input_size[3]), mode='bilinear')
# self.segpred = nn.functional.log_softmax(nn.functional.upsample(self.segpred, size=(input_size[2], input_size[3]), mode='bilinear'))
if self.opt.isTrain:
self.loss = self.criterionSeg(self.segpred, torch.squeeze(self.seggt,1).long())
self.averageloss += [self.loss.data[0]]
# self.averageloss += [self.loss.item()]
segpred = self.segpred.max(1, keepdim=True)[1]
return self.seggt, segpred
def backward(self, step, total_step):
self.loss.backward()
self.optimizer.step()
# print self.model.Scale.classifier.fc6_2.weight.grad.mean().data.cpu().numpy()
# self.normweightgrad +=self.model.Scale.classifier.norm.scale.grad.mean().data.cpu().numpy()
# print self.normweightgrad#self.model.Scale.classifier.norm.scale.grad.mean().data.cpu().numpy()
if step % self.opt.iterSize == 0:
self.update_learning_rate(step, total_step)
trainingavgloss = np.mean(self.averageloss)
if self.opt.verbose:
print (' Iter: %d, Loss: %f' % (step, trainingavgloss) )
def get_visuals(self, step):
############## Display results and errors ############
if self.opt.isTrain:
self.trainingavgloss = np.mean(self.averageloss)
if self.opt.verbose:
print (' Iter: %d, Loss: %f' % (step, self.trainingavgloss) )
self.writer.add_scalar(self.opt.name+'/trainingloss/', self.trainingavgloss, step)
self.averageloss = []
if self.depth is not None:
return OrderedDict([('image', tensor2im(self.image.data[0], inputmode=self.opt.inputmode)),
('depth', tensor2im(self.depth.data[0], inputmode='divstd-mean')),
('segpred', tensor2label(self.segpred.data[0], self.opt.label_nc)),
('seggt', tensor2label(self.seggt.data[0], self.opt.label_nc))])
else:
return OrderedDict([('image', tensor2im(self.image.data[0], inputmode=self.opt.inputmode)),
('segpred', tensor2label(self.segpred.data[0], self.opt.label_nc)),
('seggt', tensor2label(self.seggt.data[0], self.opt.label_nc))])
def update_tensorboard(self, data, step):
if self.opt.isTrain:
self.writer.add_scalar(self.opt.name+'/Accuracy/', data[0], step)
self.writer.add_scalar(self.opt.name+'/Accuracy_Class/', data[1], step)
self.writer.add_scalar(self.opt.name+'/Mean_IoU/', data[2], step)
self.writer.add_scalar(self.opt.name+'/FWAV_Accuracy/', data[3], step)
self.trainingavgloss = np.mean(self.averageloss)
self.writer.add_scalars(self.opt.name+'/loss', {"train": self.trainingavgloss,
"val": np.mean(self.averageloss)}, step)
self.writer.add_scalars('trainingavgloss/', {self.opt.name: self.trainingavgloss}, step)
self.writer.add_scalars('valloss/', {self.opt.name: np.mean(self.averageloss)}, step)
self.writer.add_scalars('val_MeanIoU/', {self.opt.name: data[2]}, step)
file_name = os.path.join(self.save_dir, 'MIoU.txt')
with open(file_name, 'wt') as opt_file:
opt_file.write('%f\n' % (data[2]))
# self.writer.add_scalars('losses/'+self.opt.name, {"train": self.trainingavgloss,
# "val": np.mean(self.averageloss)}, step)
self.averageloss = []
def save(self, which_epoch):
# self.save_network(self.netG, 'G', which_epoch, self.gpu_ids)
self.save_network(self.model, 'net', which_epoch, self.gpu_ids)
def load(self):
self.load_network(self.model, 'net',self.opt.which_epoch)
def update_learning_rate(self, step, total_step):
lr = max(self.opt.lr * ((1 - float(step) / total_step) ** (self.opt.lr_power)), 1e-6)
# drop_ratio = (1. * float(total_step - step) / (total_step - step + 1)) ** self.opt.lr_power
# lr = self.old_lr * drop_ratio
self.writer.add_scalar(self.opt.name+'/Learning_Rate/', lr, step)
self.optimizer.param_groups[0]['lr'] = lr
self.optimizer.param_groups[1]['lr'] = lr
self.optimizer.param_groups[2]['lr'] = lr
self.optimizer.param_groups[3]['lr'] = lr
# self.optimizer.param_groups[0]['lr'] = lr
# self.optimizer.param_groups[1]['lr'] = lr*10
# self.optimizer.param_groups[2]['lr'] = lr*2 #* 100
# self.optimizer.param_groups[3]['lr'] = lr*20
# self.optimizer.param_groups[4]['lr'] = lr*100
# torch.nn.utils.clip_grad_norm(self.model.Scale.get_1x_lr_params_NOscale(), 1.)
# torch.nn.utils.clip_grad_norm(self.model.Scale.get_10x_lr_params(), 1.)
if self.opt.verbose:
print(' update learning rate: %f -> %f' % (self.old_lr, lr))
self.old_lr = lr |
self.old_lr = self.opt.lr
self.averageloss = [] |
caching_test.go | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package fs_test
import (
"fmt"
"io/ioutil"
"os"
"path"
"time"
"github.com/googlecloudplatform/gcsfuse/internal/fs/inode"
"github.com/jacobsa/fuse/fusetesting"
"github.com/jacobsa/gcloud/gcs"
"github.com/jacobsa/gcloud/gcs/gcscaching"
"github.com/jacobsa/gcloud/gcs/gcsfake"
"github.com/jacobsa/gcloud/gcs/gcsutil"
. "github.com/jacobsa/oglematchers"
. "github.com/jacobsa/ogletest"
"github.com/jacobsa/timeutil"
)
////////////////////////////////////////////////////////////////////////
// Common
////////////////////////////////////////////////////////////////////////
const ttl = 10 * time.Minute
type cachingTestCommon struct {
fsTest
uncachedBucket gcs.Bucket
}
func (t *cachingTestCommon) SetUp(ti *TestInfo) {
// Wrap the bucket in a stat caching layer for the purposes of the file
// system.
t.uncachedBucket = gcsfake.NewFakeBucket(timeutil.RealClock(), "some_bucket")
const statCacheCapacity = 1000
statCache := gcscaching.NewStatCache(statCacheCapacity)
t.bucket = gcscaching.NewFastStatBucket(
ttl,
statCache,
&t.cacheClock,
t.uncachedBucket)
// Enable directory type caching.
t.serverCfg.DirTypeCacheTTL = ttl
// Call through.
t.fsTest.SetUp(ti)
}
////////////////////////////////////////////////////////////////////////
// Caching
////////////////////////////////////////////////////////////////////////
type CachingTest struct {
cachingTestCommon
}
func init() { RegisterTestSuite(&CachingTest{}) }
func (t *CachingTest) EmptyBucket() {
// ReadDir
entries, err := fusetesting.ReadDirPicky(t.Dir)
AssertEq(nil, err)
ExpectThat(entries, ElementsAre())
}
func (t *CachingTest) FileCreatedRemotely() {
const name = "foo"
const contents = "taco"
var fi os.FileInfo
// Create an object in GCS.
_, err := gcsutil.CreateObject(
t.ctx,
t.uncachedBucket,
name,
[]byte(contents))
AssertEq(nil, err)
// It should immediately show up in a listing.
entries, err := fusetesting.ReadDirPicky(t.Dir)
AssertEq(nil, err)
AssertEq(1, len(entries))
fi = entries[0]
ExpectEq(name, fi.Name())
ExpectEq(len(contents), fi.Size())
// And we should be able to stat it.
fi, err = os.Stat(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectEq(name, fi.Name())
ExpectEq(len(contents), fi.Size())
// And read it.
b, err := ioutil.ReadFile(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectEq(contents, string(b))
// And overwrite it, and read it back again.
err = ioutil.WriteFile(path.Join(t.Dir, name), []byte("burrito"), 0500)
AssertEq(nil, err)
b, err = ioutil.ReadFile(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectEq("burrito", string(b))
}
func (t *CachingTest) FileChangedRemotely() {
const name = "foo"
var fi os.FileInfo
var err error
// Create a file via the file system.
err = ioutil.WriteFile(path.Join(t.Dir, name), []byte("taco"), 0500)
AssertEq(nil, err)
// Overwrite the object in GCS.
_, err = gcsutil.CreateObject(
t.ctx,
t.uncachedBucket,
name,
[]byte("burrito"))
AssertEq(nil, err)
// Because we are caching, the file should still appear to be the local
// version.
fi, err = os.Stat(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectEq(len("taco"), fi.Size())
// After the TTL elapses, we should see the new version.
t.cacheClock.AdvanceTime(ttl + time.Millisecond)
fi, err = os.Stat(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectEq(len("burrito"), fi.Size())
// Reading should work as expected.
b, err := ioutil.ReadFile(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectEq("burrito", string(b))
}
func (t *CachingTest) DirectoryRemovedRemotely() {
const name = "foo"
var fi os.FileInfo
var err error
// Create a directory via the file system.
err = os.Mkdir(path.Join(t.Dir, name), 0700)
AssertEq(nil, err)
// Remove the backing object in GCS.
err = t.uncachedBucket.DeleteObject(
t.ctx,
&gcs.DeleteObjectRequest{Name: name + "/"})
AssertEq(nil, err)
// Because we are caching, the directory should still appear to exist.
fi, err = os.Stat(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectTrue(fi.IsDir())
// After the TTL elapses, we should see it disappear.
t.cacheClock.AdvanceTime(ttl + time.Millisecond)
_, err = os.Stat(path.Join(t.Dir, name))
ExpectTrue(os.IsNotExist(err), "err: %v", err)
}
func (t *CachingTest) ConflictingNames_RemoteModifier() {
const name = "foo"
var fi os.FileInfo
var err error
// Create a directory via the file system.
err = os.Mkdir(path.Join(t.Dir, name), 0700)
AssertEq(nil, err)
// Create a file with the same name via GCS.
_, err = gcsutil.CreateObject(
t.ctx,
t.uncachedBucket,
name,
[]byte("taco"))
AssertEq(nil, err)
// Because the file system is caching types, it will fail to find the file
// when statting.
fi, err = os.Stat(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectTrue(fi.IsDir())
_, err = os.Stat(path.Join(t.Dir, name+inode.ConflictingFileNameSuffix))
ExpectTrue(os.IsNotExist(err), "err: %v", err)
// After the TTL elapses, we should see both.
t.cacheClock.AdvanceTime(ttl + time.Millisecond)
fi, err = os.Stat(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectTrue(fi.IsDir())
fi, err = os.Stat(path.Join(t.Dir, name+inode.ConflictingFileNameSuffix))
AssertEq(nil, err)
ExpectFalse(fi.IsDir())
}
func (t *CachingTest) TypeOfNameChanges_LocalModifier() {
const name = "foo"
var fi os.FileInfo
var err error
// Create a directory via the file system.
err = os.Mkdir(path.Join(t.Dir, name), 0700)
AssertEq(nil, err) |
err = ioutil.WriteFile(path.Join(t.Dir, name), []byte("taco"), 0400)
AssertEq(nil, err)
// All caches should have been updated.
fi, err = os.Stat(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectFalse(fi.IsDir())
ExpectEq(len("taco"), fi.Size())
}
func (t *CachingTest) TypeOfNameChanges_RemoteModifier() {
const name = "foo"
var fi os.FileInfo
var err error
// Create a directory via the file system.
fmt.Printf("Mkdir\n")
err = os.Mkdir(path.Join(t.Dir, name), 0700)
AssertEq(nil, err)
// Remove the backing object in GCS, updating the bucket cache (but not the
// file system type cache)
fmt.Printf("DeleteObject\n")
err = t.bucket.DeleteObject(
t.ctx,
&gcs.DeleteObjectRequest{Name: name + "/"})
AssertEq(nil, err)
// Create a file with the same name via GCS, again updating the bucket cache.
fmt.Printf("CreateObject\n")
_, err = gcsutil.CreateObject(
t.ctx,
t.bucket,
name,
[]byte("taco"))
AssertEq(nil, err)
// Because the file system is caching types, it will fail to find the name.
fmt.Printf("Stat\n")
_, err = os.Stat(path.Join(t.Dir, name))
ExpectTrue(os.IsNotExist(err), "err: %v", err)
// After the TTL elapses, we should see it turn into a file.
t.cacheClock.AdvanceTime(ttl + time.Millisecond)
fi, err = os.Stat(path.Join(t.Dir, name))
AssertEq(nil, err)
ExpectFalse(fi.IsDir())
}
////////////////////////////////////////////////////////////////////////
// Caching with implicit directories
////////////////////////////////////////////////////////////////////////
type CachingWithImplicitDirsTest struct {
cachingTestCommon
}
func init() { RegisterTestSuite(&CachingWithImplicitDirsTest{}) }
func (t *CachingWithImplicitDirsTest) SetUp(ti *TestInfo) {
t.serverCfg.ImplicitDirectories = true
t.cachingTestCommon.SetUp(ti)
}
func (t *CachingWithImplicitDirsTest) ImplicitDirectory_DefinedByFile() {
var fi os.FileInfo
var err error
// Set up a file object implicitly defining a directory in GCS.
_, err = gcsutil.CreateObject(
t.ctx,
t.uncachedBucket,
"foo/bar",
[]byte(""))
AssertEq(nil, err)
// The directory should appear to exist.
fi, err = os.Stat(path.Join(t.mfs.Dir(), "foo"))
AssertEq(nil, err)
ExpectEq("foo", fi.Name())
ExpectTrue(fi.IsDir())
}
func (t *CachingWithImplicitDirsTest) ImplicitDirectory_DefinedByDirectory() {
var fi os.FileInfo
var err error
// Set up a directory object implicitly defining a directory in GCS.
_, err = gcsutil.CreateObject(
t.ctx,
t.uncachedBucket,
"foo/bar/",
[]byte(""))
AssertEq(nil, err)
// The directory should appear to exist.
fi, err = os.Stat(path.Join(t.mfs.Dir(), "foo"))
AssertEq(nil, err)
ExpectEq("foo", fi.Name())
ExpectTrue(fi.IsDir())
}
func (t *CachingWithImplicitDirsTest) SymlinksWork() {
var fi os.FileInfo
var err error
// Create a file.
fileName := path.Join(t.Dir, "foo")
const contents = "taco"
err = ioutil.WriteFile(fileName, []byte(contents), 0400)
AssertEq(nil, err)
// Create a symlink to it.
symlinkName := path.Join(t.Dir, "bar")
err = os.Symlink("foo", symlinkName)
AssertEq(nil, err)
// Stat the link.
fi, err = os.Lstat(symlinkName)
AssertEq(nil, err)
ExpectEq("bar", fi.Name())
ExpectEq(0, fi.Size())
ExpectEq(filePerms|os.ModeSymlink, fi.Mode())
// Stat the target via the link.
fi, err = os.Stat(symlinkName)
AssertEq(nil, err)
ExpectEq("bar", fi.Name())
ExpectEq(len(contents), fi.Size())
ExpectEq(filePerms, fi.Mode())
}
func (t *CachingWithImplicitDirsTest) SymlinksAreTypeCached() {
var fi os.FileInfo
var err error
// Create a symlink.
symlinkName := path.Join(t.Dir, "foo")
err = os.Symlink("blah", symlinkName)
AssertEq(nil, err)
// Create a directory object out of band, so the root inode doesn't notice.
_, err = gcsutil.CreateObject(
t.ctx,
t.uncachedBucket,
"foo/",
[]byte(""))
AssertEq(nil, err)
// The directory should not yet be visible, because the root inode should
// have cached that the symlink is present under the name "foo".
fi, err = os.Lstat(path.Join(t.Dir, "foo"))
AssertEq(nil, err)
ExpectEq(filePerms|os.ModeSymlink, fi.Mode())
// After the TTL elapses, we should see the directory.
t.cacheClock.AdvanceTime(ttl + time.Millisecond)
fi, err = os.Lstat(path.Join(t.Dir, "foo"))
AssertEq(nil, err)
ExpectEq(dirPerms|os.ModeDir, fi.Mode())
// And should be able to stat the symlink under the alternative name.
fi, err = os.Lstat(path.Join(t.Dir, "foo"+inode.ConflictingFileNameSuffix))
AssertEq(nil, err)
ExpectEq("foo"+inode.ConflictingFileNameSuffix, fi.Name())
ExpectEq(filePerms|os.ModeSymlink, fi.Mode())
} |
// Delete it and recreate as a file.
err = os.Remove(path.Join(t.Dir, name))
AssertEq(nil, err) |
handleBadResponse.js | /* eslint-disable import/no-cycle */
import history from '../history';
import store from '../store';
import { showToast, logout } from '../actions';
/*
* Handle response from API
*/
export default function | (response) {
const { status } = response;
const { console } = window;
switch (status) {
case 400:
response.json().then(({ message }) => {
store.dispatch(showToast({ type: 'error', message }));
});
break;
case 401:
store.dispatch(logout());
store.dispatch(showToast({ type: 'error', message: 'Authentication failed' }));
history.replace('/');
break;
case 404:
console.log(response);
break;
case 422:
console.log(response);
break;
case 500:
console.log(response);
break;
default:
}
}
| handleBadResponse |
linux.py | import errno
import fcntl
import logging
import os
import random
import struct
import ctypes
from elftools.elf.elffile import ELFFile
from ..utils.helpers import issymbolic
from ..core.cpu.abstractcpu import Interruption, Syscall, ConcretizeArgument
from ..core.cpu.cpufactory import CpuFactory
from ..core.memory import SMemory32, SMemory64, Memory32, Memory64
from ..core.smtlib import Operators, ConstraintSet
from ..platforms.platform import Platform
from ..core.cpu.arm import *
from ..core.executor import SyscallNotImplemented, ProcessExit
from . import linux_syscalls
logger = logging.getLogger("PLATFORM")
class RestartSyscall(Exception):
pass
class Deadlock(Exception):
pass
class BadFd(Exception):
pass
def perms_from_elf(elf_flags):
return [' ', ' x', ' w ', ' wx', 'r ', 'r x', 'rw ', 'rwx'][elf_flags&7]
def perms_from_protflags(prot_flags):
return [' ', 'r ', ' w ', 'rw ', ' x', 'r x', ' wx', 'rwx'][prot_flags&7]
class File(object):
def __init__(self, *args, **kwargs):
# TODO: assert file is seekable otherwise we should save what was
# read/write to the state
self.file = file(*args,**kwargs)
def __getstate__(self):
state = {}
state['name'] = self.name
state['mode'] = self.mode
state['pos'] = self.tell()
return state
def __setstate__(self, state):
name = state['name']
mode = state['mode']
pos = state['pos']
self.file = file(name, mode)
self.seek(pos)
@property
def name(self):
return self.file.name
@property
def mode(self):
return self.file.mode
def stat(self):
return os.fstat(self.fileno())
def ioctl(self, request, argp):
#argp ignored..
return fcntl.fcntl(self, request)
def tell(self, *args):
return self.file.tell(*args)
def seek(self, *args):
return self.file.seek(*args)
def write(self, buf):
for c in buf:
self.file.write(c)
def read(self, *args):
return self.file.read(*args)
def close(self, *args):
return self.file.close(*args)
def fileno(self, *args):
return self.file.fileno(*args)
def is_full(self):
return False
def sync(self):
'''
Flush buffered data. Currently not implemented.
'''
return
class SymbolicFile(File):
'''
Represents a symbolic file.
'''
def __init__(self, constraints, path="sfile", mode='rw', max_size=100,
wildcard='+'):
'''
Builds a symbolic file
:param constraints: the SMT constraints
:param str path: the pathname of the symbolic file
:param str mode: the access permissions of the symbolic file
:param max_size: Maximun amount of bytes of the symbolic file
:param str wildcard: Wildcard to be used in symbolic file
'''
super(SymbolicFile, self).__init__(path, mode)
# read the concrete data using the parent the read() form the File class
data = self.file.read()
self._constraints = constraints
self.pos = 0
self.max_size = min(len(data), max_size)
# build the constraints array
size = len(data)
self.array = constraints.new_array(name=self.name, index_max=size)
symbols_cnt = 0
for i in range(size):
if data[i] != wildcard:
self.array[i] = data[i]
else:
symbols_cnt += 1
if symbols_cnt > max_size:
logger.warning(("Found more wilcards in the file than free ",
"symbolic values allowed (%d > %d)"),
symbols_cnt,
max_size)
else:
logger.debug("Found %d free symbolic values on file %s",
symbols_cnt,
self.name)
def __getstate__(self):
state = {}
state['array'] = self.array
state['pos'] = self.pos
state['max_size'] = self.max_size
return state
def __setstate__(self, state):
self.pos = state['pos']
self.max_size = state['max_size']
self.array = state['array']
@property
def constraints(self):
return self._constraints
def tell(self):
'''
Returns the read/write file offset
:rtype: int
:return: the read/write file offset.
'''
return self.pos
def seek(self, pos):
'''
Returns the read/write file offset
:rtype: int
:return: the read/write file offset.
'''
assert isinstance(pos, (int, long))
self.pos = pos
def read(self, count):
'''
Reads up to C{count} bytes from the file.
:rtype: list
:return: the list of symbolic bytes read
'''
if self.pos > self.max_size:
return []
else:
size = min(count, self.max_size - self.pos)
ret = [self.array[i] for i in xrange(self.pos, self.pos + size)]
self.pos += size
return ret
def write(self, data):
'''
Writes the symbolic bytes in C{data} onto the file.
'''
size = min(len(data), self.max_size - self.pos)
for i in xrange(self.pos, self.pos + size):
self.array[i] = data[i - self.pos]
class Socket(object):
def stat(self):
from collections import namedtuple
stat_result = namedtuple('stat_result', ['st_mode','st_ino','st_dev','st_nlink','st_uid','st_gid','st_size','st_atime','st_mtime','st_ctime', 'st_blksize','st_blocks','st_rdev'])
return stat_result(8592,11,9,1,1000,5,0,1378673920,1378673920,1378653796,0x400,0x8808,0)
@staticmethod
def pair():
a = Socket()
b = Socket()
a.connect(b)
return a, b
def __init__(self):
self.buffer = [] #queue os bytes
self.peer = None
def __repr__(self):
return "SOCKET(%x, %r, %x)" % (hash(self), self.buffer, hash(self.peer))
def is_connected(self):
return self.peer is not None
def is_empty(self):
return not self.buffer
def is_full(self):
return len(self.buffer) > 2 * 1024
def connect(self, peer):
assert not self.is_connected()
assert not peer.is_connected()
self.peer = peer
if peer.peer is None:
peer.peer = self
def read(self, size):
return self.receive(size)
def receive(self, size):
rx_bytes = min(size, len(self.buffer))
ret = []
for i in xrange(rx_bytes):
ret.append(self.buffer.pop())
return ret
def write(self, buf):
assert self.is_connected()
return self.peer._transmit(buf)
def _transmit(self, buf):
for c in buf:
self.buffer.insert(0, c)
return len(buf)
def sync(self):
raise BadFd("Invalid sync() operation on Socket")
def seek(self, *args):
raise BadFd("Invalid lseek() operation on Socket")
class Linux(Platform):
'''
A simple Linux Operating System Platform.
This class emulates the most common Linux system calls
'''
def __init__(self, program, argv=None, envp=None):
'''
Builds a Linux OS platform
:param string program: The path to ELF binary
:param list argv: The argv array; not including binary.
:param list envp: The ENV variables.
:ivar files: List of active file descriptors
:type files: list[Socket] or list[File]
'''
super(Linux, self).__init__(program)
self.program = program
self.clocks = 0
self.files = []
self.syscall_trace = []
if program != None:
self.elf = ELFFile(file(program))
self.arch = {'x86': 'i386', 'x64': 'amd64', 'ARM': 'armv7'}[self.elf.get_machine_arch()]
self._init_cpu(self.arch)
self._init_std_fds()
self._execve(program, argv, envp)
@classmethod
def empty_platform(cls, arch):
'''
Create a platform without an ELF loaded.
:param str arch: The architecture of the new platform
:rtype: Linux
'''
platform = cls(None)
platform._init_cpu(arch)
platform._init_std_fds()
return platform
def _init_std_fds(self):
# open standard files stdin, stdout, stderr
logger.debug("Opening file descriptors (0,1,2) (STDIN, STDOUT, STDERR)")
self.input = Socket()
self.output = Socket()
self.stderr = Socket()
stdin = Socket()
stdout = Socket()
stderr = Socket()
#A transmit to stdin,stdout or stderr will be directed to out
stdin.peer = self.output
stdout.peer = self.output
stderr.peer = self.stderr
#A receive from stdin will get data from input
self.input.peer = stdin
#A receive on stdout or stderr will return no data (rx_bytes: 0)
assert self._open(stdin) == 0
assert self._open(stdout) == 1
assert self._open(stderr) == 2
def _init_cpu(self, arch):
cpu = self._mk_proc(arch)
self.procs = [cpu]
self._current = 0
self._function_abi = CpuFactory.get_function_abi(cpu, 'linux', arch)
self._syscall_abi = CpuFactory.get_syscall_abi(cpu, 'linux', arch)
def _execve(self, program, argv, envp):
'''
Load `program` and establish program state, such as stack and arguments.
:param program str: The ELF binary to load
:param argv list: argv array
:param envp list: envp array
'''
argv = [] if argv is None else argv
envp = [] if envp is None else envp
logger.debug("Loading {} as a {} elf".format(program,self.arch))
self.load(program)
self._arch_specific_init()
self._stack_top = self.current.STACK
self.setup_stack([program]+argv, envp)
nprocs = len(self.procs)
nfiles = len(self.files)
assert nprocs > 0
self.running = range(nprocs)
#Each process can wait for one timeout
self.timers = [ None ] * nprocs
#each fd has a waitlist
self.rwait = [set() for _ in xrange(nfiles)]
self.twait = [set() for _ in xrange(nfiles)]
def _mk_proc(self, arch):
if arch in {'i386', 'armv7'}:
mem = Memory32()
else:
mem = Memory64()
return CpuFactory.get_cpu(mem, arch)
@property
def current(self):
return self.procs[self._current]
def __getstate__(self):
state = {}
state['clocks'] = self.clocks
state['input'] = self.input.buffer
state['output'] = self.output.buffer
# Store the type of file descriptor and the respective contents
state_files = []
for fd in self.files:
if isinstance(fd, Socket):
state_files.append(('Socket', fd.buffer))
else:
state_files.append(('File', fd))
state['files'] = state_files
state['procs'] = self.procs
state['current'] = self._current
state['running'] = self.running
state['rwait'] = self.rwait
state['twait'] = self.twait
state['timers'] = self.timers
state['syscall_trace'] = self.syscall_trace
state['base'] = self.base
state['elf_bss'] = self.elf_bss
state['end_code'] = self.end_code
state['end_data'] = self.end_data
state['elf_brk'] = self.elf_brk
state['auxv'] = self.auxv
state['program'] = self.program
state['functionabi'] = self._function_abi
state['syscallabi'] = self._syscall_abi
state['uname_machine'] = self._uname_machine
if hasattr(self, '_arm_tls_memory'):
state['_arm_tls_memory'] = self._arm_tls_memory
return state
def __setstate__(self, state):
"""
:todo: some asserts
:todo: fix deps? (last line)
"""
self.input = Socket()
self.input.buffer = state['input']
self.output = Socket()
self.output.buffer = state['output']
# fetch each file descriptor (Socket or File())
self.files = []
for ty, buf in state['files']:
if ty == 'Socket':
f = Socket()
f.buffer = buf
self.files.append(f)
else:
self.files.append(buf)
self.files[0].peer = self.output
self.files[1].peer = self.output
self.files[2].peer = self.output
self.input.peer = self.files[0]
self.procs = state['procs']
self._current = state['current']
self.running = state['running']
self.rwait = state['rwait']
self.twait = state['twait']
self.timers = state['timers']
self.clocks = state['clocks']
self.syscall_trace = state['syscall_trace']
self.base = state['base']
self.elf_bss = state['elf_bss']
self.end_code = state['end_code']
self.end_data = state['end_data']
self.elf_brk = state['elf_brk']
self.auxv = state['auxv']
self.program = state['program']
self._function_abi = state['functionabi']
self._syscall_abi = state['syscallabi']
self._uname_machine = state['uname_machine']
if '_arm_tls_memory' in state:
self._arm_tls_memory = state['_arm_tls_memory']
def _init_arm_kernel_helpers(self):
'''
ARM kernel helpers
https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
'''
page_data = bytearray('\xf1\xde\xfd\xe7' * 1024)
# Extracted from a RPi2
preamble = (
'ff0300ea' +
'650400ea' +
'f0ff9fe5' +
'430400ea' +
'220400ea' +
'810400ea' +
'000400ea' +
'870400ea'
).decode('hex')
# XXX(yan): The following implementations of cmpxchg and cmpxchg64 were
# handwritten to not use any exclusive instructions (e.g. ldrexd) or
# locking. For actual implementations, refer to
# arch/arm64/kernel/kuser32.S in the Linux source code.
__kuser_cmpxchg64 = (
'30002de9' + # push {r4, r5}
'08c09de5' + # ldr ip, [sp, #8]
'30009ce8' + # ldm ip, {r4, r5}
'010055e1' + # cmp r5, r1
'00005401' + # cmpeq r4, r0
'0100a013' + # movne r0, #1
'0000a003' + # moveq r0, #0
'0c008c08' + # stmeq ip, {r2, r3}
'3000bde8' + # pop {r4, r5}
'1eff2fe1' # bx lr
).decode('hex')
__kuser_dmb = (
'5bf07ff5' + # dmb ish
'1eff2fe1' # bx lr
).decode('hex')
__kuser_cmpxchg = (
'003092e5' + # ldr r3, [r2]
'000053e1' + # cmp r3, r0
'0000a003' + # moveq r0, #0
'00108205' + # streq r1, [r2]
'0100a013' + # movne r0, #1
'1eff2fe1' # bx lr
).decode('hex')
# Map a TLS segment
self._arm_tls_memory = self.current.memory.mmap(None, 4, 'rw ')
__kuser_get_tls = (
'04009FE5' + # ldr r0, [pc, #4]
'010090e8' + # ldm r0, {r0}
'1eff2fe1' # bx lr
).decode('hex') + struct.pack('<I', self._arm_tls_memory)
tls_area = '\x00'*12
version = struct.pack('<I', 5)
def update(address, code):
page_data[address:address+len(code)] = code
# Offsets from Documentation/arm/kernel_user_helpers.txt in Linux
update(0x000, preamble)
update(0xf60, __kuser_cmpxchg64)
update(0xfa0, __kuser_dmb)
update(0xfc0, __kuser_cmpxchg)
update(0xfe0, __kuser_get_tls)
update(0xff0, tls_area)
update(0xffc, version)
self.current.memory.mmap(0xffff0000, len(page_data), 'r x', page_data)
def load_vdso(self, bits):
#load vdso #TODO or #IGNORE
vdso_top = {32: 0x7fff0000, 64: 0x7fff00007fff0000}[bits]
vdso_size = len(file('vdso%2d.dump'%bits).read())
vdso_addr = self.memory.mmapFile(self.memory._floor(vdso_top - vdso_size),
vdso_size,
'r x',
{32: 'vdso32.dump', 64: 'vdso64.dump'}[bits],
0)
return vdso_addr
def setup_stack(self, argv, envp):
'''
:param Cpu cpu: The cpu instance
:param argv: list of parameters for the program to execute.
:param envp: list of environment variables for the program to execute.
http://www.phrack.org/issues.html?issue=58&id=5#article
position content size (bytes) + comment
----------------------------------------------------------------------
stack pointer -> [ argc = number of args ] 4
[ argv[0] (pointer) ] 4 (program name)
[ argv[1] (pointer) ] 4
[ argv[..] (pointer) ] 4 * x
[ argv[n - 1] (pointer) ] 4
[ argv[n] (pointer) ] 4 (= NULL)
[ envp[0] (pointer) ] 4
[ envp[1] (pointer) ] 4
[ envp[..] (pointer) ] 4
[ envp[term] (pointer) ] 4 (= NULL)
[ auxv[0] (Elf32_auxv_t) ] 8
[ auxv[1] (Elf32_auxv_t) ] 8
[ auxv[..] (Elf32_auxv_t) ] 8
[ auxv[term] (Elf32_auxv_t) ] 8 (= AT_NULL vector)
[ padding ] 0 - 16
[ argument ASCIIZ strings ] >= 0
[ environment ASCIIZ str. ] >= 0
(0xbffffffc) [ end marker ] 4 (= NULL)
(0xc0000000) < top of stack > 0 (virtual)
----------------------------------------------------------------------
'''
cpu = self.current
# In case setup_stack() is called again, we make sure we're growing the
# stack from the original top
cpu.STACK = self._stack_top
auxv = self.auxv
logger.debug("Setting argv, envp and auxv.")
logger.debug("\tArguments: %s", repr(argv))
if envp:
logger.debug("\tEnvironment:")
for e in envp:
logger.debug("\t\t%s", repr(e))
logger.debug("\tAuxv:")
for name, val in auxv.items():
logger.debug("\t\t%s: %s", name, hex(val))
#We save the argument and environment pointers
argvlst = []
envplst = []
#end envp marker empty string
for evar in envp:
cpu.push_bytes('\x00')
envplst.append(cpu.push_bytes(evar))
for arg in argv:
cpu.push_bytes('\x00')
argvlst.append(cpu.push_bytes(arg))
#Put all auxv strings into the string stack area.
#And replace the value be its pointer
for name, value in auxv.items():
if hasattr(value, '__len__'):
cpu.push_bytes(value)
auxv[name] = cpu.STACK
#The "secure execution" mode of secure_getenv() is controlled by the
#AT_SECURE flag contained in the auxiliary vector passed from the
#kernel to user space.
auxvnames = {
'AT_IGNORE': 1, # Entry should be ignored
'AT_EXECFD': 2, # File descriptor of program
'AT_PHDR': 3, # Program headers for program
'AT_PHENT':4, # Size of program header entry
'AT_PHNUM':5, # Number of program headers
'AT_PAGESZ': 6, # System page size
'AT_BASE': 7, # Base address of interpreter
'AT_FLAGS':8, # Flags
'AT_ENTRY':9, # Entry point of program
'AT_NOTELF': 10, # Program is not ELF
'AT_UID':11, # Real uid
'AT_EUID': 12, # Effective uid
'AT_GID':13, # Real gid
'AT_EGID': 14, # Effective gid
'AT_CLKTCK': 17, # Frequency of times()
'AT_PLATFORM': 15, # String identifying platform.
'AT_HWCAP':16, # Machine-dependent hints about processor capabilities.
'AT_FPUCW':18, # Used FPU control word.
'AT_SECURE': 23, # Boolean, was exec setuid-like?
'AT_BASE_PLATFORM': 24, # String identifying real platforms.
'AT_RANDOM': 25, # Address of 16 random bytes.
'AT_EXECFN': 31, # Filename of executable.
'AT_SYSINFO':32, #Pointer to the global system page used for system calls and other nice things.
'AT_SYSINFO_EHDR': 33, #Pointer to the global system page used for system calls and other nice things.
}
#AT_NULL
cpu.push_int(0)
cpu.push_int(0)
for name, val in auxv.items():
cpu.push_int(val)
cpu.push_int(auxvnames[name])
# NULL ENVP
cpu.push_int(0)
for var in reversed(envplst): # ENVP n
cpu.push_int(var)
envp = cpu.STACK
# NULL ARGV
cpu.push_int(0)
for arg in reversed(argvlst): # Argv n
cpu.push_int(arg)
argv = cpu.STACK
#ARGC
cpu.push_int(len(argvlst))
def load(self, filename):
'''
Loads and an ELF program in memory and prepares the initial CPU state.
Creates the stack and loads the environment variables and the arguments in it.
:param filename: pathname of the file to be executed. (used for auxv)
:raises error:
- 'Not matching cpu': if the program is compiled for a different architecture
- 'Not matching memory': if the program is compiled for a different address size
:todo: define va_randomize and read_implies_exec personality
'''
#load elf See binfmt_elf.c
#read the ELF object file
cpu = self.current
elf = self.elf
arch = self.arch
addressbitsize = {'x86':32, 'x64':64, 'ARM': 32}[elf.get_machine_arch()]
logger.debug("Loading %s as a %s elf"%(filename, arch))
assert elf.header.e_type in ['ET_DYN', 'ET_EXEC', 'ET_CORE']
#Get interpreter elf
interpreter = None
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_INTERP':
continue
interpreter_filename = elf_segment.data()[:-1]
logger.info('Interpreter filename: %s', interpreter_filename)
interpreter = ELFFile(file(interpreter_filename))
break
if not interpreter is None:
assert interpreter.get_machine_arch() == elf.get_machine_arch()
assert interpreter.header.e_type in ['ET_DYN', 'ET_EXEC']
#Stack Executability
executable_stack = False
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_GNU_STACK':
continue
if elf_segment.header.p_flags & 0x01:
executable_stack = True
else:
executable_stack = False
break
base = 0
elf_bss = 0
end_code = 0
end_data = 0
elf_brk = 0
load_addr = 0
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_LOAD':
continue
align = 0x1000 #elf_segment.header.p_align
ELF_PAGEOFFSET = elf_segment.header.p_vaddr & (align-1)
flags = elf_segment.header.p_flags
memsz = elf_segment.header.p_memsz + ELF_PAGEOFFSET
offset = elf_segment.header.p_offset - ELF_PAGEOFFSET
filesz = elf_segment.header.p_filesz + ELF_PAGEOFFSET
vaddr = elf_segment.header.p_vaddr - ELF_PAGEOFFSET
memsz = cpu.memory._ceil(memsz)
if base == 0 and elf.header.e_type == 'ET_DYN':
assert vaddr == 0
if addressbitsize == 32:
base = 0x56555000
else:
base = 0x555555554000
perms = perms_from_elf(flags)
hint = base+vaddr
if hint == 0:
hint = None
logger.debug("Loading elf offset: %08x addr:%08x %08x %s" %(offset, base+vaddr, base+vaddr+memsz, perms))
base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset) - vaddr
if load_addr == 0 :
load_addr = base + vaddr
k = base + vaddr + filesz;
if k > elf_bss :
elf_bss = k;
if (flags & 4) and end_code < k: #PF_X
end_code = k
if end_data < k:
end_data = k
k = base + vaddr + memsz
if k > elf_brk:
elf_brk = k
elf_entry = elf.header.e_entry
if elf.header.e_type == 'ET_DYN':
elf_entry += load_addr
entry = elf_entry
real_elf_brk = elf_brk
# We need to explicitly zero any fractional pages
# after the data section (i.e. bss). This would
# contain the junk from the file that should not
# be in memory
#TODO:
#cpu.write_bytes(elf_bss, '\x00'*((elf_bss | (align-1))-elf_bss))
logger.debug("Zeroing main elf fractional pages. From %x to %x.", elf_bss, elf_brk)
logger.debug("Main elf bss:%x"%elf_bss)
logger.debug("Main elf brk %x:"%elf_brk)
#FIXME Need a way to inspect maps and perms so
#we can rollback all to the initial state after zeroing
#if elf_brk-elf_bss > 0:
# saved_perms = cpu.mem.perms(elf_bss)
# cpu.memory.mprotect(cpu.mem._ceil(elf_bss), elf_brk-elf_bss, 'rw ')
# logger.debug("Zeroing main elf fractional pages (%d bytes)", elf_brk-elf_bss)
# cpu.write_bytes(elf_bss, ['\x00'] * (elf_brk-elf_bss))
# cpu.memory.mprotect(cpu.memory._ceil(elf_bss), elf_brk-elf_bss, saved_perms)
if cpu.memory.access_ok(slice(elf_bss, elf_brk), 'w'):
cpu.memory[elf_bss:elf_brk] = '\x00'*(elf_brk-elf_bss)
else:
logger.warning("Failing to zerify the trailing: elf_brk-elf_bss")
stack_size = 0x21000
if addressbitsize == 32:
stack_top = 0xc0000000
else:
stack_top = 0x800000000000
stack_base = stack_top - stack_size
stack = cpu.memory.mmap(stack_base, stack_size, 'rwx', name='stack') + stack_size
assert stack_top == stack
reserved = cpu.memory.mmap(base+vaddr+memsz,0x1000000, ' ')
interpreter_base = 0
if interpreter is not None:
base = 0
elf_bss = 0
end_code = 0
end_data = 0
elf_brk = 0
entry = interpreter.header.e_entry
for elf_segment in interpreter.iter_segments():
if elf_segment.header.p_type != 'PT_LOAD':
continue
align = 0x1000#elf_segment.header.p_align
vaddr = elf_segment.header.p_vaddr
filesz = elf_segment.header.p_filesz
flags = elf_segment.header.p_flags
offset = elf_segment.header.p_offset
memsz = elf_segment.header.p_memsz
ELF_PAGEOFFSET = (vaddr & (align-1))
memsz = memsz + ELF_PAGEOFFSET
offset = offset - ELF_PAGEOFFSET
filesz = filesz + ELF_PAGEOFFSET
vaddr = vaddr - ELF_PAGEOFFSET
memsz = cpu.memory._ceil(memsz)
if base == 0 and interpreter.header.e_type == 'ET_DYN':
assert vaddr == 0
total_size = self._interp_total_size(interpreter)
base = stack_base - total_size
if base == 0:
assert vaddr == 0
perms = perms_from_elf(flags)
hint = base+vaddr
if hint == 0:
hint = None
base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset)
base -= vaddr
logger.debug("Loading interpreter offset: %08x addr:%08x %08x %s%s%s" %(offset, base+vaddr, base+vaddr+memsz, (flags&1 and 'r' or ' '), (flags&2 and 'w' or ' '), (flags&4 and 'x' or ' ')))
k = base + vaddr + filesz;
if k > elf_bss:
elf_bss = k
if (flags & 4) and end_code < k: #PF_X
end_code = k
if end_data < k:
end_data = k
k = base + vaddr+ memsz
if k > elf_brk:
elf_brk = k
if interpreter.header.e_type == 'ET_DYN':
entry += base
interpreter_base = base
logger.debug("Zeroing interpreter elf fractional pages. From %x to %x.", elf_bss, elf_brk)
logger.debug("Interpreter bss:%x", elf_bss)
logger.debug("Interpreter brk %x:", elf_brk)
cpu.memory.mprotect(cpu.memory._floor(elf_bss), elf_brk-elf_bss, 'rw ')
try:
cpu.memory[elf_bss:elf_brk] = '\x00'*(elf_brk-elf_bss)
except Exception, e:
logger.debug("Exception zeroing Interpreter fractional pages: %s"%str(e))
#TODO #FIXME mprotect as it was before zeroing?
#free reserved brk space
cpu.memory.munmap(reserved, 0x1000000)
#load vdso
#vdso_addr = load_vdso(addressbitsize)
cpu.STACK = stack
cpu.PC = entry
logger.debug("Entry point: %016x", entry)
logger.debug("Stack start: %016x", stack)
logger.debug("Brk: %016x", real_elf_brk)
logger.debug("Mappings:")
for m in str(cpu.memory).split('\n'):
logger.debug(" %s", m)
self.base = base
self.elf_bss = elf_bss
self.end_code = end_code
self.end_data = end_data
self.elf_brk = real_elf_brk
at_random = cpu.push_bytes('A'*16)
at_execfn = cpu.push_bytes(filename+'\x00')
self.auxv = {
'AT_PHDR' : load_addr+elf.header.e_phoff, # Program headers for program
'AT_PHENT' : elf.header.e_phentsize, # Size of program header entry
'AT_PHNUM' : elf.header.e_phnum, # Number of program headers
'AT_PAGESZ' : cpu.memory.page_size, # System page size
'AT_BASE' : interpreter_base, # Base address of interpreter
'AT_FLAGS' : elf.header.e_flags, # Flags
'AT_ENTRY' : elf_entry, # Entry point of program
'AT_UID' : 1000, # Real uid
'AT_EUID' : 1000, # Effective uid
'AT_GID' : 1000, # Real gid
'AT_EGID' : 1000, # Effective gid
'AT_CLKTCK' : 100, # Frequency of times()
'AT_HWCAP' : 0, # Machine-dependent hints about processor capabilities.
'AT_RANDOM' : at_random, # Address of 16 random bytes.
'AT_EXECFN' : at_execfn, # Filename of executable.
}
def _open(self, f):
'''
Adds a file descriptor to the current file descriptor list
:rtype: int
:param f: the file descriptor to add.
:return: the index of the file descriptor in the file descr. list
'''
if None in self.files:
fd = self.files.index(None)
self.files[fd] = f
else:
fd = len(self.files)
self.files.append(f)
return fd
def _close(self, fd):
'''
Removes a file descriptor from the file descriptor list
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.
'''
self.files[fd] = None
def _dup(self, fd):
'''
Duplicates a file descriptor
:rtype: int
:param fd: the file descriptor to duplicate.
:return: C{0} on success.
'''
return self._open(self.files[fd])
def _get_fd(self, fd):
if fd < 0 or fd >= len(self.files) or self.files[fd] is None:
raise BadFd()
else:
return self.files[fd]
def sys_umask(self, mask):
'''
umask - Set file creation mode mask
:param int mask: New mask
'''
logger.debug("umask(%o)", mask)
return os.umask(mask)
def sys_chdir(self, path):
'''
chdir - Change current working directory
:param int path: Pointer to path
'''
path_str = self.current.read_string(path)
logger.debug("chdir(%s)", path_str)
try:
os.chdir(path_str)
return 0
except OSError as e:
return e.errno
def sys_lseek(self, fd, offset, whence):
'''
lseek - reposition read/write file offset
The lseek() function repositions the file offset of the open file description associated
with the file descriptor fd to the argument offset according to the directive whence
:param self: current CPU.
:param fd: a valid file descriptor
:param offset: the offset in bytes
:param whence: SEEK_SET: The file offset is set to offset bytes.
SEEK_CUR: The file offset is set to its current location plus offset bytes.
SEEK_END: The file offset is set to the size of the file plus offset bytes.
:return: 0 (Success), or EBADF (fd is not a valid file descriptor or is not open)
'''
if self.current.address_bit_size == 32:
signed_offset = ctypes.c_int32(offset).value
else:
signed_offset = ctypes.c_int64(offset).value
try:
self._get_fd(fd).seek(signed_offset, whence)
except BadFd:
logger.info(("LSEEK: Not valid file descriptor on lseek."
"Fd not seekable. Returning EBADF"))
return -errno.EBADF
logger.debug("LSEEK(%d, 0x%08x (%d), %d)", fd, offset, signed_offset, whence)
return 0
def sys_read(self, fd, buf, count):
data = ''
if count != 0:
# TODO check count bytes from buf
if not buf in self.current.memory: # or not self.current.memory.isValid(buf+count):
logger.info("READ: buf points to invalid address. Returning EFAULT")
return -errno.EFAULT
try:
# Read the data and put in tin memory
data = self._get_fd(fd).read(count)
except BadFd:
logger.info(("READ: Not valid file descriptor on read."
" Returning EBADF"))
return -errno.EBADF
self.syscall_trace.append(("_read", fd, data))
self.current.write_bytes(buf, data)
logger.debug("READ(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)",
fd,
buf,
count,
len(data),
repr(data)[:min(count,10)],
len(data))
return len(data)
def sys_write(self, fd, buf, count):
''' write - send bytes through a file descriptor
The write system call writes up to count bytes from the buffer pointed
to by buf to the file descriptor fd. If count is zero, write returns 0
and optionally sets *tx_bytes to zero.
:param fd a valid file descriptor
:param buf a memory buffer
:param count number of bytes to send
:return: 0 Success
EBADF fd is not a valid file descriptor or is not open.
EFAULT buf or tx_bytes points to an invalid address.
'''
data = []
cpu = self.current
if count != 0:
try:
write_fd = self._get_fd(fd)
except BadFd:
logger.error("WRITE: Not valid file descriptor. Returning EBADFD %d", fd)
return -errno.EBADF
# TODO check count bytes from buf
if buf not in cpu.memory or buf + count not in cpu.memory:
logger.debug("WRITE: buf points to invalid address. Returning EFAULT")
return -errno.EFAULT
if fd > 2 and write_fd.is_full():
cpu.PC -= cpu.instruction.size
self.wait([], [fd], None)
raise RestartSyscall()
data = cpu.read_bytes(buf, count)
write_fd.write(data)
for line in ''.join([str(x) for x in data]).split('\n'):
logger.debug("WRITE(%d, 0x%08x, %d) -> <%.48r>",
fd,
buf,
count,
line)
self.syscall_trace.append(("_write", fd, data))
self.signal_transmit(fd)
return len(data)
def sys_access(self, buf, mode):
'''
Checks real user's permissions for a file
:rtype: int
:param buf: a buffer containing the pathname to the file to check its permissions.
:param mode: the access permissions to check.
:return:
- C{0} if the calling process can access the file in the desired mode.
- C{-1} if the calling process can not access the file in the desired mode.
'''
filename = ""
for i in xrange(0, 255):
c = Operators.CHR(self.current.read_int(buf + i, 8))
if c == '\x00':
break
filename += c
logger.debug("access(%s, %x) -> %r",
filename,
mode, | os.access(filename, mode))
if os.access(filename, mode):
return 0
else:
return -1
def sys_newuname(self, old_utsname):
'''
Writes system information in the variable C{old_utsname}.
:rtype: int
:param old_utsname: the buffer to write the system info.
:return: C{0} on success
'''
from datetime import datetime
def pad(s):
return s +'\x00'*(65-len(s))
now = datetime.now().strftime("%a %b %d %H:%M:%S ART %Y")
info = (('sysname', 'Linux'),
('nodename', 'ubuntu'),
('release', '4.4.0-77-generic'),
('version', '#98 SMP ' + now),
('machine', self._uname_machine),
('domainname', ''))
uname_buf = ''.join(pad(pair[1]) for pair in info)
self.current.write_bytes(old_utsname, uname_buf)
logger.debug("sys_newuname(...) -> %s", uname_buf)
return 0
def sys_brk(self, brk):
'''
Changes data segment size (moves the C{elf_brk} to the new address)
:rtype: int
:param brk: the new address for C{elf_brk}.
:return: the value of the new C{elf_brk}.
:raises error:
- "Error in brk!" if there is any error allocating the memory
'''
if brk != 0:
assert brk > self.elf_brk
mem = self.current.memory
size = brk-self.elf_brk
perms = mem.perms(self.elf_brk-1)
if brk > mem._ceil(self.elf_brk):
addr = mem.mmap(mem._ceil(self.elf_brk), size, perms)
assert mem._ceil(self.elf_brk) == addr, "Error in brk!"
self.elf_brk += size
logger.debug("sys_brk(0x%08x) -> 0x%08x", brk, self.elf_brk)
return self.elf_brk
def sys_arch_prctl(self, code, addr):
'''
Sets architecture-specific thread state
:rtype: int
:param code: must be C{ARCH_SET_FS}.
:param addr: the base address of the FS segment.
:return: C{0} on success
:raises error:
- if C{code} is different to C{ARCH_SET_FS}
'''
ARCH_SET_GS = 0x1001
ARCH_SET_FS = 0x1002
ARCH_GET_FS = 0x1003
ARCH_GET_GS = 0x1004
assert code == ARCH_SET_FS
self.current.FS = 0x63
self.current.set_descriptor(self.current.FS, addr, 0x4000, 'rw')
logger.debug("sys_arch_prctl(%04x, %016x) -> 0", code, addr)
return 0
def sys_ioctl(self, fd, request, argp):
if fd > 2:
return self.files[fd].ioctl(request, argp)
else:
return -errno.EINVAL
def _sys_open_get_file(self, filename, flags, mode):
f = File(filename, mode) # TODO (theo) modes, flags
return f
def sys_open(self, buf, flags, mode):
'''
:param buf: address of zero-terminated pathname
:param flags: file access bits
:param mode: file permission mode
'''
filename = self.current.read_string(buf)
try:
if os.path.abspath(filename).startswith('/proc/self'):
if filename == '/proc/self/exe':
filename = os.path.abspath(self.program)
else:
logger.info("FIXME!")
mode = {os.O_RDWR: 'r+', os.O_RDONLY: 'r', os.O_WRONLY: 'w'}[flags&7]
f = self._sys_open_get_file(filename, flags, mode)
logger.debug("Opening file %s for %s real fd %d",
filename, mode, f.fileno())
# FIXME(theo) generic exception
except Exception as e:
logger.info("Could not open file %s. Reason %s" % (filename, str(e)))
return -1
return self._open(f)
def sys_rename(self, oldnamep, newnamep):
'''
Rename filename `oldnamep` to `newnamep`.
:param int oldnamep: pointer to oldname
:param int newnamep: pointer to newname
'''
oldname = self.current.read_string(oldnamep)
newname = self.current.read_string(newnamep)
ret = 0
try:
os.rename(oldname, newname)
except OSError as e:
ret = -e.errno
logger.debug("sys_rename('%s', '%s') -> %s", oldname, newname, ret)
return ret
def sys_fsync(self, fd):
'''
Synchronize a file's in-core state with that on disk.
'''
ret = 0
try:
self.files[fd].sync()
except IndexError:
ret = -errno.EBADF
except BadFd:
ret = -errno.EINVAL
logger.debug("sys_fsync(%d) -> %d", fd, ret)
return ret
def sys_getpid(self, v):
logger.debug("GETPID, warning pid modeled as concrete 1000")
return 1000
def sys_ARM_NR_set_tls(self, val):
if hasattr(self, '_arm_tls_memory'):
self.current.write_int(self._arm_tls_memory, val)
self.current.set_arm_tls(val)
return 0
#Signals..
def sys_kill(self, pid, sig):
logger.debug("KILL, Ignoring Sending signal %d to pid %d", sig, pid)
return 0
def sys_rt_sigaction(self, signum, act, oldact):
"""Wrapper for sys_sigaction"""
return self.sys_sigaction(signum, act, oldact)
def sys_sigaction(self, signum, act, oldact):
logger.debug("SIGACTION, Ignoring changing signal handler for signal %d",
signum)
return 0
def sys_rt_sigprocmask(self, cpu, how, newset, oldset):
'''Wrapper for sys_sigprocmask'''
return self.sys_sigprocmask(cpu, how, newset, oldset)
def sys_sigprocmask(self, cpu, how, newset, oldset):
logger.debug("SIGACTION, Ignoring changing signal mask set cmd:%d", how)
return 0
def sys_close(self, fd):
'''
Closes a file descriptor
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.
'''
if fd > 0 :
self._close(fd)
logger.debug('sys_close(%d)', fd)
return 0
def sys_readlink(self, path, buf, bufsize):
'''
Read
:rtype: int
:param path: the "link path id"
:param buf: the buffer where the bytes will be putted.
:param bufsize: the max size for read the link.
:todo: Out eax number of bytes actually sent | EAGAIN | EBADF | EFAULT | EINTR | errno.EINVAL | EIO | ENOSPC | EPIPE
'''
if bufsize <= 0:
return -errno.EINVAL
filename = self.current.read_string(path)
if filename == '/proc/self/exe':
data = os.path.abspath(self.program)
else:
data = os.readlink(filename)[:bufsize]
self.current.write_bytes(buf, data)
logger.debug("READLINK %d %x %d -> %s",path,buf,bufsize,data)
return len(data)
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset):
'''Wrapper for mmap2'''
return self.sys_mmap2(address, size, prot, flags, fd, offset)
def sys_mmap2(self, address, size, prot, flags, fd, offset):
'''
Creates a new mapping in the virtual address space of the calling process.
:rtype: int
:param address: the starting address for the new mapping. This address is used as hint unless the
flag contains C{MAP_FIXED}.
:param size: the length of the mapping.
:param prot: the desired memory protection of the mapping.
:param flags: determines whether updates to the mapping are visible to other
processes mapping the same region, and whether updates are carried
through to the underlying file.
:param fd: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:param offset: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset}*0x1000 in the file referred to by the file descriptor C{fd}.
:return:
- C{-1} In case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address.
- the address of the new mapping.
'''
return self.sys_mmap(address, size, prot, flags, fd, offset*0x1000)
def sys_mmap(self, address, size, prot, flags, fd, offset):
'''
Creates a new mapping in the virtual address space of the calling process.
:rtype: int
:param address: the starting address for the new mapping. This address is used as hint unless the
flag contains C{MAP_FIXED}.
:param size: the length of the mapping.
:param prot: the desired memory protection of the mapping.
:param flags: determines whether updates to the mapping are visible to other
processes mapping the same region, and whether updates are carried
through to the underlying file.
:param fd: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:param offset: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:return:
- C{-1} in case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address.
- the address of the new mapping (that must be the same as address in case you included C{MAP_FIXED} in flags).
:todo: handle exception.
'''
if address == 0:
address = None
cpu = self.current
if flags & 0x10 != 0:
cpu.memory.munmap(address,size)
perms = perms_from_protflags(prot)
if flags & 0x20 != 0:
result = cpu.memory.mmap(address, size, perms)
elif fd == 0:
assert offset == 0
result = cpu.memory.mmap(address, size, perms)
data = self.files[fd].read(size)
cpu.write_bytes(result, data)
else:
#FIXME Check if file should be symbolic input and do as with fd0
result = cpu.memory.mmapFile(address, size, perms, self.files[fd].name, offset)
actually_mapped = '0x{:016x}'.format(result)
if address is None or result != address:
address = address or 0
actually_mapped += ' [requested: 0x{:016x}]'.format(address)
if flags & 0x10 != 0 and result != address:
cpu.memory.munmap(result, size)
result = -1
logger.debug("sys_mmap(%s, 0x%x, %s, %x, %d) - (0x%x)",
actually_mapped,
size,
perms,
flags,
fd,
result)
return result
def sys_mprotect(self, start, size, prot):
'''
Sets protection on a region of memory. Changes protection for the calling process's
memory page(s) containing any part of the address range in the interval [C{start}, C{start}+C{size}-1].
:rtype: int
:param start: the starting address to change the permissions.
:param size: the size of the portion of memory to change the permissions.
:param prot: the new access permission for the memory.
:return: C{0} on success.
'''
perms = perms_from_protflags(prot)
ret = self.current.memory.mprotect(start, size, perms)
logger.debug("sys_mprotect(0x%016x, 0x%x, %s) -> %r (%r)", start, size, perms, ret, prot)
return 0
def sys_munmap(self, addr, size):
'''
Unmaps a file from memory. It deletes the mappings for the specified address range
:rtype: int
:param addr: the starting address to unmap.
:param size: the size of the portion to unmap.
:return: C{0} on success.
'''
self.current.memory.munmap(addr, size)
return 0
def sys_getuid(self):
'''
Gets user identity.
:rtype: int
:return: this call returns C{1000} for all the users.
'''
return 1000
def sys_getgid(self):
'''
Gets group identity.
:rtype: int
:return: this call returns C{1000} for all the groups.
'''
return 1000
def sys_geteuid(self):
'''
Gets user identity.
:rtype: int
:return: This call returns C{1000} for all the users.
'''
return 1000
def sys_getegid(self):
'''
Gets group identity.
:rtype: int
:return: this call returns C{1000} for all the groups.
'''
return 1000
def sys_readv(self, fd, iov, count):
'''
Works just like C{sys_read} except that data is read into multiple buffers.
:rtype: int
:param fd: the file descriptor of the file to read.
:param iov: the buffer where the the bytes to read are stored.
:param count: amount of C{iov} buffers to read from the file.
:return: the amount of bytes read in total.
'''
cpu = self.current
ptrsize = cpu.address_bit_size
sizeof_iovec = 2 * (ptrsize // 8)
total = 0
for i in xrange(0, count):
buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize)
size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2),
ptrsize)
data = self.files[fd].read(size)
total += len(data)
cpu.write_bytes(buf, data)
self.syscall_trace.append(("_read", fd, data))
logger.debug("READV(%r, %r, %r) -> <%r> (size:%r)",
fd,
buf,
size,
data,
len(data))
return total
def sys_writev(self, fd, iov, count):
'''
Works just like C{sys_write} except that multiple buffers are written out.
:rtype: int
:param fd: the file descriptor of the file to write.
:param iov: the buffer where the the bytes to write are taken.
:param count: amount of C{iov} buffers to write into the file.
:return: the amount of bytes written in total.
'''
cpu = self.current
ptrsize = cpu.address_bit_size
sizeof_iovec = 2 * (ptrsize // 8)
total = 0
for i in xrange(0, count):
buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize)
size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2), ptrsize)
data = ""
for j in xrange(0,size):
data += Operators.CHR(cpu.read_int(buf + j, 8))
logger.debug("WRITEV(%r, %r, %r) -> <%r> (size:%r)"%(fd, buf, size, data, len(data)))
self.files[fd].write(data)
self.syscall_trace.append(("_write", fd, data))
total+=size
return total
def sys_set_thread_area(self, user_info):
'''
Sets a thread local storage (TLS) area. Sets the base address of the GS segment.
:rtype: int
:param user_info: the TLS array entry set corresponds to the value of C{u_info->entry_number}.
:return: C{0} on success.
'''
n = self.current.read_int(user_info, 32)
pointer = self.current.read_int(user_info + 4, 32)
m = self.current.read_int(user_info + 8, 32)
flags = self.current.read_int(user_info + 12, 32)
assert n == 0xffffffff
assert flags == 0x51 #TODO: fix
self.current.GS = 0x63
self.current.set_descriptor(self.current.GS, pointer, 0x4000, 'rw')
self.current.write_int(user_info, (0x63 - 3) / 8, 32)
return 0
def sys_getpriority(self, which, who):
'''
System call ignored.
:rtype: int
:return: C{0}
'''
logger.debug("Ignoring sys_get_priority")
return 0
def sys_setpriority(self, which, who, prio):
'''
System call ignored.
:rtype: int
:return: C{0}
'''
logger.debug("Ignoring sys_setpriority")
return 0
def sys_acct(self, path):
'''
System call not implemented.
:rtype: int
:return: C{-1}
'''
logger.debug("BSD account not implemented!")
return -1
def sys_exit(self, error_code):
'Wrapper for sys_exit_group'
return self.sys_exit_group(error_code)
def sys_exit_group(self, error_code):
'''
Exits all threads in a process
:raises Exception: 'Finished'
'''
procid = self.procs.index(self.current)
self.sched()
self.running.remove(procid)
#self.procs[procid] = None
logger.debug("EXIT_GROUP PROC_%02d %s", procid, error_code)
if len(self.running) == 0:
raise ProcessExit(error_code)
return error_code
def sys_ptrace(self, request, pid, addr, data):
logger.debug("sys_ptrace(%016x, %d, %016x, %016x) -> 0", request, pid, addr, data)
return 0
def sys_nanosleep(self, req, rem):
logger.debug("sys_nanosleep(...)")
return 0
def sys_set_tid_address(self, tidptr):
logger.debug("sys_set_tid_address(%016x) -> 0", tidptr)
return 1000 #tha pid
def sys_faccessat(self, dirfd, pathname, mode, flags):
filename = self.current.read_string(pathname)
logger.debug("sys_faccessat(%016x, %s, %x, %x) -> 0", dirfd, filename, mode, flags)
return -1
def sys_set_robust_list(self, head, length):
logger.debug("sys_set_robust_list(%016x, %d) -> -1", head, length)
return -1
def sys_futex(self, uaddr, op, val, timeout, uaddr2, val3):
logger.debug("sys_futex(...) -> -1")
return -1
def sys_getrlimit(self, resource, rlim):
logger.debug("sys_getrlimit(%x, %x) -> -1", resource, rlim)
return -1
def sys_fadvise64(self, fd, offset, length, advice):
logger.debug("sys_fadvise64(%x, %x, %x, %x) -> 0", fd, offset, length, advice)
return 0
def sys_gettimeofday(self, tv, tz):
logger.debug("sys_gettimeofday(%x, %x) -> 0", tv, tz)
return 0
#Distpatchers...
def syscall(self):
'''
Syscall dispatcher.
'''
index = self._syscall_abi.syscall_number()
try:
table = getattr(linux_syscalls, self.current.machine)
name = table.get(index, None)
implementation = getattr(self, name)
except (AttributeError, KeyError):
raise SyscallNotImplemented(self.current.address_bit_size, index, name)
return self._syscall_abi.invoke(implementation)
def sys_clock_gettime(self, clock_id, timespec):
logger.info("sys_clock_time not really implemented")
return 0
def sys_time(self, tloc):
import time
t = time.time()
if tloc != 0 :
self.current.write_int(tloc, int(t), self.current.address_bit_size)
return int(t)
def sched(self):
''' Yield CPU.
This will choose another process from the running list and change
current running process. May give the same cpu if only one running
process.
'''
if len(self.procs) > 1:
logger.debug("SCHED:")
logger.debug("\tProcess: %r", self.procs)
logger.debug("\tRunning: %r", self.running)
logger.debug("\tRWait: %r", self.rwait)
logger.debug("\tTWait: %r", self.twait)
logger.debug("\tTimers: %r", self.timers)
logger.debug("\tCurrent clock: %d", self.clocks)
logger.debug("\tCurrent cpu: %d", self._current)
if len(self.running) == 0:
logger.debug("None running checking if there is some process waiting for a timeout")
if all([x is None for x in self.timers]):
raise Deadlock()
self.clocks = min(filter(lambda x: x is not None, self.timers)) + 1
self.check_timers()
assert len(self.running) != 0, "DEADLOCK!"
self._current = self.running[0]
return
next_index = (self.running.index(self._current) + 1) % len(self.running)
next_running_idx = self.running[next_index]
if len(self.procs) > 1:
logger.debug("\tTransfer control from process %d to %d",
self._current,
next_running_idx)
self._current = next_running_idx
def wait(self, readfds, writefds, timeout):
''' Wait for file descriptors or timeout.
Adds the current process in the correspondent waiting list and
yield the cpu to another running process.
'''
logger.debug("WAIT:")
logger.debug("\tProcess %d is going to wait for [ %r %r %r ]",
self._current,
readfds,
writefds,
timeout)
logger.debug("\tProcess: %r", self.procs)
logger.debug("\tRunning: %r", self.running)
logger.debug("\tRWait: %r", self.rwait)
logger.debug("\tTWait: %r", self.twait)
logger.debug("\tTimers: %r", self.timers)
for fd in readfds:
self.rwait[fd].add(self._current)
for fd in writefds:
self.twait[fd].add(self._current)
if timeout is not None:
self.timers[self._current] = self.clocks + timeout
procid = self._current
#self.sched()
next_index = (self.running.index(procid) + 1) % len(self.running)
self._current = self.running[next_index]
logger.debug("\tTransfer control from process %d to %d", procid, self._current)
logger.debug( "\tREMOVING %r from %r. Current: %r", procid, self.running, self._current)
self.running.remove(procid)
if self._current not in self.running:
logger.debug("\tCurrent not running. Checking for timers...")
self._current = None
self.check_timers()
def awake(self, procid):
''' Remove procid from waitlists and reestablish it in the running list '''
logger.debug("Remove procid:%d from waitlists and reestablish it in the running list", procid)
for wait_list in self.rwait:
if procid in wait_list: wait_list.remove(procid)
for wait_list in self.twait:
if procid in wait_list: wait_list.remove(procid)
self.timers[procid] = None
self.running.append(procid)
if self._current is None:
self._current = procid
def connections(self, fd):
""" File descriptors are connected to each other like pipes. Except
for 0,1,2. If you write to FD(N) then that comes out from FD(N+1)
and vice-versa
"""
if fd in [0, 1, 2]:
return None
if fd % 2:
return fd + 1
else:
return fd - 1
def signal_receive(self, fd):
''' Awake one process waiting to receive data on fd '''
connections = self.connections
if connections(fd) and self.twait[connections(fd)]:
procid = random.sample(self.twait[connections(fd)], 1)[0]
self.awake(procid)
def signal_transmit(self, fd):
''' Awake one process waiting to transmit data on fd '''
connection = self.connections(fd)
if connection is None or connection >= len(self.rwait):
return
procs = self.rwait[connection]
if procs:
procid = random.sample(procs, 1)[0]
self.awake(procid)
def check_timers(self):
''' Awake process if timer has expired '''
if self._current is None:
#Advance the clocks. Go to future!!
advance = min([self.clocks] + filter(lambda x: x is not None, self.timers)) + 1
logger.debug("Advancing the clock from %d to %d", self.clocks, advance)
self.clocks = advance
for procid in range(len(self.timers)):
if self.timers[procid] is not None:
if self.clocks > self.timers[procid]:
self.procs[procid].PC += self.procs[procid].instruction.size
self.awake(procid)
def execute(self):
"""
Execute one cpu instruction in the current thread (only one supported).
:rtype: bool
:return: C{True}
:todo: This is where we could implement a simple schedule.
"""
try:
self.current.execute()
self.clocks += 1
if self.clocks % 10000 == 0:
self.check_timers()
self.sched()
except (Interruption, Syscall):
try:
self.syscall()
except RestartSyscall:
pass
return True
#64bit syscalls
def sys_newfstat(self, fd, buf):
'''
Determines information about a file based on its file descriptor.
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(width, ts):
'Note: this is a platform-dependent timespec (8 or 16 bytes)'
return add(width, int(ts)) + add(width, int(ts % 1 * 1e9))
# From linux/arch/x86/include/uapi/asm/stat.h
# Numerous fields are native width-wide
nw = self.current.address_bit_size / 8
bufstat = add(nw, stat.st_dev) # long st_dev
bufstat += add(nw, stat.st_ino) # long st_ino
bufstat += add(nw, stat.st_nlink) # long st_nlink
bufstat += add(4, stat.st_mode) # 32 mode
bufstat += add(4, stat.st_uid) # 32 uid
bufstat += add(4, stat.st_gid) # 32 gid
bufstat += add(4, 0) # 32 _pad
bufstat += add(nw, stat.st_rdev) # long st_rdev
bufstat += add(nw, stat.st_size) # long st_size
bufstat += add(nw, stat.st_blksize) # long st_blksize
bufstat += add(nw, stat.st_blocks) # long st_blocks
bufstat += to_timespec(nw, stat.st_atime) # long st_atime, nsec;
bufstat += to_timespec(nw, stat.st_mtime) # long st_mtime, nsec;
bufstat += to_timespec(nw, stat.st_ctime) # long st_ctime, nsec;
logger.debug("sys_newfstat(%d, ...) -> %d bytes", fd, len(bufstat))
self.current.write_bytes(buf, bufstat)
return 0
def sys_fstat(self, fd, buf):
'''
Determines information about a file based on its file descriptor.
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(ts):
return struct.pack('<LL', int(ts), int(ts % 1 * 1e9))
logger.debug("sys_fstat %d", fd)
bufstat = add(8, stat.st_dev) # dev_t st_dev;
bufstat += add(4, 0) # __pad1
bufstat += add(4, stat.st_ino) # unsigned long st_ino;
bufstat += add(4, stat.st_mode) # unsigned short st_mode;
bufstat += add(4, stat.st_nlink) # unsigned short st_nlink;
bufstat += add(4, stat.st_uid) # unsigned short st_uid;
bufstat += add(4, stat.st_gid) # unsigned short st_gid;
bufstat += add(4, stat.st_rdev) # unsigned long st_rdev;
bufstat += add(4, stat.st_size) # unsigned long st_size;
bufstat += add(4, stat.st_blksize)# unsigned long st_blksize;
bufstat += add(4, stat.st_blocks) # unsigned long st_blocks;
bufstat += to_timespec(stat.st_atime) # unsigned long st_atime;
bufstat += to_timespec(stat.st_mtime) # unsigned long st_mtime;
bufstat += to_timespec(stat.st_ctime) # unsigned long st_ctime;
bufstat += add(4, 0) # unsigned long __unused4;
bufstat += add(4, 0) # unsigned long __unused5;
self.current.write_bytes(buf, bufstat)
return 0
def sys_fstat64(self, fd, buf):
'''
Determines information about a file based on its file descriptor (for Linux 64 bits).
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
:todo: Fix device number.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(ts):
return struct.pack('<LL', int(ts), int(ts % 1 * 1e9))
logger.debug("sys_fstat64 %d", fd)
bufstat = add(8, stat.st_dev) # unsigned long long st_dev;
bufstat += add(4, 0) # unsigned char __pad0[4];
bufstat += add(4, stat.st_ino) # unsigned long __st_ino;
bufstat += add(4, stat.st_mode) # unsigned int st_mode;
bufstat += add(4, stat.st_nlink) # unsigned int st_nlink;
bufstat += add(4, stat.st_uid) # unsigned long st_uid;
bufstat += add(4, stat.st_gid) # unsigned long st_gid;
bufstat += add(8, stat.st_rdev) # unsigned long long st_rdev;
bufstat += add(4, 0) # unsigned char __pad3[4];
bufstat += add(4, 0) # unsigned char __pad3[4];
bufstat += add(8, stat.st_size) # long long st_size;
bufstat += add(8, stat.st_blksize) # unsigned long st_blksize;
bufstat += add(8, stat.st_blocks) # unsigned long long st_blocks;
bufstat += to_timespec(stat.st_atime) # unsigned long st_atime;
bufstat += to_timespec(stat.st_mtime) # unsigned long st_mtime;
bufstat += to_timespec(stat.st_ctime) # unsigned long st_ctime;
bufstat += add(8, stat.st_ino) # unsigned long long st_ino;
self.current.write_bytes(buf, bufstat)
return 0
def sys_newstat(self, fd, buf):
'''
Wrapper for stat64()
'''
return self.sys_stat64(fd, buf)
def sys_stat64(self, path, buf):
'''
Determines information about a file based on its filename (for Linux 64 bits).
:rtype: int
:param path: the pathname of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
return self._stat(path, buf, True)
def sys_stat32(self, path, buf):
return self._stat(path, buf, False)
def _stat(self, path, buf, is64bit):
fd = self.sys_open(path, 0, 'r')
if is64bit:
ret = self.sys_fstat64(fd, buf)
else:
ret = self.sys_fstat(fd, buf)
self.sys_close(fd)
return ret
def _arch_specific_init(self):
assert self.arch in {'i386', 'amd64', 'armv7'}
if self.arch == 'i386':
self._uname_machine = 'i386'
elif self.arch == 'amd64':
self._uname_machine = 'x86_64'
elif self.arch == 'armv7':
self._uname_machine = 'armv71'
self._init_arm_kernel_helpers()
# Establish segment registers for x86 architectures
if self.arch in {'i386', 'amd64'}:
x86_defaults = {'CS': 0x23, 'SS': 0x2b, 'DS': 0x2b, 'ES': 0x2b}
for reg, val in x86_defaults.iteritems():
self.current.regfile.write(reg, val)
@staticmethod
def _interp_total_size(interp):
'''
Compute total load size of interpreter.
:param ELFFile interp: interpreter ELF .so
:return: total load size of interpreter, not aligned
:rtype: int
'''
load_segs = filter(lambda x: x.header.p_type == 'PT_LOAD', interp.iter_segments())
last = load_segs[-1]
return last.header.p_vaddr + last.header.p_memsz
############################################################################
# Symbolic versions follows
class SLinux(Linux):
"""
Builds a symbolic extension of a Linux OS
:param str programs: path to ELF binary
:param list argv: argv not including binary
:param list envp: environment variables
:param tuple[str] symbolic_files: files to consider symbolic
"""
def __init__(self, programs, argv=None, envp=None, symbolic_files=None):
argv = [] if argv is None else argv
envp = [] if envp is None else envp
symbolic_files = [] if symbolic_files is None else symbolic_files
self._constraints = ConstraintSet()
self.random = 0
self.symbolic_files = symbolic_files
super(SLinux, self).__init__(programs, argv, envp)
def _mk_proc(self, arch):
if arch in {'i386', 'armv7'}:
mem = SMemory32(self.constraints)
else:
mem = SMemory64(self.constraints)
return CpuFactory.get_cpu(mem, arch)
@property
def constraints(self):
return self._constraints
#marshaling/pickle
def __getstate__(self):
state = super(SLinux, self).__getstate__()
state['constraints'] = self.constraints
state['random'] = self.random
state['symbolic_files'] = self.symbolic_files
return state
def __setstate__(self, state):
self._constraints = state['constraints']
self.random = state['random']
self.symbolic_files = state['symbolic_files']
super(SLinux, self).__setstate__(state)
def _sys_open_get_file(self, filename, flags, mode):
if filename in self.symbolic_files:
logger.debug("%s file is considered symbolic", filename)
assert flags & 7 == os.O_RDWR or flags & 7 == os.O_RDONLY, (
"Symbolic files should be readable?")
f = SymbolicFile(self.constraints, filename, mode)
else:
f = super(SLinux, self)._sys_open_get_file(filename, flags, mode)
return f
#Dispatchers...
def sys_read(self, fd, buf, count):
if issymbolic(fd):
logger.debug("Ask to read from a symbolic file descriptor!!")
raise ConcretizeArgument(0)
if issymbolic(buf):
logger.debug("Ask to read to a symbolic buffer")
raise ConcretizeArgument(1)
if issymbolic(count):
logger.debug("Ask to read a symbolic number of bytes ")
raise ConcretizeArgument(2)
return super(SLinux, self).sys_read(fd, buf, count)
def sys_write(self, fd, buf, count):
if issymbolic(fd):
logger.debug("Ask to write to a symbolic file descriptor!!")
raise ConcretizeArgument(0)
if issymbolic(buf):
logger.debug("Ask to write to a symbolic buffer")
raise ConcretizeArgument(1)
if issymbolic(count):
logger.debug("Ask to write a symbolic number of bytes ")
raise ConcretizeArgument(2)
return super(SLinux, self).sys_write(fd, buf, count)
class DecreeEmu(object):
RANDOM = 0
@staticmethod
def cgc_initialize_secret_page(platform):
logger.info("Skipping: cgc_initialize_secret_page()")
return 0
@staticmethod
def cgc_random(platform, buf, count, rnd_bytes):
from . import cgcrandom
if issymbolic(buf):
logger.info("Ask to write random bytes to a symbolic buffer")
raise ConcretizeArgument(0)
if issymbolic(count):
logger.info("Ask to read a symbolic number of random bytes ")
raise ConcretizeArgument(1)
if issymbolic(rnd_bytes):
logger.info("Ask to return rnd size to a symbolic address ")
raise ConcretizeArgument(2)
data = []
for i in xrange(count):
value = cgcrandom.stream[DecreeEmu.RANDOM]
data.append(value)
DecreeEmu.random += 1
cpu = platform.current
cpu.write(buf, data)
if rnd_bytes:
cpu.store(rnd_bytes, len(data), 32)
logger.info("RANDOM(0x%08x, %d, 0x%08x) -> %d", buf, count, rnd_bytes, len(data))
return 0 | |
fs.rs | use std::borrow::Cow;
use std::collections::BTreeMap;
use std::convert::{TryFrom, TryInto};
use std::fs::{
read_dir, remove_dir, remove_file, rename, DirBuilder, File, FileType, OpenOptions, ReadDir,
};
use std::io::{self, ErrorKind, Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::time::SystemTime;
use log::trace;
use rustc_data_structures::fx::FxHashMap;
use rustc_middle::ty::{self, layout::LayoutOf};
use rustc_target::abi::{Align, Size};
use crate::*;
use helpers::{check_arg_count, immty_from_int_checked, immty_from_uint_checked};
use shims::time::system_time_to_duration;
#[derive(Debug)]
struct FileHandle {
file: File,
writable: bool,
}
trait FileDescriptor: std::fmt::Debug {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle>;
fn read<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>>;
fn write<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>>;
fn seek<'tcx>(
&mut self,
communicate_allowed: bool,
offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>>;
fn close<'tcx>(
self: Box<Self>,
_communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>>;
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>>;
}
impl FileDescriptor for FileHandle {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
Ok(&self)
}
fn read<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
Ok(self.file.read(bytes))
}
fn write<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
Ok(self.file.write(bytes))
}
fn seek<'tcx>(
&mut self,
communicate_allowed: bool,
offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
Ok(self.file.seek(offset))
}
fn close<'tcx>(
self: Box<Self>,
communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>> {
assert!(communicate_allowed, "isolation should have prevented even opening a file");
// We sync the file if it was opened in a mode different than read-only.
if self.writable {
// `File::sync_all` does the checks that are done when closing a file. We do this to
// to handle possible errors correctly.
let result = self.file.sync_all().map(|_| 0i32);
// Now we actually close the file.
drop(self);
// And return the result.
Ok(result)
} else {
// We drop the file, this closes it but ignores any errors
// produced when closing it. This is done because
// `File::sync_all` cannot be done over files like
// `/dev/urandom` which are read-only. Check
// https://github.com/rust-lang/miri/issues/999#issuecomment-568920439
// for a deeper discussion.
drop(self);
Ok(Ok(0))
}
}
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
let duplicated = self.file.try_clone()?;
Ok(Box::new(FileHandle { file: duplicated, writable: self.writable }))
}
}
impl FileDescriptor for io::Stdin {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
throw_unsup_format!("stdin cannot be used as FileHandle");
}
fn read<'tcx>(
&mut self,
communicate_allowed: bool,
bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>> {
if !communicate_allowed {
// We want isolation mode to be deterministic, so we have to disallow all reads, even stdin.
helpers::isolation_abort_error("`read` from stdin")?;
}
Ok(Read::read(self, bytes))
}
fn write<'tcx>(
&mut self,
_communicate_allowed: bool,
_bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>> {
throw_unsup_format!("cannot write to stdin");
}
fn seek<'tcx>(
&mut self,
_communicate_allowed: bool,
_offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
throw_unsup_format!("cannot seek on stdin");
}
fn close<'tcx>(
self: Box<Self>,
_communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>> {
throw_unsup_format!("stdin cannot be closed");
}
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
Ok(Box::new(io::stdin()))
}
}
impl FileDescriptor for io::Stdout {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
throw_unsup_format!("stdout cannot be used as FileHandle");
}
fn read<'tcx>(
&mut self,
_communicate_allowed: bool,
_bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>> {
throw_unsup_format!("cannot read from stdout");
}
fn write<'tcx>(
&mut self,
_communicate_allowed: bool,
bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>> {
// We allow writing to stderr even with isolation enabled.
let result = Write::write(self, bytes);
// Stdout is buffered, flush to make sure it appears on the
// screen. This is the write() syscall of the interpreted
// program, we want it to correspond to a write() syscall on
// the host -- there is no good in adding extra buffering
// here.
io::stdout().flush().unwrap();
Ok(result)
}
fn seek<'tcx>(
&mut self,
_communicate_allowed: bool,
_offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
throw_unsup_format!("cannot seek on stdout");
}
fn | <'tcx>(
self: Box<Self>,
_communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>> {
throw_unsup_format!("stdout cannot be closed");
}
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
Ok(Box::new(io::stdout()))
}
}
impl FileDescriptor for io::Stderr {
fn as_file_handle<'tcx>(&self) -> InterpResult<'tcx, &FileHandle> {
throw_unsup_format!("stderr cannot be used as FileHandle");
}
fn read<'tcx>(
&mut self,
_communicate_allowed: bool,
_bytes: &mut [u8],
) -> InterpResult<'tcx, io::Result<usize>> {
throw_unsup_format!("cannot read from stderr");
}
fn write<'tcx>(
&mut self,
_communicate_allowed: bool,
bytes: &[u8],
) -> InterpResult<'tcx, io::Result<usize>> {
// We allow writing to stderr even with isolation enabled.
// No need to flush, stderr is not buffered.
Ok(Write::write(self, bytes))
}
fn seek<'tcx>(
&mut self,
_communicate_allowed: bool,
_offset: SeekFrom,
) -> InterpResult<'tcx, io::Result<u64>> {
throw_unsup_format!("cannot seek on stderr");
}
fn close<'tcx>(
self: Box<Self>,
_communicate_allowed: bool,
) -> InterpResult<'tcx, io::Result<i32>> {
throw_unsup_format!("stderr cannot be closed");
}
fn dup<'tcx>(&mut self) -> io::Result<Box<dyn FileDescriptor>> {
Ok(Box::new(io::stderr()))
}
}
#[derive(Debug)]
pub struct FileHandler {
handles: BTreeMap<i32, Box<dyn FileDescriptor>>,
}
impl<'tcx> Default for FileHandler {
fn default() -> Self {
let mut handles: BTreeMap<_, Box<dyn FileDescriptor>> = BTreeMap::new();
handles.insert(0i32, Box::new(io::stdin()));
handles.insert(1i32, Box::new(io::stdout()));
handles.insert(2i32, Box::new(io::stderr()));
FileHandler { handles }
}
}
impl<'tcx> FileHandler {
fn insert_fd(&mut self, file_handle: Box<dyn FileDescriptor>) -> i32 {
self.insert_fd_with_min_fd(file_handle, 0)
}
fn insert_fd_with_min_fd(&mut self, file_handle: Box<dyn FileDescriptor>, min_fd: i32) -> i32 {
// Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
// between used FDs, the find_map combinator will return it. If the first such unused FD
// is after all other used FDs, the find_map combinator will return None, and we will use
// the FD following the greatest FD thus far.
let candidate_new_fd =
self.handles.range(min_fd..).zip(min_fd..).find_map(|((fd, _fh), counter)| {
if *fd != counter {
// There was a gap in the fds stored, return the first unused one
// (note that this relies on BTreeMap iterating in key order)
Some(counter)
} else {
// This fd is used, keep going
None
}
});
let new_fd = candidate_new_fd.unwrap_or_else(|| {
// find_map ran out of BTreeMap entries before finding a free fd, use one plus the
// maximum fd in the map
self.handles
.last_key_value()
.map(|(fd, _)| fd.checked_add(1).unwrap())
.unwrap_or(min_fd)
});
self.handles.try_insert(new_fd, file_handle).unwrap();
new_fd
}
}
impl<'mir, 'tcx: 'mir> EvalContextExtPrivate<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
fn macos_stat_write_buf(
&mut self,
metadata: FileMetadata,
buf_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let mode: u16 = metadata.mode.to_u16()?;
let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
let dev_t_layout = this.libc_ty_layout("dev_t")?;
let mode_t_layout = this.libc_ty_layout("mode_t")?;
let nlink_t_layout = this.libc_ty_layout("nlink_t")?;
let ino_t_layout = this.libc_ty_layout("ino_t")?;
let uid_t_layout = this.libc_ty_layout("uid_t")?;
let gid_t_layout = this.libc_ty_layout("gid_t")?;
let time_t_layout = this.libc_ty_layout("time_t")?;
let long_layout = this.libc_ty_layout("c_long")?;
let off_t_layout = this.libc_ty_layout("off_t")?;
let blkcnt_t_layout = this.libc_ty_layout("blkcnt_t")?;
let blksize_t_layout = this.libc_ty_layout("blksize_t")?;
let uint32_t_layout = this.libc_ty_layout("uint32_t")?;
let imms = [
immty_from_uint_checked(0u128, dev_t_layout)?, // st_dev
immty_from_uint_checked(mode, mode_t_layout)?, // st_mode
immty_from_uint_checked(0u128, nlink_t_layout)?, // st_nlink
immty_from_uint_checked(0u128, ino_t_layout)?, // st_ino
immty_from_uint_checked(0u128, uid_t_layout)?, // st_uid
immty_from_uint_checked(0u128, gid_t_layout)?, // st_gid
immty_from_uint_checked(0u128, dev_t_layout)?, // st_rdev
immty_from_uint_checked(0u128, uint32_t_layout)?, // padding
immty_from_uint_checked(access_sec, time_t_layout)?, // st_atime
immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec
immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime
immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec
immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime
immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec
immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime
immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec
immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size
immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks
immty_from_uint_checked(0u128, blksize_t_layout)?, // st_blksize
immty_from_uint_checked(0u128, uint32_t_layout)?, // st_flags
immty_from_uint_checked(0u128, uint32_t_layout)?, // st_gen
];
let buf = this.deref_operand(buf_op)?;
this.write_packed_immediates(&buf, &imms)?;
Ok(0)
}
/// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
/// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
/// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
/// types (like `read`, that returns an `i64`).
fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
let this = self.eval_context_mut();
let ebadf = this.eval_libc("EBADF")?;
this.set_last_error(ebadf)?;
Ok((-1).into())
}
fn file_type_to_d_type(
&mut self,
file_type: std::io::Result<FileType>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
match file_type {
Ok(file_type) => {
if file_type.is_dir() {
Ok(this.eval_libc("DT_DIR")?.to_u8()?.into())
} else if file_type.is_file() {
Ok(this.eval_libc("DT_REG")?.to_u8()?.into())
} else if file_type.is_symlink() {
Ok(this.eval_libc("DT_LNK")?.to_u8()?.into())
} else {
// Certain file types are only supported when the host is a Unix system.
// (i.e. devices and sockets) If it is, check those cases, if not, fall back to
// DT_UNKNOWN sooner.
#[cfg(unix)]
{
use std::os::unix::fs::FileTypeExt;
if file_type.is_block_device() {
Ok(this.eval_libc("DT_BLK")?.to_u8()?.into())
} else if file_type.is_char_device() {
Ok(this.eval_libc("DT_CHR")?.to_u8()?.into())
} else if file_type.is_fifo() {
Ok(this.eval_libc("DT_FIFO")?.to_u8()?.into())
} else if file_type.is_socket() {
Ok(this.eval_libc("DT_SOCK")?.to_u8()?.into())
} else {
Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
}
}
#[cfg(not(unix))]
Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
}
}
Err(e) =>
return match e.raw_os_error() {
Some(error) => Ok(error),
None =>
throw_unsup_format!(
"the error {} couldn't be converted to a return value",
e
),
},
}
}
}
#[derive(Debug)]
pub struct DirHandler {
/// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
/// and closedir.
///
/// When opendir is called, a directory iterator is created on the host for the target
/// directory, and an entry is stored in this hash map, indexed by an ID which represents
/// the directory stream. When readdir is called, the directory stream ID is used to look up
/// the corresponding ReadDir iterator from this map, and information from the next
/// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
/// the map.
streams: FxHashMap<u64, ReadDir>,
/// ID number to be used by the next call to opendir
next_id: u64,
}
impl DirHandler {
fn insert_new(&mut self, read_dir: ReadDir) -> u64 {
let id = self.next_id;
self.next_id += 1;
self.streams.try_insert(id, read_dir).unwrap();
id
}
}
impl Default for DirHandler {
fn default() -> DirHandler {
DirHandler {
streams: FxHashMap::default(),
// Skip 0 as an ID, because it looks like a null pointer to libc
next_id: 1,
}
}
}
fn maybe_sync_file(
file: &File,
writable: bool,
operation: fn(&File) -> std::io::Result<()>,
) -> std::io::Result<i32> {
if !writable && cfg!(windows) {
// sync_all() and sync_data() will return an error on Windows hosts if the file is not opened
// for writing. (FlushFileBuffers requires that the file handle have the
// GENERIC_WRITE right)
Ok(0i32)
} else {
let result = operation(file);
result.map(|_| 0i32)
}
}
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
fn open(&mut self, args: &[OpTy<'tcx, Tag>]) -> InterpResult<'tcx, i32> {
if args.len() < 2 || args.len() > 3 {
throw_ub_format!(
"incorrect number of arguments for `open`: got {}, expected 2 or 3",
args.len()
);
}
let this = self.eval_context_mut();
let path_op = &args[0];
let flag = this.read_scalar(&args[1])?.to_i32()?;
let mut options = OpenOptions::new();
let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
let o_wronly = this.eval_libc_i32("O_WRONLY")?;
let o_rdwr = this.eval_libc_i32("O_RDWR")?;
// The first two bits of the flag correspond to the access mode in linux, macOS and
// windows. We need to check that in fact the access mode flags for the current target
// only use these two bits, otherwise we are in an unsupported target and should error.
if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
throw_unsup_format!("access mode flags on this target are unsupported");
}
let mut writable = true;
// Now we check the access mode
let access_mode = flag & 0b11;
if access_mode == o_rdonly {
writable = false;
options.read(true);
} else if access_mode == o_wronly {
options.write(true);
} else if access_mode == o_rdwr {
options.read(true).write(true);
} else {
throw_unsup_format!("unsupported access mode {:#x}", access_mode);
}
// We need to check that there aren't unsupported options in `flag`. For this we try to
// reproduce the content of `flag` in the `mirror` variable using only the supported
// options.
let mut mirror = access_mode;
let o_append = this.eval_libc_i32("O_APPEND")?;
if flag & o_append != 0 {
options.append(true);
mirror |= o_append;
}
let o_trunc = this.eval_libc_i32("O_TRUNC")?;
if flag & o_trunc != 0 {
options.truncate(true);
mirror |= o_trunc;
}
let o_creat = this.eval_libc_i32("O_CREAT")?;
if flag & o_creat != 0 {
// Get the mode. On macOS, the argument type `mode_t` is actually `u16`, but
// C integer promotion rules mean that on the ABI level, it gets passed as `u32`
// (see https://github.com/rust-lang/rust/issues/71915).
let mode = if let Some(arg) = args.get(2) {
this.read_scalar(arg)?.to_u32()?
} else {
throw_ub_format!(
"incorrect number of arguments for `open` with `O_CREAT`: got {}, expected 3",
args.len()
);
};
if mode != 0o666 {
throw_unsup_format!("non-default mode 0o{:o} is not supported", mode);
}
mirror |= o_creat;
let o_excl = this.eval_libc_i32("O_EXCL")?;
if flag & o_excl != 0 {
mirror |= o_excl;
options.create_new(true);
} else {
options.create(true);
}
}
let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
if flag & o_cloexec != 0 {
// We do not need to do anything for this flag because `std` already sets it.
// (Technically we do not support *not* setting this flag, but we ignore that.)
mirror |= o_cloexec;
}
// If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
// then we throw an error.
if flag != mirror {
throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
}
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`open`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let fd = options.open(&path).map(|file| {
let fh = &mut this.machine.file_handler;
fh.insert_fd(Box::new(FileHandle { file, writable }))
});
this.try_unwrap_io_result(fd)
}
fn fcntl(&mut self, args: &[OpTy<'tcx, Tag>]) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
if args.len() < 2 {
throw_ub_format!(
"incorrect number of arguments for fcntl: got {}, expected at least 2",
args.len()
);
}
let fd = this.read_scalar(&args[0])?.to_i32()?;
let cmd = this.read_scalar(&args[1])?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fcntl`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
// We only support getting the flags for a descriptor.
if cmd == this.eval_libc_i32("F_GETFD")? {
// Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
// `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
// always sets this flag when opening a file. However we still need to check that the
// file itself is open.
let &[_, _] = check_arg_count(args)?;
if this.machine.file_handler.handles.contains_key(&fd) {
Ok(this.eval_libc_i32("FD_CLOEXEC")?)
} else {
this.handle_not_found()
}
} else if cmd == this.eval_libc_i32("F_DUPFD")?
|| cmd == this.eval_libc_i32("F_DUPFD_CLOEXEC")?
{
// Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
// because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
// differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
// thus they can share the same implementation here.
let &[_, _, ref start] = check_arg_count(args)?;
let start = this.read_scalar(start)?.to_i32()?;
let fh = &mut this.machine.file_handler;
match fh.handles.get_mut(&fd) {
Some(file_descriptor) => {
let dup_result = file_descriptor.dup();
match dup_result {
Ok(dup_fd) => Ok(fh.insert_fd_with_min_fd(dup_fd, start)),
Err(e) => {
this.set_last_error_from_io_error(e.kind())?;
Ok(-1)
}
}
}
None => return this.handle_not_found(),
}
} else if this.tcx.sess.target.os == "macos" && cmd == this.eval_libc_i32("F_FULLFSYNC")? {
let &[_, _] = check_arg_count(args)?;
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
// FIXME: Support fullfsync for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
let io_result = maybe_sync_file(&file, *writable, File::sync_all);
this.try_unwrap_io_result(io_result)
} else {
this.handle_not_found()
}
} else {
throw_unsup_format!("the {:#x} command is not supported for `fcntl`)", cmd);
}
}
fn close(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
if let Some(file_descriptor) = this.machine.file_handler.handles.remove(&fd) {
let result = file_descriptor.close(this.machine.communicate())?;
this.try_unwrap_io_result(result)
} else {
this.handle_not_found()
}
}
fn read(&mut self, fd: i32, buf: Pointer<Option<Tag>>, count: u64) -> InterpResult<'tcx, i64> {
let this = self.eval_context_mut();
// Isolation check is done via `FileDescriptor` trait.
trace!("Reading from FD {}, size {}", fd, count);
// Check that the *entire* buffer is actually valid memory.
this.memory.check_ptr_access_align(
buf,
Size::from_bytes(count),
Align::ONE,
CheckInAllocMsg::MemoryAccessTest,
)?;
// We cap the number of read bytes to the largest value that we are able to fit in both the
// host's and target's `isize`. This saves us from having to handle overflows later.
let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
let communicate = this.machine.communicate();
if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
trace!("read: FD mapped to {:?}", file_descriptor);
// We want to read at most `count` bytes. We are sure that `count` is not negative
// because it was a target's `usize`. Also we are sure that its smaller than
// `usize::MAX` because it is a host's `isize`.
let mut bytes = vec![0; count as usize];
// `File::read` never returns a value larger than `count`,
// so this cannot fail.
let result =
file_descriptor.read(communicate, &mut bytes)?.map(|c| i64::try_from(c).unwrap());
match result {
Ok(read_bytes) => {
// If reading to `bytes` did not fail, we write those bytes to the buffer.
this.memory.write_bytes(buf, bytes)?;
Ok(read_bytes)
}
Err(e) => {
this.set_last_error_from_io_error(e.kind())?;
Ok(-1)
}
}
} else {
trace!("read: FD not found");
this.handle_not_found()
}
}
fn write(&mut self, fd: i32, buf: Pointer<Option<Tag>>, count: u64) -> InterpResult<'tcx, i64> {
let this = self.eval_context_mut();
// Isolation check is done via `FileDescriptor` trait.
// Check that the *entire* buffer is actually valid memory.
this.memory.check_ptr_access_align(
buf,
Size::from_bytes(count),
Align::ONE,
CheckInAllocMsg::MemoryAccessTest,
)?;
// We cap the number of written bytes to the largest value that we are able to fit in both the
// host's and target's `isize`. This saves us from having to handle overflows later.
let count = count.min(this.machine_isize_max() as u64).min(isize::MAX as u64);
let communicate = this.machine.communicate();
if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
let result =
file_descriptor.write(communicate, &bytes)?.map(|c| i64::try_from(c).unwrap());
this.try_unwrap_io_result(result)
} else {
this.handle_not_found()
}
}
fn lseek64(
&mut self,
fd_op: &OpTy<'tcx, Tag>,
offset_op: &OpTy<'tcx, Tag>,
whence_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i64> {
let this = self.eval_context_mut();
// Isolation check is done via `FileDescriptor` trait.
let fd = this.read_scalar(fd_op)?.to_i32()?;
let offset = this.read_scalar(offset_op)?.to_i64()?;
let whence = this.read_scalar(whence_op)?.to_i32()?;
let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
SeekFrom::Start(u64::try_from(offset).unwrap())
} else if whence == this.eval_libc_i32("SEEK_CUR")? {
SeekFrom::Current(offset)
} else if whence == this.eval_libc_i32("SEEK_END")? {
SeekFrom::End(offset)
} else {
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
return Ok(-1);
};
let communicate = this.machine.communicate();
if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
let result = file_descriptor
.seek(communicate, seek_from)?
.map(|offset| i64::try_from(offset).unwrap());
this.try_unwrap_io_result(result)
} else {
this.handle_not_found()
}
}
fn unlink(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`unlink`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let result = remove_file(path).map(|_| 0);
this.try_unwrap_io_result(result)
}
fn symlink(
&mut self,
target_op: &OpTy<'tcx, Tag>,
linkpath_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
#[cfg(unix)]
fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
#[cfg(windows)]
fn create_link(src: &Path, dst: &Path) -> std::io::Result<()> {
use std::os::windows::fs;
if src.is_dir() { fs::symlink_dir(src, dst) } else { fs::symlink_file(src, dst) }
}
let this = self.eval_context_mut();
let target = this.read_path_from_c_str(this.read_pointer(target_op)?)?;
let linkpath = this.read_path_from_c_str(this.read_pointer(linkpath_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`symlink`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let result = create_link(&target, &linkpath).map(|_| 0);
this.try_unwrap_io_result(result)
}
fn macos_stat(
&mut self,
path_op: &OpTy<'tcx, Tag>,
buf_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("macos", "stat");
let path_scalar = this.read_pointer(path_op)?;
let path = this.read_path_from_c_str(path_scalar)?.into_owned();
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`stat`", reject_with)?;
let eacc = this.eval_libc("EACCES")?;
this.set_last_error(eacc)?;
return Ok(-1);
}
// `stat` always follows symlinks.
let metadata = match FileMetadata::from_path(this, &path, true)? {
Some(metadata) => metadata,
None => return Ok(-1),
};
this.macos_stat_write_buf(metadata, buf_op)
}
// `lstat` is used to get symlink metadata.
fn macos_lstat(
&mut self,
path_op: &OpTy<'tcx, Tag>,
buf_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("macos", "lstat");
let path_scalar = this.read_pointer(path_op)?;
let path = this.read_path_from_c_str(path_scalar)?.into_owned();
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`lstat`", reject_with)?;
let eacc = this.eval_libc("EACCES")?;
this.set_last_error(eacc)?;
return Ok(-1);
}
let metadata = match FileMetadata::from_path(this, &path, false)? {
Some(metadata) => metadata,
None => return Ok(-1),
};
this.macos_stat_write_buf(metadata, buf_op)
}
fn macos_fstat(
&mut self,
fd_op: &OpTy<'tcx, Tag>,
buf_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("macos", "fstat");
let fd = this.read_scalar(fd_op)?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fstat`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
let metadata = match FileMetadata::from_fd(this, fd)? {
Some(metadata) => metadata,
None => return Ok(-1),
};
this.macos_stat_write_buf(metadata, buf_op)
}
fn linux_statx(
&mut self,
dirfd_op: &OpTy<'tcx, Tag>, // Should be an `int`
pathname_op: &OpTy<'tcx, Tag>, // Should be a `const char *`
flags_op: &OpTy<'tcx, Tag>, // Should be an `int`
_mask_op: &OpTy<'tcx, Tag>, // Should be an `unsigned int`
statxbuf_op: &OpTy<'tcx, Tag>, // Should be a `struct statx *`
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("linux", "statx");
let statxbuf_ptr = this.read_pointer(statxbuf_op)?;
let pathname_ptr = this.read_pointer(pathname_op)?;
// If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
if this.ptr_is_null(statxbuf_ptr)? || this.ptr_is_null(pathname_ptr)? {
let efault = this.eval_libc("EFAULT")?;
this.set_last_error(efault)?;
return Ok(-1);
}
// Under normal circumstances, we would use `deref_operand(statxbuf_op)` to produce a
// proper `MemPlace` and then write the results of this function to it. However, the
// `syscall` function is untyped. This means that all the `statx` parameters are provided
// as `isize`s instead of having the proper types. Thus, we have to recover the layout of
// `statxbuf_op` by using the `libc::statx` struct type.
let statxbuf_place = {
// FIXME: This long path is required because `libc::statx` is an struct and also a
// function and `resolve_path` is returning the latter.
let statx_ty = this
.resolve_path(&["libc", "unix", "linux_like", "linux", "gnu", "statx"])
.ty(*this.tcx, ty::ParamEnv::reveal_all());
let statx_layout = this.layout_of(statx_ty)?;
MPlaceTy::from_aligned_ptr(statxbuf_ptr, statx_layout)
};
let path = this.read_path_from_c_str(pathname_ptr)?.into_owned();
// See <https://github.com/rust-lang/rust/pull/79196> for a discussion of argument sizes.
let flags = this.read_scalar(flags_op)?.to_i32()?;
let empty_path_flag = flags & this.eval_libc("AT_EMPTY_PATH")?.to_i32()? != 0;
let dirfd = this.read_scalar(dirfd_op)?.to_i32()?;
// We only support:
// * interpreting `path` as an absolute directory,
// * interpreting `path` as a path relative to `dirfd` when the latter is `AT_FDCWD`, or
// * interpreting `dirfd` as any file descriptor when `path` is empty and AT_EMPTY_PATH is
// set.
// Other behaviors cannot be tested from `libstd` and thus are not implemented. If you
// found this error, please open an issue reporting it.
if !(path.is_absolute()
|| dirfd == this.eval_libc_i32("AT_FDCWD")?
|| (path.as_os_str().is_empty() && empty_path_flag))
{
throw_unsup_format!(
"using statx is only supported with absolute paths, relative paths with the file \
descriptor `AT_FDCWD`, and empty paths with the `AT_EMPTY_PATH` flag set and any \
file descriptor"
)
}
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`statx`", reject_with)?;
let ecode = if path.is_absolute() || dirfd == this.eval_libc_i32("AT_FDCWD")? {
// since `path` is provided, either absolute or
// relative to CWD, `EACCES` is the most relevant.
this.eval_libc("EACCES")?
} else {
// `dirfd` is set to target file, and `path` is empty
// (or we would have hit the `throw_unsup_format`
// above). `EACCES` would violate the spec.
assert!(empty_path_flag);
this.eval_libc("EBADF")?
};
this.set_last_error(ecode)?;
return Ok(-1);
}
// the `_mask_op` paramter specifies the file information that the caller requested.
// However `statx` is allowed to return information that was not requested or to not
// return information that was requested. This `mask` represents the information we can
// actually provide for any target.
let mut mask =
this.eval_libc("STATX_TYPE")?.to_u32()? | this.eval_libc("STATX_SIZE")?.to_u32()?;
// If the `AT_SYMLINK_NOFOLLOW` flag is set, we query the file's metadata without following
// symbolic links.
let follow_symlink = flags & this.eval_libc("AT_SYMLINK_NOFOLLOW")?.to_i32()? == 0;
// If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
// represented by dirfd, whether it's a directory or otherwise.
let metadata = if path.as_os_str().is_empty() && empty_path_flag {
FileMetadata::from_fd(this, dirfd)?
} else {
FileMetadata::from_path(this, &path, follow_symlink)?
};
let metadata = match metadata {
Some(metadata) => metadata,
None => return Ok(-1),
};
// The `mode` field specifies the type of the file and the permissions over the file for
// the owner, its group and other users. Given that we can only provide the file type
// without using platform specific methods, we only set the bits corresponding to the file
// type. This should be an `__u16` but `libc` provides its values as `u32`.
let mode: u16 = metadata
.mode
.to_u32()?
.try_into()
.unwrap_or_else(|_| bug!("libc contains bad value for constant"));
// We need to set the corresponding bits of `mask` if the access, creation and modification
// times were available. Otherwise we let them be zero.
let (access_sec, access_nsec) = metadata
.accessed
.map(|tup| {
mask |= this.eval_libc("STATX_ATIME")?.to_u32()?;
InterpResult::Ok(tup)
})
.unwrap_or(Ok((0, 0)))?;
let (created_sec, created_nsec) = metadata
.created
.map(|tup| {
mask |= this.eval_libc("STATX_BTIME")?.to_u32()?;
InterpResult::Ok(tup)
})
.unwrap_or(Ok((0, 0)))?;
let (modified_sec, modified_nsec) = metadata
.modified
.map(|tup| {
mask |= this.eval_libc("STATX_MTIME")?.to_u32()?;
InterpResult::Ok(tup)
})
.unwrap_or(Ok((0, 0)))?;
let __u32_layout = this.libc_ty_layout("__u32")?;
let __u64_layout = this.libc_ty_layout("__u64")?;
let __u16_layout = this.libc_ty_layout("__u16")?;
// Now we transform all this fields into `ImmTy`s and write them to `statxbuf`. We write a
// zero for the unavailable fields.
let imms = [
immty_from_uint_checked(mask, __u32_layout)?, // stx_mask
immty_from_uint_checked(0u128, __u32_layout)?, // stx_blksize
immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
immty_from_uint_checked(0u128, __u32_layout)?, // stx_nlink
immty_from_uint_checked(0u128, __u32_layout)?, // stx_uid
immty_from_uint_checked(0u128, __u32_layout)?, // stx_gid
immty_from_uint_checked(mode, __u16_layout)?, // stx_mode
immty_from_uint_checked(0u128, __u16_layout)?, // statx padding
immty_from_uint_checked(0u128, __u64_layout)?, // stx_ino
immty_from_uint_checked(metadata.size, __u64_layout)?, // stx_size
immty_from_uint_checked(0u128, __u64_layout)?, // stx_blocks
immty_from_uint_checked(0u128, __u64_layout)?, // stx_attributes
immty_from_uint_checked(access_sec, __u64_layout)?, // stx_atime.tv_sec
immty_from_uint_checked(access_nsec, __u32_layout)?, // stx_atime.tv_nsec
immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
immty_from_uint_checked(created_sec, __u64_layout)?, // stx_btime.tv_sec
immty_from_uint_checked(created_nsec, __u32_layout)?, // stx_btime.tv_nsec
immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
immty_from_uint_checked(0u128, __u64_layout)?, // stx_ctime.tv_sec
immty_from_uint_checked(0u128, __u32_layout)?, // stx_ctime.tv_nsec
immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
immty_from_uint_checked(modified_sec, __u64_layout)?, // stx_mtime.tv_sec
immty_from_uint_checked(modified_nsec, __u32_layout)?, // stx_mtime.tv_nsec
immty_from_uint_checked(0u128, __u32_layout)?, // statx_timestamp padding
immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_major
immty_from_uint_checked(0u128, __u64_layout)?, // stx_rdev_minor
immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_major
immty_from_uint_checked(0u128, __u64_layout)?, // stx_dev_minor
];
this.write_packed_immediates(&statxbuf_place, &imms)?;
Ok(0)
}
fn rename(
&mut self,
oldpath_op: &OpTy<'tcx, Tag>,
newpath_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let oldpath_ptr = this.read_pointer(oldpath_op)?;
let newpath_ptr = this.read_pointer(newpath_op)?;
if this.ptr_is_null(oldpath_ptr)? || this.ptr_is_null(newpath_ptr)? {
let efault = this.eval_libc("EFAULT")?;
this.set_last_error(efault)?;
return Ok(-1);
}
let oldpath = this.read_path_from_c_str(oldpath_ptr)?;
let newpath = this.read_path_from_c_str(newpath_ptr)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`rename`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let result = rename(oldpath, newpath).map(|_| 0);
this.try_unwrap_io_result(result)
}
fn mkdir(
&mut self,
path_op: &OpTy<'tcx, Tag>,
mode_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
#[cfg_attr(not(unix), allow(unused_variables))]
let mode = if this.tcx.sess.target.os == "macos" {
u32::from(this.read_scalar(mode_op)?.to_u16()?)
} else {
this.read_scalar(mode_op)?.to_u32()?
};
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`mkdir`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
#[cfg_attr(not(unix), allow(unused_mut))]
let mut builder = DirBuilder::new();
// If the host supports it, forward on the mode of the directory
// (i.e. permission bits and the sticky bit)
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(mode.into());
}
let result = builder.create(path).map(|_| 0i32);
this.try_unwrap_io_result(result)
}
fn rmdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`rmdir`", reject_with)?;
this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
return Ok(-1);
}
let result = remove_dir(path).map(|_| 0i32);
this.try_unwrap_io_result(result)
}
fn opendir(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
let this = self.eval_context_mut();
let name = this.read_path_from_c_str(this.read_pointer(name_op)?)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`opendir`", reject_with)?;
let eacc = this.eval_libc("EACCES")?;
this.set_last_error(eacc)?;
return Ok(Scalar::null_ptr(this));
}
let result = read_dir(name);
match result {
Ok(dir_iter) => {
let id = this.machine.dir_handler.insert_new(dir_iter);
// The libc API for opendir says that this method returns a pointer to an opaque
// structure, but we are returning an ID number. Thus, pass it as a scalar of
// pointer width.
Ok(Scalar::from_machine_usize(id, this))
}
Err(e) => {
this.set_last_error_from_io_error(e.kind())?;
Ok(Scalar::null_ptr(this))
}
}
}
fn linux_readdir64_r(
&mut self,
dirp_op: &OpTy<'tcx, Tag>,
entry_op: &OpTy<'tcx, Tag>,
result_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("linux", "readdir64_r");
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`readdir64_r`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
err_unsup_format!("the DIR pointer passed to readdir64_r did not come from opendir")
})?;
match dir_iter.next() {
Some(Ok(dir_entry)) => {
// Write into entry, write pointer to result, return 0 on success.
// The name is written with write_os_str_to_c_str, while the rest of the
// dirent64 struct is written using write_packed_immediates.
// For reference:
// pub struct dirent64 {
// pub d_ino: ino64_t,
// pub d_off: off64_t,
// pub d_reclen: c_ushort,
// pub d_type: c_uchar,
// pub d_name: [c_char; 256],
// }
let entry_place = this.deref_operand(entry_op)?;
let name_place = this.mplace_field(&entry_place, 4)?;
let file_name = dir_entry.file_name(); // not a Path as there are no separators!
let (name_fits, _) = this.write_os_str_to_c_str(
&file_name,
name_place.ptr,
name_place.layout.size.bytes(),
)?;
if !name_fits {
throw_unsup_format!(
"a directory entry had a name too large to fit in libc::dirent64"
);
}
let entry_place = this.deref_operand(entry_op)?;
let ino64_t_layout = this.libc_ty_layout("ino64_t")?;
let off64_t_layout = this.libc_ty_layout("off64_t")?;
let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
// If the host is a Unix system, fill in the inode number with its real value.
// If not, use 0 as a fallback value.
#[cfg(unix)]
let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
#[cfg(not(unix))]
let ino = 0u64;
let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
let imms = [
immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
];
this.write_packed_immediates(&entry_place, &imms)?;
let result_place = this.deref_operand(result_op)?;
this.write_scalar(this.read_scalar(entry_op)?, &result_place.into())?;
Ok(0)
}
None => {
// end of stream: return 0, assign *result=NULL
this.write_null(&this.deref_operand(result_op)?.into())?;
Ok(0)
}
Some(Err(e)) =>
match e.raw_os_error() {
// return positive error number on error
Some(error) => Ok(error),
None => {
throw_unsup_format!(
"the error {} couldn't be converted to a return value",
e
)
}
},
}
}
fn macos_readdir_r(
&mut self,
dirp_op: &OpTy<'tcx, Tag>,
entry_op: &OpTy<'tcx, Tag>,
result_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
this.assert_target_os("macos", "readdir_r");
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`readdir_r`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
let dir_iter = this.machine.dir_handler.streams.get_mut(&dirp).ok_or_else(|| {
err_unsup_format!("the DIR pointer passed to readdir_r did not come from opendir")
})?;
match dir_iter.next() {
Some(Ok(dir_entry)) => {
// Write into entry, write pointer to result, return 0 on success.
// The name is written with write_os_str_to_c_str, while the rest of the
// dirent struct is written using write_packed_Immediates.
// For reference:
// pub struct dirent {
// pub d_ino: u64,
// pub d_seekoff: u64,
// pub d_reclen: u16,
// pub d_namlen: u16,
// pub d_type: u8,
// pub d_name: [c_char; 1024],
// }
let entry_place = this.deref_operand(entry_op)?;
let name_place = this.mplace_field(&entry_place, 5)?;
let file_name = dir_entry.file_name(); // not a Path as there are no separators!
let (name_fits, file_name_len) = this.write_os_str_to_c_str(
&file_name,
name_place.ptr,
name_place.layout.size.bytes(),
)?;
if !name_fits {
throw_unsup_format!(
"a directory entry had a name too large to fit in libc::dirent"
);
}
let entry_place = this.deref_operand(entry_op)?;
let ino_t_layout = this.libc_ty_layout("ino_t")?;
let off_t_layout = this.libc_ty_layout("off_t")?;
let c_ushort_layout = this.libc_ty_layout("c_ushort")?;
let c_uchar_layout = this.libc_ty_layout("c_uchar")?;
// If the host is a Unix system, fill in the inode number with its real value.
// If not, use 0 as a fallback value.
#[cfg(unix)]
let ino = std::os::unix::fs::DirEntryExt::ino(&dir_entry);
#[cfg(not(unix))]
let ino = 0u64;
let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
let imms = [
immty_from_uint_checked(ino, ino_t_layout)?, // d_ino
immty_from_uint_checked(0u128, off_t_layout)?, // d_seekoff
immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
immty_from_uint_checked(file_name_len, c_ushort_layout)?, // d_namlen
immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
];
this.write_packed_immediates(&entry_place, &imms)?;
let result_place = this.deref_operand(result_op)?;
this.write_scalar(this.read_scalar(entry_op)?, &result_place.into())?;
Ok(0)
}
None => {
// end of stream: return 0, assign *result=NULL
this.write_null(&this.deref_operand(result_op)?.into())?;
Ok(0)
}
Some(Err(e)) =>
match e.raw_os_error() {
// return positive error number on error
Some(error) => Ok(error),
None => {
throw_unsup_format!(
"the error {} couldn't be converted to a return value",
e
)
}
},
}
}
fn closedir(&mut self, dirp_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let dirp = this.read_scalar(dirp_op)?.to_machine_usize(this)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`closedir`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(dir_iter) = this.machine.dir_handler.streams.remove(&dirp) {
drop(dir_iter);
Ok(0)
} else {
this.handle_not_found()
}
}
fn ftruncate64(
&mut self,
fd_op: &OpTy<'tcx, Tag>,
length_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
let length = this.read_scalar(length_op)?.to_i64()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`ftruncate64`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(file_descriptor) = this.machine.file_handler.handles.get_mut(&fd) {
// FIXME: Support ftruncate64 for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
if *writable {
if let Ok(length) = length.try_into() {
let result = file.set_len(length);
this.try_unwrap_io_result(result.map(|_| 0i32))
} else {
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
Ok(-1)
}
} else {
// The file is not writable
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
Ok(-1)
}
} else {
this.handle_not_found()
}
}
fn fsync(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
// On macOS, `fsync` (unlike `fcntl(F_FULLFSYNC)`) does not wait for the
// underlying disk to finish writing. In the interest of host compatibility,
// we conservatively implement this with `sync_all`, which
// *does* wait for the disk.
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fsync`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
// FIXME: Support fsync for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
let io_result = maybe_sync_file(&file, *writable, File::sync_all);
this.try_unwrap_io_result(io_result)
} else {
this.handle_not_found()
}
}
fn fdatasync(&mut self, fd_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`fdatasync`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
// FIXME: Support fdatasync for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
let io_result = maybe_sync_file(&file, *writable, File::sync_data);
this.try_unwrap_io_result(io_result)
} else {
this.handle_not_found()
}
}
fn sync_file_range(
&mut self,
fd_op: &OpTy<'tcx, Tag>,
offset_op: &OpTy<'tcx, Tag>,
nbytes_op: &OpTy<'tcx, Tag>,
flags_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i32> {
let this = self.eval_context_mut();
let fd = this.read_scalar(fd_op)?.to_i32()?;
let offset = this.read_scalar(offset_op)?.to_i64()?;
let nbytes = this.read_scalar(nbytes_op)?.to_i64()?;
let flags = this.read_scalar(flags_op)?.to_i32()?;
if offset < 0 || nbytes < 0 {
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
return Ok(-1);
}
let allowed_flags = this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_BEFORE")?
| this.eval_libc_i32("SYNC_FILE_RANGE_WRITE")?
| this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_AFTER")?;
if flags & allowed_flags != flags {
let einval = this.eval_libc("EINVAL")?;
this.set_last_error(einval)?;
return Ok(-1);
}
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`sync_file_range`", reject_with)?;
// Set error code as "EBADF" (bad fd)
return this.handle_not_found();
}
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
// FIXME: Support sync_data_range for all FDs
let FileHandle { file, writable } = file_descriptor.as_file_handle()?;
let io_result = maybe_sync_file(&file, *writable, File::sync_data);
this.try_unwrap_io_result(io_result)
} else {
this.handle_not_found()
}
}
fn readlink(
&mut self,
pathname_op: &OpTy<'tcx, Tag>,
buf_op: &OpTy<'tcx, Tag>,
bufsize_op: &OpTy<'tcx, Tag>,
) -> InterpResult<'tcx, i64> {
let this = self.eval_context_mut();
let pathname = this.read_path_from_c_str(this.read_pointer(pathname_op)?)?;
let buf = this.read_pointer(buf_op)?;
let bufsize = this.read_scalar(bufsize_op)?.to_machine_usize(this)?;
// Reject if isolation is enabled.
if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
this.reject_in_isolation("`readlink`", reject_with)?;
let eacc = this.eval_libc("EACCES")?;
this.set_last_error(eacc)?;
return Ok(-1);
}
let result = std::fs::read_link(pathname);
match result {
Ok(resolved) => {
let resolved = this.convert_path_separator(
Cow::Borrowed(resolved.as_ref()),
crate::shims::os_str::PathConversion::HostToTarget,
);
let mut path_bytes = crate::shims::os_str::os_str_to_bytes(resolved.as_ref())?;
let bufsize: usize = bufsize.try_into().unwrap();
if path_bytes.len() > bufsize {
path_bytes = &path_bytes[..bufsize]
}
// 'readlink' truncates the resolved path if
// the provided buffer is not large enough.
this.memory.write_bytes(buf, path_bytes.iter().copied())?;
Ok(path_bytes.len().try_into().unwrap())
}
Err(e) => {
this.set_last_error_from_io_error(e.kind())?;
Ok(-1)
}
}
}
}
/// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
/// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
/// epoch.
fn extract_sec_and_nsec<'tcx>(
time: std::io::Result<SystemTime>,
) -> InterpResult<'tcx, Option<(u64, u32)>> {
time.ok()
.map(|time| {
let duration = system_time_to_duration(&time)?;
Ok((duration.as_secs(), duration.subsec_nanos()))
})
.transpose()
}
/// Stores a file's metadata in order to avoid code duplication in the different metadata related
/// shims.
struct FileMetadata {
mode: Scalar<Tag>,
size: u64,
created: Option<(u64, u32)>,
accessed: Option<(u64, u32)>,
modified: Option<(u64, u32)>,
}
impl FileMetadata {
fn from_path<'tcx, 'mir>(
ecx: &mut MiriEvalContext<'mir, 'tcx>,
path: &Path,
follow_symlink: bool,
) -> InterpResult<'tcx, Option<FileMetadata>> {
let metadata =
if follow_symlink { std::fs::metadata(path) } else { std::fs::symlink_metadata(path) };
FileMetadata::from_meta(ecx, metadata)
}
fn from_fd<'tcx, 'mir>(
ecx: &mut MiriEvalContext<'mir, 'tcx>,
fd: i32,
) -> InterpResult<'tcx, Option<FileMetadata>> {
let option = ecx.machine.file_handler.handles.get(&fd);
let file = match option {
Some(file_descriptor) => &file_descriptor.as_file_handle()?.file,
None => return ecx.handle_not_found().map(|_: i32| None),
};
let metadata = file.metadata();
FileMetadata::from_meta(ecx, metadata)
}
fn from_meta<'tcx, 'mir>(
ecx: &mut MiriEvalContext<'mir, 'tcx>,
metadata: Result<std::fs::Metadata, std::io::Error>,
) -> InterpResult<'tcx, Option<FileMetadata>> {
let metadata = match metadata {
Ok(metadata) => metadata,
Err(e) => {
ecx.set_last_error_from_io_error(e.kind())?;
return Ok(None);
}
};
let file_type = metadata.file_type();
let mode_name = if file_type.is_file() {
"S_IFREG"
} else if file_type.is_dir() {
"S_IFDIR"
} else {
"S_IFLNK"
};
let mode = ecx.eval_libc(mode_name)?;
let size = metadata.len();
let created = extract_sec_and_nsec(metadata.created())?;
let accessed = extract_sec_and_nsec(metadata.accessed())?;
let modified = extract_sec_and_nsec(metadata.modified())?;
// FIXME: Provide more fields using platform specific methods.
Ok(Some(FileMetadata { mode, size, created, accessed, modified }))
}
}
| close |
part_authority_discovery.rs | use super::*;
parameter_types! {
pub const MaxAuthorities: u32 = 100;
} |
impl pallet_authority_discovery::Config for Runtime {
type MaxAuthorities = MaxAuthorities;
} | |
mount.rs | #![allow(dead_code)]
use std::ffi::CString;
use std::fs::{read_link};
use std::io::{ErrorKind, Error as IoError};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path};
use std::ptr::null;
use libc::{c_ulong, c_int};
use libmount::BindMount;
use super::super::path_util::ToCString;
// sys/mount.h
static MS_RDONLY: c_ulong = 1; /* Mount read-only. */
static MS_NOSUID: c_ulong = 2; /* Ignore suid and sgid bits. */
static MS_NODEV: c_ulong = 4; /* Disallow access to device special files. */
static MS_NOEXEC: c_ulong = 8; /* Disallow program execution. */
static MS_SYNCHRONOUS: c_ulong = 16; /* Writes are synced at once. */
static MS_REMOUNT: c_ulong = 32; /* Alter flags of a mounted FS. */
static MS_MANDLOCK: c_ulong = 64; /* Allow mandatory locks on an FS. */
static MS_DIRSYNC: c_ulong = 128; /* Directory modifications are synchronous. */
static MS_NOATIME: c_ulong = 1024; /* Do not update access times. */
static MS_NODIRATIME: c_ulong = 2048; /* Do not update directory access times. */
static MS_BIND: c_ulong = 4096; /* Bind directory at different place. */
static MS_MOVE: c_ulong = 8192;
static MS_REC: c_ulong = 16384;
static MS_SILENT: c_ulong = 32768;
static MS_POSIXACL: c_ulong = 1 << 16; /* VFS does not apply the umask. */
static MS_UNBINDABLE: c_ulong = 1 << 17; /* Change to unbindable. */
static MS_PRIVATE: c_ulong = 1 << 18; /* Change to private. */
static MS_SLAVE: c_ulong = 1 << 19; /* Change to slave. */
static MS_SHARED: c_ulong = 1 << 20; /* Change to shared. */
static MS_RELATIME: c_ulong = 1 << 21; /* Update atime relative to mtime/ctime. */
static MS_KERNMOUNT: c_ulong = 1 << 22; /* This is a kern_mount call. */
static MS_I_VERSION: c_ulong = 1 << 23; /* Update inode I_version field. */
static MS_STRICTATIME: c_ulong = 1 << 24; /* Always perform atime updates. */
static MS_ACTIVE: c_ulong = 1 << 30;
static MS_NOUSER: c_ulong = 1 << 31;
static MNT_FORCE: c_int = 1; /* Force unmounting. */
static MNT_DETACH: c_int = 2; /* Just detach from the tree. */
static MNT_EXPIRE: c_int = 4; /* Mark for expiry. */
static UMOUNT_NOFOLLOW: c_int = 8; /* Don't follow symlink on umount. */
extern {
fn mount(source: *const u8, target: *const u8,
filesystemtype: *const u8, flags: c_ulong,
data: *const u8) -> c_int;
fn umount(target: *const u8) -> c_int;
fn umount2(target: *const u8, flags: c_int) -> c_int;
}
pub fn remount_ro(target: &Path) -> Result<(), String> {
let none = CString::new("none").unwrap();
debug!("Remount readonly: {:?}", target);
let c_target = target.to_cstring();
let rc = unsafe { mount(
none.as_bytes().as_ptr(),
c_target.as_bytes().as_ptr(),
null(), MS_BIND|MS_REMOUNT|MS_RDONLY, null()) };
if rc != 0 {
let err = IoError::last_os_error();
return Err(format!("Remount readonly {:?}: {}", target, err));
}
return Ok(());
}
pub fn mount_private(target: &Path) -> Result<(), String> {
let none = CString::new("none").unwrap();
let c_target = target.to_cstring();
debug!("Making private {:?}", target);
let rc = unsafe { mount(
none.as_bytes().as_ptr(),
c_target.as_bytes().as_ptr(),
null(), MS_PRIVATE, null()) };
if rc == 0 {
return Ok(());
} else {
let err = IoError::last_os_error();
return Err(format!("Can't make {:?} a slave: {}", target, err));
}
}
pub fn mount_proc(target: &Path) -> Result<(), String>
{
let c_target = target.to_cstring();
// I don't know why we need this flag for mounting proc, but it's somehow
// works (see https://github.com/tailhook/vagga/issues/12 for the
// error it fixes)
let flags = 0xC0ED0000; //MS_MGC_VAL
debug!("Procfs mount {:?}", target);
let rc = unsafe { mount(
b"proc\x00".as_ptr(), c_target.as_bytes().as_ptr(),
b"proc\x00".as_ptr(), flags, null()) };
if rc == 0 {
return Ok(());
} else {
let err = IoError::last_os_error();
return Err(format!("Can't mount proc at {:?}: {}",
target, err));
}
}
pub fn mount_pseudo(target: &Path, name: &str, options: &str)
-> Result<(), String>
{
let c_name = name.to_cstring();
let c_target = target.to_cstring();
let c_opts = options.to_cstring();
// Seems this is similar to why proc is mounted with the flag
let flags = 0xC0ED0000; //MS_MGC_VAL
debug!("Pseusofs mount {:?} {} {}", target, name, options);
let rc = unsafe { mount(
c_name.as_bytes().as_ptr(),
c_target.as_bytes().as_ptr(),
c_name.as_bytes().as_ptr(),
flags,
c_opts.as_bytes().as_ptr()) };
if rc == 0 {
return Ok(());
} else {
let err = IoError::last_os_error();
return Err(format!("Can't mount pseudofs {:?} ({}, options: {}): {}",
target, options, name, err));
}
}
#[cfg(not(feature="containers"))]
pub fn unmount(target: &Path) -> Result<(), String> {
unimplemented!();
}
#[cfg(feature="containers")]
pub fn unmount(target: &Path) -> Result<(), String> {
let c_target = target.to_cstring();
let rc = unsafe { umount2(c_target.as_bytes().as_ptr(), MNT_DETACH) };
if rc == 0 {
return Ok(());
} else {
let err = IoError::last_os_error();
return Err(format!("Can't unmount {:?} : {}", target, err));
}
}
pub fn mount_system_dirs() -> Result<(), String> {
try!(mount_dev(&Path::new("/vagga/root/dev")));
try!(BindMount::new("/sys", "/vagga/root/sys").mount()
.map_err(|e| e.to_string()));
try!(mount_proc(&Path::new("/vagga/root/proc")));
try!(BindMount::new("/work", "/vagga/root/work").mount()
.map_err(|e| e.to_string()));
return Ok(())
}
pub fn unmount_system_dirs() -> Result<(), String> |
pub fn mount_dev(dev_dir: &Path) -> Result<(), String> {
try!(BindMount::new("/dev", &dev_dir).mount()
.map_err(|e| e.to_string()));
let pts_dir = dev_dir.join("pts");
try!(mount_pseudo(&pts_dir, "devpts", "newinstance"));
let ptmx_path = dev_dir.join("ptmx");
match read_link(&ptmx_path) {
Ok(x) => {
if Path::new(&x) != Path::new("/dev/pts/ptmx")
&& Path::new(&x) != Path::new("pts/ptmx")
{
warn!("The /dev/ptmx refers to {:?}. We need /dev/pts/ptmx \
to operate properly. \
Probably pseudo-ttys will not work", x);
}
}
Err(ref e) if e.kind() == ErrorKind::InvalidInput => {
// It's just a device. Let's try bind mount
try!(BindMount::new(pts_dir.join("ptmx"), &ptmx_path).mount()
.map_err(|e| e.to_string()));
}
Err(e) => {
warn!("Can't stat /dev/ptmx: {}. \
Probably pseudo-ttys will not work", e);
}
}
Ok(())
}
| {
try!(unmount(Path::new("/vagga/root/work")));
try!(unmount(Path::new("/vagga/root/proc")));
try!(unmount(Path::new("/vagga/root/sys")));
try!(unmount(Path::new("/vagga/root/dev")));
Ok(())
} |
params.rs | // Copyright 2020 Shift Crypto AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
|
/// Parameters for BTC-like coins. See also:
/// https://en.bitcoin.it/wiki/List_of_address_prefixes
pub struct Params {
/// https://github.com/satoshilabs/slips/blob/master/slip-0044.md
pub bip44_coin: u32,
pub base58_version_p2pkh: u8,
pub base58_version_p2sh: u8,
pub bech32_hrp: &'static str,
pub name: &'static str,
pub unit: &'static str,
pub rbf_support: bool,
}
/// Keep these in sync with btc_params.c.
const PARAMS_BTC: Params = Params {
bip44_coin: 0 + HARDENED,
base58_version_p2pkh: 0x00, // starts with 1
base58_version_p2sh: 0x05, // starts with 3
bech32_hrp: "bc",
name: "Bitcoin",
unit: "BTC",
rbf_support: true,
};
const PARAMS_TBTC: Params = Params {
bip44_coin: 1 + HARDENED,
base58_version_p2pkh: 0x6f, // starts with m or n
base58_version_p2sh: 0xc4, // starts with 2
bech32_hrp: "tb",
name: "BTC Testnet",
unit: "TBTC",
rbf_support: true,
};
const PARAMS_LTC: Params = Params {
bip44_coin: 2 + HARDENED,
base58_version_p2pkh: 0x30, // starts with L
base58_version_p2sh: 0x32, // starts with M
bech32_hrp: "ltc",
name: "Litecoin",
unit: "LTC",
rbf_support: false,
};
const PARAMS_TLTC: Params = Params {
bip44_coin: 1 + HARDENED,
base58_version_p2pkh: 0x6f, // starts with m or n
base58_version_p2sh: 0xc4, // starts with 2
bech32_hrp: "tltc",
name: "LTC Testnet",
unit: "TLTC",
rbf_support: false,
};
pub fn get(coin: BtcCoin) -> &'static Params {
use BtcCoin::*;
match coin {
Btc => &PARAMS_BTC,
Tbtc => &PARAMS_TBTC,
Ltc => &PARAMS_LTC,
Tltc => &PARAMS_TLTC,
}
} | use super::pb;
use pb::BtcCoin;
use util::bip32::HARDENED; |
exporter.go | // Copyright 2017-2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package exporter is a Prometheus exporter for NATS.
package exporter
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"io/ioutil"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/nats-io/prometheus-nats-exporter/collector"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/crypto/bcrypt"
)
const (
modeStarted uint8 = iota + 1
modeStopped
)
// NATSExporterOptions are options to configure the NATS collector
type NATSExporterOptions struct {
collector.LoggerOptions
ListenAddress string
ListenPort int
ScrapePath string
GetConnz bool
GetVarz bool
GetSubz bool
GetRoutez bool
GetGatewayz bool
GetReplicatorVarz bool
GetStreamingChannelz bool
GetStreamingServerz bool
RetryInterval time.Duration
CertFile string
KeyFile string
CaFile string
NATSServerURL string
NATSServerTag string
HTTPUser string // User in metrics scrape by prometheus.
HTTPPassword string
Prefix string
UseInternalServerID bool
}
// NATSExporter collects NATS metrics
type NATSExporter struct {
sync.Mutex
opts *NATSExporterOptions
doneWg sync.WaitGroup
http net.Listener
collectors []prometheus.Collector
servers []*collector.CollectedServer
mode uint8
}
// Defaults
var (
DefaultListenPort = 7777
DefaultListenAddress = "0.0.0.0"
DefaultScrapePath = "/metrics"
DefaultMonitorURL = "http://localhost:8222"
DefaultRetryIntervalSecs = 30
// bcryptPrefix from gnatsd
bcryptPrefix = "$2a$"
)
// GetDefaultExporterOptions returns the default set of exporter options
// The NATS server url must be set
func | () *NATSExporterOptions {
opts := &NATSExporterOptions{
ListenAddress: DefaultListenAddress,
ListenPort: DefaultListenPort,
ScrapePath: DefaultScrapePath,
RetryInterval: time.Duration(DefaultRetryIntervalSecs) * time.Second,
}
return opts
}
// NewExporter creates a new NATS exporter
func NewExporter(opts *NATSExporterOptions) *NATSExporter {
o := opts
if o == nil {
o = GetDefaultExporterOptions()
o.GetVarz = true
}
collector.ConfigureLogger(&o.LoggerOptions)
ne := &NATSExporter{
opts: o,
http: nil,
}
if o.NATSServerURL != "" {
_ = ne.AddServer(o.NATSServerTag, o.NATSServerURL)
}
return ne
}
func (ne *NATSExporter) createCollector(system, endpoint string) {
ne.registerCollector(system, endpoint,
collector.NewCollector(system, endpoint,
ne.opts.Prefix,
ne.servers))
}
func (ne *NATSExporter) registerCollector(system, endpoint string, nc prometheus.Collector) {
if err := prometheus.Register(nc); err != nil {
if _, ok := err.(prometheus.AlreadyRegisteredError); ok {
collector.Errorf("A collector for this server's metrics has already been registered.")
} else {
collector.Debugf("Unable to register collector %s (%v), Retrying.", endpoint, err)
time.AfterFunc(ne.opts.RetryInterval, func() {
collector.Debugf("Creating a collector for endpoint: %s", endpoint)
ne.Lock()
ne.createCollector(system, endpoint)
ne.Unlock()
})
}
} else {
collector.Debugf("Registered collector for system %s, endpoint: %s", system, endpoint)
ne.collectors = append(ne.collectors, nc)
}
}
// AddServer is an advanced API; normally the NATS server should be set
// through the options. Adding more than one server will
// violate Prometheus.io guidelines.
func (ne *NATSExporter) AddServer(id, url string) error {
ne.Lock()
defer ne.Unlock()
if ne.mode == modeStarted {
return fmt.Errorf("servers cannot be added after the exporter is started")
}
cs := &collector.CollectedServer{ID: id, URL: url}
if ne.servers == nil {
ne.servers = make([]*collector.CollectedServer, 0)
}
ne.servers = append(ne.servers, cs)
return nil
}
// initializeCollectors initializes the collectors for the exporter.
// Caller must lock
func (ne *NATSExporter) initializeCollectors() error {
opts := ne.opts
if len(ne.servers) == 0 {
return fmt.Errorf("no servers configured to obtain metrics")
}
if !opts.GetConnz && !opts.GetRoutez && !opts.GetSubz && !opts.GetVarz &&
!opts.GetGatewayz && !opts.GetStreamingChannelz &&
!opts.GetStreamingServerz && !opts.GetReplicatorVarz {
return fmt.Errorf("no collectors specfied")
}
if opts.GetReplicatorVarz && opts.GetVarz {
return fmt.Errorf("replicatorVarz cannot be used with varz")
}
if opts.GetSubz {
ne.createCollector(collector.CoreSystem, "subsz")
}
if opts.GetVarz {
ne.createCollector(collector.CoreSystem, "varz")
}
if opts.GetConnz {
ne.createCollector(collector.CoreSystem, "connz")
}
if opts.GetGatewayz {
ne.createCollector(collector.CoreSystem, "gatewayz")
}
if opts.GetRoutez {
ne.createCollector(collector.CoreSystem, "routez")
}
if opts.GetStreamingChannelz {
ne.createCollector(collector.StreamingSystem, "channelsz")
}
if opts.GetStreamingServerz {
ne.createCollector(collector.StreamingSystem, "serverz")
}
if opts.GetReplicatorVarz {
ne.createCollector(collector.ReplicatorSystem, "varz")
}
return nil
}
// caller must lock
func (ne *NATSExporter) clearCollectors() {
if ne.collectors != nil {
for _, c := range ne.collectors {
prometheus.Unregister(c)
}
ne.collectors = nil
}
}
// Start runs the exporter process.
func (ne *NATSExporter) Start() error {
ne.Lock()
defer ne.Unlock()
if ne.mode == modeStarted {
return nil
}
if err := ne.initializeCollectors(); err != nil {
ne.clearCollectors()
return err
}
if err := ne.startHTTP(); err != nil {
ne.clearCollectors()
return fmt.Errorf("error serving http: %v", err)
}
ne.doneWg.Add(1)
ne.mode = modeStarted
return nil
}
// generates the TLS config for https
func (ne *NATSExporter) generateTLSConfig() (*tls.Config, error) {
// Load in cert and private key
cert, err := tls.LoadX509KeyPair(ne.opts.CertFile, ne.opts.KeyFile)
if err != nil {
return nil, fmt.Errorf("error parsing X509 certificate/key pair (%s, %s): %v",
ne.opts.CertFile, ne.opts.KeyFile, err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return nil, fmt.Errorf("error parsing certificate (%s): %v",
ne.opts.CertFile, err)
}
// Create our TLS configuration
config := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.NoClientCert,
MinVersion: tls.VersionTLS12,
}
// Add in CAs if applicable.
if ne.opts.CaFile != "" {
rootPEM, err := ioutil.ReadFile(ne.opts.CaFile)
if err != nil || rootPEM == nil {
return nil, fmt.Errorf("failed to load root ca certificate (%s): %v", ne.opts.CaFile, err)
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(rootPEM)
if !ok {
return nil, fmt.Errorf("failed to parse root ca certificate")
}
config.ClientCAs = pool
}
return config, nil
}
// isBcrypt checks whether the given password or token is bcrypted.
func isBcrypt(password string) bool {
return strings.HasPrefix(password, bcryptPrefix)
}
func (ne *NATSExporter) isValidUserPass(user, password string) bool {
if user != ne.opts.HTTPUser {
return false
}
exporterPassword := ne.opts.HTTPPassword
if isBcrypt(exporterPassword) {
if err := bcrypt.CompareHashAndPassword([]byte(exporterPassword), []byte(password)); err != nil {
return false
}
} else if exporterPassword != password {
return false
}
return true
}
// getScrapeHandler returns the default handler if no nttp
// auhtorization has been specificed. Otherwise, it checks
// basic authorization.
func (ne *NATSExporter) getScrapeHandler() http.Handler {
h := promhttp.Handler()
if ne.opts.HTTPUser != "" {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(auth) != 2 || auth[0] != "Basic" {
http.Error(rw, "authorization failed", http.StatusUnauthorized)
return
}
payload, err := base64.StdEncoding.DecodeString(auth[1])
if err != nil {
http.Error(rw, "authorization failed", http.StatusBadRequest)
return
}
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) != 2 || !ne.isValidUserPass(pair[0], pair[1]) {
http.Error(rw, "authorization failed", http.StatusUnauthorized)
return
}
h.ServeHTTP(rw, r)
})
}
return h
}
// startHTTP configures and starts the HTTP server for applications to poll data from
// exporter.
// caller must lock
func (ne *NATSExporter) startHTTP() error {
var hp string
var path string
var err error
var proto string
var config *tls.Config
hp = net.JoinHostPort(ne.opts.ListenAddress, strconv.Itoa(ne.opts.ListenPort))
path = ne.opts.ScrapePath
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
// If a certificate file has been specified, setup TLS with the
// key provided.
if ne.opts.CertFile != "" {
proto = "https"
collector.Debugf("Certificate file specfied; using https.")
config, err = ne.generateTLSConfig()
if err != nil {
return err
}
ne.http, err = tls.Listen("tcp", hp, config)
} else {
proto = "http"
collector.Debugf("No certificate file specified; using http.")
ne.http, err = net.Listen("tcp", hp)
}
collector.Noticef("Prometheus exporter listening at %s://%s%s", proto, hp, path)
if err != nil {
collector.Errorf("can't start HTTP listener: %v", err)
return err
}
mux := http.NewServeMux()
mux.Handle(path, ne.getScrapeHandler())
srv := &http.Server{
Addr: hp,
Handler: mux,
MaxHeaderBytes: 1 << 20,
TLSConfig: config,
}
sHTTP := ne.http
go func() {
for i := 0; i < 10; i++ {
var err error
if err = srv.Serve(sHTTP); err != nil {
// In a test environment, this can fail because the server is
// already running.
srvState := ne.getMode()
if srvState == modeStopped {
collector.Debugf("Server has been stopped, skipping reconnects")
return
}
collector.Debugf("Unable to start HTTP server (mode=%d): %v", srvState, err)
} else {
collector.Debugf("Started HTTP server.")
}
}
}()
return nil
}
func (ne *NATSExporter) getMode() uint8 {
ne.Lock()
mode := ne.mode
ne.Unlock()
return mode
}
// WaitUntilDone blocks until the collector is stopped.
func (ne *NATSExporter) WaitUntilDone() {
ne.Lock()
wg := &ne.doneWg
ne.Unlock()
wg.Wait()
}
// Stop stops the collector.
func (ne *NATSExporter) Stop() {
collector.Debugf("Stopping.")
ne.Lock()
defer ne.Unlock()
if ne.mode == modeStopped {
return
}
if err := ne.http.Close(); err != nil {
collector.Debugf("Did not close HTTP: %v", err)
}
ne.clearCollectors()
ne.doneWg.Done()
ne.mode = modeStopped
}
| GetDefaultExporterOptions |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-22 19:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Choice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
],
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.AddField(
model_name='choice',
name='question',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'),
),
] |
|
app.js | /* jshint node: true */
"use strict";
var options = require('./options');
var fs = require('fs');
var exists = require('./exists');
var cluster = require('cluster');
var makeserver = require('./makeserver');
function portInUse(port, host, callback) {
var server = require('net').createServer();
server.listen(port, host);
server.on('error', function () {
callback(true);
});
server.on('listening', function () {
server.close();
callback(false);
});
}
function error(message) {
console.error('Error: ' + message);
process.exit(1);
}
function warn(message) {
console.warn('Warning: ' + message);
}
function runMaster() {
function | () {
console.log('(TerriaJS-Server exiting.)');
if (fs.existsSync('terriajs.pid')) {
fs.unlinkSync('terriajs.pid');
}
process.exit(0);
}
var cpuCount = require('os').cpus().length;
// Let's equate non-public, localhost mode with "single-cpu, don't restart".
if (options.listenHost === 'localhost') {
cpuCount = 1;
}
console.log('Serving directory "' + options.wwwroot + '" on port ' + options.port + ' to ' + (options.listenHost ? options.listenHost: 'the world') + '.');
require('./controllers/convert')().testGdal();
if (!exists(options.wwwroot)) {
warn('"' + options.wwwroot + '" does not exist.');
} else if (!exists(options.wwwroot + '/index.html')) {
warn('"' + options.wwwroot + '" is not a TerriaJS wwwroot directory.');
} else if (!exists(options.wwwroot + '/build')) {
warn('"' + options.wwwroot + '" has not been built. You should do this:\n\n' +
'> cd ' + options.wwwroot + '/..\n' +
'> gulp\n');
}
if (typeof options.settings.allowProxyFor === 'undefined') {
warn('The configuration does not contain a "allowProxyFor" list. The server will proxy _any_ request.');
}
process.on('SIGTERM', handleExit);
// Listen for dying workers
cluster.on('exit', function (worker) {
if (!worker.suicide) {
// Replace the dead worker if not a startup error like port in use.
if (options.listenHost === 'localhost') {
console.log('Worker ' + worker.id + ' died. Not replacing it as we\'re running in non-public mode.');
} else {
console.log('Worker ' + worker.id + ' died. Replacing it.');
cluster.fork();
}
}
});
fs.writeFileSync('terriajs.pid', process.pid.toString());
console.log('(TerriaJS-Server running with pid ' + process.pid + ')');
console.log('Launching ' + cpuCount + ' worker processes.');
// Create a worker for each CPU
for (var i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
}
function startServer(options) {
makeserver(options).listen(options.port, options.listenHost);
}
if (cluster.isMaster) {
// The master process just spins up a few workers and quits.
console.log ('TerriaJS Server ' + require('../package.json').version);
options.init();
if (fs.existsSync('terriajs.pid')) {
warn('TerriaJS-Server seems to already be running.');
}
portInUse(options.port, options.listenHost, function (inUse) {
if (inUse) {
error('Port ' + options.port + ' is in use. Exiting.');
} else {
if (options.listenHost !== 'localhost') {
runMaster();
} else {
// Let's equate non-public, localhost mode with "single-cpu, don't restart".
startServer(options);
}
}
});
return;
} else {
// We're a forked process.
options.init(true);
startServer(options);
}
| handleExit |
auth.go | package auth
import (
"fmt"
"net/http"
"time"
"github.com/gorilla/context"
"github.com/gorilla/securecookie"
"github.com/oesmith/agr/db"
"github.com/oesmith/agr/db/model"
)
import "flag"
const (
authCookie = "auth"
cookieExpiry = time.Hour * 24 * 60 // 60-day cookie validity
userKey = "oesmith/agr/user"
)
var (
cookieKeyFlag = flag.String("cookie_key", "", "Key for encrypted auth cookies")
passwordSaltFlag = flag.String("password_salt", "", "Salt used for password auth")
)
type Auth struct {
PingHandler http.Handler
db db.DB
passwordSalt []byte
secureCookie *securecookie.SecureCookie
}
func New(db db.DB) *Auth {
return newAuthWithKeys(db, []byte(*cookieKeyFlag), []byte(*passwordSaltFlag))
}
func (a *Auth) AuthCookie(u string) (*http.Cookie, error) {
value := map[string]string{
"username": u,
}
encoded, err := a.secureCookie.Encode(authCookie, value)
if err != nil {
return nil, err
}
ret := &http.Cookie{
Name: authCookie,
Value: encoded,
Path: "/",
HttpOnly: true,
Expires: time.Now().Add(cookieExpiry),
}
return ret, nil
}
// VerifyCookie checks the given cookie is valid and returns the username
// encoded within.
func (a *Auth) VerifyCookie(c *http.Cookie) (*model.User, error) {
value := make(map[string]string)
if err := a.secureCookie.Decode(authCookie, c.Value, &value); err != nil {
return nil, err
}
u, err := a.db.GetUser(value["username"])
if err != nil {
return nil, err
}
return u, nil
}
func (a * Auth) RequireUser(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie(authCookie); err == nil && c != nil {
if u, err := a.VerifyCookie(c); err == nil {
context.Set(r, userKey, u)
h.ServeHTTP(w, r)
return
}
}
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
})
}
func (a *Auth) pingHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "OK")
}
func | (db db.DB, cookieKey []byte, passwordSalt []byte) *Auth {
if len(cookieKey) != 64 {
panic("Cookie key should be 64 bytes long")
}
a := &Auth{
db: db,
passwordSalt: passwordSalt,
secureCookie: securecookie.New(cookieKey, nil),
}
a.PingHandler = a.RequireUser(http.HandlerFunc(a.pingHandler))
return a
}
| newAuthWithKeys |
tib-functions.js | // version 12
var tibWindow = null;
var tibWindowCheck = null;
function | (payaddr, subref) // open tibdit window, watch for closing
{
tibWindow= window.open("https://tib.tibdit.com/t/" + payaddr + "/" + subref + "?callback_url=" + encodeURIComponent(window.location) ,
"tibdit", "height=600,width=700,menubar=no,location=no,resizable=no,status=no");
tibWindowCheck= setInterval(function(){bd_plugin_tibbedReload();}, 1000); // 100);
tibWindow.focus();
}
function bd_plugin_tibbedReload() // reload on tibdit window close
{
if (tibWindow.closed)
{
clearInterval(tibWindowCheck);
location.reload();
}
}
function bd_plugin_getCookie(cname) // get the cookie based on a name
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i];
while (c.charAt(0)==' ') { c = c.substring(1); }
if (c.indexOf(name) != -1) { return c.substring(name.length,c.length); }
}
return "";
}
function bd_plugin_tibbed(subref) // tell me if there are cookies
{
return (bd_plugin_getCookie('tibbed_'+subref)) ? true : false;
}
function bd_plugin_setCookie(lifespan, subref) // set the tibbed cookie and give it a lifespan (minutes / days)
{
var expires = new Date();
expires.setTime(expires.getTime() + lifespan * 60 * 1000 ); // -> microseconds
document.cookie = 'tibbed_'+ subref + '=true;expires=' + expires.toUTCString() +'"';
}
function bd_plugin_lowercase_tib( f)
{
ss = f.selectionStart;
se = f.selectionEnd;
f.value = f.value.replace( /([Tt][iI][bB])([^ACE-Zace-z][\w]*|$)/g, function(tibword) { return tibword.toLowerCase(); } );
f.setSelectionRange(ss,se);
}
function bd_plugin_anytibbedcookies()
{
var tibsfound = document.cookie.search('tibbed');
if (tibsfound == -1)
{
var buttons = document.getElementsByClassName("bd button");
for( i=0; i<buttons.length; i++)
{
buttons[i].className += " show";
console.log(buttons[i]);
}
return true;
}
return false;
}
| bd_plugin_tib |
rejuvenate.py | from gui.rejuv_gui import RejuvGUI
from controller import Controller
'''
Program: Rejuvenate
Author: Drew Crawford
Last Date Modified: 12/14/21
Purpose: The is program will update installed addons
from the game The Elder Scrolls Online.
Input: The uesr will select the Addon folder if not
found, they will also correct any incorrectly
matched addons by selecting them and then selecting
the correct addon match from the complete list.
Output: Various screens of feedback, lists of installed
addons with web name matches, installed addons
with versions and installed addons with web versions.
'''
root = RejuvGUI()
if Controller.is_initial():
root.create_setup_screen()
local_addon_path = Controller.find_local_addon_folder()
if local_addon_path == '':
|
else:
root.create_db_update_screen()
else:
root.create_compare_msg_screen()
if __name__ == '__main__':
root.mainloop() | root.create_not_found_screen() |
lib.rs | // SPDX-License-Identifier: Apache-2.0
//! Intel SGX Documentation is available at the following link.
//! Section references in further documentation refer to this document.
//! https://www.intel.com/content/dam/www/public/emea/xe/en/documents/manuals/64-ia-32-architectures-software-developer-vol-3d-part-4-manual.pdf
#![no_std]
#![deny(clippy::all)]
#![allow(clippy::identity_op)]
#![deny(missing_docs)]
pub mod attr;
pub mod isv;
pub mod misc;
pub mod page;
pub mod report;
pub mod secs; | pub mod ti; | pub mod sig;
pub mod ssa;
pub mod tcs; |
local.strategy.ts | import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { Strategy } from "passport-local";
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy){
constructor(private readonly authService:AuthService){
super()
}
async validate(username:string,password:string):Promise<any>{
const user = await this.authService.validateUser(username,password);
if(!user){
throw new UnauthorizedException();
}
return user
} |
} |
|
identity.go | /*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package msp
import (
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core"
"github.com/pkg/errors"
)
var (
// ErrUserNotFound indicates the user was not found
ErrUserNotFound = errors.New("user not found")
)
// IdentityOption captures options used for creating a new SigningIdentity instance
type IdentityOption struct {
Cert []byte
PrivateKey []byte
}
// SigningIdentityOption describes a functional parameter for creating a new SigningIdentity instance
type SigningIdentityOption func(*IdentityOption) error
// WithPrivateKey can be passed as an option when creating a new SigningIdentity.
// It cannot be used without the WithCert option
func WithPrivateKey(key []byte) SigningIdentityOption {
return func(o *IdentityOption) error {
o.PrivateKey = key
return nil
}
}
// WithCert can be passed as an option when creating a new SigningIdentity.
// When used alone, SDK will lookup the corresponding private key.
func WithCert(cert []byte) SigningIdentityOption {
return func(o *IdentityOption) error {
o.Cert = cert | }
// IdentityManager provides management of identities in Fabric network
type IdentityManager interface {
GetSigningIdentity(name string) (SigningIdentity, error)
CreateSigningIdentity(ops ...SigningIdentityOption) (SigningIdentity, error)
}
// Identity represents a Fabric client identity
type Identity interface {
// Identifier returns the identifier of that identity
Identifier() *IdentityIdentifier
// Verify a signature over some message using this identity as reference
Verify(msg []byte, sig []byte) error
// Serialize converts an identity to bytes
Serialize() ([]byte, error)
// EnrollmentCertificate Returns the underlying ECert representing this user’s identity.
EnrollmentCertificate() []byte
}
// SigningIdentity is an extension of Identity to cover signing capabilities.
type SigningIdentity interface {
// Extends Identity
Identity
// Sign the message
Sign(msg []byte) ([]byte, error)
// GetPublicVersion returns the public parts of this identity
PublicVersion() Identity
// PrivateKey returns the crypto suite representation of the private key
PrivateKey() core.Key
}
// IdentityIdentifier is a holder for the identifier of a specific
// identity, naturally namespaced, by its provider identifier.
type IdentityIdentifier struct {
// The identifier of the associated membership service provider
MSPID string
// The identifier for an identity within a provider
ID string
} | return nil
} |
Conf.js | /**
* fileOverview:
* Project:
* File: Conf
* Date:
* Author:
*/
// import SoundData from './Data/Sound.js';
export default class Conf {
constructor() {
// ------------------------------------------------------------
// 本番フラグ
// ------------------------------------------------------------
this.RELEASE = true;
// this.RELEASE = false;
// ------------------------------------------------------------
// フラグ関連
// ------------------------------------------------------------
this.FLG = {
LOG:true, // ログ出力
PARAM:true, // パラメータチェック
STATS:true // Stats表示
};
if (!this.RELEASE) {
this.FLG = {
LOG:false,
PARAM:false,
STATS:false
};
}
// ------------------------------------------------------------
// 基本 width height
// ------------------------------------------------------------
this.defW = 1300;
this.defH = 850;
this.W = 1200;
this.H = 750;
this.spW = 375;
this.spH = 667;
// ------------------------------------------------------------
// ブレイクポイント
// ------------------------------------------------------------
this.bp = 768; | // ------------------------------------------------------------
this.mode = null;
this.keys = [
{
'key': 'movie',
'value': ['morning','afternoon','night'],
},
{
'key': 'data',
'value': ['data01','data02','data03'],
},
{
'key': 'product',
'value': ['01'],
},
]
this.switchMode();
// ------------------------------------------------------------
// sound data
// ------------------------------------------------------------
// this.soundData = new SoundData();
// ------------------------------------------------------------
// sec02 bg Img Num
// ------------------------------------------------------------
this.sec02ImgNum = 396;
// ------------------------------------------------------------
// youtube ID
// ------------------------------------------------------------
this.youtubeID01 = 'xW2oNpNrKd0';
this.youtubeID02 = 't2WeRRdAFeI';
// ------------------------------------------------------------
// web font loaded
// ------------------------------------------------------------
this.webFontLoaded = false;
}
switchMode(){
var i, key, len, param, ref, ref1, value;
ref = location.search.replace('?', '').split('&');
for (i = 0, len = ref.length; i < len; i++) {
param = ref[i];
ref1 = param.split('='), key = ref1[0], value = ref1[1];
for (var j = 0; j < this.keys.length; j++) {
var obj = this.keys[j];
// パラメータがキーと一緒だったら
if (obj.key === key) {
// 各値と比較
for (var k = 0; k < obj.value.length; k++) {
var val = obj.value[k];
// キーをthis.keysのkeyに、valueを比較して同値だったものに
if (val === value) this[obj.key] = val;
};
};
};
}
}
} |
// ------------------------------------------------------------
// mode |
packageutil.py | import os
import importlib
import logging
def import_methodmeta_decorated_classes(globals_d, package_name):
"""Prepare a package namespace by importing all subclasses following PEP8
rules that have @takes decorated functions"""
def finder(package_fs_path, fname):
if fname.endswith(".py") and fname != "__init__.py":
# import it and see what it produces
import_name = "%s.%s" % (package_name, fname[:-3])
logging.debug("Importing %s" % import_name)
module = importlib.import_module(import_name)
for n in dir(module):
cls = getattr(module, n)
module_name = module.__name__.split(".")[-1]
if n.lower() == module_name:
if hasattr(cls, "MethodMeta"):
logging.debug("Found child class %s" % cls)
yield cls.__name__, cls
__all__ = prepare_globals_for_package(globals_d, package_name, finder)
return __all__
def import_sub_packages(globals_d, package_name):
def finder(package_fs_path, fname):
if os.path.isdir(os.path.join(package_fs_path, fname)):
# import it and add it to the list | import_name = "%s.%s" % (package_name, fname)
logging.debug("Importing %s", import_name)
try:
module = importlib.import_module(import_name)
except Exception:
logging.exception("Importing %s failed", import_name)
else:
yield fname, module
__all__ = prepare_globals_for_package(globals_d, package_name, finder)
return __all__
def prepare_globals_for_package(globals_d, package_name, finder):
update_dict = {}
# this is the path to the package
package_relative = package_name.split(".")[1:]
package_fs_path = os.path.join(os.path.dirname(__file__), *package_relative)
for f in os.listdir(package_fs_path):
for name, ob in finder(package_fs_path, f):
update_dict[name] = ob
globals_d.update(update_dict)
__all__ = list(update_dict)
return __all__ | |
dirstructure.py | import os
from glob import glob
import pandas as pd
def get_list_of_full_child_dirs(d):
"""
For a directory d (full path),
return a list of its subdirectories
in a full path form.
"""
children = (os.path.join(d, child) for child in os.listdir(d))
dirs = filter(os.path.isdir, children)
return list(dirs)
def | (full_path, base_dir):
"""
Given a full path, return:
- relative_dir: the part of the path that does not
include the base directory and the basename
- basename
"""
fname = os.path.basename(full_path)
relative_path = full_path.split(base_dir)[-1]
relative_dir = relative_path.split(fname)[0]
relative_dir = relative_dir[1:-1] # clip slashes
return relative_dir, fname
def gather_files(base_dir, file_mask):
"""
Walk the directory base_dir using os.walk
and gather files that match file_mask (e.g. '*.jpg').
Return the result as a Pandas dataframe with columns
'relative_dir' and 'basename'.
"""
res_tuples = []
for dir_name, subdirs, files in os.walk(base_dir):
dir_has_files = len(files) > 0
if dir_has_files:
full_mask = os.path.join(dir_name, file_mask)
mask_matches = glob(full_mask)
res_tuples += [split_full_path(f, base_dir) for f in mask_matches]
return pd.DataFrame(res_tuples, columns=['relative_dir', 'basename'])
| split_full_path |
model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .sprin import GlobalInfoProp, SparseSO3Conv
import numpy as np
class | (torch.nn.Module):
def __init__(self, dim_in, dim_out, bn=False) -> None:
super().__init__()
assert(bn is False)
self.fc1 = torch.nn.Linear(dim_in, dim_out)
if bn:
self.bn1 = torch.nn.BatchNorm1d(dim_out)
else:
self.bn1 = lambda x: x
self.fc2 = torch.nn.Linear(dim_out, dim_out)
if bn:
self.bn2 = torch.nn.BatchNorm1d(dim_out)
else:
self.bn2 = lambda x: x
if dim_in != dim_out:
self.fc0 = torch.nn.Linear(dim_in, dim_out)
else:
self.fc0 = None
def forward(self, x):
x_res = x if self.fc0 is None else self.fc0(x)
x = F.relu(self.bn1(self.fc1(x)))
x = self.bn2(self.fc2(x))
return x + x_res
class PointEncoder(nn.Module):
def __init__(self, k, spfcs, out_dim, num_layers=2, num_nbr_feats=2) -> None:
super().__init__()
self.k = k
self.spconvs = nn.ModuleList()
self.spconvs.append(SparseSO3Conv(32, num_nbr_feats, out_dim, *spfcs))
self.aggrs = nn.ModuleList()
self.aggrs.append(GlobalInfoProp(out_dim, out_dim // 4))
for _ in range(num_layers - 1):
self.spconvs.append(SparseSO3Conv(32, out_dim + out_dim // 4, out_dim, *spfcs))
self.aggrs.append(GlobalInfoProp(out_dim, out_dim // 4))
def forward(self, pc, pc_normal, dist):
nbrs_idx = torch.topk(dist, self.k, largest=False, sorted=False)[1] #[..., N, K]
pc_nbrs = torch.gather(pc.unsqueeze(-3).expand(*pc.shape[:-1], *pc.shape[-2:]), -2, nbrs_idx[..., None].expand(*nbrs_idx.shape, pc.shape[-1])) #[..., N, K, 3]
pc_nbrs_centered = pc_nbrs - pc.unsqueeze(-2) #[..., N, K, 3]
pc_nbrs_norm = torch.norm(pc_nbrs_centered, dim=-1, keepdim=True)
pc_normal_nbrs = torch.gather(pc_normal.unsqueeze(-3).expand(*pc_normal.shape[:-1], *pc_normal.shape[-2:]), -2, nbrs_idx[..., None].expand(*nbrs_idx.shape, pc_normal.shape[-1])) #[..., N, K, 3]
pc_normal_cos = torch.sum(pc_normal_nbrs * pc_normal.unsqueeze(-2), -1, keepdim=True)
feat = self.aggrs[0](self.spconvs[0](pc_nbrs, torch.cat([pc_nbrs_norm, pc_normal_cos], -1), pc))
for i in range(len(self.spconvs) - 1):
spconv = self.spconvs[i + 1]
aggr = self.aggrs[i + 1]
feat_nbrs = torch.gather(feat.unsqueeze(-3).expand(*feat.shape[:-1], *feat.shape[-2:]), -2, nbrs_idx[..., None].expand(*nbrs_idx.shape, feat.shape[-1]))
feat = aggr(spconv(pc_nbrs, feat_nbrs, pc))
return feat
def forward_nbrs(self, pc, pc_normal, nbrs_idx):
pc_nbrs = torch.gather(pc.unsqueeze(-3).expand(*pc.shape[:-1], *pc.shape[-2:]), -2, nbrs_idx[..., None].expand(*nbrs_idx.shape, pc.shape[-1])) #[..., N, K, 3]
pc_nbrs_centered = pc_nbrs - pc.unsqueeze(-2) #[..., N, K, 3]
pc_nbrs_norm = torch.norm(pc_nbrs_centered, dim=-1, keepdim=True)
pc_normal_nbrs = torch.gather(pc_normal.unsqueeze(-3).expand(*pc_normal.shape[:-1], *pc_normal.shape[-2:]), -2, nbrs_idx[..., None].expand(*nbrs_idx.shape, pc_normal.shape[-1])) #[..., N, K, 3]
pc_normal_cos = torch.sum(pc_normal_nbrs * pc_normal.unsqueeze(-2), -1, keepdim=True)
feat = self.aggrs[0](self.spconvs[0](pc_nbrs, torch.cat([pc_nbrs_norm, pc_normal_cos], -1), pc))
for i in range(len(self.spconvs) - 1):
spconv = self.spconvs[i + 1]
aggr = self.aggrs[i + 1]
feat_nbrs = torch.gather(feat.unsqueeze(-3).expand(*feat.shape[:-1], *feat.shape[-2:]), -2, nbrs_idx[..., None].expand(*nbrs_idx.shape, feat.shape[-1]))
feat = aggr(spconv(pc_nbrs, feat_nbrs, pc))
return feat
class PPFEncoder(nn.Module):
def __init__(self, ppffcs, out_dim) -> None:
super().__init__()
self.res_layers = nn.ModuleList()
for i in range(len(ppffcs) - 1):
dim_in, dim_out = ppffcs[i], ppffcs[i + 1]
self.res_layers.append(ResLayer(dim_in, dim_out, bn=False))
self.final = nn.Linear(ppffcs[-1], out_dim)
def forward(self, pc, pc_normal, feat, dist=None, idxs=None):
if idxs is not None:
return self.forward_with_idx(pc[0], pc_normal[0], feat[0], idxs)[None]
xx = pc.unsqueeze(-2) - pc.unsqueeze(-3)
xx_normed = xx / (dist[..., None] + 1e-7)
outputs = []
for idx in torch.chunk(torch.arange(pc.shape[1]), 5):
feat_chunk = feat[..., idx, :]
target_shape = [*feat_chunk.shape[:-2], feat_chunk.shape[-2], feat.shape[-2], feat_chunk.shape[-1]] # B x NC x N x F
xx_normed_chunk = xx_normed[..., idx, :, :]
ppf = torch.cat([
torch.sum(pc_normal[..., idx, :].unsqueeze(-2) * xx_normed_chunk, -1, keepdim=True),
torch.sum(pc_normal.unsqueeze(-3) * xx_normed_chunk, -1, keepdim=True),
torch.sum(pc_normal[..., idx, :].unsqueeze(-2) * pc_normal.unsqueeze(-3), -1, keepdim=True),
dist[..., idx, :, None],
], -1)
# ppf.zero_()
final_feat = torch.cat([feat_chunk[..., None, :].expand(*target_shape), feat[..., None, :, :].expand(*target_shape), ppf], -1)
output = final_feat
for res_layer in self.res_layers:
output = res_layer(output)
outputs.append(output)
output = torch.cat(outputs, dim=-3)
return self.final(output)
def forward_with_idx(self, pc, pc_normal, feat, idxs):
a_idxs = idxs[:, 0]
b_idxs = idxs[:, 1]
xy = pc[a_idxs] - pc[b_idxs]
xy_norm = torch.norm(xy, dim=-1)
xy_normed = xy / (xy_norm[..., None] + 1e-7)
pnormal_cos = pc_normal[a_idxs] * pc_normal[b_idxs]
ppf = torch.cat([
torch.sum(pc_normal[a_idxs] * xy_normed, -1, keepdim=True),
torch.sum(pc_normal[b_idxs] * xy_normed, -1, keepdim=True),
torch.sum(pnormal_cos, -1, keepdim=True),
xy_norm[..., None],
], -1)
# ppf.zero_()
final_feat = torch.cat([feat[a_idxs], feat[b_idxs], ppf], -1)
output = final_feat
for res_layer in self.res_layers:
output = res_layer(output)
return self.final(output)
| ResLayer |
kendo.all.d.ts | // Type definitions for Kendo UI Professional v2019.1.220
// Project: http://www.telerik.com/kendo-ui
// Definitions by: Telerik <https://github.com/telerik>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/*
* Please, submit Pull Requests in the telerik/kendo-ui-core repo at
* https://github.com/telerik/kendo-ui-core/tree/master/typescript
*
* See contributor instructions at
* https://github.com/telerik/kendo-ui-core#how-to-contribute
*/
declare namespace kendo {
function culture(): {
name: string;
calendar: {
AM: string[];
PM: string[];
"/": string;
":": string;
days: {
names: string[];
namesAbbr: string[];
namesShort: string[];
};
months: {
names: string[];
namesAbbr: string[];
};
patterns: {
D: string;
F: string;
G: string;
M: string;
T: string;
Y: string;
d: string;
g: string;
m: string;
s: string;
t: string;
u: string;
y: string;
};
firstDay: number;
twoDigitYearMax: number;
};
calendars: {
standard: {
AM: string[];
PM: string[];
"/": string;
":": string;
days: {
names: string[];
namesAbbr: string[];
namesShort: string[];
};
months: {
names: string[];
namesAbbr: string[];
};
patterns: {
D: string;
F: string;
G: string;
M: string;
T: string;
Y: string;
d: string;
g: string;
m: string;
s: string;
t: string;
u: string;
y: string;
};
firstDay: string;
twoDigitYearMax: number;
};
};
numberFormat: {
currency: {
decimals: number;
",": string;
".": string;
groupSize: number[];
pattern: string[];
symbol: string;
};
decimals: number;
",": string;
".": string;
groupSize: number[];
pattern: string[];
percent: {
decimals: number;
",": string;
".": string;
groupSize: number[];
pattern: string[];
symbol: string;
};
};
};
var cultures: {[culture: string] : {
name?: string;
calendar?: {
AM: string[];
PM: string[];
"/": string;
":": string;
days: {
names: string[];
namesAbbr: string[];
namesShort: string[];
};
months: {
names: string[];
namesAbbr: string[];
};
patterns: {
D: string;
F: string;
G: string;
M: string;
T: string;
Y: string;
d: string;
g: string;
m: string;
s: string;
t: string;
u: string;
y: string;
};
firstDay: number;
twoDigitYearMax: number;
};
calendars?: {
standard: {
AM: string[];
PM: string[];
"/": string;
":": string;
days: {
names: string[];
namesAbbr: string[];
namesShort: string[];
};
months: {
names: string[];
namesAbbr: string[];
};
patterns: {
D: string;
F: string;
G: string;
M: string;
T: string;
Y: string;
d: string;
g: string;
m: string;
s: string;
t: string;
u: string;
y: string;
};
firstDay: number;
twoDigitYearMax: number;
};
};
numberFormat?: {
currency: {
decimals: number;
",": string;
".": string;
groupSize: number[];
pattern: string[];
symbol: string;
};
decimals: number;
",": string;
".": string;
groupSize: number[];
pattern: string[];
percent: {
decimals: number;
",": string;
".": string;
groupSize: number[];
pattern: string[];
symbol: string;
};
};
}};
function format(format: string, ...values: any[]): string;
function fx(selector: string): effects.Element;
function fx(element: Element): effects.Element;
function fx(element: JQuery): effects.Element;
function init(selector: string, ...namespaces: any[]): void;
function init(element: JQuery, ...namespaces: any[]): void;
function init(element: Element, ...namespaces: any[]): void;
function observable(data: any): kendo.data.ObservableObject;
function observableHierarchy(array: any[]): kendo.data.ObservableArray;
function render(template: (data: any) => string, data: any[]): string;
function template(template: string, options?: TemplateOptions): (data: any) => string;
function guid(): string;
function widgetInstance(element: JQuery, suite?: typeof kendo.ui): kendo.ui.Widget;
function widgetInstance(element: JQuery, suite?: typeof kendo.mobile.ui): kendo.ui.Widget;
function widgetInstance(element: JQuery, suite?: typeof kendo.dataviz.ui): kendo.ui.Widget;
var ns: string;
var keys: {
INSERT: number;
DELETE: number;
BACKSPACE: number;
TAB: number;
ENTER: number;
ESC: number;
LEFT: number;
UP: number;
RIGHT: number;
DOWN: number;
END: number;
HOME: number;
SPACEBAR: number;
PAGEUP: number;
PAGEDOWN: number;
F2: number;
F10: number;
F12: number;
NUMPAD_PLUS: number;
NUMPAD_MINUS: number;
NUMPAD_DOT: number;
};
var support: {
touch: boolean;
pointers: boolean;
scrollbar(): number;
hasHW3D: boolean;
hasNativeScrolling: boolean;
devicePixelRatio: number;
placeholder: boolean;
zoomLevel: number;
mobileOS: {
device: string;
tablet: any;
browser: string;
name: string;
majorVersion: string;
minorVersion: string;
flatVersion: number;
appMode: boolean;
};
browser: {
edge: boolean;
msie: boolean;
webkit: boolean;
safari: boolean;
opera: boolean;
mozilla: boolean;
version: string;
};
};
var version: string;
interface TemplateOptions {
paramName?: string;
useWithBlock?: boolean;
}
class Class {
static fn: Class;
static extend(prototype: Object): Class;
}
class Observable extends Class {
static fn: Observable;
static extend(prototype: Object): Observable;
init(...args: any[]): void;
bind(eventName: string, handler: Function): Observable;
bind(events: string[], handler: Function): Observable;
bind(events: string[], handlers: { [eventName: string]: Function}): Observable;
one(eventName: string, handler: Function): Observable;
one(events: string[], handler: Function): Observable;
one(events: string[], handlers: { [eventName: string]: Function}): Observable;
first(eventName: string, handler: Function): Observable;
first(events: string[], handler: Function): Observable;
first(events: string[], handlers: { [eventName: string]: Function}): Observable;
trigger(eventName: string, e?: any): boolean;
unbind(eventName: string, handler?: any): Observable;
}
interface ViewOptions {
tagName?: string;
wrap?: boolean;
model?: Object;
evalTemplate?: boolean;
init?: (e: ViewEvent) => void;
show?: (e: ViewEvent) => void;
hide?: (e: ViewEvent) => void;
}
interface ViewEvent {
sender: View;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class View extends Observable {
constructor(element: Element, options?: ViewOptions);
constructor(element: string, options?: ViewOptions);
element: JQuery;
content: any;
tagName: string;
model: Object;
init(element: Element, options?: ViewOptions): void;
init(element: string, options?: ViewOptions): void;
render(container?: any): JQuery;
destroy(): void;
}
class ViewContainer extends Observable {
view: View;
}
class Layout extends View {
containers: { [selector: string]: ViewContainer; };
showIn(selector: string, view: View, transitionClass?: string): void;
}
class History extends Observable {
current: string;
root: string;
start(options: Object): void;
stop(): void;
change(callback: Function): void;
navigate(location: string, silent?: boolean): void;
}
var history: History;
interface RouterOptions {
init?: (e: RouterEvent) => void;
pushState?: boolean;
hashBang?: boolean;
root?: string;
ignoreCase?: boolean;
change?(e: RouterChangeEvent): void;
routeMissing?(e: RouterRouteMissingEvent): void;
same?(e: RouterEvent): void;
}
interface RouterEvent {
sender: Router;
url: string;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface RouterChangeEvent extends RouterEvent {
params: any;
backButtonPressed: boolean;
}
interface RouterRouteMissingEvent extends RouterEvent {
params: any;
}
class Route extends Class {
route: RegExp;
callback(url: string): void;
worksWith(url: string): void;
}
class Router extends Observable {
constructor(options?: RouterOptions);
routes: Route[];
init(options?: RouterOptions): void;
start(): void;
destroy(): void;
route(route: string, callback: Function): void;
navigate(location: string, silent?: boolean): void;
replace(location: string, silent?: boolean): void;
}
}
declare namespace kendo.effects {
function enable(): void;
function disable(): void;
interface Element {
expand(direction: string): effects.Expand;
expandHorizontal(): effects.Expand;
expandVertical(): effects.Expand;
fade(direction: string): effects.Fade;
fadeIn(): effects.Fade;
fadeOut(): effects.Fade;
flip(axis: string, face: JQuery, back: JQuery): effects.Flip;
flipHorizontal(face: JQuery, back: JQuery): effects.Flip;
flipVertical(face: JQuery, back: JQuery): effects.Flip;
pageturn(axis: string, face: JQuery, back: JQuery): effects.PageTurn;
pageturnHorizontal(face: JQuery, back: JQuery): effects.PageTurn;
pageturnVertical(face: JQuery, back: JQuery): effects.PageTurn;
slideIn(direction: string): effects.SlideIn;
slideInDown(): effects.SlideIn;
slideInLeft(): effects.SlideIn;
slideInRight(): effects.SlideIn;
slideInUp(): effects.SlideIn;
tile(direction: string, previous: JQuery): effects.Tile;
tileDown(previous: JQuery): effects.Tile;
tileLeft(previous: JQuery): effects.Tile;
tileRight(previous: JQuery): effects.Tile;
tileUp(previous: JQuery): effects.Tile;
transfer(target: JQuery): effects.Transfer;
zoom(direction: string): effects.Zoom;
zoomIn(): effects.Zoom;
zoomOut(): effects.Zoom;
}
interface Effect {
play(): JQueryPromise<any>;
reverse(): JQueryPromise<any>;
duration(value: number): Effect;
add(effect: Effect): Effect;
stop(): Effect;
}
interface Expand extends Effect {
duration(value: number): Expand;
direction(value: string): Expand;
stop(): Expand;
add(effect: Effect): Expand;
}
interface Fade extends Effect {
duration(value: number): Fade;
direction(value: string): Fade;
stop(): Fade;
add(effect: Effect): Fade;
startValue(value: number): Fade;
endValue(value: number): Fade;
}
interface Flip extends Effect {
duration(value: number): Flip;
direction(value: string): Flip;
stop(): Flip;
add(effect: Effect): Flip;
}
interface PageTurn extends Effect {
duration(value: number): PageTurn;
direction(value: string): PageTurn;
stop(): PageTurn;
add(effect: Effect): PageTurn;
}
interface SlideIn extends Effect {
duration(value: number): SlideIn;
direction(value: string): SlideIn;
stop(): SlideIn;
add(effect: Effect): SlideIn;
}
interface Tile extends Effect {
duration(value: number): Tile;
direction(value: string): Tile;
stop(): Tile;
add(effect: Effect): Tile;
}
interface Transfer extends Effect {
duration(value: number): Transfer;
stop(): Transfer;
add(effect: Effect): Transfer;
}
interface Zoom extends Effect {
duration(value: number): Zoom;
direction(value: string): Zoom;
stop(): Zoom;
add(effect: Effect): Zoom;
startValue(value: number): Zoom;
endValue(value: number): Zoom;
}
}
declare namespace kendo.data {
interface ObservableObjectEvent {
sender?: ObservableObject;
field?: string;
}
interface ObservableObjectSetEvent extends ObservableObjectEvent {
value?: any;
preventDefault?: Function;
}
class Binding extends Observable {
source: any;
parents: any[];
path: string;
observable: boolean;
dependencies: { [path: string]: boolean; };
constructor(parents: any[], path: string);
change(e: Object): void;
start(source: kendo.Observable): void;
stop(source: kendo.Observable): void;
get (): any;
set (value: any): void;
destroy(): void;
}
class BindingTarget {
target: any;
options: any;
source: any;
}
class EventBinding extends Binding {
get (): void;
}
class TemplateBinding extends Binding {
constructor(source: kendo.Observable, path: string, template: Function);
render(value: Object): string;
}
namespace binders { }
interface Bindings {
[key: string]: Binding;
}
class Binder extends Class {
static fn: Binder;
element: any;
bindings: Bindings;
options: BinderOptions;
constructor(element: any, bindings: Bindings, options?: BinderOptions);
static extend(prototype: Object): Binder;
init(element: any, bindings: Bindings, options?: BinderOptions): void;
bind(binding: Binding, attribute: string): void;
destroy(): void;
refresh(): void;
refresh(attribute: string): void;
}
interface BinderOptions {
}
class ObservableObject extends Observable{
constructor(value?: any);
uid: string;
init(value?: any): void;
get(name: string): any;
parent(): ObservableObject;
set(name: string, value: any): void;
toJSON(): Object;
}
class Model extends ObservableObject {
static idField: string;
static fields: DataSourceSchemaModelFields;
idField: string;
_defaultId: any;
fields: DataSourceSchemaModelFields;
defaults: {
[field: string]: any;
};
id: any;
dirty: boolean;
static define(options: DataSourceSchemaModelWithFieldsObject): typeof Model;
static define(options: DataSourceSchemaModelWithFieldsArray): typeof Model;
constructor(data?: any);
init(data?: any): void;
accept(data?: any): void;
editable(field: string): boolean;
isNew(): boolean;
}
interface SchedulerEventData {
description?: string;
end?: Date;
endTimezone?: string;
isAllDay?: boolean;
id?: any;
start?: Date;
startTimezone?: string;
recurrenceId?: any;
recurrenceRule?: string;
recurrenceException?: string;
title?: string;
}
class SchedulerEvent extends Model {
static idField: string;
static fields: DataSourceSchemaModelFields;
constructor(data?: SchedulerEventData);
description: string;
end: Date;
endTimezone: string;
isAllDay: boolean;
id: any;
start: Date;
startTimezone: string;
recurrenceId: any;
recurrenceRule: string;
recurrenceException: string;
title: string;
static define(options: DataSourceSchemaModelWithFieldsObject): typeof SchedulerEvent;
static define(options: DataSourceSchemaModelWithFieldsArray): typeof SchedulerEvent;
init(data?: SchedulerEventData): void;
clone(options: any, updateUid: boolean): SchedulerEvent;
duration(): number;
expand(start: Date, end: Date, zone: any): SchedulerEvent[];
update(eventInfo: SchedulerEventData): void;
isMultiDay(): boolean;
isException(): boolean;
isOccurrence(): boolean;
isRecurring(): boolean;
isRecurrenceHead(): boolean;
toOccurrence(options: any): SchedulerEvent;
}
class TreeListModel extends Model {
static idField: string;
static fields: DataSourceSchemaModelFields;
id: any;
parentId: any;
static define(options: DataSourceSchemaModelWithFieldsObject): typeof TreeListModel;
static define(options: DataSourceSchemaModelWithFieldsArray): typeof TreeListModel;
constructor(data?: any);
init(data?: any): void;
loaded(value: boolean): void;
loaded(): boolean;
}
class TreeListDataSource extends DataSource {
load(model: kendo.data.TreeListModel): JQueryPromise<any>;
childNodes(model: kendo.data.TreeListModel): kendo.data.TreeListModel[];
rootNodes(): kendo.data.TreeListModel[];
parentNode(model: kendo.data.TreeListModel): kendo.data.TreeListModel;
level(model: kendo.data.TreeListModel): number;
level(model: any): number;
add(model: Object): kendo.data.TreeListModel;
add(model: kendo.data.TreeListModel): kendo.data.TreeListModel;
at(index: number): kendo.data.TreeListModel;
cancelChanges(model?: kendo.data.TreeListModel): void;
get(id: any): kendo.data.TreeListModel;
getByUid(uid: string): kendo.data.TreeListModel;
indexOf(value: kendo.data.TreeListModel): number;
insert(index: number, model: kendo.data.TreeListModel): kendo.data.TreeListModel;
insert(index: number, model: Object): kendo.data.TreeListModel;
remove(model: kendo.data.TreeListModel): void;
}
class GanttTask extends Model {
static idField: string;
static fields: DataSourceSchemaModelFields;
id: any;
parentId: number;
orderId: number;
title: string;
start: Date;
end: Date;
percentComplete: number;
summary: boolean;
expanded: boolean;
static define(options: DataSourceSchemaModelWithFieldsObject): typeof GanttTask;
static define(options: DataSourceSchemaModelWithFieldsArray): typeof GanttTask;
constructor(data?: any);
init(data?: any): void;
}
class GanttDependency extends Model {
static idField: string;
static fields: DataSourceSchemaModelFields;
id: any;
predecessorId: number;
successorId: number;
type: number;
static define(options: DataSourceSchemaModelWithFieldsObject): typeof GanttDependency;
static define(options: DataSourceSchemaModelWithFieldsArray): typeof GanttDependency;
constructor(data?: any);
init(data?: any): void;
}
class Node extends Model {
children: HierarchicalDataSource;
append(model: any): void;
level(): number;
load(id: any): void;
loaded(value: boolean): void;
loaded(): boolean;
parentNode(): Node;
}
class SchedulerDataSource extends DataSource {
add(model: Object): kendo.data.SchedulerEvent;
add(model: kendo.data.SchedulerEvent): kendo.data.SchedulerEvent;
at(index: number): kendo.data.SchedulerEvent;
cancelChanges(model?: kendo.data.SchedulerEvent): void;
get(id: any): kendo.data.SchedulerEvent;
getByUid(uid: string): kendo.data.SchedulerEvent;
indexOf(value: kendo.data.SchedulerEvent): number;
insert(index: number, model: kendo.data.SchedulerEvent): kendo.data.SchedulerEvent;
insert(index: number, model: Object): kendo.data.SchedulerEvent;
remove(model: kendo.data.SchedulerEvent): void;
}
class GanttDataSource extends DataSource {
add(model: Object): kendo.data.GanttTask;
add(model: kendo.data.GanttTask): kendo.data.GanttTask;
at(index: number): kendo.data.GanttTask;
cancelChanges(model?: kendo.data.GanttTask): void;
get(id: any): kendo.data.GanttTask;
getByUid(uid: string): kendo.data.GanttTask;
indexOf(value: kendo.data.GanttTask): number;
insert(index: number, model: Object): kendo.data.GanttTask;
insert(index: number, model: kendo.data.GanttTask): kendo.data.GanttTask;
remove(model: kendo.data.GanttTask): void;
}
class GanttDependencyDataSource extends DataSource {
add(model: Object): kendo.data.GanttDependency;
add(model: kendo.data.GanttDependency): kendo.data.GanttDependency;
at(index: number): kendo.data.GanttDependency;
cancelChanges(model?: kendo.data.GanttDependency): void;
get(id: any): kendo.data.GanttDependency;
getByUid(uid: string): kendo.data.GanttDependency;
indexOf(value: kendo.data.GanttDependency): number;
insert(index: number, model: Object): kendo.data.GanttDependency;
insert(index: number, model: kendo.data.GanttDependency): kendo.data.GanttDependency;
remove(model: kendo.data.GanttDependency): void;
}
class HierarchicalDataSource extends DataSource {
constructor(options?: HierarchicalDataSourceOptions);
init(options?: HierarchicalDataSourceOptions): void;
}
interface HierarchicalDataSourceOptions extends DataSourceOptions {
schema?: HierarchicalDataSourceSchema;
}
interface HierarchicalDataSourceSchema extends DataSourceSchemaWithOptionsModel {
model?: HierarchicalDataSourceSchemaModel;
}
interface HierarchicalDataSourceSchemaModel extends DataSourceSchemaModel {
hasChildren?: any;
children?: any;
}
interface PivotDiscoverRequestRestrictionOptions {
catalogName: string;
cubeName: string;
}
interface PivotDiscoverRequestDataOptions {
command: string;
restrictions: PivotDiscoverRequestRestrictionOptions;
}
interface PivotDiscoverRequestOptions {
data: PivotDiscoverRequestDataOptions;
}
interface PivotTransportConnection {
catalog?: string;
cube?: string;
}
interface PivotTransportDiscover {
cache?: boolean;
contentType?: string;
data?: any;
dataType?: string;
type?: string;
url?: any;
}
interface PivotTransport {
discover?: any;
read?: any;
}
interface PivotTransportWithObjectOperations extends PivotTransport {
connection: PivotTransportConnection;
discover?: PivotTransportDiscover;
read?: DataSourceTransportRead;
}
interface PivotTransportWithFunctionOperations extends PivotTransport {
discover?: (options: DataSourceTransportOptions) => void;
read?: (options: DataSourceTransportOptions) => void;
}
interface PivotDataSourceAxisOptions {
name: string;
expand?: boolean;
}
interface PivotDataSourceMeasureOptions {
values: string[];
axis?: string;
}
interface PivotDataSourceOptions extends DataSourceOptions {
columns?: string[]|PivotDataSourceAxisOptions[];
measures?: string[]|PivotDataSourceMeasureOptions;
rows?: string[]|PivotDataSourceAxisOptions[];
transport?: PivotTransport;
schema?: PivotSchema;
}
interface PivotTupleModel {
children: PivotTupleModel[];
caption?: string;
name: string;
levelName?: string;
levelNum: number;
hasChildren?: boolean;
hierarchy?: string;
}
interface PivotSchemaRowAxis {
tuples: PivotTupleModel[];
}
interface PivotSchemaColumnAxis {
tuples: PivotTupleModel[];
}
interface PivotSchemaAxes {
rows: PivotSchemaRowAxis;
columns: PivotSchemaColumnAxis;
}
interface PivotSchema extends DataSourceSchema{
axes?: any;
catalogs?: any;
cubes?: any;
cube?: any;
data?: any;
dimensions?: any;
hierarchies?: any;
levels?: any;
measures?: any;
}
class PivotDataSource extends DataSource {
axes(): PivotSchemaAxes;
constructor(options?: PivotDataSourceOptions);
init(options?: PivotDataSourceOptions): void;
catalog(val: string): void;
catalog(): string;
columns(val: string[]): void;
columns(): string[];
cube(val: string): void;
cube(): string;
discover(options: PivotDiscoverRequestOptions): JQueryPromise<any>;
measures(val: string[]): void;
measures(): string[];
measuresAxis(): string;
rows(val: string[]): void;
rows(): string[];
schemaCatalogs(): JQueryPromise<any>;
schemaCubes(): JQueryPromise<any>;
schemaDimensions(): JQueryPromise<any>;
schemaHierarchies(): JQueryPromise<any>;
schemaLevels(): JQueryPromise<any>;
schemaMeasures(): JQueryPromise<any>;
}
interface DataSourceTransport {
create?: string | DataSourceTransportCreate | ((options: DataSourceTransportOptions) => void);
destroy?: string | DataSourceTransportDestroy | ((options: DataSourceTransportOptions) => void);
push?: Function;
submit?: Function;
read?: string | DataSourceTransportRead | ((options: DataSourceTransportOptions) => void);
signalr?: DataSourceTransportSignalr | ((options: DataSourceTransportOptions) => void);
update?: string | DataSourceTransportUpdate | ((options: DataSourceTransportOptions) => void);
parameterMap?(data: DataSourceTransportParameterMapData, type: "create"|"destroy"|"read"|"update"): any;
}
interface DataSourceTransportSignalrClient {
create?: string;
destroy?: string;
read?: string;
update?: string;
}
interface DataSourceTransportSignalrServer {
create?: string;
destroy?: string;
read?: string;
update?: string;
}
interface DataSourceTransportSignalr {
client?: DataSourceTransportSignalrClient;
hub?: any;
promise?: any;
server?: DataSourceTransportSignalrServer;
}
interface DataSourceParameterMapDataAggregate {
field?: string;
aggregate?: string;
}
interface DataSourceParameterMapDataGroup {
aggregate?: DataSourceParameterMapDataAggregate[];
field?: string;
dir?: string;
}
interface DataSourceParameterMapDataFilter {
field?: string;
filters?: DataSourceParameterMapDataFilter[];
logic?: string;
operator?: string;
value?: any;
}
interface DataSourceParameterMapDataSort {
field?: string;
dir?: string;
}
interface DataSourceTransportParameterMapData {
aggregate?: DataSourceParameterMapDataAggregate[];
group?: DataSourceParameterMapDataGroup[];
filter?: DataSourceParameterMapDataFilter;
models?: Model[];
page?: number;
pageSize?: number;
skip?: number;
sort?: DataSourceParameterMapDataSort[];
take?: number;
}
interface DataSourceSchema {
model?: any;
}
interface DataSourceSchemaWithTimezone extends DataSourceSchema {
timezone?: String;
}
interface DataSourceSchemaWithOptionsModel extends DataSourceSchema {
model?: DataSourceSchemaModel;
}
interface DataSourceSchemaWithConstructorModel extends DataSourceSchema {
model?: typeof Model;
}
interface DataSourceSchemaModel {
id?: string;
fields?: any;
[index: string]: any;
}
interface DataSourceSchemaModelWithFieldsArray extends DataSourceSchemaModel {
fields?: DataSourceSchemaModelField[];
}
interface DataSourceSchemaModelWithFieldsObject extends DataSourceSchemaModel {
fields?: DataSourceSchemaModelFields;
}
interface DataSourceSchemaModelFields {
[index: string]: DataSourceSchemaModelField;
}
interface DataSourceSchemaModelField {
field?: string;
from?: string;
defaultValue?: any;
editable?: boolean;
nullable?: boolean;
parse?: Function;
type?: string;
validation?: DataSourceSchemaModelFieldValidation;
}
interface DataSourceSchemaModelFieldValidation {
required?: boolean;
min?: any;
max?: any;
minLength?: any;
maxLength?: any;
[rule: string]: any;
}
class ObservableArray extends Observable {
length: number;
[index: number]: any;
constructor(array: any[]);
init(array: any[]): void;
empty(): void;
every(callback: (item: Object, index: number, source: ObservableArray) => boolean): boolean;
filter(callback: (item: Object, index: number, source: ObservableArray) => boolean): any[];
find(callback: (item: Object, index: number, source: ObservableArray) => boolean): any;
forEach(callback: (item: Object, index: number, source: ObservableArray) => void ): void;
indexOf(item: any): number;
join(separator: string): string;
map(callback: (item: Object, index: number, source: ObservableArray) => any): any[];
parent(): ObservableObject;
pop(): ObservableObject;
push(...items: any[]): number;
remove(item: Object): void;
shift(): any;
slice(begin: number, end?: number): any[];
some(callback: (item: Object, index: number, source: ObservableArray) => boolean): boolean;
splice(start: number): any[];
splice(start: number, deleteCount: number, ...items: any[]): any[];
toJSON(): any[];
unshift(...items: any[]): number;
wrap(object: Object, parent: Object): any;
wrapAll(source: Object, target: Object): any;
}
interface ObservableArrayEvent {
field?: string;
action?: string;
index?: number;
items?: kendo.data.Model[];
}
class DataSource extends Observable{
options: DataSourceOptions;
static create(options?: DataSourceOptions): DataSource;
constructor(options?: DataSourceOptions);
init(options?: DataSourceOptions): void;
add(model: Object): kendo.data.Model;
add(model: kendo.data.Model): kendo.data.Model;
aggregate(val: any): void;
aggregate(): any;
aggregates(): any;
at(index: number): kendo.data.ObservableObject;
cancelChanges(model?: kendo.data.Model): void;
data(): kendo.data.ObservableArray;
data(value: any): void;
fetch(callback?: Function): JQueryPromise<any>;
filter(filters: DataSourceFilterItem): void;
filter(filters: DataSourceFilterItem[]): void;
filter(filters: DataSourceFilters): void;
filter(): DataSourceFilters;
get(id: any): kendo.data.Model;
getByUid(uid: string): kendo.data.Model;
group(groups: any): void;
group(): any;
hasChanges(): boolean;
indexOf(value: kendo.data.ObservableObject): number;
insert(index: number, model: kendo.data.Model): kendo.data.Model;
insert(index: number, model: Object): kendo.data.Model;
online(value: boolean): void;
online(): boolean;
offlineData(data: any[]): void;
offlineData(): any[];
page(): number;
page(page: number): void;
pageSize(): number;
pageSize(size: number): void;
pushCreate(model: Object): void;
pushCreate(models: any[]): void;
pushDestroy(model: Object): void;
pushDestroy(models: any[]): void;
pushUpdate(model: Object): void;
pushUpdate(models: any[]): void;
query(options?: any): JQueryPromise<any>;
read(data?: any): JQueryPromise<any>;
remove(model: kendo.data.ObservableObject): void;
skip(): number;
sort(sort: DataSourceSortItem): void;
sort(sort: DataSourceSortItem[]): void;
sort(): DataSourceSortItem[];
sync(): JQueryPromise<any>;
total(): number;
totalPages(): number;
view(): kendo.data.ObservableArray;
}
class Query {
data: any[];
static process(data: any[], options: DataSourceTransportReadOptionsData): QueryResult;
constructor(data: any[]);
toArray(): any[];
range(intex: number, count: number): kendo.data.Query;
skip(count: number): kendo.data.Query;
take(count: number): kendo.data.Query;
select(selector: Function): kendo.data.Query;
order(selector: string, dir?: string): kendo.data.Query;
order(selector: Function, dir?: string): kendo.data.Query;
filter(filters: DataSourceFilterItem): kendo.data.Query;
filter(filters: DataSourceFilterItem[]): kendo.data.Query;
filter(filters: DataSourceFilters): kendo.data.Query;
group(descriptors: DataSourceGroupItem): kendo.data.Query;
group(descriptors: DataSourceGroupItem[]): kendo.data.Query;
}
interface QueryResult {
total?: number;
data?: any[];
}
interface DataSourceAggregateItem {
field?: string;
aggregate?: string;
}
interface DataSourceFilter {
}
interface DataSourceFilterItem extends DataSourceFilter {
operator?: string|Function;
field?: string;
value?: any;
}
interface DataSourceFilters extends DataSourceFilter {
logic?: string;
filters?: DataSourceFilter[];
}
interface DataSourceGroupItemAggregate {
field?: string;
aggregate?: string;
}
interface DataSourceGroupItem {
field?: string;
dir?: string;
aggregates?: DataSourceGroupItemAggregate[];
}
interface DataSourceSchema {
aggregates?: any;
data?: any;
errors?: any;
groups?: any;
parse?: Function;
total?: any;
type?: string;
}
interface DataSourceSortItem {
field?: string;
dir?: string;
}
interface DataSourceTransportCreate extends JQueryAjaxSettings {
cache?: boolean;
contentType?: string;
data?: any;
dataType?: string;
type?: string;
url?: any;
}
interface DataSourceTransportDestroy extends JQueryAjaxSettings {
cache?: boolean;
contentType?: string;
data?: any;
dataType?: string;
type?: string;
url?: any;
}
interface DataSourceTransportRead extends JQueryAjaxSettings {
cache?: boolean;
contentType?: string;
data?: any;
dataType?: string;
type?: string;
url?: any;
}
interface DataSourceTransportUpdate extends JQueryAjaxSettings {
cache?: boolean;
contentType?: string;
data?: any;
dataType?: string;
type?: string;
url?: any;
}
interface DataSourceTransportWithObjectOperations extends DataSourceTransport {
create?: DataSourceTransportCreate;
destroy?: DataSourceTransportDestroy;
read?: DataSourceTransportRead;
update?: DataSourceTransportUpdate;
}
interface DataSourceTransportWithFunctionOperations extends DataSourceTransport {
create?: (options: DataSourceTransportOptions) => void;
destroy?: (options: DataSourceTransportOptions) => void;
read?: (options: DataSourceTransportReadOptions) => void;
update?: (options: DataSourceTransportOptions) => void;
}
interface DataSourceTransportOptions {
success: (data?: any) => void;
error: (error?: any) => void;
data: any;
}
interface DataSourceTransportReadOptionsData {
sort?: DataSourceSortItem[];
filter?: DataSourceFilters;
group?: DataSourceGroupItem[];
take?: number;
skip?: number;
}
interface DataSourceTransportReadOptions extends DataSourceTransportOptions {
data: DataSourceTransportReadOptionsData;
}
interface DataSourceTransportBatchOptionsData {
models: any[];
}
interface DataSourceTransportBatchOptions extends DataSourceTransportOptions {
data: DataSourceTransportBatchOptionsData;
}
interface DataSourceOptions {
aggregate?: DataSourceAggregateItem[];
autoSync?: boolean;
batch?: boolean;
data?: any;
filter?: any;
group?: DataSourceGroupItem | DataSourceGroupItem[];
inPlaceSort?: boolean;
offlineStorage?: any;
page?: number;
pageSize?: number;
schema?: DataSourceSchema;
serverAggregates?: boolean;
serverFiltering?: boolean;
serverGrouping?: boolean;
serverPaging?: boolean;
serverSorting?: boolean;
sort?: any;
transport?: DataSourceTransport;
type?: string;
change? (e: DataSourceChangeEvent): void;
error?(e: DataSourceErrorEvent): void;
push?(e: DataSourcePushEvent): void;
sync?(e: DataSourceEvent): void;
requestStart?(e: DataSourceRequestStartEvent): void;
requestEnd?(e: DataSourceRequestEndEvent): void;
}
interface DataSourceEvent {
sender?: DataSource;
}
interface DataSourceItemOrGroup {
}
interface DataSourceGroup extends DataSourceItemOrGroup {
aggregates: any[];
field: string;
hasSubgroups: boolean;
items: DataSourceItemOrGroup[];
value: any;
}
interface DataSourceChangeEvent extends DataSourceEvent {
field?: string;
value?: Model;
action?: string;
index?: number;
items?: DataSourceItemOrGroup[];
node?: any;
}
interface DataSourcePushEvent extends DataSourceEvent {
items?: DataSourceItemOrGroup[];
type?: string;
}
interface DataSourceErrorEvent extends DataSourceEvent {
xhr: JQueryXHR;
status: string;
errorThrown: any;
errors?: any;
}
interface DataSourceRequestStartEvent extends DataSourceEvent {
type?: string;
preventDefault(): void;
}
interface DataSourceRequestEndEvent extends DataSourceEvent {
response?: any;
type?: string;
}
}
declare namespace kendo.data.transports {
var odata: DataSourceTransport;
}
declare namespace kendo.ui {
function progress(container: JQuery, toggle: boolean): void;
class Widget extends Observable {
static fn: any;
element: JQuery;
options: any;
events: string[];
static extend(prototype: Object): Widget;
constructor(element: Element, options?: Object);
constructor(element: JQuery, options?: Object);
constructor(selector: String, options?: Object);
init(element: Element, options?: Object): void;
init(element: JQuery, options?: Object): void;
init(selector: String, options?: Object): void;
destroy(): void;
setOptions(options: Object): void;
resize(force?: boolean): void;
}
function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.ui, prefix?: String): void;
function plugin(widget: any, register?: typeof kendo.ui, prefix?: String): void;
function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.mobile.ui, prefix?: String): void;
function plugin(widget: any, register?: typeof kendo.mobile.ui, prefix?: String): void;
function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.dataviz.ui, prefix?: String): void;
function plugin(widget: any, register?: typeof kendo.dataviz.ui, prefix?: String): void;
class Draggable extends kendo.ui.Widget{
element: JQuery;
currentTarget: JQuery;
constructor(element: Element, options?: DraggableOptions);
options: DraggableOptions;
cancelHold(): void;
}
interface DraggableEvent {
sender?: Draggable;
}
class DropTarget extends kendo.ui.Widget{
element: JQuery;
constructor(element: Element, options?: DropTargetOptions);
options: DropTargetOptions;
static destroyGroup(groupName: string): void;
}
interface DropTargetOptions {
group?: string;
dragenter?(e: DropTargetDragenterEvent): void;
dragleave?(e: DropTargetDragleaveEvent): void;
drop?(e: DropTargetDropEvent): void;
}
interface DropTargetEvent extends JQueryEventObject {
sender?: DropTarget;
draggable?: kendo.ui.Draggable;
dropTarget?: JQuery
}
interface DropTargetDragenterEvent extends DropTargetEvent {
}
interface DropTargetDragleaveEvent extends DropTargetEvent {
}
interface DropTargetDropEvent extends DropTargetEvent {
}
class DropTargetArea extends kendo.ui.Widget{
element: JQuery;
constructor(element: Element, options?: DropTargetAreaOptions);
options: DropTargetAreaOptions;
}
interface DropTargetAreaOptions {
group?: string;
filter?: string;
dragenter?(e: DropTargetAreaDragenterEvent): void;
dragleave?(e: DropTargetAreaDragleaveEvent): void;
drop?(e: DropTargetAreaDropEvent): void;
}
interface DropTargetAreaEvent {
sender: DropTargetArea;
}
interface DropTargetAreaDragenterEvent extends DropTargetAreaEvent {
draggable?: kendo.ui.Draggable;
dropTarget?: JQuery;
target?: Element;
}
interface DropTargetAreaDragleaveEvent extends DropTargetAreaEvent {
draggable?: kendo.ui.Draggable;
dropTarget?: JQuery;
target?: Element;
}
interface DropTargetAreaDropEvent extends DropTargetAreaEvent {
draggable?: kendo.ui.Draggable;
dropTarget?: JQuery;
target?: Element;
}
interface DraggableOptions {
axis?: string;
autoScroll?: boolean;
container?: JQuery;
cursorOffset?: any;
distance?: number;
filter?: string;
group?: string;
hint?: Function|JQuery;
holdToDrag?: boolean;
ignore?: string;
drag?(e: DraggableEvent): void;
dragcancel?(e: DraggableEvent): void;
dragend?(e: DraggableEvent): void;
dragstart?(e: DraggableEvent): void;
hold?(e: DraggableEvent): void;
}
interface GridColumnEditorOptions {
field?: string;
format?: string;
model?: kendo.data.Model;
values?: any[];
}
interface GridColumn {
editor?(container: JQuery, options: GridColumnEditorOptions): void;
}
interface TreeListEditorOptions {
field?: string;
format?: string;
model?: kendo.data.Model;
values?: any[];
}
interface TreeListColumn {
editor?(container: JQuery, options: TreeListEditorOptions): void;
}
}
declare namespace kendo.ui.editor {
class Toolbar extends kendo.ui.Widget{
window: kendo.ui.Window;
}
}
declare namespace kendo.mobile {
function init(selector: string): void;
function init(element: JQuery): void;
function init(element: Element): void;
class Application extends Observable {
options: ApplicationOptions;
router: kendo.Router;
pane: kendo.mobile.ui.Pane;
constructor(element?: any, options?: ApplicationOptions);
init(element?: any, options?: ApplicationOptions): void;
changeLoadingMessage(text: string): void;
hideLoading(): void;
navigate(url: string, transition?: string): void;
replace(url: string, transition?: string): void;
scroller(): kendo.mobile.ui.Scroller;
showLoading(): void;
view(): kendo.mobile.ui.View;
}
interface ApplicationOptions {
browserHistory?: boolean;
hideAddressBar?: boolean;
updateDocumentTitle?: boolean;
initial?: string;
layout?: string;
loading?: string;
modelScope?: Object;
platform?: string;
retina?: boolean;
serverNavigation?: boolean;
skin?: string;
statusBarStyle?: string;
transition?: string;
useNativeScrolling?: boolean;
init?(e: ApplicationEvent): void;
}
interface ApplicationEvent {
sender: Application;
}
}
declare namespace kendo.mobile.ui {
class Widget extends kendo.ui.Widget {
}
interface TouchAxis {
location?: number;
startLocation?: number;
client?: number;
delta?: number;
velocity?: number;
}
interface TouchEventOptions {
target?: JQuery;
x?: TouchAxis;
y?: TouchAxis;
}
interface Point {
x?: number;
y?: number;
}
}
declare namespace kendo.dataviz.ui {
function registerTheme(name: string, options: any): void;
function plugin(widget: typeof kendo.ui.Widget): void;
function plugin(widget: any): void;
}
declare namespace kendo.dataviz.map.layer {
class Shape {
}
}
declare namespace kendo.drawing.pdf {
function saveAs(group: kendo.drawing.Group, fileName: string,
proxyUrl?: string, callback?: Function): void;
}
declare namespace kendo.ui {
class Alert extends kendo.ui.Dialog {
static fn: Alert;
options: AlertOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Alert;
constructor(element: Element, options?: AlertOptions);
}
interface AlertMessages {
okText?: string;
}
interface AlertOptions {
name?: string;
messages?: AlertMessages;
}
interface AlertEvent {
sender: Alert;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class AutoComplete extends kendo.ui.Widget {
static fn: AutoComplete;
options: AutoCompleteOptions;
dataSource: kendo.data.DataSource;
list: JQuery;
ul: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): AutoComplete;
constructor(element: Element, options?: AutoCompleteOptions);
close(): void;
dataItem(index: number): any;
dataItem(index: Element): any;
dataItem(index: JQuery): any;
destroy(): void;
enable(enable: boolean): void;
focus(): void;
items(): any;
readonly(readonly: boolean): void;
refresh(): void;
search(word: string): void;
select(item: string): void;
select(item: Element): void;
select(item: JQuery): void;
setDataSource(dataSource: kendo.data.DataSource): void;
suggest(value: string): void;
value(): string;
value(value: string): void;
}
interface AutoCompleteAnimationClose {
duration?: number;
effects?: string;
}
interface AutoCompleteAnimationOpen {
duration?: number;
effects?: string;
}
interface AutoCompleteAnimation {
close?: AutoCompleteAnimationClose;
open?: AutoCompleteAnimationOpen;
}
interface AutoCompleteVirtual {
itemHeight?: number;
mapValueTo?: string;
valueMapper?: Function;
}
interface AutoCompleteOptions {
name?: string;
animation?: boolean | AutoCompleteAnimation;
autoWidth?: boolean;
dataSource?: any|any|kendo.data.DataSource;
clearButton?: boolean;
dataTextField?: string;
delay?: number;
enable?: boolean;
enforceMinLength?: boolean;
filter?: string;
fixedGroupTemplate?: string|Function;
footerTemplate?: string|Function;
groupTemplate?: string|Function;
height?: number;
highlightFirst?: boolean;
ignoreCase?: boolean;
minLength?: number;
noDataTemplate?: string|Function;
placeholder?: string;
popup?: any;
separator?: string|any;
suggest?: boolean;
headerTemplate?: string|Function;
template?: string|Function;
value?: string;
valuePrimitive?: boolean;
virtual?: boolean | AutoCompleteVirtual;
change?(e: AutoCompleteChangeEvent): void;
close?(e: AutoCompleteCloseEvent): void;
dataBound?(e: AutoCompleteDataBoundEvent): void;
filtering?(e: AutoCompleteFilteringEvent): void;
open?(e: AutoCompleteOpenEvent): void;
select?(e: AutoCompleteSelectEvent): void;
}
interface AutoCompleteEvent {
sender: AutoComplete;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface AutoCompleteChangeEvent extends AutoCompleteEvent {
}
interface AutoCompleteCloseEvent extends AutoCompleteEvent {
}
interface AutoCompleteDataBoundEvent extends AutoCompleteEvent {
}
interface AutoCompleteFilteringEvent extends AutoCompleteEvent {
filter?: any;
}
interface AutoCompleteOpenEvent extends AutoCompleteEvent {
}
interface AutoCompleteSelectEvent extends AutoCompleteEvent {
dataItem?: any;
item?: JQuery;
}
class Button extends kendo.ui.Widget {
static fn: Button;
options: ButtonOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Button;
constructor(element: Element, options?: ButtonOptions);
enable(toggle: boolean): void;
}
interface ButtonOptions {
name?: string;
enable?: boolean;
icon?: string;
iconClass?: string;
imageUrl?: string;
spriteCssClass?: string;
click?(e: ButtonClickEvent): void;
}
interface ButtonEvent {
sender: Button;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ButtonClickEvent extends ButtonEvent {
event?: any;
}
class ButtonGroup extends kendo.ui.Widget {
static fn: ButtonGroup;
options: ButtonGroupOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ButtonGroup;
constructor(element: Element, options?: ButtonGroupOptions);
badge(button: string, value: string): string;
badge(button: string, value: boolean): string;
badge(button: number, value: string): string;
badge(button: number, value: boolean): string;
current(): JQuery;
destroy(): void;
enable(enable: boolean): void;
select(li: JQuery): void;
select(li: number): void;
selectedIndices: Array<number>;
}
interface ButtonGroupItem {
attributes?: any;
badge?: string;
enabled?: boolean;
icon?: string;
iconClass?: string;
imageUrl?: string;
selected?: boolean;
text?: string;
encoded?: boolean;
}
interface ButtonGroupOptions {
name?: string;
enable?: boolean;
index?: number;
selection?: string;
items?: ButtonGroupItem[];
select?(e: ButtonGroupSelectEvent): void;
}
interface ButtonGroupEvent {
sender: ButtonGroup;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ButtonGroupSelectEvent extends ButtonGroupEvent {
indices?: any;
}
class Calendar extends kendo.ui.Widget {
static fn: Calendar;
options: CalendarOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Calendar;
constructor(element: Element, options?: CalendarOptions);
current(): Date;
destroy(): void;
max(): Date;
max(value: Date): void;
max(value: string): void;
min(): Date;
min(value: Date): void;
min(value: string): void;
navigate(value: Date, view: string): void;
navigateDown(value: Date): void;
navigateToFuture(): void;
navigateToPast(): void;
navigateUp(): void;
selectDates(): void;
selectDates(): void;
value(): Date;
value(value: Date): void;
value(value: string): void;
view(): any;
}
interface CalendarMessages {
weekColumnHeader?: string;
}
interface CalendarMonth {
content?: string;
weekNumber?: string;
empty?: string;
}
interface CalendarOptions {
name?: string;
culture?: string;
dates?: any;
depth?: string;
disableDates?: any|Function;
footer?: boolean | string | Function;
format?: string;
max?: Date;
messages?: CalendarMessages;
min?: Date;
month?: CalendarMonth;
selectable?: string;
selectDates?: any;
weekNumber?: boolean;
start?: string;
value?: Date;
change?(e: CalendarEvent): void;
navigate?(e: CalendarEvent): void;
}
interface CalendarEvent {
sender: Calendar;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Chat extends kendo.ui.Widget {
static fn: Chat;
options: ChatOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Chat;
constructor(element: Element, options?: ChatOptions);
getUser(): any;
postMessage(message: string): void;
renderAttachments(options: any, sender: any): void;
renderMessage(message: any, sender: any): void;
renderSuggestedActions(suggestedActions: any): void;
}
interface ChatMessages {
placeholder?: string;
}
interface ChatUser {
iconUrl?: string;
name?: string;
}
interface ChatRenderAttachmentsOptionsAttachments {
content?: any;
contentType?: string;
}
interface ChatRenderAttachmentsOptions {
attachments?: ChatRenderAttachmentsOptionsAttachments;
attachmentLayout?: string;
}
interface ChatRenderAttachmentsSender {
id?: any;
name?: string;
iconUrl?: string;
}
interface ChatRenderMessageMessage {
type?: string;
text?: string;
}
interface ChatRenderMessageSender {
id?: any;
name?: string;
iconUrl?: string;
}
interface ChatRenderSuggestedActionsSuggestedActions {
title?: string;
value?: string;
}
interface ChatOptions {
name?: string;
messages?: ChatMessages;
user?: ChatUser;
actionClick?(e: ChatActionClickEvent): void;
post?(e: ChatPostEvent): void;
sendMessage?(e: ChatSendMessageEvent): void;
typingEnd?(e: ChatTypingEndEvent): void;
typingStart?(e: ChatTypingStartEvent): void;
}
interface ChatEvent {
sender: Chat;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ChatActionClickEvent extends ChatEvent {
text?: string;
}
interface ChatPostEvent extends ChatEvent {
text?: string;
timestamp?: Date;
from?: any;
}
interface ChatSendMessageEvent extends ChatEvent {
text?: string;
}
interface ChatTypingEndEvent extends ChatEvent {
}
interface ChatTypingStartEvent extends ChatEvent {
}
class ColorPalette extends kendo.ui.Widget {
static fn: ColorPalette;
options: ColorPaletteOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ColorPalette;
constructor(element: Element, options?: ColorPaletteOptions);
value(): string;
value(color?: string): void;
color(): kendo.Color;
color(color?: kendo.Color): void;
enable(enable?: boolean): void;
}
interface ColorPaletteTileSize {
width?: number;
height?: number;
}
interface ColorPaletteOptions {
name?: string;
palette?: string|any;
columns?: number;
tileSize?: ColorPaletteTileSize;
value?: string;
change?(e: ColorPaletteEvent): void;
}
interface ColorPaletteEvent {
sender: ColorPalette;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ColorPicker extends kendo.ui.Widget {
static fn: ColorPicker;
options: ColorPickerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ColorPicker;
constructor(element: Element, options?: ColorPickerOptions);
close(): void;
open(): void;
toggle(): void;
value(): string;
value(color?: string): void;
color(): kendo.Color;
color(color?: kendo.Color): void;
enable(enable?: boolean): void;
}
interface ColorPickerMessages {
apply?: string;
cancel?: string;
previewInput?: string;
}
interface ColorPickerTileSize {
width?: number;
height?: number;
}
interface ColorPickerOptions {
name?: string;
buttons?: boolean;
clearButton?: boolean;
columns?: number;
tileSize?: ColorPickerTileSize;
messages?: ColorPickerMessages;
palette?: string|any;
opacity?: boolean;
preview?: boolean;
toolIcon?: string;
value?: string;
change?(e: ColorPickerChangeEvent): void;
select?(e: ColorPickerSelectEvent): void;
open?(e: ColorPickerEvent): void;
close?(e: ColorPickerEvent): void;
}
interface ColorPickerEvent {
sender: ColorPicker;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ColorPickerChangeEvent extends ColorPickerEvent {
value?: string;
}
interface ColorPickerSelectEvent extends ColorPickerEvent {
value?: string;
}
class ComboBox extends kendo.ui.Widget {
static fn: ComboBox;
options: ComboBoxOptions;
dataSource: kendo.data.DataSource;
input: JQuery;
list: JQuery;
ul: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ComboBox;
constructor(element: Element, options?: ComboBoxOptions);
close(): void;
dataItem(index?: number): any;
destroy(): void;
enable(enable: boolean): void;
focus(): void;
items(): any;
open(): void;
readonly(readonly: boolean): void;
refresh(): void;
search(word: string): void;
select(): number;
select(li: JQuery): void;
select(li: number): void;
select(li: Function): void;
setDataSource(dataSource: kendo.data.DataSource): void;
suggest(value: string): void;
text(): string;
text(text: string): void;
toggle(toggle: boolean): void;
value(): string;
value(value: string): void;
}
interface ComboBoxAnimationClose {
effects?: string;
duration?: number;
}
interface ComboBoxAnimationOpen {
effects?: string;
duration?: number;
}
interface ComboBoxAnimation {
close?: ComboBoxAnimationClose;
open?: ComboBoxAnimationOpen;
}
interface ComboBoxPopup {
appendTo?: string;
origin?: string;
position?: string;
}
interface ComboBoxVirtual {
itemHeight?: number;
mapValueTo?: string;
valueMapper?: Function;
}
interface ComboBoxOptions {
name?: string;
animation?: ComboBoxAnimation;
autoBind?: boolean;
autoWidth?: boolean;
cascadeFrom?: string;
cascadeFromField?: string;
clearButton?: boolean;
dataSource?: any|any|kendo.data.DataSource;
dataTextField?: string;
dataValueField?: string;
delay?: number;
enable?: boolean;
enforceMinLength?: boolean;
filter?: string;
fixedGroupTemplate?: string|Function;
footerTemplate?: string|Function;
groupTemplate?: string|Function;
height?: number;
highlightFirst?: boolean;
ignoreCase?: boolean;
index?: number;
minLength?: number;
noDataTemplate?: string|Function;
placeholder?: string;
popup?: ComboBoxPopup;
suggest?: boolean;
syncValueAndText?: boolean;
headerTemplate?: string|Function;
template?: string|Function;
text?: string;
value?: string;
valuePrimitive?: boolean;
virtual?: boolean | ComboBoxVirtual;
change?(e: ComboBoxChangeEvent): void;
close?(e: ComboBoxCloseEvent): void;
dataBound?(e: ComboBoxDataBoundEvent): void;
filtering?(e: ComboBoxFilteringEvent): void;
open?(e: ComboBoxOpenEvent): void;
select?(e: ComboBoxSelectEvent): void;
cascade?(e: ComboBoxCascadeEvent): void;
}
interface ComboBoxEvent {
sender: ComboBox;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ComboBoxChangeEvent extends ComboBoxEvent {
}
interface ComboBoxCloseEvent extends ComboBoxEvent {
}
interface ComboBoxDataBoundEvent extends ComboBoxEvent {
}
interface ComboBoxFilteringEvent extends ComboBoxEvent {
filter?: any;
}
interface ComboBoxOpenEvent extends ComboBoxEvent {
}
interface ComboBoxSelectEvent extends ComboBoxEvent {
dataItem?: any;
item?: JQuery;
}
interface ComboBoxCascadeEvent extends ComboBoxEvent {
}
class Confirm extends kendo.ui.Dialog {
static fn: Confirm;
options: ConfirmOptions;
result: JQueryPromise<any>;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Confirm;
constructor(element: Element, options?: ConfirmOptions);
}
interface ConfirmMessages {
okText?: string;
cancel?: string;
}
interface ConfirmOptions {
name?: string;
messages?: ConfirmMessages;
}
interface ConfirmEvent {
sender: Confirm;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ContextMenu extends kendo.ui.Widget {
static fn: ContextMenu;
options: ContextMenuOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ContextMenu;
constructor(element: Element, options?: ContextMenuOptions);
append(item: any, referenceItem?: string): kendo.ui.ContextMenu;
append(item: any, referenceItem?: JQuery): kendo.ui.ContextMenu;
close(element: Element): kendo.ui.ContextMenu;
close(element: JQuery): kendo.ui.ContextMenu;
destroy(): void;
enable(element: string, enable: boolean): kendo.ui.ContextMenu;
enable(element: Element, enable: boolean): kendo.ui.ContextMenu;
enable(element: JQuery, enable: boolean): kendo.ui.ContextMenu;
insertAfter(item: any, referenceItem: string): kendo.ui.ContextMenu;
insertAfter(item: any, referenceItem: Element): kendo.ui.ContextMenu;
insertAfter(item: any, referenceItem: JQuery): kendo.ui.ContextMenu;
insertBefore(item: any, referenceItem: string): kendo.ui.ContextMenu;
insertBefore(item: any, referenceItem: Element): kendo.ui.ContextMenu;
insertBefore(item: any, referenceItem: JQuery): kendo.ui.ContextMenu;
open(x: number, y?: number): kendo.ui.ContextMenu;
open(x: Element, y?: number): kendo.ui.ContextMenu;
open(x: JQuery, y?: number): kendo.ui.ContextMenu;
remove(element: string): kendo.ui.ContextMenu;
remove(element: Element): kendo.ui.ContextMenu;
remove(element: JQuery): kendo.ui.ContextMenu;
}
interface ContextMenuAnimationClose {
effects?: string;
duration?: number;
}
interface ContextMenuAnimationOpen {
effects?: string;
duration?: number;
}
interface ContextMenuAnimation {
close?: ContextMenuAnimationClose;
open?: ContextMenuAnimationOpen;
}
interface ContextMenuOptions {
name?: string;
alignToAnchor?: boolean;
animation?: boolean | ContextMenuAnimation;
appendTo?: string|JQuery;
closeOnClick?: boolean;
copyAnchorStyles?: boolean;
dataSource?: any|any;
direction?: string;
filter?: string;
hoverDelay?: number;
orientation?: string;
popupCollision?: string;
showOn?: string;
target?: string|JQuery;
close?(e: ContextMenuCloseEvent): void;
open?(e: ContextMenuOpenEvent): void;
activate?(e: ContextMenuActivateEvent): void;
deactivate?(e: ContextMenuDeactivateEvent): void;
select?(e: ContextMenuSelectEvent): void;
}
interface ContextMenuEvent {
sender: ContextMenu;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ContextMenuCloseEvent extends ContextMenuEvent {
item?: Element;
type?: string;
target?: Element;
event?: JQueryEventObject;
}
interface ContextMenuOpenEvent extends ContextMenuEvent {
item?: Element;
type?: string;
target?: Element;
event?: JQueryEventObject;
}
interface ContextMenuActivateEvent extends ContextMenuEvent {
item?: Element;
type?: string;
target?: Element;
}
interface ContextMenuDeactivateEvent extends ContextMenuEvent {
item?: Element;
type?: string;
target?: Element;
}
interface ContextMenuSelectEvent extends ContextMenuEvent {
item?: Element;
type?: string;
target?: Element;
}
class DateInput extends kendo.ui.Widget {
static fn: DateInput;
options: DateInputOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): DateInput;
constructor(element: Element, options?: DateInputOptions);
destroy(): void;
enable(enable: boolean): void;
readonly(readonly: boolean): void;
max(): Date;
max(value: Date): void;
max(value: string): void;
min(): Date;
min(value: Date): void;
min(value: string): void;
setOptions(options: any): void;
value(): Date;
value(value: Date): void;
value(value: string): void;
}
interface DateInputMessages {
year?: string;
month?: string;
day?: string;
weekday?: string;
hour?: string;
minute?: string;
second?: string;
dayperiod?: string;
}
interface DateInputOptions {
name?: string;
format?: string;
max?: Date;
min?: Date;
value?: Date;
messages?: DateInputMessages;
change?(e: DateInputChangeEvent): void;
}
interface DateInputEvent {
sender: DateInput;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DateInputChangeEvent extends DateInputEvent {
}
class DatePicker extends kendo.ui.Widget {
static fn: DatePicker;
options: DatePickerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): DatePicker;
constructor(element: Element, options?: DatePickerOptions);
close(): void;
destroy(): void;
enable(enable: boolean): void;
readonly(readonly: boolean): void;
max(): Date;
max(value: Date): void;
max(value: string): void;
min(): Date;
min(value: Date): void;
min(value: string): void;
open(): void;
setOptions(options: any): void;
value(): Date;
value(value: Date): void;
value(value: string): void;
}
interface DatePickerAnimationClose {
effects?: string;
duration?: number;
}
interface DatePickerAnimationOpen {
effects?: string;
duration?: number;
}
interface DatePickerAnimation {
close?: DatePickerAnimationClose;
open?: DatePickerAnimationOpen;
}
interface DatePickerMonth {
content?: string;
weekNumber?: string;
empty?: string;
}
interface DatePickerOptions {
name?: string;
animation?: boolean | DatePickerAnimation;
ARIATemplate?: string;
culture?: string;
dateInput?: boolean;
dates?: any;
depth?: string;
disableDates?: any|Function;
footer?: boolean|string|Function;
format?: string;
max?: Date;
min?: Date;
month?: DatePickerMonth;
weekNumber?: boolean;
parseFormats?: any;
start?: string;
value?: Date;
change?(e: DatePickerChangeEvent): void;
close?(e: DatePickerCloseEvent): void;
open?(e: DatePickerOpenEvent): void;
}
interface DatePickerEvent {
sender: DatePicker;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DatePickerChangeEvent extends DatePickerEvent {
}
interface DatePickerCloseEvent extends DatePickerEvent {
}
interface DatePickerOpenEvent extends DatePickerEvent {
}
class DateRangePicker extends kendo.ui.Widget {
static fn: DateRangePicker;
options: DateRangePickerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): DateRangePicker;
constructor(element: Element, options?: DateRangePickerOptions);
close(): void;
destroy(): void;
enable(enable: boolean): void;
readonly(readonly: boolean): void;
max(): Date;
max(value: Date): void;
max(value: string): void;
min(): Date;
min(value: Date): void;
min(value: string): void;
open(): void;
range(): any;
range(range: DateRangePickerRange): void;
setOptions(options: any): void;
}
interface DateRangePickerMessages {
startLabel?: string;
endLabel?: string;
}
interface DateRangePickerMonth {
content?: string;
weekNumber?: string;
empty?: string;
}
interface DateRangePickerRange {
start?: Date;
end?: Date;
}
interface DateRangePickerOptions {
name?: string;
ARIATemplate?: string;
culture?: string;
dates?: any;
depth?: string;
disableDates?: any|Function;
footer?: string|Function;
format?: string;
max?: Date;
messages?: DateRangePickerMessages;
min?: Date;
month?: DateRangePickerMonth;
labels?: boolean;
weekNumber?: boolean;
range?: DateRangePickerRange;
start?: string;
change?(e: DateRangePickerChangeEvent): void;
close?(e: DateRangePickerCloseEvent): void;
open?(e: DateRangePickerOpenEvent): void;
}
interface DateRangePickerEvent {
sender: DateRangePicker;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DateRangePickerChangeEvent extends DateRangePickerEvent {
}
interface DateRangePickerCloseEvent extends DateRangePickerEvent {
}
interface DateRangePickerOpenEvent extends DateRangePickerEvent {
}
class DateTimePicker extends kendo.ui.Widget {
static fn: DateTimePicker;
options: DateTimePickerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): DateTimePicker;
constructor(element: Element, options?: DateTimePickerOptions);
close(view: string): void;
destroy(): void;
enable(enable: boolean): void;
readonly(readonly: boolean): void;
max(): Date;
max(value: Date): void;
max(value: string): void;
min(): Date;
min(value: Date): void;
min(value: string): void;
open(view: string): void;
setOptions(options: any): void;
toggle(view: string): void;
value(): Date;
value(value: Date): void;
value(value: string): void;
}
interface DateTimePickerAnimationClose {
effects?: string;
duration?: number;
}
interface DateTimePickerAnimationOpen {
effects?: string;
duration?: number;
}
interface DateTimePickerAnimation {
close?: DateTimePickerAnimationClose;
open?: DateTimePickerAnimationOpen;
}
interface DateTimePickerMonth {
content?: string;
weekNumber?: string;
empty?: string;
}
interface DateTimePickerOptions {
name?: string;
animation?: boolean | DateTimePickerAnimation;
ARIATemplate?: string;
culture?: string;
dateInput?: boolean;
dates?: any;
depth?: string;
disableDates?: any|Function;
footer?: boolean|string|Function;
format?: string;
interval?: number;
max?: Date;
min?: Date;
month?: DateTimePickerMonth;
weekNumber?: boolean;
parseFormats?: any;
start?: string;
timeFormat?: string;
value?: Date;
change?(e: DateTimePickerChangeEvent): void;
close?(e: DateTimePickerCloseEvent): void;
open?(e: DateTimePickerOpenEvent): void;
}
interface DateTimePickerEvent {
sender: DateTimePicker;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DateTimePickerChangeEvent extends DateTimePickerEvent {
}
interface DateTimePickerCloseEvent extends DateTimePickerEvent {
view?: string;
}
interface DateTimePickerOpenEvent extends DateTimePickerEvent {
view?: string;
}
class Dialog extends kendo.ui.Widget {
static fn: Dialog;
options: any;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Dialog;
constructor(element: Element, options?: DialogOptions);
close(): kendo.ui.Dialog;
content(): string;
content(content?: string): kendo.ui.Dialog;
content(content?: JQuery): kendo.ui.Dialog;
destroy(): void;
open(): kendo.ui.Dialog;
title(): string;
title(text?: string): kendo.ui.Dialog;
toFront(): kendo.ui.Dialog;
}
interface DialogAction {
text?: string;
action?: Function;
primary?: boolean;
}
interface DialogAnimationClose {
effects?: string;
duration?: number;
}
interface DialogAnimationOpen {
effects?: string;
duration?: number;
}
interface DialogAnimation {
close?: DialogAnimationClose;
open?: DialogAnimationOpen;
}
interface DialogMessages {
close?: string;
promptInput?: string;
}
interface DialogModal {
preventScroll?: string;
}
interface DialogOptions {
name?: string;
actions?: DialogAction[];
animation?: boolean | DialogAnimation;
buttonLayout?: string;
closable?: boolean;
content?: string;
height?: number|string;
maxHeight?: number;
maxWidth?: number;
messages?: DialogMessages;
minHeight?: number;
minWidth?: number;
modal?: boolean | DialogModal;
title?: string|boolean;
visible?: boolean;
width?: number|string;
size?: string;
close?(e: DialogCloseEvent): void;
hide?(e: DialogEvent): void;
initOpen?(e: DialogEvent): void;
open?(e: DialogEvent): void;
show?(e: DialogEvent): void;
}
interface DialogEvent {
sender: Dialog;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DialogCloseEvent extends DialogEvent {
userTriggered?: boolean;
}
class DropDownList extends kendo.ui.Widget {
static fn: DropDownList;
options: DropDownListOptions;
dataSource: kendo.data.DataSource;
span: JQuery;
filterInput: JQuery;
list: JQuery;
ul: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): DropDownList;
constructor(element: Element, options?: DropDownListOptions);
close(): void;
dataItem(index?: JQuery): any;
dataItem(index?: number): any;
destroy(): void;
focus(): void;
items(): any;
enable(enable: boolean): void;
open(): void;
readonly(readonly: boolean): void;
refresh(): void;
search(word: string): void;
select(): number;
select(li: JQuery): void;
select(li: number): void;
select(li: Function): void;
setDataSource(dataSource: kendo.data.DataSource): void;
text(): string;
text(text: string): void;
toggle(toggle: boolean): void;
value(): string;
value(value: string): void;
}
interface DropDownListAnimationClose {
effects?: string;
duration?: number;
}
interface DropDownListAnimationOpen {
effects?: string;
duration?: number;
}
interface DropDownListAnimation {
close?: DropDownListAnimationClose;
open?: DropDownListAnimationOpen;
}
interface DropDownListPopup {
appendTo?: string;
origin?: string;
position?: string;
}
interface DropDownListVirtual {
itemHeight?: number;
mapValueTo?: string;
valueMapper?: Function;
}
interface DropDownListOptions {
name?: string;
animation?: boolean | DropDownListAnimation;
autoBind?: boolean;
autoWidth?: boolean;
cascadeFrom?: string;
cascadeFromField?: string;
dataSource?: any|any|kendo.data.DataSource;
dataTextField?: string;
dataValueField?: string;
delay?: number;
enable?: boolean;
enforceMinLength?: boolean;
filter?: string;
fixedGroupTemplate?: string|Function;
footerTemplate?: string|Function;
groupTemplate?: string|Function;
height?: number;
ignoreCase?: boolean;
index?: number;
minLength?: number;
noDataTemplate?: string|Function;
popup?: DropDownListPopup;
optionLabel?: string|any;
optionLabelTemplate?: string|Function;
headerTemplate?: string|Function;
template?: string|Function;
valueTemplate?: string|Function;
text?: string;
value?: string;
valuePrimitive?: boolean;
virtual?: boolean | DropDownListVirtual;
change?(e: DropDownListChangeEvent): void;
close?(e: DropDownListCloseEvent): void;
dataBound?(e: DropDownListDataBoundEvent): void;
filtering?(e: DropDownListFilteringEvent): void;
open?(e: DropDownListOpenEvent): void;
select?(e: DropDownListSelectEvent): void;
cascade?(e: DropDownListCascadeEvent): void;
}
interface DropDownListEvent {
sender: DropDownList;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DropDownListChangeEvent extends DropDownListEvent {
}
interface DropDownListCloseEvent extends DropDownListEvent {
}
interface DropDownListDataBoundEvent extends DropDownListEvent {
}
interface DropDownListFilteringEvent extends DropDownListEvent {
filter?: any;
}
interface DropDownListOpenEvent extends DropDownListEvent {
}
interface DropDownListSelectEvent extends DropDownListEvent {
dataItem?: any;
item?: JQuery;
}
interface DropDownListCascadeEvent extends DropDownListEvent {
}
class DropDownTree extends kendo.ui.Widget {
static fn: DropDownTree;
options: DropDownTreeOptions;
dataSource: kendo.data.DataSource;
tagList: JQuery;
tree: JQuery;
treeview: kendo.ui.TreeView;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): DropDownTree;
constructor(element: Element, options?: DropDownTreeOptions);
close(): void;
destroy(): void;
enable(enable: boolean): void;
focus(): void;
items(): any;
open(): void;
readonly(readonly: boolean): void;
refresh(): void;
search(word: string): void;
setDataSource(dataSource: kendo.data.HierarchicalDataSource): void;
toggle(toggle?: boolean): void;
value(): any;
value(value: any): void;
value(value: string): void;
}
interface DropDownTreeAnimationClose {
effects?: string;
duration?: number;
}
interface DropDownTreeAnimationOpen {
effects?: string;
duration?: number;
}
interface DropDownTreeAnimation {
close?: DropDownTreeAnimationClose;
open?: DropDownTreeAnimationOpen;
}
interface DropDownTreeCheckboxes {
checkChildren?: boolean;
name?: string;
template?: string|Function;
}
interface DropDownTreeMessages {
clear?: string;
deleteTag?: string;
singleTag?: string;
}
interface DropDownTreePopup {
appendTo?: string;
origin?: string;
position?: string;
}
interface DropDownTreeOptions {
name?: string;
animation?: boolean | DropDownTreeAnimation;
autoBind?: boolean;
autoClose?: boolean;
autoWidth?: boolean;
checkAll?: boolean;
checkAllTemplate?: string|Function;
checkboxes?: boolean | DropDownTreeCheckboxes;
clearButton?: boolean;
dataImageUrlField?: string;
dataSource?: any|any|kendo.data.HierarchicalDataSource;
dataSpriteCssClassField?: string;
dataTextField?: string|any;
dataUrlField?: string;
dataValueField?: string|any;
delay?: number;
enable?: boolean;
enforceMinLength?: boolean;
filter?: string;
footerTemplate?: string|Function;
height?: string|number;
ignoreCase?: boolean;
loadOnDemand?: boolean;
messages?: DropDownTreeMessages;
minLength?: number;
noDataTemplate?: string|Function;
placeholder?: string;
popup?: DropDownTreePopup;
headerTemplate?: string|Function;
valueTemplate?: string|Function;
tagMode?: string;
template?: string|Function;
text?: string;
value?: string|any;
valuePrimitive?: boolean;
change?(e: DropDownTreeChangeEvent): void;
close?(e: DropDownTreeCloseEvent): void;
dataBound?(e: DropDownTreeDataBoundEvent): void;
filtering?(e: DropDownTreeFilteringEvent): void;
open?(e: DropDownTreeOpenEvent): void;
select?(e: DropDownTreeSelectEvent): void;
}
interface DropDownTreeEvent {
sender: DropDownTree;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DropDownTreeChangeEvent extends DropDownTreeEvent {
}
interface DropDownTreeCloseEvent extends DropDownTreeEvent {
}
interface DropDownTreeDataBoundEvent extends DropDownTreeEvent {
}
interface DropDownTreeFilteringEvent extends DropDownTreeEvent {
filter?: any;
}
interface DropDownTreeOpenEvent extends DropDownTreeEvent {
}
interface DropDownTreeSelectEvent extends DropDownTreeEvent {
node?: Element;
}
class Editor extends kendo.ui.Widget {
static fn: Editor;
options: EditorOptions;
body: Element;
toolbar: kendo.ui.editor.Toolbar;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Editor;
constructor(element: Element, options?: EditorOptions);
createRange(document?: Document): Range;
destroy(): void;
encodedValue(): string;
exec(name: string, params: any): void;
focus(): void;
getRange(): Range;
getSelection(): Selection;
paste(html: string, options: any): void;
selectedHtml(): string;
refresh(): void;
saveAsPDF(): JQueryPromise<any>;
selectRange(range: Range): void;
update(): void;
state(toolName: string): boolean;
value(): string;
value(value: string): void;
}
interface EditorDeserialization {
custom?: Function;
}
interface EditorFileBrowserMessages {
uploadFile?: string;
orderBy?: string;
orderByName?: string;
orderBySize?: string;
directoryNotFound?: string;
emptyFolder?: string;
deleteFile?: string;
invalidFileType?: string;
overwriteFile?: string;
search?: string;
}
interface EditorFileBrowserSchemaModelFieldsName {
field?: string;
parse?: Function;
}
interface EditorFileBrowserSchemaModelFieldsSize {
field?: string;
parse?: Function;
}
interface EditorFileBrowserSchemaModelFieldsType {
parse?: Function;
field?: string;
}
interface EditorFileBrowserSchemaModelFields {
name?: string | EditorFileBrowserSchemaModelFieldsName;
type?: string | EditorFileBrowserSchemaModelFieldsType;
size?: string | EditorFileBrowserSchemaModelFieldsSize;
}
interface EditorFileBrowserSchemaModel {
id?: string;
fields?: EditorFileBrowserSchemaModelFields;
}
interface EditorFileBrowserSchema {
}
interface EditorFileBrowserTransportCreate {
contentType?: string;
data?: any|string|Function;
dataType?: string;
type?: string;
url?: string|Function;
}
interface EditorFileBrowserTransportDestroy {
contentType?: string;
data?: any|string|Function;
dataType?: string;
type?: string;
url?: string|Function;
}
interface EditorFileBrowserTransportRead {
contentType?: string;
data?: any|string|Function;
dataType?: string;
type?: string;
url?: string|Function;
}
interface EditorFileBrowserTransport {
read?: string | Function | EditorFileBrowserTransportRead;
uploadUrl?: string;
fileUrl?: string|Function;
destroy?: string | EditorFileBrowserTransportDestroy;
create?: string | EditorFileBrowserTransportCreate;
}
interface EditorFileBrowser {
fileTypes?: string;
path?: string;
transport?: EditorFileBrowserTransport;
schema?: EditorFileBrowserSchema;
messages?: EditorFileBrowserMessages;
}
interface EditorImageBrowserMessages {
uploadFile?: string;
orderBy?: string;
orderByName?: string;
orderBySize?: string;
directoryNotFound?: string;
emptyFolder?: string;
deleteFile?: string;
invalidFileType?: string;
overwriteFile?: string;
search?: string;
}
interface EditorImageBrowserSchemaModelFieldsName {
field?: string;
parse?: Function;
}
interface EditorImageBrowserSchemaModelFieldsSize {
field?: string;
parse?: Function;
}
interface EditorImageBrowserSchemaModelFieldsType {
parse?: Function;
field?: string;
}
interface EditorImageBrowserSchemaModelFields {
name?: string | EditorImageBrowserSchemaModelFieldsName;
type?: string | EditorImageBrowserSchemaModelFieldsType;
size?: string | EditorImageBrowserSchemaModelFieldsSize;
}
interface EditorImageBrowserSchemaModel {
id?: string;
fields?: EditorImageBrowserSchemaModelFields;
}
interface EditorImageBrowserSchema {
}
interface EditorImageBrowserTransportCreate {
contentType?: string;
data?: any|string|Function;
dataType?: string;
type?: string;
url?: string|Function;
}
interface EditorImageBrowserTransportDestroy {
contentType?: string;
data?: any|string|Function;
dataType?: string;
type?: string;
url?: string|Function;
}
interface EditorImageBrowserTransportRead {
contentType?: string;
data?: any|string|Function;
dataType?: string;
type?: string;
url?: string|Function;
}
interface EditorImageBrowserTransport {
read?: string | Function | EditorImageBrowserTransportRead;
thumbnailUrl?: string|Function;
uploadUrl?: string;
imageUrl?: string|Function;
destroy?: string | EditorImageBrowserTransportDestroy;
create?: string | EditorImageBrowserTransportCreate;
}
interface EditorImageBrowser {
fileTypes?: string;
path?: string;
transport?: EditorImageBrowserTransport;
schema?: EditorImageBrowserSchema;
messages?: EditorImageBrowserMessages;
}
interface EditorImmutables {
deserialization?: Function;
serialization?: string|Function;
}
interface EditorMessages {
accessibilityTab?: string;
addColumnLeft?: string;
addColumnRight?: string;
addRowAbove?: string;
addRowBelow?: string;
alignCenter?: string;
alignCenterBottom?: string;
alignCenterMiddle?: string;
alignCenterTop?: string;
alignLeft?: string;
alignLeftBottom?: string;
alignLeftMiddle?: string;
alignLeftTop?: string;
alignRemove?: string;
alignRight?: string;
alignRightBottom?: string;
alignRightMiddle?: string;
alignRightTop?: string;
alignment?: string;
associateCellsWithHeaders?: string;
backColor?: string;
background?: string;
bold?: string;
border?: string;
style?: string;
caption?: string;
cellMargin?: string;
cellPadding?: string;
cellSpacing?: string;
cellTab?: string;
cleanFormatting?: string;
collapseBorders?: string;
columns?: string;
createLink?: string;
createTable?: string;
createTableHint?: string;
cssClass?: string;
deleteColumn?: string;
deleteRow?: string;
dialogCancel?: string;
dialogInsert?: string;
dialogOk?: string;
dialogUpdate?: string;
editAreaTitle?: string;
fileTitle?: string;
fileWebAddress?: string;
fontName?: string;
fontNameInherit?: string;
fontSize?: string;
fontSizeInherit?: string;
foreColor?: string;
formatBlock?: string;
formatting?: string;
height?: string;
id?: string;
imageAltText?: string;
imageHeight?: string;
imageWebAddress?: string;
imageWidth?: string;
indent?: string;
insertFile?: string;
insertHtml?: string;
insertImage?: string;
insertOrderedList?: string;
insertUnorderedList?: string;
italic?: string;
overflowAnchor?: string;
justifyCenter?: string;
justifyFull?: string;
justifyLeft?: string;
justifyRight?: string;
linkOpenInNewWindow?: string;
linkText?: string;
linkToolTip?: string;
linkWebAddress?: string;
outdent?: string;
print?: string;
rows?: string;
selectAllCells?: string;
strikethrough?: string;
subscript?: string;
summary?: string;
superscript?: string;
tableTab?: string;
tableWizard?: string;
underline?: string;
units?: string;
unlink?: string;
viewHtml?: string;
width?: string;
wrapText?: string;
}
interface EditorPasteCleanup {
all?: boolean;
css?: boolean;
custom?: Function;
keepNewLines?: boolean;
msAllFormatting?: boolean;
msConvertLists?: boolean;
msTags?: boolean;
none?: boolean;
span?: boolean;
}
interface EditorPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface EditorPdf {
author?: string;
avoidLinks?: boolean|string;
creator?: string;
date?: Date;
fileName?: string;
forceProxy?: boolean;
keywords?: string;
landscape?: boolean;
margin?: EditorPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface EditorResizable {
content?: boolean;
min?: number;
max?: number;
toolbar?: boolean;
}
interface EditorSerialization {
custom?: Function;
entities?: boolean;
scripts?: boolean;
semantic?: boolean;
}
interface EditorToolItem {
text?: string;
value?: string;
context?: string;
}
interface EditorTool {
name?: string;
tooltip?: string;
exec?: Function;
items?: EditorToolItem[];
palette?: string|any;
columns?: number;
template?: string;
}
interface EditorExecParams {
value?: any;
}
interface EditorPasteOptions {
split?: boolean;
}
interface EditorOptions {
name?: string;
placeholder?: string;
deserialization?: EditorDeserialization;
domain?: string;
encoded?: boolean;
immutables?: boolean | EditorImmutables;
messages?: EditorMessages;
pasteCleanup?: EditorPasteCleanup;
pdf?: EditorPdf;
resizable?: boolean | EditorResizable;
serialization?: EditorSerialization;
stylesheets?: any;
tools?: EditorTool[];
imageBrowser?: EditorImageBrowser;
fileBrowser?: EditorFileBrowser;
change?(e: EditorEvent): void;
execute?(e: EditorExecuteEvent): void;
keydown?(e: EditorEvent): void;
keyup?(e: EditorEvent): void;
paste?(e: EditorPasteEvent): void;
pdfExport?(e: EditorPdfExportEvent): void;
select?(e: EditorEvent): void;
}
interface EditorEvent {
sender: Editor;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface EditorExecuteEvent extends EditorEvent {
name?: string;
command?: any;
}
interface EditorPasteEvent extends EditorEvent {
html?: any;
}
interface EditorPdfExportEvent extends EditorEvent {
promise?: JQueryPromise<any>;
}
class FilterMenu extends kendo.ui.Widget {
static fn: FilterMenu;
options: FilterMenuOptions;
field: string;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): FilterMenu;
constructor(element: Element, options?: FilterMenuOptions);
clear(): void;
}
interface FilterMenuMessages {
and?: string;
clear?: string;
filter?: string;
info?: string;
title?: string;
additionalValue?: string;
additionalOperator?: string;
logic?: string;
isFalse?: string;
isTrue?: string;
or?: string;
selectValue?: string;
}
interface FilterMenuOperatorsDate {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
gte?: string;
gt?: string;
lte?: string;
lt?: string;
}
interface FilterMenuOperatorsEnums {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
}
interface FilterMenuOperatorsNumber {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
gte?: string;
gt?: string;
lte?: string;
lt?: string;
}
interface FilterMenuOperatorsString {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
isempty?: string;
isnotempty?: string;
startswith?: string;
contains?: string;
doesnotcontain?: string;
endswith?: string;
isnullorempty?: string;
isnotnullorempty?: string;
}
interface FilterMenuOperators {
string?: FilterMenuOperatorsString;
number?: FilterMenuOperatorsNumber;
date?: FilterMenuOperatorsDate;
enums?: FilterMenuOperatorsEnums;
}
interface FilterMenuOptions {
name?: string;
dataSource?: any|any|kendo.data.DataSource;
extra?: boolean;
field?: string;
messages?: FilterMenuMessages;
operators?: FilterMenuOperators;
}
interface FilterMenuEvent {
sender: FilterMenu;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class FlatColorPicker extends kendo.ui.Widget {
static fn: FlatColorPicker;
options: FlatColorPickerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): FlatColorPicker;
constructor(element: Element, options?: FlatColorPickerOptions);
focus(): void;
value(): string;
value(color?: string): void;
color(): kendo.Color;
color(color?: kendo.Color): void;
enable(enable?: boolean): void;
}
interface FlatColorPickerMessages {
apply?: string;
cancel?: string;
}
interface FlatColorPickerOptions {
name?: string;
opacity?: boolean;
buttons?: boolean;
value?: string;
preview?: boolean;
autoupdate?: boolean;
messages?: FlatColorPickerMessages;
change?(e: FlatColorPickerChangeEvent): void;
}
interface FlatColorPickerEvent {
sender: FlatColorPicker;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface FlatColorPickerChangeEvent extends FlatColorPickerEvent {
value?: string;
}
class Gantt extends kendo.ui.Widget {
static fn: Gantt;
options: GanttOptions;
dataSource: kendo.data.DataSource;
dependencies: kendo.data.GanttDependencyDataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Gantt;
constructor(element: Element, options?: GanttOptions);
clearSelection(): void;
dataItem(row: string): kendo.data.GanttTask;
dataItem(row: Element): kendo.data.GanttTask;
dataItem(row: JQuery): kendo.data.GanttTask;
date(date?: Date): Date;
destroy(): void;
range(range?: any): any;
refresh(): void;
refreshDependencies(): void;
removeDependency(dependency: string): void;
removeDependency(dependency: kendo.data.GanttDependency): void;
removeTask(task: string): void;
removeTask(task: kendo.data.GanttTask): void;
saveAsPDF(): JQueryPromise<any>;
select(): JQuery;
select(row: string): void;
select(row: Element): void;
select(row: JQuery): void;
setDataSource(dataSource: kendo.data.GanttDataSource): void;
setDependenciesDataSource(dataSource: kendo.data.GanttDependencyDataSource): void;
view(): kendo.ui.GanttView;
view(type?: string): void;
}
interface GanttAssignments {
dataSource?: any|any|kendo.data.DataSource;
dataResourceIdField?: string;
dataTaskIdField?: string;
dataValueField?: string;
}
interface GanttColumn {
field?: string;
title?: string;
format?: string;
width?: string|number;
editable?: boolean;
sortable?: boolean;
}
interface GanttCurrentTimeMarker {
updateInterval?: number;
}
interface GanttEditable {
confirmation?: boolean;
create?: boolean;
dependencyCreate?: boolean;
dependencyDestroy?: boolean;
dragPercentComplete?: boolean;
destroy?: boolean;
move?: boolean;
reorder?: boolean;
resize?: boolean;
template?: string|Function;
update?: boolean;
}
interface GanttMessagesActions {
addChild?: string;
append?: string;
insertAfter?: string;
insertBefore?: string;
pdf?: string;
}
interface GanttMessagesEditor {
assignButton?: string;
editorTitle?: string;
end?: string;
percentComplete?: string;
resources?: string;
resourcesEditorTitle?: string;
resourcesHeader?: string;
start?: string;
title?: string;
unitsHeader?: string;
}
interface GanttMessagesViews {
day?: string;
end?: string;
month?: string;
start?: string;
week?: string;
year?: string;
}
interface GanttMessages {
actions?: GanttMessagesActions;
cancel?: string;
deleteDependencyConfirmation?: string;
deleteDependencyWindowTitle?: string;
deleteTaskConfirmation?: string;
deleteTaskWindowTitle?: string;
destroy?: string;
editor?: GanttMessagesEditor;
save?: string;
views?: GanttMessagesViews;
}
interface GanttPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface GanttPdf {
author?: string;
avoidLinks?: boolean|string;
creator?: string;
date?: Date;
fileName?: string;
forceProxy?: boolean;
keywords?: string;
landscape?: boolean;
margin?: GanttPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface GanttRange {
start?: Date;
end?: Date;
}
interface GanttResources {
dataFormatField?: string;
dataColorField?: string;
dataSource?: any|any|kendo.data.DataSource;
dataTextField?: string;
field?: string;
}
interface GanttToolbarItem {
name?: string;
template?: string|Function;
text?: string;
}
interface GanttTooltip {
template?: string|Function;
visible?: boolean;
}
interface GanttViewRange {
start?: Date;
end?: Date;
}
interface GanttView {
date?: Date;
range?: GanttViewRange;
type?: string;
selected?: boolean;
slotSize?: number|string;
timeHeaderTemplate?: string|Function;
dayHeaderTemplate?: string|Function;
weekHeaderTemplate?: string|Function;
monthHeaderTemplate?: string|Function;
yearHeaderTemplate?: string|Function;
resizeTooltipFormat?: string;
}
interface GanttOptions {
name?: string;
assignments?: GanttAssignments;
autoBind?: boolean;
columnResizeHandleWidth?: number;
columns?: GanttColumn[];
currentTimeMarker?: boolean | GanttCurrentTimeMarker;
dataSource?: any|any|kendo.data.GanttDataSource;
date?: Date;
dependencies?: any|any|kendo.data.GanttDependencyDataSource;
editable?: boolean | GanttEditable;
navigatable?: boolean;
workDayStart?: Date;
workDayEnd?: Date;
workWeekStart?: number;
workWeekEnd?: number;
hourSpan?: number;
snap?: boolean;
height?: number|string;
listWidth?: string|number;
messages?: GanttMessages;
pdf?: GanttPdf;
range?: GanttRange;
resizable?: boolean;
selectable?: boolean;
showWorkDays?: boolean;
showWorkHours?: boolean;
taskTemplate?: string|Function;
toolbar?: GanttToolbarItem[];
tooltip?: GanttTooltip;
views?: GanttView[];
resources?: GanttResources;
rowHeight?: number|string;
dataBinding?(e: GanttDataBindingEvent): void;
dataBound?(e: GanttDataBoundEvent): void;
add?(e: GanttAddEvent): void;
edit?(e: GanttEditEvent): void;
remove?(e: GanttRemoveEvent): void;
cancel?(e: GanttCancelEvent): void;
save?(e: GanttSaveEvent): void;
change?(e: GanttChangeEvent): void;
columnResize?(e: GanttColumnResizeEvent): void;
navigate?(e: GanttNavigateEvent): void;
moveStart?(e: GanttMoveStartEvent): void;
move?(e: GanttMoveEvent): void;
moveEnd?(e: GanttMoveEndEvent): void;
pdfExport?(e: GanttPdfExportEvent): void;
resizeStart?(e: GanttResizeStartEvent): void;
resize?(e: GanttResizeEvent): void;
resizeEnd?(e: GanttResizeEndEvent): void;
}
interface GanttEvent {
sender: Gantt;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface GanttDataBindingEvent extends GanttEvent {
}
interface GanttDataBoundEvent extends GanttEvent {
}
interface GanttAddEvent extends GanttEvent {
task?: kendo.data.GanttTask;
dependency?: kendo.data.GanttDependency;
}
interface GanttEditEvent extends GanttEvent {
container?: JQuery;
task?: kendo.data.GanttTask;
}
interface GanttRemoveEvent extends GanttEvent {
task?: kendo.data.GanttTask;
dependencies?: any;
}
interface GanttCancelEvent extends GanttEvent {
container?: JQuery;
task?: kendo.data.GanttTask;
}
interface GanttSaveEvent extends GanttEvent {
task?: kendo.data.GanttTask;
values?: any;
}
interface GanttChangeEvent extends GanttEvent {
}
interface GanttColumnResizeEvent extends GanttEvent {
column?: any;
newWidth?: number;
oldWidth?: number;
}
interface GanttNavigateEvent extends GanttEvent {
view?: string;
}
interface GanttMoveStartEvent extends GanttEvent {
task?: kendo.data.GanttTask;
}
interface GanttMoveEvent extends GanttEvent {
task?: kendo.data.GanttTask;
start?: Date;
end?: Date;
}
interface GanttMoveEndEvent extends GanttEvent {
task?: kendo.data.GanttTask;
start?: Date;
end?: Date;
}
interface GanttPdfExportEvent extends GanttEvent {
promise?: JQueryPromise<any>;
}
interface GanttResizeStartEvent extends GanttEvent {
task?: kendo.data.GanttTask;
}
interface GanttResizeEvent extends GanttEvent {
task?: kendo.data.GanttTask;
start?: Date;
end?: Date;
}
interface GanttResizeEndEvent extends GanttEvent {
task?: kendo.data.GanttTask;
start?: Date;
end?: Date;
}
class Grid extends kendo.ui.Widget {
static fn: Grid;
options: GridOptions;
dataSource: kendo.data.DataSource;
columns: GridColumn[];
footer: JQuery;
pager: kendo.ui.Pager;
table: JQuery;
tbody: JQuery;
thead: JQuery;
content: JQuery;
lockedHeader: JQuery;
lockedTable: JQuery;
lockedContent: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Grid;
constructor(element: Element, options?: GridOptions);
addRow(): void;
autoFitColumn(column: number): void;
autoFitColumn(column: string): void;
autoFitColumn(column: any): void;
cancelChanges(): void;
cancelRow(): void;
cellIndex(cell: string): number;
cellIndex(cell: Element): number;
cellIndex(cell: JQuery): number;
clearSelection(): void;
closeCell(isCancel?: boolean): void;
collapseGroup(row: string): void;
collapseGroup(row: Element): void;
collapseGroup(row: JQuery): void;
collapseRow(row: string): void;
collapseRow(row: Element): void;
collapseRow(row: JQuery): void;
current(): JQuery;
current(cell: JQuery): void;
dataItem(row: string): kendo.data.ObservableObject;
dataItem(row: Element): kendo.data.ObservableObject;
dataItem(row: JQuery): kendo.data.ObservableObject;
destroy(): void;
editCell(cell: JQuery): void;
editRow(row: JQuery): void;
expandGroup(row: string): void;
expandGroup(row: Element): void;
expandGroup(row: JQuery): void;
expandRow(row: string): void;
expandRow(row: Element): void;
expandRow(row: JQuery): void;
getOptions(): GridOptions;
hideColumn(column: number): void;
hideColumn(column: string): void;
hideColumn(column: any): void;
items(): any;
lockColumn(column: number): void;
lockColumn(column: string): void;
refresh(): void;
removeRow(row: string): void;
removeRow(row: Element): void;
removeRow(row: JQuery): void;
reorderColumn(destIndex: number, column: any): void;
resizeColumn(column: any, value: number): void;
saveAsExcel(): void;
saveAsPDF(): JQueryPromise<any>;
saveChanges(): void;
saveRow(): void;
select(): JQuery;
select(rows: string): void;
select(rows: Element): void;
select(rows: JQuery): void;
selectedKeyNames(): any;
setDataSource(dataSource: kendo.data.DataSource): void;
setOptions(options: any): void;
showColumn(column: number): void;
showColumn(column: string): void;
showColumn(column: any): void;
unlockColumn(column: number): void;
unlockColumn(column: string): void;
}
interface GridAllowCopy {
delimeter?: string|any;
}
interface GridColumnMenuMessages {
columns?: string;
filter?: string;
sortAscending?: string;
sortDescending?: string;
settings?: string;
done?: string;
lock?: string;
unlock?: string;
}
interface GridColumnMenu {
columns?: boolean;
filterable?: boolean;
sortable?: boolean;
messages?: GridColumnMenuMessages;
}
interface GridColumnCommandItemIconClass {
cancel?: string;
edit?: string;
update?: string;
}
interface GridColumnCommandItemText {
edit?: string;
cancel?: string;
update?: string;
}
interface GridColumnCommandItem {
className?: string;
click?: Function;
iconClass?: string | GridColumnCommandItemIconClass;
name?: string;
template?: string;
text?: string | GridColumnCommandItemText;
visible?: Function;
}
interface GridColumnFilterableCell {
dataSource?: any|kendo.data.DataSource;
dataTextField?: string;
delay?: number;
inputWidth?: number;
suggestionOperator?: string;
minLength?: number;
enabled?: boolean;
operator?: string;
showOperators?: boolean;
template?: Function;
}
interface GridColumnFilterable {
cell?: GridColumnFilterableCell;
extra?: boolean;
multi?: boolean;
dataSource?: any|any|kendo.data.DataSource;
checkAll?: boolean;
itemTemplate?: Function;
operators?: any;
search?: boolean;
ignoreCase?: boolean;
ui?: string|Function;
}
interface GridColumnGroupable {
compare?: Function;
dir?: string;
}
interface GridColumnSortable {
allowUnsort?: boolean;
compare?: Function;
initialDirection?: string;
}
interface GridColumn {
aggregates?: any;
attributes?: any;
columns?: any;
command?: string | string[] | GridColumnCommandItem | GridColumnCommandItem[];
editable?: Function;
encoded?: boolean;
field?: string;
filterable?: boolean | GridColumnFilterable;
footerAttributes?: any;
footerTemplate?: string|Function;
format?: string;
groupable?: boolean | GridColumnGroupable;
groupHeaderColumnTemplate?: string|Function;
groupHeaderTemplate?: string|Function;
groupFooterTemplate?: string|Function;
headerAttributes?: any;
headerTemplate?: string|Function;
hidden?: boolean;
locked?: boolean;
lockable?: boolean;
media?: string;
minResizableWidth?: number;
minScreenWidth?: number;
selectable?: boolean;
sortable?: boolean | GridColumnSortable;
template?: string|Function;
title?: string;
width?: string|number;
values?: any;
menu?: boolean;
}
interface GridEditable {
confirmation?: boolean|string|Function;
cancelDelete?: string;
confirmDelete?: string;
createAt?: string;
destroy?: boolean;
mode?: string;
template?: string|Function;
update?: boolean;
window?: any;
}
interface GridExcel {
allPages?: boolean;
fileName?: string;
filterable?: boolean;
forceProxy?: boolean;
proxyURL?: string;
}
interface GridFilterableMessages {
and?: string;
clear?: string;
filter?: string;
info?: string;
title?: string;
isFalse?: string;
isTrue?: string;
or?: string;
search?: string;
selectValue?: string;
cancel?: string;
selectedItemsFormat?: string;
operator?: string;
value?: string;
checkAll?: string;
}
interface GridFilterableOperatorsDate {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
gte?: string;
gt?: string;
lte?: string;
lt?: string;
}
interface GridFilterableOperatorsEnums {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
}
interface GridFilterableOperatorsNumber {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
gte?: string;
gt?: string;
lte?: string;
lt?: string;
}
interface GridFilterableOperatorsString {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
isempty?: string;
isnotempty?: string;
startswith?: string;
contains?: string;
doesnotcontain?: string;
endswith?: string;
}
interface GridFilterableOperators {
string?: GridFilterableOperatorsString;
number?: GridFilterableOperatorsNumber;
date?: GridFilterableOperatorsDate;
enums?: GridFilterableOperatorsEnums;
}
interface GridFilterable {
extra?: boolean;
messages?: GridFilterableMessages;
mode?: string;
operators?: GridFilterableOperators;
}
interface GridGroupableMessages {
empty?: string;
}
interface GridGroupable {
enabled?: boolean;
showFooter?: boolean;
messages?: GridGroupableMessages;
compare?: Function;
dir?: string;
}
interface GridMessagesCommands {
cancel?: string;
canceledit?: string;
create?: string;
destroy?: string;
edit?: string;
excel?: string;
save?: string;
update?: string;
}
interface GridMessages {
commands?: GridMessagesCommands;
noRecords?: string;
expandCollapseColumnHeader?: string;
}
interface GridNoRecords {
template?: string|Function;
}
interface GridPageableMessages {
display?: string;
empty?: string;
page?: string;
of?: string;
itemsPerPage?: string;
first?: string;
last?: string;
next?: string;
previous?: string;
refresh?: string;
morePages?: string;
}
interface GridPageable {
alwaysVisible?: boolean;
pageSize?: number;
previousNext?: boolean;
numeric?: boolean;
buttonCount?: number;
input?: boolean;
pageSizes?: boolean|any;
refresh?: boolean;
info?: boolean;
messages?: GridPageableMessages;
}
interface GridPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface GridPdf {
allPages?: boolean;
author?: string;
avoidLinks?: boolean|string;
creator?: string;
date?: Date;
fileName?: string;
forceProxy?: boolean;
keywords?: string;
landscape?: boolean;
margin?: GridPdfMargin;
paperSize?: string|any;
template?: string;
repeatHeaders?: boolean;
scale?: number;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface GridScrollable {
virtual?: boolean;
endless?: boolean;
}
interface GridSortable {
allowUnsort?: boolean;
showIndexes?: boolean;
initialDirection?: string;
mode?: string;
}
interface GridToolbarItem {
iconClass?: string;
name?: string;
template?: string|Function;
text?: string;
}
interface GridOptions {
name?: string;
allowCopy?: boolean | GridAllowCopy;
altRowTemplate?: string|Function;
autoBind?: boolean;
columnResizeHandleWidth?: number;
columns?: GridColumn[];
columnMenu?: boolean | GridColumnMenu;
dataSource?: any|any|kendo.data.DataSource;
detailTemplate?: string|Function;
editable?: boolean | "inline" | "incell" | "popup" | GridEditable;
excel?: GridExcel;
filterable?: boolean | GridFilterable;
groupable?: boolean | GridGroupable;
height?: number|string;
messages?: GridMessages;
mobile?: boolean|string;
navigatable?: boolean;
noRecords?: boolean | GridNoRecords;
pageable?: boolean | GridPageable;
pdf?: GridPdf;
persistSelection?: boolean;
reorderable?: boolean;
resizable?: boolean;
rowTemplate?: string|Function;
scrollable?: boolean | GridScrollable;
selectable?: boolean|string;
sortable?: boolean | GridSortable;
toolbar?: string | Function | (string | GridToolbarItem)[];
beforeEdit?(e: GridBeforeEditEvent): void;
cancel?(e: GridCancelEvent): void;
cellClose?(e: GridCellCloseEvent): void;
change?(e: GridChangeEvent): void;
columnHide?(e: GridColumnHideEvent): void;
columnLock?(e: GridColumnLockEvent): void;
columnMenuInit?(e: GridColumnMenuInitEvent): void;
columnMenuOpen?(e: GridColumnMenuOpenEvent): void;
columnReorder?(e: GridColumnReorderEvent): void;
columnResize?(e: GridColumnResizeEvent): void;
columnShow?(e: GridColumnShowEvent): void;
columnUnlock?(e: GridColumnUnlockEvent): void;
dataBinding?(e: GridDataBindingEvent): void;
dataBound?(e: GridDataBoundEvent): void;
detailCollapse?(e: GridDetailCollapseEvent): void;
detailExpand?(e: GridDetailExpandEvent): void;
detailInit?(e: GridDetailInitEvent): void;
edit?(e: GridEditEvent): void;
excelExport?(e: GridExcelExportEvent): void;
filter?(e: GridFilterEvent): void;
filterMenuInit?(e: GridFilterMenuInitEvent): void;
filterMenuOpen?(e: GridFilterMenuOpenEvent): void;
group?(e: GridGroupEvent): void;
groupCollapse?(e: GridGroupCollapseEvent): void;
groupExpand?(e: GridGroupExpandEvent): void;
navigate?(e: GridNavigateEvent): void;
page?(e: GridPageEvent): void;
pdfExport?(e: GridPdfExportEvent): void;
remove?(e: GridRemoveEvent): void;
save?(e: GridSaveEvent): void;
saveChanges?(e: GridSaveChangesEvent): void;
sort?(e: GridSortEvent): void;
}
interface GridEvent {
sender: Grid;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface GridBeforeEditEvent extends GridEvent {
model?: kendo.data.Model;
}
interface GridCancelEvent extends GridEvent {
container?: JQuery;
model?: kendo.data.Model;
}
interface GridCellCloseEvent extends GridEvent {
container?: JQuery;
model?: kendo.data.Model;
type?: string;
}
interface GridChangeEvent extends GridEvent {
}
interface GridColumnHideEvent extends GridEvent {
column?: any;
}
interface GridColumnLockEvent extends GridEvent {
column?: any;
}
interface GridColumnMenuInitEvent extends GridEvent {
container?: JQuery;
field?: string;
}
interface GridColumnMenuOpenEvent extends GridEvent {
container?: JQuery;
field?: string;
}
interface GridColumnReorderEvent extends GridEvent {
column?: any;
newIndex?: number;
oldIndex?: number;
}
interface GridColumnResizeEvent extends GridEvent {
column?: any;
newWidth?: number;
oldWidth?: number;
}
interface GridColumnShowEvent extends GridEvent {
column?: any;
}
interface GridColumnUnlockEvent extends GridEvent {
column?: any;
}
interface GridDataBindingEvent extends GridEvent {
action?: string;
index?: number;
items?: any;
}
interface GridDataBoundEvent extends GridEvent {
}
interface GridDetailCollapseEvent extends GridEvent {
detailRow?: JQuery;
masterRow?: JQuery;
}
interface GridDetailExpandEvent extends GridEvent {
detailRow?: JQuery;
masterRow?: JQuery;
}
interface GridDetailInitEvent extends GridEvent {
data?: kendo.data.ObservableObject;
detailCell?: JQuery;
detailRow?: JQuery;
masterRow?: JQuery;
}
interface GridEditEvent extends GridEvent {
container?: JQuery;
model?: kendo.data.Model;
}
interface GridExcelExportEvent extends GridEvent {
data?: any;
workbook?: kendo.ooxml.Workbook;
}
interface GridFilterEvent extends GridEvent {
filter?: any;
field?: string;
}
interface GridFilterMenuInitEvent extends GridEvent {
container?: JQuery;
field?: string;
}
interface GridFilterMenuOpenEvent extends GridEvent {
container?: JQuery;
field?: string;
}
interface GridGroupEvent extends GridEvent {
groups?: any;
}
interface GridGroupCollapseEvent extends GridEvent {
element?: JQuery;
group?: any;
}
interface GridGroupExpandEvent extends GridEvent {
element?: JQuery;
group?: any;
}
interface GridNavigateEvent extends GridEvent {
element?: JQuery;
}
interface GridPageEvent extends GridEvent {
page?: number;
}
interface GridPdfExportEvent extends GridEvent {
promise?: JQueryPromise<any>;
}
interface GridRemoveEvent extends GridEvent {
model?: kendo.data.Model;
row?: JQuery;
}
interface GridSaveEvent extends GridEvent {
model?: kendo.data.Model;
container?: JQuery;
values?: any;
}
interface GridSaveChangesEvent extends GridEvent {
}
interface GridSortEvent extends GridEvent {
sort?: any;
}
class ListBox extends kendo.ui.Widget {
static fn: ListBox;
options: ListBoxOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ListBox;
constructor(element: Element, options?: ListBoxOptions);
clearSelection(): void;
dataItem(element: JQuery): kendo.data.ObservableObject;
dataItem(element: Element): kendo.data.ObservableObject;
dataItem(element: string): kendo.data.ObservableObject;
dataItems(): kendo.data.ObservableArray;
destroy(): void;
enable(element: JQuery, enable?: boolean): void;
enable(element: Element, enable?: boolean): void;
enable(element: string, enable?: boolean): void;
items(): any;
refresh(): void;
reorder(element: JQuery, index: number): void;
reorder(element: Element, index: number): void;
reorder(element: string, index: number): void;
remove(element: JQuery): void;
remove(element: Element): void;
remove(element: string): void;
remove(element: any): void;
select(): JQuery;
select(items: JQuery): void;
select(items: any): void;
setDataSource(dataSource: kendo.data.DataSource): void;
}
interface ListBoxDraggable {
enabled?: boolean;
hint?: Function|string|JQuery;
placeholder?: Function|string|JQuery;
}
interface ListBoxMessagesTools {
moveDown?: string;
moveUp?: string;
remove?: string;
transferAllFrom?: string;
transferAllTo?: string;
transferFrom?: string;
transferTo?: string;
}
interface ListBoxMessages {
tools?: ListBoxMessagesTools;
}
interface ListBoxToolbar {
position?: string;
tools?: any;
}
interface ListBoxOptions {
name?: string;
autoBind?: boolean;
connectWith?: string;
dataSource?: any|any|kendo.data.DataSource;
dataTextField?: string;
dataValueField?: string;
draggable?: boolean | ListBoxDraggable;
dropSources?: any;
navigatable?: boolean;
messages?: ListBoxMessages;
selectable?: string;
template?: string|Function;
toolbar?: ListBoxToolbar;
add?(e: ListBoxAddEvent): void;
change?(e: ListBoxEvent): void;
dataBound?(e: ListBoxEvent): void;
dragstart?(e: ListBoxDragstartEvent): void;
drag?(e: ListBoxDragEvent): void;
drop?(e: ListBoxDropEvent): void;
dragend?(e: ListBoxDragendEvent): void;
remove?(e: ListBoxRemoveEvent): void;
reorder?(e: ListBoxReorderEvent): void;
}
interface ListBoxEvent {
sender: ListBox;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ListBoxAddEvent extends ListBoxEvent {
items?: any;
dataItems?: any;
}
interface ListBoxDragstartEvent extends ListBoxEvent {
draggableEvent?: any;
items?: JQuery;
}
interface ListBoxDragEvent extends ListBoxEvent {
items?: JQuery;
dataItems?: any;
draggableEvent?: any;
}
interface ListBoxDropEvent extends ListBoxEvent {
items?: any;
dataItems?: any;
}
interface ListBoxDragendEvent extends ListBoxEvent {
items?: any;
dataItems?: any;
draggableEvent?: any;
}
interface ListBoxRemoveEvent extends ListBoxEvent {
items?: any;
dataItems?: any;
}
interface ListBoxReorderEvent extends ListBoxEvent {
items?: any;
dataItems?: any;
offset?: number;
}
class ListView extends kendo.ui.Widget {
static fn: ListView;
options: ListViewOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ListView;
constructor(element: Element, options?: ListViewOptions);
add(): void;
cancel(): void;
clearSelection(): void;
dataItem(row: string): kendo.data.ObservableObject;
dataItem(row: Element): kendo.data.ObservableObject;
dataItem(row: JQuery): kendo.data.ObservableObject;
dataItems(): kendo.data.ObservableArray;
destroy(): void;
edit(item: JQuery): void;
items(): any;
refresh(): void;
remove(item: any): void;
save(): void;
select(): JQuery;
select(items: JQuery): void;
select(items: any): void;
setDataSource(dataSource: kendo.data.DataSource): void;
}
interface ListViewOptions {
name?: string;
autoBind?: boolean;
dataSource?: any|any|kendo.data.DataSource;
editTemplate?: Function;
navigatable?: boolean;
selectable?: boolean|string;
template?: Function;
altTemplate?: Function;
cancel?(e: ListViewCancelEvent): void;
change?(e: ListViewEvent): void;
dataBound?(e: ListViewEvent): void;
dataBinding?(e: ListViewEvent): void;
edit?(e: ListViewEditEvent): void;
remove?(e: ListViewRemoveEvent): void;
save?(e: ListViewSaveEvent): void;
}
interface ListViewEvent {
sender: ListView;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ListViewCancelEvent extends ListViewEvent {
container?: JQuery;
model?: kendo.data.Model;
}
interface ListViewEditEvent extends ListViewEvent {
item?: JQuery;
model?: kendo.data.Model;
}
interface ListViewRemoveEvent extends ListViewEvent {
item?: JQuery;
model?: kendo.data.Model;
}
interface ListViewSaveEvent extends ListViewEvent {
model?: kendo.data.Model;
item?: JQuery;
}
class MaskedTextBox extends kendo.ui.Widget {
static fn: MaskedTextBox;
options: MaskedTextBoxOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): MaskedTextBox;
constructor(element: Element, options?: MaskedTextBoxOptions);
destroy(): void;
enable(enable: boolean): void;
readonly(readonly: boolean): void;
raw(): string;
value(): string;
value(value: string): void;
}
interface MaskedTextBoxOptions {
name?: string;
clearPromptChar?: boolean;
culture?: string;
mask?: string;
promptChar?: string;
rules?: any;
unmaskOnPost?: boolean;
value?: string;
change?(e: MaskedTextBoxChangeEvent): void;
}
interface MaskedTextBoxEvent {
sender: MaskedTextBox;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface MaskedTextBoxChangeEvent extends MaskedTextBoxEvent {
}
class MediaPlayer extends kendo.ui.Widget {
static fn: MediaPlayer;
options: MediaPlayerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): MediaPlayer;
constructor(element: Element, options?: MediaPlayerOptions);
fullScreen(): boolean;
fullScreen(value: boolean): void;
media(): any;
media(value: any): void;
volume(): number;
volume(value: number): void;
mute(value: boolean): boolean;
isEnded(): boolean;
isPaused(): boolean;
isPlaying(): boolean;
pause(): void;
play(): void;
seek(milliseconds: number): number;
stop(): void;
titlebar(): JQuery;
toolbar(): kendo.ui.ToolBar;
}
interface MediaPlayerMedia {
source?: string;
title?: string;
}
interface MediaPlayerMessages {
pause?: string;
play?: string;
mute?: string;
unmute?: string;
quality?: string;
fullscreen?: string;
}
interface MediaPlayerOptions {
name?: string;
autoPlay?: boolean;
autoRepeat?: boolean;
forwardSeek?: boolean;
fullScreen?: boolean;
media?: MediaPlayerMedia;
messages?: MediaPlayerMessages;
mute?: boolean;
navigatable?: boolean;
volume?: number;
end?(e: MediaPlayerEvent): void;
pause?(e: MediaPlayerEvent): void;
play?(e: MediaPlayerEvent): void;
ready?(e: MediaPlayerEvent): void;
timeChange?(e: MediaPlayerEvent): void;
volumeChange?(e: MediaPlayerEvent): void;
}
interface MediaPlayerEvent {
sender: MediaPlayer;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Menu extends kendo.ui.Widget {
static fn: Menu;
options: MenuOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Menu;
constructor(element: Element, options?: MenuOptions);
append(item: any, referenceItem?: string): kendo.ui.Menu;
append(item: any, referenceItem?: JQuery): kendo.ui.Menu;
close(element: string): kendo.ui.Menu;
close(element: Element): kendo.ui.Menu;
close(element: JQuery): kendo.ui.Menu;
destroy(): void;
enable(element: string, enable: boolean): kendo.ui.Menu;
enable(element: Element, enable: boolean): kendo.ui.Menu;
enable(element: JQuery, enable: boolean): kendo.ui.Menu;
insertAfter(item: any, referenceItem: string): kendo.ui.Menu;
insertAfter(item: any, referenceItem: Element): kendo.ui.Menu;
insertAfter(item: any, referenceItem: JQuery): kendo.ui.Menu;
insertBefore(item: any, referenceItem: string): kendo.ui.Menu;
insertBefore(item: any, referenceItem: Element): kendo.ui.Menu;
insertBefore(item: any, referenceItem: JQuery): kendo.ui.Menu;
open(element: string): kendo.ui.Menu;
open(element: Element): kendo.ui.Menu;
open(element: JQuery): kendo.ui.Menu;
remove(element: string): kendo.ui.Menu;
remove(element: Element): kendo.ui.Menu;
remove(element: JQuery): kendo.ui.Menu;
}
interface MenuAnimationClose {
effects?: string;
duration?: number;
}
interface MenuAnimationOpen {
effects?: string;
duration?: number;
}
interface MenuAnimation {
close?: MenuAnimationClose;
open?: MenuAnimationOpen;
}
interface MenuOpenOnClick {
rootMenuItems?: boolean;
subMenuItems?: boolean;
}
interface MenuScrollable {
distance?: number;
}
interface MenuOptions {
name?: string;
animation?: boolean | MenuAnimation;
closeOnClick?: boolean;
dataSource?: any|any;
direction?: string;
hoverDelay?: number;
openOnClick?: boolean | MenuOpenOnClick;
orientation?: string;
popupCollision?: string;
scrollable?: boolean | MenuScrollable;
close?(e: MenuCloseEvent): void;
open?(e: MenuOpenEvent): void;
activate?(e: MenuActivateEvent): void;
deactivate?(e: MenuDeactivateEvent): void;
select?(e: MenuSelectEvent): void;
}
interface MenuEvent {
sender: Menu;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface MenuCloseEvent extends MenuEvent {
item?: HTMLElement;
}
interface MenuOpenEvent extends MenuEvent {
item?: HTMLElement;
}
interface MenuActivateEvent extends MenuEvent {
item?: HTMLElement;
}
interface MenuDeactivateEvent extends MenuEvent {
item?: HTMLElement;
}
interface MenuSelectEvent extends MenuEvent {
item?: HTMLElement;
}
class MultiColumnComboBox extends kendo.ui.Widget {
static fn: MultiColumnComboBox;
options: MultiColumnComboBoxOptions;
dataSource: kendo.data.DataSource;
input: JQuery;
list: JQuery;
ul: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): MultiColumnComboBox;
constructor(element: Element, options?: MultiColumnComboBoxOptions);
close(): void;
dataItem(index?: number): any;
destroy(): void;
enable(enable: boolean): void;
focus(): void;
items(): any;
open(): void;
readonly(readonly: boolean): void;
refresh(): void;
search(word: string): void;
select(): number;
select(li: JQuery): void;
select(li: number): void;
select(li: Function): void;
setDataSource(dataSource: kendo.data.DataSource): void;
suggest(value: string): void;
text(): string;
text(text: string): void;
toggle(toggle: boolean): void;
value(): string;
value(value: string): void;
}
interface MultiColumnComboBoxAnimationClose {
effects?: string;
duration?: number;
}
interface MultiColumnComboBoxAnimationOpen {
effects?: string;
duration?: number;
}
interface MultiColumnComboBoxAnimation {
close?: MultiColumnComboBoxAnimationClose;
open?: MultiColumnComboBoxAnimationOpen;
}
interface MultiColumnComboBoxColumn {
field?: string;
title?: string;
template?: string|Function;
headerTemplate?: string|Function;
width?: number|string;
}
interface MultiColumnComboBoxPopup {
appendTo?: string;
origin?: string;
position?: string;
}
interface MultiColumnComboBoxVirtual {
itemHeight?: number;
mapValueTo?: string;
valueMapper?: Function;
}
interface MultiColumnComboBoxOptions {
name?: string;
animation?: MultiColumnComboBoxAnimation;
autoBind?: boolean;
autoWidth?: boolean;
cascadeFrom?: string;
cascadeFromField?: string;
columns?: MultiColumnComboBoxColumn[];
clearButton?: boolean;
dataSource?: any|any|kendo.data.DataSource;
dataTextField?: string;
dataValueField?: string;
delay?: number;
dropDownWidth?: string|number;
enable?: boolean;
enforceMinLength?: boolean;
filter?: string;
filterFields?: any;
fixedGroupTemplate?: string|Function;
footerTemplate?: string|Function;
groupTemplate?: string|Function;
height?: number;
highlightFirst?: boolean;
ignoreCase?: boolean;
index?: number;
minLength?: number;
noDataTemplate?: string|Function;
placeholder?: string;
popup?: MultiColumnComboBoxPopup;
suggest?: boolean;
syncValueAndText?: boolean;
headerTemplate?: string|Function;
template?: string|Function;
text?: string;
value?: string;
valuePrimitive?: boolean;
virtual?: boolean | MultiColumnComboBoxVirtual;
change?(e: MultiColumnComboBoxChangeEvent): void;
close?(e: MultiColumnComboBoxCloseEvent): void;
dataBound?(e: MultiColumnComboBoxDataBoundEvent): void;
filtering?(e: MultiColumnComboBoxFilteringEvent): void;
open?(e: MultiColumnComboBoxOpenEvent): void;
select?(e: MultiColumnComboBoxSelectEvent): void;
cascade?(e: MultiColumnComboBoxCascadeEvent): void;
}
interface MultiColumnComboBoxEvent {
sender: MultiColumnComboBox;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface MultiColumnComboBoxChangeEvent extends MultiColumnComboBoxEvent {
}
interface MultiColumnComboBoxCloseEvent extends MultiColumnComboBoxEvent {
}
interface MultiColumnComboBoxDataBoundEvent extends MultiColumnComboBoxEvent {
}
interface MultiColumnComboBoxFilteringEvent extends MultiColumnComboBoxEvent {
filter?: any;
}
interface MultiColumnComboBoxOpenEvent extends MultiColumnComboBoxEvent {
}
interface MultiColumnComboBoxSelectEvent extends MultiColumnComboBoxEvent {
dataItem?: any;
item?: JQuery;
}
interface MultiColumnComboBoxCascadeEvent extends MultiColumnComboBoxEvent {
}
class MultiSelect extends kendo.ui.Widget {
static fn: MultiSelect;
options: MultiSelectOptions;
dataSource: kendo.data.DataSource;
input: JQuery;
list: JQuery;
ul: JQuery;
tagList: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): MultiSelect;
constructor(element: Element, options?: MultiSelectOptions);
close(): void;
dataItems(): any;
destroy(): void;
enable(enable: boolean): void;
focus(): void;
items(): any;
open(): void;
readonly(readonly: boolean): void;
refresh(): void;
search(word: string): void;
setDataSource(dataSource: kendo.data.DataSource): void;
toggle(toggle?: boolean): void;
value(): any;
value(value: any): void;
value(value: string): void;
}
interface MultiSelectAnimationClose {
effects?: string;
duration?: number;
}
interface MultiSelectAnimationOpen {
effects?: string;
duration?: number;
}
interface MultiSelectAnimation {
close?: MultiSelectAnimationClose;
open?: MultiSelectAnimationOpen;
}
interface MultiSelectPopup {
appendTo?: string;
origin?: string;
position?: string;
}
interface MultiSelectVirtual {
itemHeight?: number;
mapValueTo?: string;
valueMapper?: Function;
}
interface MultiSelectOptions {
name?: string;
animation?: boolean | MultiSelectAnimation;
autoBind?: boolean;
autoClose?: boolean;
autoWidth?: boolean;
clearButton?: boolean;
dataSource?: any|any|kendo.data.DataSource;
dataTextField?: string;
dataValueField?: string;
delay?: number;
enable?: boolean;
enforceMinLength?: boolean;
filter?: string;
fixedGroupTemplate?: string|Function;
footerTemplate?: string|Function;
groupTemplate?: string|Function;
height?: number;
highlightFirst?: boolean;
ignoreCase?: boolean;
minLength?: number;
maxSelectedItems?: number;
noDataTemplate?: string|Function;
placeholder?: string;
popup?: MultiSelectPopup;
headerTemplate?: string|Function;
itemTemplate?: string|Function;
tagTemplate?: string|Function;
tagMode?: string;
value?: any;
valuePrimitive?: boolean;
virtual?: boolean | MultiSelectVirtual;
change?(e: MultiSelectChangeEvent): void;
close?(e: MultiSelectCloseEvent): void;
dataBound?(e: MultiSelectDataBoundEvent): void;
filtering?(e: MultiSelectFilteringEvent): void;
open?(e: MultiSelectOpenEvent): void;
select?(e: MultiSelectSelectEvent): void;
deselect?(e: MultiSelectDeselectEvent): void;
}
interface MultiSelectEvent {
sender: MultiSelect;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface MultiSelectChangeEvent extends MultiSelectEvent {
}
interface MultiSelectCloseEvent extends MultiSelectEvent {
}
interface MultiSelectDataBoundEvent extends MultiSelectEvent {
}
interface MultiSelectFilteringEvent extends MultiSelectEvent {
filter?: any;
}
interface MultiSelectOpenEvent extends MultiSelectEvent {
}
interface MultiSelectSelectEvent extends MultiSelectEvent {
dataItem?: any;
item?: JQuery;
}
interface MultiSelectDeselectEvent extends MultiSelectEvent {
dataItem?: any;
item?: JQuery;
}
class MultiViewCalendar extends kendo.ui.Widget {
static fn: MultiViewCalendar;
options: MultiViewCalendarOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): MultiViewCalendar;
constructor(element: Element, options?: MultiViewCalendarOptions);
current(): Date;
destroy(): void;
max(): Date;
max(value: Date): void;
max(value: string): void;
min(): Date;
min(value: Date): void;
min(value: string): void;
navigate(value: Date, view: string): void;
navigateDown(value: Date): void;
navigateToFuture(): void;
navigateToPast(): void;
navigateUp(): void;
selectDates(): any;
selectDates(dates: any): void;
selectRange(): any;
selectRange(range: any): void;
value(): Date;
value(value: Date): void;
value(value: string): void;
view(): any;
}
interface MultiViewCalendarMessages {
weekColumnHeader?: string;
}
interface MultiViewCalendarMonth {
content?: string;
weekNumber?: string;
empty?: string;
}
interface MultiViewCalendarRange {
start?: Date;
end?: Date;
}
interface MultiViewCalendarOptions {
name?: string;
culture?: string;
dates?: any;
depth?: string;
disableDates?: any|Function;
footer?: string|Function;
format?: string;
max?: Date;
messages?: MultiViewCalendarMessages;
min?: Date;
month?: MultiViewCalendarMonth;
views?: number;
range?: MultiViewCalendarRange;
selectable?: string;
selectDates?: any;
showViewHeader?: boolean;
weekNumber?: boolean;
start?: string;
value?: Date;
change?(e: MultiViewCalendarEvent): void;
navigate?(e: MultiViewCalendarEvent): void;
}
interface MultiViewCalendarEvent {
sender: MultiViewCalendar;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Notification extends kendo.ui.Widget {
static fn: Notification;
options: NotificationOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Notification;
constructor(element: Element, options?: NotificationOptions);
error(data: any): void;
error(data: string): void;
error(data: Function): void;
getNotifications(): JQuery;
hide(): void;
info(data: any): void;
info(data: string): void;
info(data: Function): void;
show(data: any, type: string): void;
show(data: string, type: string): void;
show(data: Function, type: string): void;
showText(data: any, type: string): void;
showText(data: string, type: string): void;
showText(data: Function, type: string): void;
success(data: any): void;
success(data: string): void;
success(data: Function): void;
warning(data: any): void;
warning(data: string): void;
warning(data: Function): void;
}
interface NotificationPosition {
bottom?: number;
left?: number;
pinned?: boolean;
right?: number;
top?: number;
}
interface NotificationTemplate {
type?: string;
template?: string;
}
interface NotificationOptions {
name?: string;
allowHideAfter?: number;
animation?: any|boolean;
appendTo?: string|JQuery;
autoHideAfter?: number;
button?: boolean;
height?: number|string;
hideOnClick?: boolean;
position?: NotificationPosition;
stacking?: string;
templates?: NotificationTemplate[];
width?: number|string;
hide?(e: NotificationHideEvent): void;
show?(e: NotificationShowEvent): void;
}
interface NotificationEvent {
sender: Notification;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface NotificationHideEvent extends NotificationEvent {
element?: JQuery;
}
interface NotificationShowEvent extends NotificationEvent {
element?: JQuery;
}
class NumericTextBox extends kendo.ui.Widget {
static fn: NumericTextBox;
options: NumericTextBoxOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): NumericTextBox;
constructor(element: Element, options?: NumericTextBoxOptions);
destroy(): void;
enable(enable: boolean): void;
readonly(readonly: boolean): void;
focus(): void;
max(): number;
max(value: number): void;
max(value: string): void;
min(): number;
min(value: number): void;
min(value: string): void;
step(): number;
step(value: number): void;
step(value: string): void;
value(): number;
value(value: number): void;
value(value: string): void;
}
interface NumericTextBoxOptions {
name?: string;
culture?: string;
decimals?: number;
downArrowText?: string;
factor?: number;
format?: string;
max?: number;
min?: number;
placeholder?: string;
restrictDecimals?: boolean;
round?: boolean;
spinners?: boolean;
step?: number;
upArrowText?: string;
value?: number;
change?(e: NumericTextBoxChangeEvent): void;
spin?(e: NumericTextBoxSpinEvent): void;
}
interface NumericTextBoxEvent {
sender: NumericTextBox;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface NumericTextBoxChangeEvent extends NumericTextBoxEvent {
}
interface NumericTextBoxSpinEvent extends NumericTextBoxEvent {
}
class Pager extends kendo.ui.Widget {
static fn: Pager;
options: PagerOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Pager;
constructor(element: Element, options?: PagerOptions);
totalPages(): number;
pageSize(): number;
page(): number;
page(page: number): void;
refresh(): void;
destroy(): void;
}
interface PagerMessages {
display?: string;
empty?: string;
allPages?: string;
page?: string;
of?: string;
itemsPerPage?: string;
first?: string;
previous?: string;
next?: string;
last?: string;
refresh?: string;
}
interface PagerOptions {
name?: string;
autoBind?: boolean;
buttonCount?: number;
dataSource?: any|kendo.data.DataSource;
selectTemplate?: string;
linkTemplate?: string;
info?: boolean;
input?: boolean;
numeric?: boolean;
pageSizes?: boolean|any;
previousNext?: boolean;
refresh?: boolean;
messages?: PagerMessages;
change?(e: PagerChangeEvent): void;
}
interface PagerEvent {
sender: Pager;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface PagerChangeEvent extends PagerEvent {
}
class PanelBar extends kendo.ui.Widget {
static fn: PanelBar;
options: PanelBarOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): PanelBar;
constructor(element: Element, options?: PanelBarOptions);
append(item: string, referenceItem?: string): kendo.ui.PanelBar;
append(item: string, referenceItem?: Element): kendo.ui.PanelBar;
append(item: string, referenceItem?: JQuery): kendo.ui.PanelBar;
append(item: Element, referenceItem?: string): kendo.ui.PanelBar;
append(item: Element, referenceItem?: Element): kendo.ui.PanelBar;
append(item: Element, referenceItem?: JQuery): kendo.ui.PanelBar;
append(item: JQuery, referenceItem?: string): kendo.ui.PanelBar;
append(item: JQuery, referenceItem?: Element): kendo.ui.PanelBar;
append(item: JQuery, referenceItem?: JQuery): kendo.ui.PanelBar;
append(item: any, referenceItem?: string): kendo.ui.PanelBar;
append(item: any, referenceItem?: Element): kendo.ui.PanelBar;
append(item: any, referenceItem?: JQuery): kendo.ui.PanelBar;
clearSelection(): void;
collapse(element: string, useAnimation: boolean): kendo.ui.PanelBar;
collapse(element: Element, useAnimation: boolean): kendo.ui.PanelBar;
collapse(element: JQuery, useAnimation: boolean): kendo.ui.PanelBar;
destroy(): void;
enable(element: string, enable: boolean): void;
enable(element: Element, enable: boolean): void;
enable(element: JQuery, enable: boolean): void;
expand(element: string, useAnimation: boolean): kendo.ui.PanelBar;
expand(element: Element, useAnimation: boolean): kendo.ui.PanelBar;
expand(element: JQuery, useAnimation: boolean): kendo.ui.PanelBar;
insertAfter(item: string, referenceItem: string): void;
insertAfter(item: string, referenceItem: Element): void;
insertAfter(item: string, referenceItem: JQuery): void;
insertAfter(item: Element, referenceItem: string): void;
insertAfter(item: Element, referenceItem: Element): void;
insertAfter(item: Element, referenceItem: JQuery): void;
insertAfter(item: JQuery, referenceItem: string): void;
insertAfter(item: JQuery, referenceItem: Element): void;
insertAfter(item: JQuery, referenceItem: JQuery): void;
insertAfter(item: any, referenceItem: string): void;
insertAfter(item: any, referenceItem: Element): void;
insertAfter(item: any, referenceItem: JQuery): void;
insertBefore(item: string, referenceItem: string): kendo.ui.PanelBar;
insertBefore(item: string, referenceItem: Element): kendo.ui.PanelBar;
insertBefore(item: string, referenceItem: JQuery): kendo.ui.PanelBar;
insertBefore(item: Element, referenceItem: string): kendo.ui.PanelBar;
insertBefore(item: Element, referenceItem: Element): kendo.ui.PanelBar;
insertBefore(item: Element, referenceItem: JQuery): kendo.ui.PanelBar;
insertBefore(item: JQuery, referenceItem: string): kendo.ui.PanelBar;
insertBefore(item: JQuery, referenceItem: Element): kendo.ui.PanelBar;
insertBefore(item: JQuery, referenceItem: JQuery): kendo.ui.PanelBar;
insertBefore(item: any, referenceItem: string): kendo.ui.PanelBar;
insertBefore(item: any, referenceItem: Element): kendo.ui.PanelBar;
insertBefore(item: any, referenceItem: JQuery): kendo.ui.PanelBar;
reload(element: string): void;
reload(element: Element): void;
reload(element: JQuery): void;
remove(element: string): void;
remove(element: Element): void;
remove(element: JQuery): void;
select(): JQuery;
select(element?: string): void;
select(element?: Element): void;
select(element?: JQuery): void;
}
interface PanelBarAnimationCollapse {
duration?: number;
effects?: string;
}
interface PanelBarAnimationExpand {
duration?: number;
effects?: string;
}
interface PanelBarAnimation {
collapse?: PanelBarAnimationCollapse;
expand?: PanelBarAnimationExpand;
}
interface PanelBarMessages {
loading?: string;
requestFailed?: string;
retry?: string;
}
interface PanelBarOptions {
name?: string;
animation?: boolean | PanelBarAnimation;
autoBind?: boolean;
contentUrls?: any;
dataImageUrlField?: string;
dataSource?: any|any|kendo.data.HierarchicalDataSource;
dataSpriteCssClassField?: string;
dataTextField?: string|any;
dataUrlField?: string;
expandMode?: string;
loadOnDemand?: boolean;
messages?: PanelBarMessages;
template?: string|Function;
activate?(e: PanelBarActivateEvent): void;
collapse?(e: PanelBarCollapseEvent): void;
contentLoad?(e: PanelBarContentLoadEvent): void;
dataBound?(e: PanelBarDataBoundEvent): void;
error?(e: PanelBarErrorEvent): void;
expand?(e: PanelBarExpandEvent): void;
select?(e: PanelBarSelectEvent): void;
}
interface PanelBarEvent {
sender: PanelBar;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface PanelBarActivateEvent extends PanelBarEvent {
item?: Element;
}
interface PanelBarCollapseEvent extends PanelBarEvent {
item?: Element;
}
interface PanelBarContentLoadEvent extends PanelBarEvent {
item?: Element;
contentElement?: Element;
}
interface PanelBarDataBoundEvent extends PanelBarEvent {
node?: JQuery;
}
interface PanelBarErrorEvent extends PanelBarEvent {
xhr?: JQueryXHR;
status?: string;
}
interface PanelBarExpandEvent extends PanelBarEvent {
item?: Element;
}
interface PanelBarSelectEvent extends PanelBarEvent {
item?: Element;
}
class PivotConfigurator extends kendo.ui.Widget {
static fn: PivotConfigurator;
options: PivotConfiguratorOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): PivotConfigurator;
constructor(element: Element, options?: PivotConfiguratorOptions);
destroy(): void;
refresh(): void;
setDataSource(dataSource: kendo.data.PivotDataSource): void;
}
interface PivotConfiguratorMessagesFieldMenuOperators {
contains?: string;
doesnotcontain?: string;
startswith?: string;
endswith?: string;
eq?: string;
neq?: string;
}
interface PivotConfiguratorMessagesFieldMenu {
info?: string;
sortAscending?: string;
sortDescending?: string;
filterFields?: string;
filter?: string;
include?: string;
title?: string;
clear?: string;
ok?: string;
cancel?: string;
operators?: PivotConfiguratorMessagesFieldMenuOperators;
}
interface PivotConfiguratorMessages {
measures?: string;
columns?: string;
rows?: string;
measuresLabel?: string;
rowsLabel?: string;
columnsLabel?: string;
fieldsLabel?: string;
fieldMenu?: PivotConfiguratorMessagesFieldMenu;
}
interface PivotConfiguratorSortable {
allowUnsort?: boolean;
}
interface PivotConfiguratorOptions {
name?: string;
dataSource?: any|kendo.data.PivotDataSource;
filterable?: boolean;
sortable?: boolean | PivotConfiguratorSortable;
height?: number|string;
messages?: PivotConfiguratorMessages;
}
interface PivotConfiguratorEvent {
sender: PivotConfigurator;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class PivotGrid extends kendo.ui.Widget {
static fn: PivotGrid;
options: PivotGridOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): PivotGrid;
constructor(element: Element, options?: PivotGridOptions);
cellInfo(columnIndex: number, rowIndex: number): any;
cellInfoByElement(cell: string): any;
cellInfoByElement(cell: Element): any;
cellInfoByElement(cell: JQuery): any;
destroy(): void;
refresh(): void;
setDataSource(dataSource: kendo.data.PivotDataSource): void;
saveAsExcel(): void;
saveAsPDF(): JQueryPromise<any>;
}
interface PivotGridExcel {
fileName?: string;
filterable?: boolean;
forceProxy?: boolean;
proxyURL?: string;
}
interface PivotGridMessagesFieldMenuOperators {
contains?: string;
doesnotcontain?: string;
startswith?: string;
endswith?: string;
eq?: string;
neq?: string;
}
interface PivotGridMessagesFieldMenu {
info?: string;
sortAscending?: string;
sortDescending?: string;
filterFields?: string;
filter?: string;
include?: string;
title?: string;
clear?: string;
ok?: string;
cancel?: string;
operators?: PivotGridMessagesFieldMenuOperators;
}
interface PivotGridMessages {
measureFields?: string;
columnFields?: string;
rowFields?: string;
fieldMenu?: PivotGridMessagesFieldMenu;
}
interface PivotGridPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface PivotGridPdf {
author?: string;
avoidLinks?: boolean|string;
creator?: string;
date?: Date;
fileName?: string;
forceProxy?: boolean;
keywords?: string;
landscape?: boolean;
margin?: PivotGridPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface PivotGridSortable {
allowUnsort?: boolean;
}
interface PivotGridOptions {
name?: string;
dataSource?: any|kendo.data.PivotDataSource;
autoBind?: boolean;
reorderable?: boolean;
excel?: PivotGridExcel;
pdf?: PivotGridPdf;
filterable?: boolean;
sortable?: boolean | PivotGridSortable;
columnWidth?: number;
height?: number|string;
columnHeaderTemplate?: string|Function;
dataCellTemplate?: string|Function;
kpiStatusTemplate?: string|Function;
kpiTrendTemplate?: string|Function;
rowHeaderTemplate?: string|Function;
messages?: PivotGridMessages;
dataBinding?(e: PivotGridDataBindingEvent): void;
dataBound?(e: PivotGridDataBoundEvent): void;
expandMember?(e: PivotGridExpandMemberEvent): void;
collapseMember?(e: PivotGridCollapseMemberEvent): void;
excelExport?(e: PivotGridExcelExportEvent): void;
pdfExport?(e: PivotGridPdfExportEvent): void;
}
interface PivotGridEvent {
sender: PivotGrid;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface PivotGridDataBindingEvent extends PivotGridEvent {
}
interface PivotGridDataBoundEvent extends PivotGridEvent {
}
interface PivotGridExpandMemberEvent extends PivotGridEvent {
axis?: string;
path?: string[];
}
interface PivotGridCollapseMemberEvent extends PivotGridEvent {
axis?: string;
path?: string[];
}
interface PivotGridExcelExportEvent extends PivotGridEvent {
data?: any;
workbook?: any;
}
interface PivotGridPdfExportEvent extends PivotGridEvent {
promise?: JQueryPromise<any>;
}
class Popup extends kendo.ui.Widget {
static fn: Popup;
options: PopupOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Popup;
constructor(element: Element, options?: PopupOptions);
close(): void;
open(): void;
position(): void;
setOptions(options: any): void;
visible(): boolean;
}
interface PopupAnimationClose {
effects?: string;
duration?: number;
}
interface PopupAnimationOpen {
effects?: string;
duration?: number;
}
interface PopupAnimation {
close?: PopupAnimationClose;
open?: PopupAnimationOpen;
}
interface PopupOptions {
name?: string;
adjustSize?: any;
animation?: boolean | PopupAnimation;
anchor?: string|JQuery;
appendTo?: string|JQuery;
collision?: string;
origin?: string;
position?: string;
activate?(e: PopupActivateEvent): void;
close?(e: PopupCloseEvent): void;
deactivate?(e: PopupDeactivateEvent): void;
open?(e: PopupOpenEvent): void;
}
interface PopupEvent {
sender: Popup;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface PopupActivateEvent extends PopupEvent {
}
interface PopupCloseEvent extends PopupEvent {
}
interface PopupDeactivateEvent extends PopupEvent {
}
interface PopupOpenEvent extends PopupEvent {
}
class ProgressBar extends kendo.ui.Widget {
static fn: ProgressBar;
options: ProgressBarOptions;
progressStatus: JQuery;
progressWrapper: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ProgressBar;
constructor(element: Element, options?: ProgressBarOptions);
enable(enable: boolean): void;
value(): number;
value(value: number): void;
}
interface ProgressBarAnimation {
duration?: number;
}
interface ProgressBarOptions {
name?: string;
animation?: boolean | ProgressBarAnimation;
chunkCount?: number;
enable?: boolean;
max?: number;
min?: number;
orientation?: string;
reverse?: boolean;
showStatus?: boolean;
type?: string;
value?: number;
change?(e: ProgressBarChangeEvent): void;
complete?(e: ProgressBarCompleteEvent): void;
}
interface ProgressBarEvent {
sender: ProgressBar;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ProgressBarChangeEvent extends ProgressBarEvent {
value?: number;
}
interface ProgressBarCompleteEvent extends ProgressBarEvent {
value?: number;
}
class Prompt extends kendo.ui.Dialog {
static fn: Prompt;
options: PromptOptions;
result: JQueryPromise<any>;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Prompt;
constructor(element: Element, options?: PromptOptions);
}
interface PromptMessages {
okText?: string;
cancel?: string;
}
interface PromptOptions {
name?: string;
messages?: PromptMessages;
}
interface PromptEvent {
sender: Prompt;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class RangeSlider extends kendo.ui.Widget {
static fn: RangeSlider;
options: RangeSliderOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): RangeSlider;
constructor(element: Element, options?: RangeSliderOptions);
destroy(): void;
enable(enable: boolean): void;
value(): any;
value(startEndArray: any): void;
values(): any;
values(selectionStart: number, selectionEnd: number): void;
resize(): void;
}
interface RangeSliderTooltip {
enabled?: boolean;
format?: string;
template?: string;
}
interface RangeSliderOptions {
name?: string;
largeStep?: number;
leftDragHandleTitle?: string;
max?: number;
min?: number;
orientation?: string;
rightDragHandleTitle?: string;
selectionEnd?: number;
selectionStart?: number;
smallStep?: number;
tickPlacement?: string;
tooltip?: RangeSliderTooltip;
change?(e: RangeSliderChangeEvent): void;
slide?(e: RangeSliderSlideEvent): void;
}
interface RangeSliderEvent {
sender: RangeSlider;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface RangeSliderChangeEvent extends RangeSliderEvent {
value?: any;
}
interface RangeSliderSlideEvent extends RangeSliderEvent {
value?: any;
}
class ResponsivePanel extends kendo.ui.Widget {
static fn: ResponsivePanel;
options: ResponsivePanelOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ResponsivePanel;
constructor(element: Element, options?: ResponsivePanelOptions);
close(): void;
destroy(): void;
open(): void;
}
interface SchedulerSelectOptions {
events?: SchedulerEvent[] | any[];
resources? : any[];
start?: Date;
end?: Date;
isAllDay?: boolean;
}
interface ResponsivePanelOptions {
name?: string;
autoClose?: boolean;
breakpoint?: number;
orientation?: string;
toggleButton?: string;
close?(e: ResponsivePanelEvent): void;
open?(e: ResponsivePanelEvent): void;
}
interface ResponsivePanelEvent {
sender: ResponsivePanel;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Scheduler extends kendo.ui.Widget {
static fn: Scheduler;
options: SchedulerOptions;
dataSource: kendo.data.DataSource;
resources: any;
calendar: kendo.ui.Calendar;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Scheduler;
constructor(element: Element, options?: SchedulerOptions);
addEvent(data: any): void;
cancelEvent(): void;
data(): void;
date(): Date;
date(value?: Date): void;
destroy(): void;
editEvent(event: string): void;
editEvent(event: kendo.data.SchedulerEvent): void;
items(): any;
occurrenceByUid(uid: string): kendo.data.SchedulerEvent;
occurrencesInRange(start: Date, end: Date): any;
refresh(): void;
removeEvent(event: string): void;
removeEvent(event: kendo.data.SchedulerEvent): void;
resourcesBySlot(slot: any): any;
saveAsPDF(): JQueryPromise<any>;
saveEvent(): void;
select(): void;
select(options: SchedulerEvent[] | SchedulerSelectOptions): void;
setDataSource(dataSource: kendo.data.SchedulerDataSource): void;
slotByPosition(xPosition: number, yPosition: number): any;
slotByElement(element: Element): any;
slotByElement(element: JQuery): any;
view(): kendo.ui.SchedulerView;
view(type?: string): void;
viewName(): string;
}
interface SchedulerCurrentTimeMarker {
updateInterval?: number;
useLocalTimezone?: boolean;
}
interface SchedulerEditable {
confirmation?: boolean|string;
create?: boolean;
destroy?: boolean;
editRecurringMode?: string;
move?: boolean;
resize?: boolean;
template?: string|Function;
update?: boolean;
window?: any;
}
interface SchedulerFooter {
command?: string|boolean;
}
interface SchedulerGroup {
date?: boolean;
resources?: any;
orientation?: string;
}
interface SchedulerMessagesEditable {
confirmation?: string;
}
interface SchedulerMessagesEditor {
allDayEvent?: string;
description?: string;
editorTitle?: string;
end?: string;
endTimezone?: string;
repeat?: string;
separateTimezones?: string;
start?: string;
startTimezone?: string;
timezone?: string;
timezoneEditorButton?: string;
timezoneEditorTitle?: string;
title?: string;
}
interface SchedulerMessagesRecurrenceEditorDaily {
interval?: string;
repeatEvery?: string;
}
interface SchedulerMessagesRecurrenceEditorEnd {
after?: string;
occurrence?: string;
label?: string;
never?: string;
mobileLabel?: string;
on?: string;
}
interface SchedulerMessagesRecurrenceEditorFrequencies {
daily?: string;
monthly?: string;
never?: string;
weekly?: string;
yearly?: string;
}
interface SchedulerMessagesRecurrenceEditorMonthly {
day?: string;
interval?: string;
repeatEvery?: string;
repeatOn?: string;
}
interface SchedulerMessagesRecurrenceEditorOffsetPositions {
first?: string;
second?: string;
third?: string;
fourth?: string;
last?: string;
}
interface SchedulerMessagesRecurrenceEditorWeekdays {
day?: string;
weekday?: string;
weekend?: string;
}
interface SchedulerMessagesRecurrenceEditorWeekly {
interval?: string;
repeatEvery?: string;
repeatOn?: string;
}
interface SchedulerMessagesRecurrenceEditorYearly {
of?: string;
repeatEvery?: string;
repeatOn?: string;
interval?: string;
}
interface SchedulerMessagesRecurrenceEditor {
daily?: SchedulerMessagesRecurrenceEditorDaily;
end?: SchedulerMessagesRecurrenceEditorEnd;
frequencies?: SchedulerMessagesRecurrenceEditorFrequencies;
monthly?: SchedulerMessagesRecurrenceEditorMonthly;
offsetPositions?: SchedulerMessagesRecurrenceEditorOffsetPositions;
recurrenceEditorTitle?: string;
weekly?: SchedulerMessagesRecurrenceEditorWeekly;
weekdays?: SchedulerMessagesRecurrenceEditorWeekdays;
yearly?: SchedulerMessagesRecurrenceEditorYearly;
}
interface SchedulerMessagesRecurrenceMessages {
deleteRecurring?: string;
deleteWindowOccurrence?: string;
deleteWindowSeries?: string;
deleteWindowTitle?: string;
editRecurring?: string;
editWindowOccurrence?: string;
editWindowSeries?: string;
editWindowTitle?: string;
}
interface SchedulerMessagesViews {
day?: string;
week?: string;
month?: string;
agenda?: string;
}
interface SchedulerMessages {
allDay?: string;
ariaEventLabel?: string;
ariaSlotLabel?: string;
cancel?: string;
date?: string;
deleteWindowTitle?: string;
destroy?: string;
event?: string;
defaultRowText?: string;
next?: string;
pdf?: string;
previous?: string;
save?: string;
showFullDay?: string;
showWorkDay?: string;
time?: string;
today?: string;
editable?: SchedulerMessagesEditable;
editor?: SchedulerMessagesEditor;
recurrenceEditor?: SchedulerMessagesRecurrenceEditor;
recurrenceMessages?: SchedulerMessagesRecurrenceMessages;
views?: SchedulerMessagesViews;
}
interface SchedulerPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface SchedulerPdf {
author?: string;
avoidLinks?: boolean|string;
creator?: string;
date?: Date;
fileName?: string;
forceProxy?: boolean;
keywords?: string;
landscape?: boolean;
margin?: SchedulerPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface SchedulerResource {
dataColorField?: string;
dataSource?: any|any|kendo.data.DataSource;
dataTextField?: string;
dataValueField?: string;
field?: string;
multiple?: boolean;
name?: string;
title?: string;
valuePrimitive?: boolean;
}
interface SchedulerToolbarItem {
name?: string;
}
interface SchedulerViewEditable {
create?: boolean;
destroy?: boolean;
update?: boolean;
}
interface SchedulerViewGroup {
date?: boolean;
orientation?: string;
}
interface SchedulerView {
allDayEventTemplate?: string|Function;
allDaySlot?: boolean;
allDaySlotTemplate?: string|Function;
columnWidth?: number;
dateHeaderTemplate?: string|Function;
dayTemplate?: string|Function;
editable?: boolean | SchedulerViewEditable;
endTime?: Date;
eventHeight?: number;
eventTemplate?: string|Function;
eventTimeTemplate?: string|Function;
group?: SchedulerViewGroup;
majorTick?: number;
majorTimeHeaderTemplate?: string|Function;
minorTickCount?: number;
minorTimeHeaderTemplate?: string|Function;
name?: string;
selected?: boolean;
selectedDateFormat?: string;
selectedShortDateFormat?: string;
showWorkHours?: boolean;
slotTemplate?: string|Function;
startTime?: Date;
title?: string;
type?: string;
workWeekStart?: number;
workWeekEnd?: number;
}
interface SchedulerOptions {
name?: string;
allDayEventTemplate?: string|Function;
allDaySlot?: boolean;
autoBind?: boolean;
currentTimeMarker?: boolean | SchedulerCurrentTimeMarker;
dataSource?: any|any|kendo.data.SchedulerDataSource;
date?: Date;
dateHeaderTemplate?: string|Function;
editable?: boolean | SchedulerEditable;
endTime?: Date;
eventTemplate?: string|Function;
footer?: boolean | SchedulerFooter;
group?: SchedulerGroup;
groupHeaderTemplate?: string|Function;
height?: number|string;
majorTick?: number;
majorTimeHeaderTemplate?: string|Function;
max?: Date;
messages?: SchedulerMessages;
min?: Date;
minorTickCount?: number;
minorTimeHeaderTemplate?: string|Function;
mobile?: boolean|string;
pdf?: SchedulerPdf;
resources?: SchedulerResource[];
selectable?: boolean;
showWorkHours?: boolean;
snap?: boolean;
startTime?: Date;
timezone?: string;
toolbar?: SchedulerToolbarItem[];
views?: SchedulerView[];
width?: number|string;
workDayStart?: Date;
workDayEnd?: Date;
workWeekStart?: number;
workWeekEnd?: number;
add?(e: SchedulerAddEvent): void;
cancel?(e: SchedulerCancelEvent): void;
change?(e: SchedulerChangeEvent): void;
dataBinding?(e: SchedulerDataBindingEvent): void;
dataBound?(e: SchedulerDataBoundEvent): void;
edit?(e: SchedulerEditEvent): void;
moveStart?(e: SchedulerMoveStartEvent): void;
move?(e: SchedulerMoveEvent): void;
moveEnd?(e: SchedulerMoveEndEvent): void;
navigate?(e: SchedulerNavigateEvent): void;
pdfExport?(e: SchedulerPdfExportEvent): void;
remove?(e: SchedulerRemoveEvent): void;
resizeStart?(e: SchedulerResizeStartEvent): void;
resize?(e: SchedulerResizeEvent): void;
resizeEnd?(e: SchedulerResizeEndEvent): void;
save?(e: SchedulerSaveEvent): void;
}
interface SchedulerEvent {
sender: Scheduler;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SchedulerAddEvent extends SchedulerEvent {
event?: any;
}
interface SchedulerCancelEvent extends SchedulerEvent {
container?: JQuery;
event?: kendo.data.SchedulerEvent;
}
interface SchedulerChangeEvent extends SchedulerEvent {
start?: Date;
end?: Date;
events?: any;
slots?: any;
resources?: any;
}
interface SchedulerDataBindingEvent extends SchedulerEvent {
}
interface SchedulerDataBoundEvent extends SchedulerEvent {
}
interface SchedulerEditEvent extends SchedulerEvent {
container?: JQuery;
event?: kendo.data.SchedulerEvent;
}
interface SchedulerMoveStartEvent extends SchedulerEvent {
event?: kendo.data.SchedulerEvent;
}
interface SchedulerMoveEvent extends SchedulerEvent {
event?: kendo.data.SchedulerEvent;
slot?: any;
}
interface SchedulerMoveEndEvent extends SchedulerEvent {
start?: Date;
end?: Date;
event?: kendo.data.SchedulerEvent;
slot?: any;
resources?: any;
}
interface SchedulerNavigateEvent extends SchedulerEvent {
action?: string;
date?: Date;
view?: string;
}
interface SchedulerPdfExportEvent extends SchedulerEvent {
promise?: JQueryPromise<any>;
}
interface SchedulerRemoveEvent extends SchedulerEvent {
event?: kendo.data.SchedulerEvent;
}
interface SchedulerResizeStartEvent extends SchedulerEvent {
event?: kendo.data.SchedulerEvent;
}
interface SchedulerResizeEvent extends SchedulerEvent {
event?: kendo.data.SchedulerEvent;
slot?: any;
}
interface SchedulerResizeEndEvent extends SchedulerEvent {
start?: Date;
end?: Date;
event?: kendo.data.SchedulerEvent;
slot?: any;
}
interface SchedulerSaveEvent extends SchedulerEvent {
container?: JQuery;
event?: kendo.data.SchedulerEvent;
}
class ScrollView extends kendo.ui.Widget {
static fn: ScrollView;
options: ScrollViewOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ScrollView;
constructor(element: Element, options?: ScrollViewOptions);
content(content: string): void;
content(content: JQuery): void;
destroy(): void;
next(): void;
prev(): void;
refresh(): void;
scrollTo(page: number, instant: boolean): void;
setDataSource(dataSource: kendo.data.DataSource): void;
}
interface ScrollViewOptions {
name?: string;
autoBind?: boolean;
bounceVelocityThreshold?: number;
contentHeight?: number|string;
dataSource?: kendo.data.DataSource|any;
duration?: number;
emptyTemplate?: string;
enablePager?: boolean;
page?: number;
template?: string;
velocityThreshold?: number;
change?(e: ScrollViewChangeEvent): void;
refresh?(e: ScrollViewRefreshEvent): void;
}
interface ScrollViewEvent {
sender: ScrollView;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ScrollViewChangeEvent extends ScrollViewEvent {
currentPage?: number;
nextPage?: number;
element?: JQuery;
data?: any;
}
interface ScrollViewRefreshEvent extends ScrollViewEvent {
pageCount?: number;
page?: number;
}
class Slider extends kendo.ui.Widget {
static fn: Slider;
options: SliderOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Slider;
constructor(element: Element, options?: SliderOptions);
destroy(): void;
enable(enable: boolean): void;
max(): number;
max(value: number): void;
max(value: string): void;
min(): number;
min(value: number): void;
min(value: string): void;
setOptions(options: any): void;
value(): number;
value(value: number): void;
resize(): void;
}
interface SliderTooltip {
enabled?: boolean;
format?: string;
template?: string|Function;
}
interface SliderOptions {
name?: string;
decreaseButtonTitle?: string;
dragHandleTitle?: string;
increaseButtonTitle?: string;
largeStep?: number;
max?: number;
min?: number;
orientation?: string;
showButtons?: boolean;
smallStep?: number;
tickPlacement?: string;
tooltip?: SliderTooltip;
value?: number;
change?(e: SliderChangeEvent): void;
slide?(e: SliderSlideEvent): void;
}
interface SliderEvent {
sender: Slider;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SliderChangeEvent extends SliderEvent {
value?: number;
}
interface SliderSlideEvent extends SliderEvent {
value?: number;
}
class Sortable extends kendo.ui.Widget {
static fn: Sortable;
options: SortableOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Sortable;
constructor(element: Element, options?: SortableOptions);
indexOf(element: JQuery): number;
items(): JQuery;
}
interface SortableCursorOffset {
left?: number;
top?: number;
}
interface SortableOptions {
name?: string;
axis?: string;
autoScroll?: boolean;
container?: string|JQuery;
connectWith?: string;
cursor?: string;
cursorOffset?: SortableCursorOffset;
disabled?: string;
filter?: string;
handler?: string;
hint?: Function|string|JQuery;
holdToDrag?: boolean;
ignore?: string;
placeholder?: Function|string|JQuery;
start?(e: SortableStartEvent): void;
move?(e: SortableMoveEvent): void;
end?(e: SortableEndEvent): void;
change?(e: SortableChangeEvent): void;
cancel?(e: SortableCancelEvent): void;
}
interface SortableEvent {
sender: Sortable;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SortableStartEvent extends SortableEvent {
draggableEvent?: any;
item?: JQuery;
}
interface SortableMoveEvent extends SortableEvent {
item?: JQuery;
target?: JQuery;
list?: kendo.ui.Sortable;
draggableEvent?: any;
}
interface SortableEndEvent extends SortableEvent {
action?: string;
item?: JQuery;
oldIndex?: number;
newIndex?: number;
draggableEvent?: any;
}
interface SortableChangeEvent extends SortableEvent {
action?: string;
item?: JQuery;
oldIndex?: number;
newIndex?: number;
draggableEvent?: any;
}
interface SortableCancelEvent extends SortableEvent {
item?: JQuery;
}
class Splitter extends kendo.ui.Widget {
static fn: Splitter;
options: SplitterOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Splitter;
constructor(element: Element, options?: SplitterOptions);
ajaxRequest(pane: string, url: string, data: any): void;
ajaxRequest(pane: string, url: string, data: string): void;
ajaxRequest(pane: Element, url: string, data: any): void;
ajaxRequest(pane: Element, url: string, data: string): void;
ajaxRequest(pane: JQuery, url: string, data: any): void;
ajaxRequest(pane: JQuery, url: string, data: string): void;
append(config?: any): JQuery;
collapse(pane: string): void;
collapse(pane: Element): void;
collapse(pane: JQuery): void;
destroy(): void;
expand(pane: string): void;
expand(pane: Element): void;
expand(pane: JQuery): void;
insertAfter(config: any, referencePane: string): JQuery;
insertAfter(config: any, referencePane: Element): JQuery;
insertAfter(config: any, referencePane: JQuery): JQuery;
insertBefore(config: any, referencePane: string): JQuery;
insertBefore(config: any, referencePane: Element): JQuery;
insertBefore(config: any, referencePane: JQuery): JQuery;
max(pane: string, value: string): void;
max(pane: Element, value: string): void;
max(pane: JQuery, value: string): void;
min(pane: string, value: string): void;
min(pane: Element, value: string): void;
min(pane: JQuery, value: string): void;
remove(pane: string): void;
remove(pane: Element): void;
remove(pane: JQuery): void;
size(pane: string): any;
size(pane: Element): any;
size(pane: JQuery): any;
size(pane: string, value?: string): void;
size(pane: Element, value?: string): void;
size(pane: JQuery, value?: string): void;
toggle(pane: string, expand?: boolean): void;
toggle(pane: Element, expand?: boolean): void;
toggle(pane: JQuery, expand?: boolean): void;
}
interface SplitterPane {
collapsed?: boolean;
collapsedSize?: string;
collapsible?: boolean;
contentUrl?: string;
max?: string;
min?: string;
resizable?: boolean;
scrollable?: boolean;
size?: string;
}
interface SplitterOptions {
name?: string;
orientation?: string;
panes?: SplitterPane[];
collapse?(e: SplitterCollapseEvent): void;
contentLoad?(e: SplitterContentLoadEvent): void;
error?(e: SplitterErrorEvent): void;
expand?(e: SplitterExpandEvent): void;
layoutChange?(e: SplitterEvent): void;
resize?(e: SplitterEvent): void;
}
interface SplitterEvent {
sender: Splitter;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SplitterCollapseEvent extends SplitterEvent {
pane?: Element;
}
interface SplitterContentLoadEvent extends SplitterEvent {
pane?: Element;
}
interface SplitterErrorEvent extends SplitterEvent {
xhr?: JQueryXHR;
status?: string;
}
interface SplitterExpandEvent extends SplitterEvent {
pane?: Element;
}
class Spreadsheet extends kendo.ui.Widget {
static fn: Spreadsheet;
options: SpreadsheetOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Spreadsheet;
constructor(element: Element, options?: SpreadsheetOptions);
activeSheet(): kendo.spreadsheet.Sheet;
activeSheet(sheet?: kendo.spreadsheet.Sheet): void;
cellContextMenu(): kendo.ui.ContextMenu;
rowHeaderContextMenu(): kendo.ui.ContextMenu;
colHeaderContextMenu(): kendo.ui.ContextMenu;
sheets(): any;
fromFile(blob: Blob): JQueryPromise<any>;
fromFile(blob: File): JQueryPromise<any>;
saveAsExcel(): void;
saveAsPDF(): JQueryPromise<any>;
sheetByName(name: string): kendo.spreadsheet.Sheet;
sheetIndex(sheet: kendo.spreadsheet.Sheet): number;
sheetByIndex(index: number): kendo.spreadsheet.Sheet;
insertSheet(options: any): kendo.spreadsheet.Sheet;
moveSheetToIndex(sheet: kendo.spreadsheet.Sheet, index: number): void;
refresh(): void;
removeSheet(sheet: kendo.spreadsheet.Sheet): void;
renameSheet(sheet: kendo.spreadsheet.Sheet, newSheetName: string): kendo.spreadsheet.Sheet;
toJSON(): any;
fromJSON(data: any): void;
defineName(name: string, value: string, hidden: boolean): void;
undefineName(name: string): void;
}
interface SpreadsheetDefaultCellStyle {
background?: string;
color?: string;
fontFamily?: string;
fontSize?: string;
Italic?: boolean;
bold?: boolean;
underline?: boolean;
wrap?: boolean;
}
interface SpreadsheetExcel {
fileName?: string;
forceProxy?: boolean;
proxyURL?: string;
}
interface SpreadsheetPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface SpreadsheetPdf {
area?: string;
author?: string;
creator?: string;
date?: Date;
fileName?: string;
fitWidth?: boolean;
forceProxy?: boolean;
guidelines?: boolean;
hCenter?: boolean;
keywords?: string;
landscape?: boolean;
margin?: SpreadsheetPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
vCenter?: boolean;
}
interface SpreadsheetSheetColumn {
index?: number;
width?: number;
}
interface SpreadsheetSheetFilterColumnCriteriaItem {
operator?: string;
value?: string;
}
interface SpreadsheetSheetFilterColumn {
criteria?: SpreadsheetSheetFilterColumnCriteriaItem[];
filter?: string;
index?: number;
logic?: string;
type?: string;
value?: number|string|Date;
values?: any;
}
interface SpreadsheetSheetFilter {
columns?: SpreadsheetSheetFilterColumn[];
ref?: string;
}
interface SpreadsheetSheetRowCellBorderBottom {
color?: string;
size?: string;
}
interface SpreadsheetSheetRowCellBorderLeft {
color?: string;
size?: string;
}
interface SpreadsheetSheetRowCellBorderRight {
color?: string;
size?: string;
}
interface SpreadsheetSheetRowCellBorderTop {
color?: string;
size?: string;
}
interface SpreadsheetSheetRowCellValidation {
type?: string;
comparerType?: string;
dataType?: string;
from?: string;
showButton?: boolean;
to?: string;
allowNulls?: boolean;
messageTemplate?: string;
titleTemplate?: string;
}
interface SpreadsheetSheetRowCell {
background?: string;
borderBottom?: SpreadsheetSheetRowCellBorderBottom;
borderLeft?: SpreadsheetSheetRowCellBorderLeft;
borderTop?: SpreadsheetSheetRowCellBorderTop;
borderRight?: SpreadsheetSheetRowCellBorderRight;
color?: string;
fontFamily?: string;
fontSize?: number;
italic?: boolean;
bold?: boolean;
enable?: boolean;
format?: string;
formula?: string;
index?: number;
link?: string;
textAlign?: string;
underline?: boolean;
value?: number|string|boolean|Date;
validation?: SpreadsheetSheetRowCellValidation;
verticalAlign?: string;
wrap?: boolean;
}
interface SpreadsheetSheetRow {
cells?: SpreadsheetSheetRowCell[];
height?: number;
index?: number;
type?: string;
}
interface SpreadsheetSheetSortColumn {
ascending?: boolean;
index?: number;
}
interface SpreadsheetSheetSort {
columns?: SpreadsheetSheetSortColumn[];
ref?: string;
}
interface SpreadsheetSheet {
activeCell?: string;
name?: string;
columns?: SpreadsheetSheetColumn[];
dataSource?: kendo.data.DataSource;
filter?: SpreadsheetSheetFilter;
frozenColumns?: number;
frozenRows?: number;
mergedCells?: any;
rows?: SpreadsheetSheetRow[];
selection?: string;
showGridLines?: boolean;
sort?: SpreadsheetSheetSort;
}
interface SpreadsheetToolbar {
home?: boolean|any;
insert?: boolean|any;
data?: boolean|any;
}
interface SpreadsheetInsertSheetOptions {
rows?: number;
columns?: number;
rowHeight?: number;
columnWidth?: number;
headerHeight?: number;
headerWidth?: number;
dataSource?: kendo.data.DataSource;
data?: any;
}
interface SpreadsheetOptions {
name?: string;
activeSheet?: string;
columnWidth?: number;
columns?: number;
defaultCellStyle?: SpreadsheetDefaultCellStyle;
headerHeight?: number;
headerWidth?: number;
excel?: SpreadsheetExcel;
pdf?: SpreadsheetPdf;
rowHeight?: number;
rows?: number;
sheets?: SpreadsheetSheet[];
sheetsbar?: boolean;
toolbar?: boolean | SpreadsheetToolbar;
insertSheet?(e: SpreadsheetInsertSheetEvent): void;
removeSheet?(e: SpreadsheetRemoveSheetEvent): void;
renameSheet?(e: SpreadsheetRenameSheetEvent): void;
selectSheet?(e: SpreadsheetSelectSheetEvent): void;
unhideColumn?(e: SpreadsheetUnhideColumnEvent): void;
unhideRow?(e: SpreadsheetUnhideRowEvent): void;
hideColumn?(e: SpreadsheetHideColumnEvent): void;
hideRow?(e: SpreadsheetHideRowEvent): void;
deleteColumn?(e: SpreadsheetDeleteColumnEvent): void;
deleteRow?(e: SpreadsheetDeleteRowEvent): void;
insertColumn?(e: SpreadsheetInsertColumnEvent): void;
insertRow?(e: SpreadsheetInsertRowEvent): void;
select?(e: SpreadsheetSelectEvent): void;
changeFormat?(e: SpreadsheetChangeFormatEvent): void;
change?(e: SpreadsheetChangeEvent): void;
render?(e: SpreadsheetRenderEvent): void;
excelExport?(e: SpreadsheetExcelExportEvent): void;
excelImport?(e: SpreadsheetExcelImportEvent): void;
pdfExport?(e: SpreadsheetPdfExportEvent): void;
}
interface SpreadsheetEvent {
sender: Spreadsheet;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SpreadsheetInsertSheetEvent extends SpreadsheetEvent {
}
interface SpreadsheetRemoveSheetEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
}
interface SpreadsheetRenameSheetEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
newSheetName?: string;
}
interface SpreadsheetSelectSheetEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
}
interface SpreadsheetUnhideColumnEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
index?: number;
}
interface SpreadsheetUnhideRowEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
index?: number;
}
interface SpreadsheetHideColumnEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
index?: number;
}
interface SpreadsheetHideRowEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
index?: number;
}
interface SpreadsheetDeleteColumnEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
index?: number;
}
interface SpreadsheetDeleteRowEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
index?: number;
}
interface SpreadsheetInsertColumnEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
index?: number;
}
interface SpreadsheetInsertRowEvent extends SpreadsheetEvent {
sheet?: kendo.spreadsheet.Sheet;
index?: number;
}
interface SpreadsheetSelectEvent extends SpreadsheetEvent {
range?: kendo.spreadsheet.Range;
}
interface SpreadsheetChangeFormatEvent extends SpreadsheetEvent {
range?: kendo.spreadsheet.Range;
}
interface SpreadsheetChangeEvent extends SpreadsheetEvent {
range?: kendo.spreadsheet.Range;
}
interface SpreadsheetRenderEvent extends SpreadsheetEvent {
}
interface SpreadsheetExcelExportEvent extends SpreadsheetEvent {
data?: any;
workbook?: kendo.ooxml.Workbook;
}
interface SpreadsheetExcelImportEvent extends SpreadsheetEvent {
file?: Blob|File;
progress?: JQueryPromise<any>;
}
interface SpreadsheetPdfExportEvent extends SpreadsheetEvent {
promise?: JQueryPromise<any>;
}
class Switch extends kendo.ui.Widget {
static fn: Switch;
options: SwitchOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Switch;
constructor(element: Element, options?: SwitchOptions);
check(): boolean;
check(check: boolean): void;
destroy(): void;
enable(enable: boolean): void;
toggle(): void;
setOptions(options: any): void;
}
interface SwitchOptions {
name?: string;
checked?: boolean;
enabled?: boolean;
readonly?: boolean;
width?: number|string;
change?(e: SwitchChangeEvent): void;
}
interface SwitchMessages {
checked?: string;
unchecked?: string;
}
interface SwitchEvent {
sender: Switch;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SwitchChangeEvent extends SwitchEvent {
checked?: any;
}
class TabStrip extends kendo.ui.Widget {
static fn: TabStrip;
options: TabStripOptions;
dataSource: kendo.data.DataSource;
tabGroup: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): TabStrip;
constructor(element: Element, options?: TabStripOptions);
activateTab(item: JQuery): void;
append(tab: any): kendo.ui.TabStrip;
contentElement(itemIndex: number): Element;
contentHolder(itemIndex: number): Element;
deactivateTab(item: JQuery): void;
destroy(): void;
disable(element: string): kendo.ui.TabStrip;
disable(element: Element): kendo.ui.TabStrip;
disable(element: JQuery): kendo.ui.TabStrip;
enable(element: string, enable?: boolean): kendo.ui.TabStrip;
enable(element: Element, enable?: boolean): kendo.ui.TabStrip;
enable(element: JQuery, enable?: boolean): kendo.ui.TabStrip;
insertAfter(item: any, referenceTab: string): kendo.ui.TabStrip;
insertAfter(item: any, referenceTab: Element): kendo.ui.TabStrip;
insertAfter(item: any, referenceTab: JQuery): kendo.ui.TabStrip;
insertAfter(item: string, referenceTab: string): kendo.ui.TabStrip;
insertAfter(item: string, referenceTab: Element): kendo.ui.TabStrip;
insertAfter(item: string, referenceTab: JQuery): kendo.ui.TabStrip;
insertAfter(item: Element, referenceTab: string): kendo.ui.TabStrip;
insertAfter(item: Element, referenceTab: Element): kendo.ui.TabStrip;
insertAfter(item: Element, referenceTab: JQuery): kendo.ui.TabStrip;
insertAfter(item: JQuery, referenceTab: string): kendo.ui.TabStrip;
insertAfter(item: JQuery, referenceTab: Element): kendo.ui.TabStrip;
insertAfter(item: JQuery, referenceTab: JQuery): kendo.ui.TabStrip;
insertBefore(item: any, referenceTab: string): kendo.ui.TabStrip;
insertBefore(item: any, referenceTab: Element): kendo.ui.TabStrip;
insertBefore(item: any, referenceTab: JQuery): kendo.ui.TabStrip;
insertBefore(item: string, referenceTab: string): kendo.ui.TabStrip;
insertBefore(item: string, referenceTab: Element): kendo.ui.TabStrip;
insertBefore(item: string, referenceTab: JQuery): kendo.ui.TabStrip;
insertBefore(item: Element, referenceTab: string): kendo.ui.TabStrip;
insertBefore(item: Element, referenceTab: Element): kendo.ui.TabStrip;
insertBefore(item: Element, referenceTab: JQuery): kendo.ui.TabStrip;
insertBefore(item: JQuery, referenceTab: string): kendo.ui.TabStrip;
insertBefore(item: JQuery, referenceTab: Element): kendo.ui.TabStrip;
insertBefore(item: JQuery, referenceTab: JQuery): kendo.ui.TabStrip;
items(): HTMLCollection;
reload(element: string): kendo.ui.TabStrip;
reload(element: Element): kendo.ui.TabStrip;
reload(element: JQuery): kendo.ui.TabStrip;
remove(element: string): kendo.ui.TabStrip;
remove(element: number): kendo.ui.TabStrip;
remove(element: JQuery): kendo.ui.TabStrip;
select(): JQuery;
select(element: string): void;
select(element: Element): void;
select(element: JQuery): void;
select(element: number): void;
setDataSource(dataSource: any): void;
setDataSource(dataSource: kendo.data.DataSource): void;
}
interface TabStripAnimationClose {
duration?: number;
effects?: string;
}
interface TabStripAnimationOpen {
duration?: number;
effects?: string;
}
interface TabStripAnimation {
close?: TabStripAnimationClose;
open?: TabStripAnimationOpen;
}
interface TabStripScrollable {
distance?: number;
}
interface TabStripOptions {
name?: string;
animation?: boolean | TabStripAnimation;
collapsible?: boolean;
contentUrls?: any;
dataContentField?: string;
dataContentUrlField?: string;
dataImageUrlField?: string;
dataSource?: any|any|kendo.data.DataSource;
dataSpriteCssClass?: string;
dataTextField?: string;
dataUrlField?: string;
navigatable?: boolean;
scrollable?: boolean | TabStripScrollable;
tabPosition?: string;
value?: string;
activate?(e: TabStripActivateEvent): void;
contentLoad?(e: TabStripContentLoadEvent): void;
error?(e: TabStripErrorEvent): void;
select?(e: TabStripSelectEvent): void;
show?(e: TabStripShowEvent): void;
}
interface TabStripEvent {
sender: TabStrip;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TabStripActivateEvent extends TabStripEvent {
item?: Element;
contentElement?: Element;
}
interface TabStripContentLoadEvent extends TabStripEvent {
item?: Element;
contentElement?: Element;
}
interface TabStripErrorEvent extends TabStripEvent {
xhr?: JQueryXHR;
status?: string;
}
interface TabStripSelectEvent extends TabStripEvent {
item?: Element;
contentElement?: Element;
}
interface TabStripShowEvent extends TabStripEvent {
item?: Element;
contentElement?: Element;
}
class TimePicker extends kendo.ui.Widget {
static fn: TimePicker;
options: TimePickerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): TimePicker;
constructor(element: Element, options?: TimePickerOptions);
close(): void;
destroy(): void;
enable(enable: boolean): void;
readonly(readonly: boolean): void;
max(): Date;
max(value: Date): void;
max(value: string): void;
min(): Date;
min(value: Date): void;
min(value: string): void;
open(): void;
setOptions(options: any): void;
value(): Date;
value(value: Date): void;
value(value: string): void;
}
interface TimePickerAnimationClose {
effects?: string;
duration?: number;
}
interface TimePickerAnimationOpen {
effects?: string;
duration?: number;
}
interface TimePickerAnimation {
close?: TimePickerAnimationClose;
open?: TimePickerAnimationOpen;
}
interface TimePickerOptions {
name?: string;
animation?: boolean | TimePickerAnimation;
culture?: string;
dateInput?: boolean;
dates?: any;
format?: string;
interval?: number;
max?: Date;
min?: Date;
parseFormats?: any;
value?: Date;
change?(e: TimePickerChangeEvent): void;
close?(e: TimePickerCloseEvent): void;
open?(e: TimePickerOpenEvent): void;
}
interface TimePickerEvent {
sender: TimePicker;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TimePickerChangeEvent extends TimePickerEvent {
}
interface TimePickerCloseEvent extends TimePickerEvent {
}
interface TimePickerOpenEvent extends TimePickerEvent {
}
class ToolBar extends kendo.ui.Widget {
static fn: ToolBar;
options: ToolBarOptions;
element: JQuery;
wrapper: JQuery;
popup: kendo.ui.Popup;
static extend(proto: Object): ToolBar;
constructor(element: Element, options?: ToolBarOptions);
add(command: any): void;
destroy(): void;
enable(command: string, enable: boolean): void;
enable(command: Element, enable: boolean): void;
enable(command: JQuery, enable: boolean): void;
getSelectedFromGroup(groupName: string): void;
hide(command: string): void;
hide(command: Element): void;
hide(command: JQuery): void;
remove(command: string): void;
remove(command: Element): void;
remove(command: JQuery): void;
show(command: string): void;
show(command: Element): void;
show(command: JQuery): void;
toggle(command: string, state: boolean): void;
toggle(command: Element, state: boolean): void;
toggle(command: JQuery, state: boolean): void;
}
interface ToolBarItemButton {
attributes?: any;
click?: Function;
enable?: boolean;
group?: string;
hidden?: boolean;
icon?: string;
id?: string;
imageUrl?: string;
selected?: boolean;
showIcon?: string;
showText?: string;
spriteCssClass?: string;
toggle?: Function;
togglable?: boolean;
text?: string;
url?: string;
}
interface ToolBarItemMenuButton {
attributes?: any;
enable?: boolean;
hidden?: boolean;
icon?: string;
id?: string;
imageUrl?: string;
spriteCssClass?: string;
text?: string;
url?: string;
}
interface ToolBarItem {
attributes?: any;
buttons?: ToolBarItemButton[];
click?: Function;
enable?: boolean;
group?: string;
hidden?: boolean;
icon?: string;
id?: string;
imageUrl?: string;
menuButtons?: ToolBarItemMenuButton[];
overflow?: string;
overflowTemplate?: string|Function;
primary?: boolean;
selected?: boolean;
showIcon?: string;
showText?: string;
spriteCssClass?: string;
template?: string|Function;
text?: string;
togglable?: boolean;
toggle?: Function;
type?: string;
url?: string;
}
interface ToolBarOptions {
name?: string;
resizable?: boolean;
items?: ToolBarItem[];
click?(e: ToolBarClickEvent): void;
close?(e: ToolBarCloseEvent): void;
open?(e: ToolBarOpenEvent): void;
toggle?(e: ToolBarToggleEvent): void;
overflowClose?(e: ToolBarOverflowCloseEvent): void;
overflowOpen?(e: ToolBarOverflowOpenEvent): void;
}
interface ToolBarEvent {
sender: ToolBar;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ToolBarClickEvent extends ToolBarEvent {
target?: JQuery;
id?: string;
}
interface ToolBarCloseEvent extends ToolBarEvent {
SplitButton?: JQuery;
}
interface ToolBarOpenEvent extends ToolBarEvent {
SplitButton?: JQuery;
}
interface ToolBarToggleEvent extends ToolBarEvent {
target?: JQuery;
checked?: boolean;
id?: string;
}
interface ToolBarOverflowCloseEvent extends ToolBarEvent {
}
interface ToolBarOverflowOpenEvent extends ToolBarEvent {
}
class Tooltip extends kendo.ui.Widget {
static fn: Tooltip;
options: TooltipOptions;
popup: kendo.ui.Popup;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Tooltip;
constructor(element: Element, options?: TooltipOptions);
show(element: JQuery): void;
hide(): void;
refresh(): void;
target(): JQuery;
}
interface TooltipAnimationClose {
effects?: string;
duration?: number;
}
interface TooltipAnimationOpen {
effects?: string;
duration?: number;
}
interface TooltipAnimation {
close?: TooltipAnimationClose;
open?: TooltipAnimationOpen;
}
interface TooltipContent {
url?: string;
}
interface TooltipOptions {
name?: string;
autoHide?: boolean;
animation?: boolean | TooltipAnimation;
content?: string | Function | TooltipContent;
callout?: boolean;
filter?: string;
iframe?: boolean;
height?: number;
width?: number;
position?: string;
showAfter?: number;
showOn?: string;
contentLoad?(e: TooltipEvent): void;
show?(e: TooltipEvent): void;
hide?(e: TooltipEvent): void;
requestStart?(e: TooltipRequestStartEvent): void;
error?(e: TooltipErrorEvent): void;
}
interface TooltipEvent {
sender: Tooltip;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TooltipRequestStartEvent extends TooltipEvent {
target?: JQuery;
options?: any;
}
interface TooltipErrorEvent extends TooltipEvent {
xhr?: JQueryXHR;
status?: string;
}
class Touch extends kendo.ui.Widget {
static fn: Touch;
options: TouchOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Touch;
constructor(element: Element, options?: TouchOptions);
cancel(): void;
destroy(): void;
}
interface TouchOptions {
name?: string;
filter?: string;
surface?: JQuery;
multiTouch?: boolean;
enableSwipe?: boolean;
minXDelta?: number;
maxYDelta?: number;
maxDuration?: number;
minHold?: number;
doubleTapTimeout?: number;
touchstart?(e: TouchTouchstartEvent): void;
dragstart?(e: TouchDragstartEvent): void;
drag?(e: TouchDragEvent): void;
dragend?(e: TouchDragendEvent): void;
tap?(e: TouchTapEvent): void;
doubletap?(e: TouchDoubletapEvent): void;
hold?(e: TouchHoldEvent): void;
swipe?(e: TouchSwipeEvent): void;
gesturestart?(e: TouchGesturestartEvent): void;
gesturechange?(e: TouchGesturechangeEvent): void;
gestureend?(e: TouchGestureendEvent): void;
}
interface TouchEvent {
sender: Touch;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TouchTouchstartEvent extends TouchEvent {
touch?: kendo.mobile.ui.TouchEventOptions;
event?: JQueryEventObject;
}
interface TouchDragstartEvent extends TouchEvent {
touch?: kendo.mobile.ui.TouchEventOptions;
event?: JQueryEventObject;
}
interface TouchDragEvent extends TouchEvent {
touch?: kendo.mobile.ui.TouchEventOptions;
event?: JQueryEventObject;
}
interface TouchDragendEvent extends TouchEvent {
touch?: kendo.mobile.ui.TouchEventOptions;
event?: JQueryEventObject;
}
interface TouchTapEvent extends TouchEvent {
touch?: kendo.mobile.ui.TouchEventOptions;
event?: JQueryEventObject;
}
interface TouchDoubletapEvent extends TouchEvent {
touch?: kendo.mobile.ui.TouchEventOptions;
event?: JQueryEventObject;
}
interface TouchHoldEvent extends TouchEvent {
touch?: kendo.mobile.ui.TouchEventOptions;
event?: JQueryEventObject;
}
interface TouchSwipeEvent extends TouchEvent {
touch?: kendo.mobile.ui.TouchEventOptions;
event?: JQueryEventObject;
direction?: string;
}
interface TouchGesturestartEvent extends TouchEvent {
touches?: any;
event?: JQueryEventObject;
distance?: number;
center?: kendo.mobile.ui.Point;
}
interface TouchGesturechangeEvent extends TouchEvent {
touches?: any;
event?: JQueryEventObject;
distance?: number;
center?: kendo.mobile.ui.Point;
}
interface TouchGestureendEvent extends TouchEvent {
touches?: any;
event?: JQueryEventObject;
distance?: number;
center?: kendo.mobile.ui.Point;
}
class TreeList extends kendo.ui.Widget {
static fn: TreeList;
options: TreeListOptions;
dataSource: kendo.data.DataSource;
columns: any;
table: JQuery;
tbody: JQuery;
thead: JQuery;
content: JQuery;
lockedHeader: JQuery;
lockedTable: JQuery;
lockedContent: JQuery;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): TreeList;
constructor(element: Element, options?: TreeListOptions);
addRow(parentRow: string): void;
addRow(parentRow: Element): void;
addRow(parentRow: JQuery): void;
autoFitColumn(column: number): void;
autoFitColumn(column: string): void;
autoFitColumn(column: any): void;
cancelChanges(): void;
cancelRow(): void;
clearSelection(): void;
closeCell(isCancel?: boolean): void;
collapse(row: string): JQueryPromise<any>;
collapse(row: Element): JQueryPromise<any>;
collapse(row: JQuery): JQueryPromise<any>;
dataItem(row: string): kendo.data.TreeListModel;
dataItem(row: Element): kendo.data.TreeListModel;
dataItem(row: JQuery): kendo.data.TreeListModel;
destroy(): void;
editCell(cell: JQuery): void;
editRow(row: JQuery): void;
expand(row: string): JQueryPromise<any>;
expand(row: Element): JQueryPromise<any>;
expand(row: JQuery): JQueryPromise<any>;
itemFor(model: kendo.data.TreeListModel): JQuery;
itemFor(model: any): JQuery;
items(): any;
refresh(): void;
removeRow(row: string): void;
removeRow(row: Element): void;
removeRow(row: JQuery): void;
saveAsExcel(): void;
saveAsPDF(): JQueryPromise<any>;
saveChanges(): void;
saveRow(): void;
select(): JQuery;
select(rows: Element): void;
select(rows: JQuery): void;
setDataSource(dataSource: kendo.data.TreeListDataSource): void;
showColumn(column: number): void;
showColumn(column: string): void;
hideColumn(column: number): void;
hideColumn(column: string): void;
lockColumn(column: number): void;
lockColumn(column: string): void;
unlockColumn(column: number): void;
unlockColumn(column: string): void;
reorderColumn(destIndex: number, column: any): void;
}
interface TreeListColumnMenuMessages {
columns?: string;
filter?: string;
sortAscending?: string;
sortDescending?: string;
settings?: string;
lock?: string;
unlock?: string;
}
interface TreeListColumnMenu {
columns?: boolean;
filterable?: boolean;
sortable?: boolean;
messages?: TreeListColumnMenuMessages;
}
interface TreeListColumnCommandItem {
className?: string;
imageClass?: string;
click?: Function;
name?: string;
text?: string;
}
interface TreeListColumnFilterable {
ui?: string|Function;
}
interface TreeListColumnSortable {
compare?: Function;
}
interface TreeListColumn {
attributes?: any;
columns?: any;
command?: TreeListColumnCommandItem[];
editable?: Function;
encoded?: boolean;
expandable?: boolean;
field?: string;
filterable?: boolean | TreeListColumnFilterable;
footerTemplate?: string|Function;
format?: string;
headerAttributes?: any;
headerTemplate?: string|Function;
minScreenWidth?: number;
sortable?: boolean | TreeListColumnSortable;
template?: string|Function;
title?: string;
width?: string|number;
hidden?: boolean;
menu?: boolean;
locked?: boolean;
lockable?: boolean;
}
interface TreeListEditable {
mode?: string;
move?: boolean;
template?: string|Function;
window?: any;
}
interface TreeListExcel {
fileName?: string;
filterable?: boolean;
forceProxy?: boolean;
proxyURL?: string;
}
interface TreeListFilterableMessages {
and?: string;
clear?: string;
filter?: string;
info?: string;
title?: string;
isFalse?: string;
isTrue?: string;
or?: string;
}
interface TreeListFilterableOperatorsDate {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
gte?: string;
gt?: string;
lte?: string;
lt?: string;
}
interface TreeListFilterableOperatorsNumber {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
gte?: string;
gt?: string;
lte?: string;
lt?: string;
}
interface TreeListFilterableOperatorsString {
eq?: string;
neq?: string;
isnull?: string;
isnotnull?: string;
isempty?: string;
isnotempty?: string;
startswith?: string;
contains?: string;
doesnotcontain?: string;
endswith?: string;
}
interface TreeListFilterableOperators {
string?: TreeListFilterableOperatorsString;
number?: TreeListFilterableOperatorsNumber;
date?: TreeListFilterableOperatorsDate;
}
interface TreeListFilterable {
extra?: boolean;
messages?: TreeListFilterableMessages;
operators?: TreeListFilterableOperators;
}
interface TreeListMessagesCommands {
canceledit?: string;
create?: string;
createchild?: string;
destroy?: string;
edit?: string;
save?: string;
cancel?: string;
excel?: string;
pdf?: string;
update?: string;
}
interface TreeListMessages {
commands?: TreeListMessagesCommands;
loading?: string;
noRows?: string;
requestFailed?: string;
retry?: string;
}
interface TreeListPageableMessages {
display?: string;
empty?: string;
page?: string;
of?: string;
itemsPerPage?: string;
first?: string;
last?: string;
next?: string;
previous?: string;
refresh?: string;
morePages?: string;
}
interface TreeListPageable {
alwaysVisible?: boolean;
pageSize?: number;
previousNext?: boolean;
numeric?: boolean;
buttonCount?: number;
input?: boolean;
pageSizes?: boolean|any;
refresh?: boolean;
info?: boolean;
messages?: TreeListPageableMessages;
}
interface TreeListPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface TreeListPdf {
author?: string;
avoidLinks?: boolean|string;
creator?: string;
date?: Date;
fileName?: string;
forceProxy?: boolean;
keywords?: string;
landscape?: boolean;
margin?: TreeListPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface TreeListSortable {
allowUnsort?: boolean;
mode?: string;
}
interface TreeListToolbarItem {
click?: Function;
imageClass?: string;
name?: string;
text?: string;
}
interface TreeListOptions {
name?: string;
autoBind?: boolean;
columns?: TreeListColumn[];
resizable?: boolean;
reorderable?: boolean;
columnMenu?: boolean | TreeListColumnMenu;
dataSource?: any|any|kendo.data.TreeListDataSource;
editable?: boolean | TreeListEditable;
excel?: TreeListExcel;
filterable?: boolean | TreeListFilterable;
height?: number|string;
messages?: TreeListMessages;
navigatable?: boolean;
pageable?: boolean | TreeListPageable;
pdf?: TreeListPdf;
scrollable?: boolean|any;
selectable?: boolean|string;
sortable?: boolean | TreeListSortable;
toolbar?: TreeListToolbarItem[] | any;
beforeEdit?(e: TreeListBeforeEditEvent): void;
cancel?(e: TreeListCancelEvent): void;
cellClose?(e: TreeListCellCloseEvent): void;
change?(e: TreeListChangeEvent): void;
collapse?(e: TreeListCollapseEvent): void;
dataBinding?(e: TreeListDataBindingEvent): void;
dataBound?(e: TreeListDataBoundEvent): void;
dragstart?(e: TreeListDragstartEvent): void;
drag?(e: TreeListDragEvent): void;
dragend?(e: TreeListDragendEvent): void;
drop?(e: TreeListDropEvent): void;
edit?(e: TreeListEditEvent): void;
excelExport?(e: TreeListExcelExportEvent): void;
expand?(e: TreeListExpandEvent): void;
filterMenuInit?(e: TreeListFilterMenuInitEvent): void;
filterMenuOpen?(e: TreeListFilterMenuOpenEvent): void;
pdfExport?(e: TreeListPdfExportEvent): void;
remove?(e: TreeListRemoveEvent): void;
save?(e: TreeListSaveEvent): void;
saveChanges?(e: TreeListSaveChangesEvent): void;
columnShow?(e: TreeListColumnShowEvent): void;
columnHide?(e: TreeListColumnHideEvent): void;
columnReorder?(e: TreeListColumnReorderEvent): void;
columnResize?(e: TreeListColumnResizeEvent): void;
columnMenuInit?(e: TreeListColumnMenuInitEvent): void;
columnMenuOpen?(e: TreeListColumnMenuOpenEvent): void;
columnLock?(e: TreeListColumnLockEvent): void;
columnUnlock?(e: TreeListColumnUnlockEvent): void;
}
interface TreeListEvent {
sender: TreeList;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TreeListBeforeEditEvent extends TreeListEvent {
model?: kendo.data.Model;
}
interface TreeListCancelEvent extends TreeListEvent {
container?: JQuery;
model?: kendo.data.TreeListModel;
}
interface TreeListCellCloseEvent extends TreeListEvent {
container?: JQuery;
model?: kendo.data.Model;
type?: string;
}
interface TreeListChangeEvent extends TreeListEvent {
}
interface TreeListCollapseEvent extends TreeListEvent {
model?: kendo.data.TreeListModel;
}
interface TreeListDataBindingEvent extends TreeListEvent {
}
interface TreeListDataBoundEvent extends TreeListEvent {
}
interface TreeListDragstartEvent extends TreeListEvent {
source?: kendo.data.TreeListModel;
}
interface TreeListDragEvent extends TreeListEvent {
source?: kendo.data.TreeListModel;
target?: JQuery;
}
interface TreeListDragendEvent extends TreeListEvent {
source?: kendo.data.TreeListModel;
destination?: kendo.data.TreeListModel;
}
interface TreeListDropEvent extends TreeListEvent {
source?: kendo.data.TreeListModel;
destination?: kendo.data.TreeListModel;
dropTarget?: Element;
valid?: boolean;
setValid?: boolean;
}
interface TreeListEditEvent extends TreeListEvent {
container?: JQuery;
model?: kendo.data.TreeListModel;
}
interface TreeListExcelExportEvent extends TreeListEvent {
data?: any;
workbook?: any;
}
interface TreeListExpandEvent extends TreeListEvent {
model?: kendo.data.TreeListModel;
}
interface TreeListFilterMenuInitEvent extends TreeListEvent {
container?: JQuery;
field?: string;
}
interface TreeListFilterMenuOpenEvent extends TreeListEvent {
container?: JQuery;
field?: string;
}
interface TreeListPdfExportEvent extends TreeListEvent {
promise?: JQueryPromise<any>;
}
interface TreeListRemoveEvent extends TreeListEvent {
model?: kendo.data.TreeListModel;
row?: JQuery;
}
interface TreeListSaveEvent extends TreeListEvent {
model?: kendo.data.TreeListModel;
container?: JQuery;
}
interface TreeListSaveChangesEvent extends TreeListEvent {
}
interface TreeListColumnShowEvent extends TreeListEvent {
column?: any;
}
interface TreeListColumnHideEvent extends TreeListEvent {
column?: any;
}
interface TreeListColumnReorderEvent extends TreeListEvent {
column?: any;
newIndex?: number;
oldIndex?: number;
}
interface TreeListColumnResizeEvent extends TreeListEvent {
column?: any;
newWidth?: number;
oldWidth?: number;
}
interface TreeListColumnMenuInitEvent extends TreeListEvent {
container?: JQuery;
field?: string;
}
interface TreeListColumnMenuOpenEvent extends TreeListEvent {
container?: JQuery;
field?: string;
}
interface TreeListColumnLockEvent extends TreeListEvent {
column?: any;
}
interface TreeListColumnUnlockEvent extends TreeListEvent {
column?: any;
}
class TreeView extends kendo.ui.Widget {
static fn: TreeView;
options: TreeViewOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): TreeView;
constructor(element: Element, options?: TreeViewOptions);
append(nodeData: any, parentNode?: JQuery, success?: Function): JQuery;
append(nodeData: JQuery, parentNode?: JQuery, success?: Function): JQuery;
collapse(nodes: JQuery): void;
collapse(nodes: Element): void;
collapse(nodes: string): void;
dataItem(node: JQuery): kendo.data.Node;
dataItem(node: Element): kendo.data.Node;
dataItem(node: string): kendo.data.Node;
destroy(): void;
detach(node: JQuery): JQuery;
detach(node: Element): JQuery;
detach(node: string): JQuery;
enable(nodes: JQuery, enable?: boolean): void;
enable(nodes: Element, enable?: boolean): void;
enable(nodes: string, enable?: boolean): void;
enable(nodes: boolean, enable?: boolean): void;
expand(nodes: JQuery): void;
expand(nodes: Element): void;
expand(nodes: string): void;
expandPath(path: any, complete: Function): void;
expandTo(targetNode: kendo.data.Node): void;
expandTo(targetNode: any): void;
findByText(text: string): JQuery;
findByUid(uid: string): JQuery;
focus(): void;
insertAfter(nodeData: any, referenceNode: JQuery): JQuery;
insertBefore(nodeData: any, referenceNode: JQuery): JQuery;
items(): any;
parent(node: JQuery): JQuery;
parent(node: Element): JQuery;
parent(node: string): JQuery;
remove(node: JQuery): void;
remove(node: Element): void;
remove(node: string): void;
select(): JQuery;
select(node?: JQuery): void;
select(node?: Element): void;
select(node?: string): void;
setDataSource(dataSource: kendo.data.HierarchicalDataSource): void;
text(node: JQuery): string;
text(node: Element): string;
text(node: string): string;
text(node: JQuery, newText: string): void;
text(node: Element, newText: string): void;
text(node: string, newText: string): void;
toggle(node: JQuery): void;
toggle(node: Element): void;
toggle(node: string): void;
updateIndeterminate(node: JQuery): void;
}
interface TreeViewAnimationCollapse {
duration?: number;
effects?: string;
}
interface TreeViewAnimationExpand {
duration?: number;
effects?: string;
}
interface TreeViewAnimation {
collapse?: boolean | TreeViewAnimationCollapse;
expand?: boolean | TreeViewAnimationExpand;
}
interface TreeViewCheckboxes {
checkChildren?: boolean;
name?: string;
template?: string|Function;
}
interface TreeViewMessages {
loading?: string;
requestFailed?: string;
retry?: string;
}
interface TreeViewOptions {
name?: string;
animation?: boolean | TreeViewAnimation;
autoBind?: boolean;
autoScroll?: boolean;
checkboxes?: boolean | TreeViewCheckboxes;
dataImageUrlField?: string;
dataSource?: any|any|kendo.data.HierarchicalDataSource;
dataSpriteCssClassField?: string;
dataTextField?: string|any;
dataUrlField?: string;
dragAndDrop?: boolean;
loadOnDemand?: boolean;
messages?: TreeViewMessages;
template?: string|Function;
change?(e: TreeViewEvent): void;
check?(e: TreeViewCheckEvent): void;
collapse?(e: TreeViewCollapseEvent): void;
dataBound?(e: TreeViewDataBoundEvent): void;
drag?(e: TreeViewDragEvent): void;
dragend?(e: TreeViewDragendEvent): void;
dragstart?(e: TreeViewDragstartEvent): void;
drop?(e: TreeViewDropEvent): void;
expand?(e: TreeViewExpandEvent): void;
navigate?(e: TreeViewNavigateEvent): void;
select?(e: TreeViewSelectEvent): void;
}
interface TreeViewEvent {
sender: TreeView;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TreeViewCheckEvent extends TreeViewEvent {
node?: Element;
}
interface TreeViewCollapseEvent extends TreeViewEvent {
node?: Element;
}
interface TreeViewDataBoundEvent extends TreeViewEvent {
node?: JQuery;
}
interface TreeViewDragEvent extends TreeViewEvent {
sourceNode?: Element;
dropTarget?: Element;
pageX?: number;
pageY?: number;
statusClass?: string;
setStatusClass?: Function;
}
interface TreeViewDragendEvent extends TreeViewEvent {
sourceNode?: Element;
destinationNode?: Element;
dropPosition?: string;
}
interface TreeViewDragstartEvent extends TreeViewEvent {
sourceNode?: Element;
}
interface TreeViewDropEvent extends TreeViewEvent {
sourceNode?: Element;
destinationNode?: Element;
valid?: boolean;
setValid?: Function;
dropTarget?: Element;
dropPosition?: string;
}
interface TreeViewExpandEvent extends TreeViewEvent {
node?: Element;
}
interface TreeViewNavigateEvent extends TreeViewEvent {
node?: Element;
}
interface TreeViewSelectEvent extends TreeViewEvent {
node?: Element;
}
class Upload extends kendo.ui.Widget {
static fn: Upload;
options: UploadOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Upload;
constructor(element: Element, options?: UploadOptions);
clearAllFiles(): void;
clearFile(callback: Function): void;
clearFileByUid(uid: string): void;
destroy(): void;
disable(): void;
enable(enable?: boolean): void;
focus(): void;
getFiles(): any;
pause(li: JQuery): void;
resume(li: JQuery): void;
removeAllFiles(): void;
removeFile(callback: Function): void;
removeFileByUid(uid: string): void;
toggle(enable: boolean): void;
upload(): void;
}
interface UploadAsync {
autoUpload?: boolean;
batch?: boolean;
chunkSize?: number;
concurrent?: boolean;
autoRetryAfter?: number;
maxAutoRetries?: number;
removeField?: string;
removeUrl?: string;
removeVerb?: string;
saveField?: string;
saveUrl?: string;
useArrayBuffer?: boolean;
withCredentials?: boolean;
}
interface UploadFile {
extension?: string;
name?: string;
size?: number;
}
interface UploadLocalization {
cancel?: string;
clearSelectedFiles?: string;
dropFilesHere?: string;
headerStatusUploaded?: string;
headerStatusUploading?: string;
invalidFileExtension?: string;
invalidFiles?: string;
invalidMaxFileSize?: string;
invalidMinFileSize?: string;
remove?: string;
retry?: string;
select?: string;
statusFailed?: string;
statusUploaded?: string;
statusUploading?: string;
uploadSelectedFiles?: string;
}
interface UploadValidation {
allowedExtensions?: any;
maxFileSize?: number;
minFileSize?: number;
}
interface UploadOptions {
name?: string;
async?: UploadAsync;
directory?: boolean;
directoryDrop?: boolean;
dropZone?: string;
enabled?: boolean;
files?: UploadFile[];
localization?: UploadLocalization;
multiple?: boolean;
showFileList?: boolean;
template?: string|Function;
validation?: UploadValidation;
cancel?(e: UploadCancelEvent): void;
clear?(e: UploadClearEvent): void;
complete?(e: UploadEvent): void;
error?(e: UploadErrorEvent): void;
pause?(e: UploadPauseEvent): void;
progress?(e: UploadProgressEvent): void;
resume?(e: UploadEvent): void;
remove?(e: UploadRemoveEvent): void;
select?(e: UploadSelectEvent): void;
success?(e: UploadSuccessEvent): void;
upload?(e: UploadUploadEvent): void;
}
interface UploadEvent {
sender: Upload;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface UploadCancelEvent extends UploadEvent {
files?: any[];
}
interface UploadClearEvent extends UploadEvent {
e?: any;
}
interface UploadErrorEvent extends UploadEvent {
files?: any[];
operation?: string;
XMLHttpRequest?: any;
}
interface UploadPauseEvent extends UploadEvent {
e?: any;
}
interface UploadProgressEvent extends UploadEvent {
files?: any[];
percentComplete?: number;
}
interface UploadRemoveEvent extends UploadEvent {
files?: any[];
headers?: any;
data?: any;
}
interface UploadSelectEvent extends UploadEvent {
e?: any;
files?: any[];
}
interface UploadSuccessEvent extends UploadEvent {
files?: any[];
operation?: string;
response?: any;
XMLHttpRequest?: any;
}
interface UploadUploadEvent extends UploadEvent {
files?: any[];
data?: any;
formData?: any;
XMLHttpRequest?: any;
}
class Validator extends kendo.ui.Widget {
static fn: Validator;
options: ValidatorOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Validator;
constructor(element: Element, options?: ValidatorOptions);
errors(): any;
hideMessages(): void;
validate(): boolean;
validateInput(input: Element): boolean;
validateInput(input: JQuery): boolean;
}
interface ValidatorOptions {
name?: string;
errorTemplate?: string;
messages?: any;
rules?: any;
validateOnBlur?: boolean;
validate?(e: ValidatorValidateEvent): void;
validateInput?(e: ValidatorValidateInputEvent): void;
}
interface ValidatorEvent {
sender: Validator;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ValidatorValidateEvent extends ValidatorEvent {
valid?: boolean;
}
interface ValidatorValidateInputEvent extends ValidatorEvent {
input?: JQuery;
valid?: boolean;
}
class Window extends kendo.ui.Widget {
static fn: Window;
options: WindowOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Window;
constructor(element: Element, options?: WindowOptions);
center(): kendo.ui.Window;
close(): kendo.ui.Window;
content(): string;
content(content?: string): kendo.ui.Window;
content(content?: JQuery): kendo.ui.Window;
destroy(): void;
isMaximized(): boolean;
isMinimized(): boolean;
maximize(): kendo.ui.Window;
minimize(): kendo.ui.Window;
open(): kendo.ui.Window;
pin(): void;
refresh(options: any): kendo.ui.Window;
restore(): kendo.ui.Window;
setOptions(options: any): void;
title(): string;
title(text?: string): kendo.ui.Window;
toFront(): kendo.ui.Window;
toggleMaximization(): kendo.ui.Window;
unpin(): void;
}
interface WindowAnimationClose {
effects?: string;
duration?: number;
}
interface WindowAnimationOpen {
effects?: string;
duration?: number;
}
interface WindowAnimation {
close?: WindowAnimationClose;
open?: WindowAnimationOpen;
}
interface WindowContent {
template?: string;
}
interface WindowPosition {
top?: number|string;
left?: number|string;
}
interface WindowModal {
preventScroll?: boolean;
}
interface WindowRefreshOptions {
url?: string;
cache?: boolean;
data?: any;
type?: string;
template?: string;
iframe?: boolean;
}
interface WindowDraggable {
containment?: any|string;
dragHandle?: any|string;
axis?: string;
}
interface WindowOptions {
name?: string;
actions?: any;
animation?: boolean | WindowAnimation;
appendTo?: any|string;
autoFocus?: boolean;
content?: string | WindowContent;
draggable?: boolean | WindowDraggable;
iframe?: boolean;
height?: number|string;
maxHeight?: number;
maxWidth?: number;
minHeight?: number;
minWidth?: number;
modal?: boolean | WindowModal;
pinned?: boolean;
position?: WindowPosition;
resizable?: boolean;
scrollable?: boolean;
title?: string|boolean;
visible?: boolean;
width?: number|string;
size?: string;
activate?(e: WindowEvent): void;
close?(e: WindowCloseEvent): void;
deactivate?(e: WindowEvent): void;
dragend?(e: WindowEvent): void;
dragstart?(e: WindowEvent): void;
error?(e: WindowErrorEvent): void;
maximize?(e: WindowEvent): void;
minimize?(e: WindowEvent): void;
open?(e: WindowEvent): void;
refresh?(e: WindowEvent): void;
resize?(e: WindowEvent): void;
}
interface WindowEvent {
sender: Window;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface WindowCloseEvent extends WindowEvent {
userTriggered?: boolean;
}
interface WindowErrorEvent extends WindowEvent {
xhr?: JQueryXHR;
status?: string;
}
}
declare namespace kendo.drawing {
class Arc extends kendo.drawing.Element {
options: ArcOptions;
constructor(geometry: kendo.geometry.Arc, options?: ArcOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
geometry(): kendo.geometry.Arc;
geometry(value: kendo.geometry.Arc): void;
fill(color: string, opacity?: number): kendo.drawing.Arc;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Arc;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface ArcOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface ArcEvent {
sender: Arc;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Circle extends kendo.drawing.Element {
options: CircleOptions;
constructor(geometry: kendo.geometry.Circle, options?: CircleOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
geometry(): kendo.geometry.Circle;
geometry(value: kendo.geometry.Circle): void;
fill(color: string, opacity?: number): kendo.drawing.Circle;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Circle;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface CircleOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface CircleEvent {
sender: Circle;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Element extends kendo.Class {
options: ElementOptions;
parent: kendo.drawing.Group;
constructor(options?: ElementOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
opacity(): number;
opacity(opacity: number): void;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface ElementOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
opacity?: number;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface ElementEvent {
sender: Element;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface FillOptions {
color?: string;
opacity?: number;
}
class Gradient extends kendo.Class {
options: GradientOptions;
stops: any;
constructor(options?: GradientOptions);
addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop;
removeStop(stop: kendo.drawing.GradientStop): void;
}
interface GradientOptions {
name?: string;
stops?: any;
}
interface GradientEvent {
sender: Gradient;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class GradientStop extends kendo.Class {
options: GradientStopOptions;
constructor(options?: GradientStopOptions);
}
interface GradientStopOptions {
name?: string;
offset?: number;
color?: string;
opacity?: number;
}
interface GradientStopEvent {
sender: GradientStop;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Group extends kendo.drawing.Element {
options: GroupOptions;
children: any;
constructor(options?: GroupOptions);
append(...elements: kendo.drawing.Element[]): void;
clear(): void;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
insert(position: number, element: kendo.drawing.Element): void;
opacity(): number;
opacity(opacity: number): void;
remove(element: kendo.drawing.Element): void;
removeAt(index: number): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface GroupOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
opacity?: number;
pdf?: kendo.drawing.PDFOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface GroupEvent {
sender: Group;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Image extends kendo.drawing.Element {
options: ImageOptions;
constructor(src: string, rect: kendo.geometry.Rect);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
opacity(): number;
opacity(opacity: number): void;
src(): string;
src(value: string): void;
rect(): kendo.geometry.Rect;
rect(value: kendo.geometry.Rect): void;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface ImageOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
opacity?: number;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface ImageEvent {
sender: Image;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Layout extends kendo.drawing.Group {
options: LayoutOptions;
constructor(rect: kendo.geometry.Rect, options?: LayoutOptions);
rect(): kendo.geometry.Rect;
rect(rect: kendo.geometry.Rect): void;
reflow(): void;
}
interface LayoutOptions {
name?: string;
alignContent?: string;
alignItems?: string;
justifyContent?: string;
lineSpacing?: number;
spacing?: number;
orientation?: string;
wrap?: boolean;
}
interface LayoutEvent {
sender: Layout;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class LinearGradient extends kendo.drawing.Gradient {
options: LinearGradientOptions;
stops: any;
constructor(options?: LinearGradientOptions);
addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop;
end(): kendo.geometry.Point;
end(end: any): void;
end(end: kendo.geometry.Point): void;
start(): kendo.geometry.Point;
start(start: any): void;
start(start: kendo.geometry.Point): void;
removeStop(stop: kendo.drawing.GradientStop): void;
}
interface LinearGradientOptions {
name?: string;
stops?: any;
}
interface LinearGradientEvent {
sender: LinearGradient;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class MultiPath extends kendo.drawing.Element {
options: MultiPathOptions;
paths: any;
constructor(options?: MultiPathOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
close(): kendo.drawing.MultiPath;
containsPoint(point: kendo.geometry.Point): boolean;
curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.MultiPath;
curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath;
curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.MultiPath;
curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath;
curveTo(controlOut: kendo.geometry.Point, controlIn: any, endPoint: any): kendo.drawing.MultiPath;
curveTo(controlOut: kendo.geometry.Point, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath;
curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.MultiPath;
curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath;
fill(color: string, opacity?: number): kendo.drawing.MultiPath;
lineTo(x: number, y?: number): kendo.drawing.MultiPath;
lineTo(x: any, y?: number): kendo.drawing.MultiPath;
lineTo(x: kendo.geometry.Point, y?: number): kendo.drawing.MultiPath;
moveTo(x: number, y?: number): kendo.drawing.MultiPath;
moveTo(x: any, y?: number): kendo.drawing.MultiPath;
moveTo(x: kendo.geometry.Point, y?: number): kendo.drawing.MultiPath;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.MultiPath;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface MultiPathOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface MultiPathEvent {
sender: MultiPath;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class OptionsStore extends kendo.Class {
options: OptionsStoreOptions;
observer: any;
constructor(options?: OptionsStoreOptions);
get(field: string): any;
set(field: string, value: any): void;
}
interface OptionsStoreOptions {
name?: string;
}
interface OptionsStoreEvent {
sender: OptionsStore;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface PDFOptions {
creator?: string;
date?: Date;
imgDPI?: number;
keywords?: string;
landscape?: boolean;
margin?: any;
paperSize?: any;
subject?: string;
title?: string;
}
class Path extends kendo.drawing.Element {
options: PathOptions;
segments: any;
constructor(options?: PathOptions);
static fromArc(arc: kendo.geometry.Arc, options?: any): kendo.drawing.Path;
static fromPoints(points: any, options?: any): kendo.drawing.Path;
static fromRect(rect: kendo.geometry.Rect, options?: any): kendo.drawing.Path;
static parse(svgPath: string, options?: any): kendo.drawing.MultiPath;
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
close(): kendo.drawing.Path;
containsPoint(point: kendo.geometry.Point): boolean;
curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.Path;
curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.Path;
curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.Path;
curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: kendo.geometry.Point): kendo.drawing.Path;
curveTo(controlOut: kendo.geometry.Point, controlIn: any, endPoint: any): kendo.drawing.Path;
curveTo(controlOut: kendo.geometry.Point, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.Path;
curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.Path;
curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point, endPoint: kendo.geometry.Point): kendo.drawing.Path;
fill(color: string, opacity?: number): kendo.drawing.Path;
lineTo(x: number, y?: number): kendo.drawing.Path;
lineTo(x: any, y?: number): kendo.drawing.Path;
lineTo(x: kendo.geometry.Point, y?: number): kendo.drawing.Path;
moveTo(x: number, y?: number): kendo.drawing.Path;
moveTo(x: any, y?: number): kendo.drawing.Path;
moveTo(x: kendo.geometry.Point, y?: number): kendo.drawing.Path;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Path;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface PathOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface PathEvent {
sender: Path;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class RadialGradient extends kendo.drawing.Gradient {
options: RadialGradientOptions;
stops: any;
constructor(options?: RadialGradientOptions);
addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop;
center(): kendo.geometry.Point;
center(center: any): void;
center(center: kendo.geometry.Point): void;
radius(): number;
radius(value: number): void;
removeStop(stop: kendo.drawing.GradientStop): void;
}
interface RadialGradientOptions {
name?: string;
center?: any|kendo.geometry.Point;
radius?: number;
stops?: any;
}
interface RadialGradientEvent {
sender: RadialGradient;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Rect extends kendo.drawing.Element {
options: RectOptions;
constructor(geometry: kendo.geometry.Rect, options?: RectOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
geometry(): kendo.geometry.Rect;
geometry(value: kendo.geometry.Rect): void;
fill(color: string, opacity?: number): kendo.drawing.Rect;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Rect;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface RectOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface RectEvent {
sender: Rect;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Segment extends kendo.Class {
options: SegmentOptions;
constructor(anchor: kendo.geometry.Point, controlIn: kendo.geometry.Point, controlOut: kendo.geometry.Point);
anchor(): kendo.geometry.Point;
anchor(value: kendo.geometry.Point): void;
controlIn(): kendo.geometry.Point;
controlIn(value: kendo.geometry.Point): void;
controlOut(): kendo.geometry.Point;
controlOut(value: kendo.geometry.Point): void;
}
interface SegmentOptions {
name?: string;
}
interface SegmentEvent {
sender: Segment;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface StrokeOptions {
color?: string;
dashType?: string;
lineCap?: string;
lineJoin?: string;
opacity?: number;
width?: number;
}
class Surface extends kendo.Observable {
options: SurfaceOptions;
constructor(options?: SurfaceOptions);
static create(element: JQuery, options?: any): kendo.drawing.Surface;
static create(element: Element, options?: any): kendo.drawing.Surface;
element: JQuery;
clear(): void;
draw(element: kendo.drawing.Element): void;
eventTarget(e: any): kendo.drawing.Element;
hideTooltip(): void;
resize(force?: boolean): void;
showTooltip(element: kendo.drawing.Element, options?: any): void;
}
interface SurfaceTooltipAnimationClose {
effects?: string;
duration?: number;
}
interface SurfaceTooltipAnimationOpen {
effects?: string;
duration?: number;
}
interface SurfaceTooltipAnimation {
close?: SurfaceTooltipAnimationClose;
open?: SurfaceTooltipAnimationOpen;
}
interface SurfaceTooltip {
animation?: boolean | SurfaceTooltipAnimation;
appendTo?: string|JQuery;
}
interface SurfaceOptions {
name?: string;
type?: string;
height?: string;
width?: string;
tooltip?: SurfaceTooltip;
click?(e: SurfaceClickEvent): void;
mouseenter?(e: SurfaceMouseenterEvent): void;
mouseleave?(e: SurfaceMouseleaveEvent): void;
tooltipClose?(e: SurfaceTooltipCloseEvent): void;
tooltipOpen?(e: SurfaceTooltipOpenEvent): void;
}
interface SurfaceEvent {
sender: Surface;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SurfaceClickEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
originalEvent?: any;
}
interface SurfaceMouseenterEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
originalEvent?: any;
}
interface SurfaceMouseleaveEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
originalEvent?: any;
}
interface SurfaceTooltipCloseEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
target?: kendo.drawing.Element;
}
interface SurfaceTooltipOpenEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
target?: kendo.drawing.Element;
}
class Text extends kendo.drawing.Element {
options: TextOptions;
constructor(content: string, position: kendo.geometry.Point, options?: TextOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
content(): string;
content(value: string): void;
fill(color: string, opacity?: number): kendo.drawing.Text;
opacity(): number;
opacity(opacity: number): void;
position(): kendo.geometry.Point;
position(value: kendo.geometry.Point): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Text;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface TextOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
font?: string;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface TextEvent {
sender: Text;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TooltipOptions {
autoHide?: boolean;
content?: string|Function;
position?: string;
height?: number|string;
hideDelay?: number;
offset?: number;
shared?: boolean;
showAfter?: number;
showOn?: string;
width?: number|string;
}
}
declare namespace kendo.geometry {
class Arc extends Observable {
options: ArcOptions;
anticlockwise: boolean;
center: kendo.geometry.Point;
endAngle: number;
radiusX: number;
radiusY: number;
startAngle: number;
constructor(center: any|kendo.geometry.Point, options?: ArcOptions);
bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect;
getAnticlockwise(): boolean;
getCenter(): kendo.geometry.Point;
getEndAngle(): number;
getRadiusX(): number;
getRadiusY(): number;
getStartAngle(): number;
pointAt(angle: number): kendo.geometry.Point;
setAnticlockwise(value: boolean): kendo.geometry.Arc;
setCenter(value: kendo.geometry.Point): kendo.geometry.Arc;
setEndAngle(value: number): kendo.geometry.Arc;
setRadiusX(value: number): kendo.geometry.Arc;
setRadiusY(value: number): kendo.geometry.Arc;
setStartAngle(value: number): kendo.geometry.Arc;
}
interface ArcOptions {
name?: string;
}
interface ArcEvent {
sender: Arc;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Circle extends Observable {
options: CircleOptions;
center: kendo.geometry.Point;
radius: number;
constructor(center: any|kendo.geometry.Point, radius: number);
bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect;
clone(): kendo.geometry.Circle;
equals(other: kendo.geometry.Circle): boolean;
getCenter(): kendo.geometry.Point;
getRadius(): number;
pointAt(angle: number): kendo.geometry.Point;
setCenter(value: kendo.geometry.Point): kendo.geometry.Point;
setCenter(value: any): kendo.geometry.Point;
setRadius(value: number): kendo.geometry.Circle;
}
interface CircleOptions {
name?: string;
}
interface CircleEvent {
sender: Circle;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Matrix extends Observable {
options: MatrixOptions;
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix;
static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix;
static translate(x: number, y: number): kendo.geometry.Matrix;
static unit(): kendo.geometry.Matrix;
clone(): kendo.geometry.Matrix;
equals(other: kendo.geometry.Matrix): boolean;
round(digits: number): kendo.geometry.Matrix;
multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix;
toArray(digits: number): any;
toString(digits: number, separator: string): string;
}
interface MatrixOptions {
name?: string;
}
interface MatrixEvent {
sender: Matrix;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Point extends Observable {
options: PointOptions;
x: number;
y: number;
constructor(x: number, y: number);
static create(x: number, y: number): kendo.geometry.Point;
static create(x: any, y: number): kendo.geometry.Point;
static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point;
static min(): kendo.geometry.Point;
static max(): kendo.geometry.Point;
static minPoint(): kendo.geometry.Point;
static maxPoint(): kendo.geometry.Point;
clone(): kendo.geometry.Point;
distanceTo(point: kendo.geometry.Point): number;
equals(other: kendo.geometry.Point): boolean;
getX(): number;
getY(): number;
move(x: number, y: number): kendo.geometry.Point;
rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point;
rotate(angle: number, center: any): kendo.geometry.Point;
round(digits: number): kendo.geometry.Point;
scale(scaleX: number, scaleY: number): kendo.geometry.Point;
scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point;
setX(value: number): kendo.geometry.Point;
setY(value: number): kendo.geometry.Point;
toArray(digits: number): any;
toString(digits: number, separator: string): string;
transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point;
transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point;
translate(dx: number, dy: number): kendo.geometry.Point;
translateWith(vector: kendo.geometry.Point): kendo.geometry.Point;
translateWith(vector: any): kendo.geometry.Point;
}
interface PointOptions {
name?: string;
}
interface PointEvent {
sender: Point;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Rect extends Observable {
options: RectOptions;
origin: kendo.geometry.Point;
size: kendo.geometry.Size;
constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any);
static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect;
static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect;
bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect;
bottomLeft(): kendo.geometry.Point;
bottomRight(): kendo.geometry.Point;
center(): kendo.geometry.Point;
clone(): kendo.geometry.Rect;
equals(other: kendo.geometry.Rect): boolean;
getOrigin(): kendo.geometry.Point;
getSize(): kendo.geometry.Size;
height(): number;
setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect;
setOrigin(value: any): kendo.geometry.Rect;
setSize(value: kendo.geometry.Size): kendo.geometry.Rect;
setSize(value: any): kendo.geometry.Rect;
topLeft(): kendo.geometry.Point;
topRight(): kendo.geometry.Point;
width(): number;
}
interface RectOptions {
name?: string;
}
interface RectEvent {
sender: Rect;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Size extends Observable {
options: SizeOptions;
width: number;
height: number;
static create(width: number, height: number): kendo.geometry.Size;
static create(width: any, height: number): kendo.geometry.Size;
static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size;
clone(): kendo.geometry.Size;
equals(other: kendo.geometry.Size): boolean;
getWidth(): number;
getHeight(): number;
setWidth(value: number): kendo.geometry.Size;
setHeight(value: number): kendo.geometry.Size;
}
interface SizeOptions {
name?: string;
}
interface SizeEvent {
sender: Size;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Transformation extends Observable {
options: TransformationOptions;
clone(): kendo.geometry.Transformation;
equals(other: kendo.geometry.Transformation): boolean;
matrix(): kendo.geometry.Matrix;
multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation;
rotate(angle: number, center: any): kendo.geometry.Transformation;
rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation;
scale(scaleX: number, scaleY: number): kendo.geometry.Transformation;
translate(x: number, y: number): kendo.geometry.Transformation;
}
interface TransformationOptions {
name?: string;
}
interface TransformationEvent {
sender: Transformation;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
}
declare namespace kendo.dataviz.ui {
class ArcGauge extends kendo.ui.Widget {
static fn: ArcGauge;
options: ArcGaugeOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ArcGauge;
constructor(element: Element, options?: ArcGaugeOptions);
destroy(): void;
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
redraw(): void;
resize(force?: boolean): void;
setOptions(options: any): void;
svg(): void;
imageDataURL(): string;
value(): void;
value(): void;
}
interface ArcGaugeColor {
color?: string;
from?: number;
to?: number;
}
interface ArcGaugeGaugeAreaBorder {
color?: string;
dashType?: string;
opacity?: number;
width?: number;
}
interface ArcGaugeGaugeAreaMargin {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface ArcGaugeGaugeArea {
background?: string;
border?: ArcGaugeGaugeAreaBorder;
height?: number;
margin?: ArcGaugeGaugeAreaMargin;
width?: number;
}
interface ArcGaugeScaleLabelsBorder {
color?: string;
dashType?: string;
opacity?: number;
width?: number;
}
interface ArcGaugeScaleLabelsMargin {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface ArcGaugeScaleLabelsPadding {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface ArcGaugeScaleLabels {
background?: string;
border?: ArcGaugeScaleLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: ArcGaugeScaleLabelsMargin;
padding?: ArcGaugeScaleLabelsPadding;
position?: string;
template?: string|Function;
visible?: boolean;
}
interface ArcGaugeScaleMajorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
}
interface ArcGaugeScaleMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
}
interface ArcGaugeScale {
endAngle?: number;
labels?: ArcGaugeScaleLabels;
majorTicks?: ArcGaugeScaleMajorTicks;
majorUnit?: number;
max?: number;
min?: number;
minorTicks?: ArcGaugeScaleMinorTicks;
minorUnit?: number;
rangeLineCap?: string;
rangePlaceholderColor?: string;
rangeSize?: number;
rangeDistance?: number;
reverse?: boolean;
startAngle?: number;
}
interface ArcGaugeExportImageOptions {
width?: string;
height?: string;
}
interface ArcGaugeExportSVGOptions {
raw?: boolean;
}
interface ArcGaugeOptions {
name?: string;
color?: string;
colors?: ArcGaugeColor[];
gaugeArea?: ArcGaugeGaugeArea;
opacity?: number;
renderAs?: string;
scale?: ArcGaugeScale;
theme?: string;
transitions?: boolean;
value?: number;
}
interface ArcGaugeEvent {
sender: ArcGauge;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Barcode extends kendo.ui.Widget {
static fn: Barcode;
options: BarcodeOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Barcode;
constructor(element: Element, options?: BarcodeOptions);
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
imageDataURL(): string;
redraw(): void;
resize(force?: boolean): void;
svg(): string;
value(): string;
value(value: number): void;
value(value: string): void;
}
interface BarcodeBorder {
color?: string;
dashType?: string;
width?: number;
}
interface BarcodePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface BarcodeTextMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface BarcodeText {
color?: string;
font?: string;
margin?: BarcodeTextMargin;
visible?: boolean;
}
interface BarcodeExportImageOptions {
width?: string;
height?: string;
}
interface BarcodeExportSVGOptions {
raw?: boolean;
}
interface BarcodeOptions {
name?: string;
renderAs?: string;
background?: string;
border?: BarcodeBorder;
checksum?: boolean;
color?: string;
height?: number;
padding?: BarcodePadding;
text?: BarcodeText;
type?: string;
value?: string;
width?: number;
}
interface BarcodeEvent {
sender: Barcode;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Chart extends kendo.ui.Widget {
static fn: Chart;
options: ChartOptions;
dataSource: kendo.data.DataSource;
surface: kendo.drawing.Surface;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Chart;
constructor(element: Element, options?: ChartOptions);
destroy(): void;
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
findAxisByName(name: string): kendo.dataviz.ChartAxis;
findPaneByIndex(index: number): kendo.dataviz.ChartPane;
findPaneByName(name: string): kendo.dataviz.ChartPane;
findSeries(callback: Function): kendo.dataviz.ChartSeries;
findSeriesByIndex(index: number): kendo.dataviz.ChartSeries;
findSeriesByName(name: string): kendo.dataviz.ChartSeries;
getAxis(name: string): kendo.dataviz.ChartAxis;
hideTooltip(): void;
plotArea(): kendo.dataviz.ChartPlotArea;
redraw(): void;
refresh(): void;
resize(force?: boolean): void;
saveAsPDF(): void;
setDataSource(dataSource: kendo.data.DataSource): void;
setOptions(options: any): void;
showTooltip(filter: Function): void;
showTooltip(filter: number): void;
showTooltip(filter: Date): void;
showTooltip(filter: string): void;
svg(): string;
imageDataURL(): string;
toggleHighlight(show: boolean, options: any): void;
}
interface ChartAxisDefaultsCrosshairTooltipBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartAxisDefaultsCrosshairTooltipPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartAxisDefaultsCrosshairTooltip {
background?: string;
border?: ChartAxisDefaultsCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: ChartAxisDefaultsCrosshairTooltipPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartAxisDefaultsCrosshair {
color?: string;
dashType?: string;
opacity?: number;
tooltip?: ChartAxisDefaultsCrosshairTooltip;
visible?: boolean;
width?: number;
}
interface ChartAxisDefaultsLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartAxisDefaultsLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartAxisDefaultsLabelsRotation {
align?: string;
angle?: number|string;
}
interface ChartAxisDefaultsLabels {
font?: string;
format?: string;
margin?: ChartAxisDefaultsLabelsMargin;
mirror?: boolean;
padding?: ChartAxisDefaultsLabelsPadding;
rotation?: string | number | ChartAxisDefaultsLabelsRotation;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
visual?: Function;
}
interface ChartAxisDefaultsLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface ChartAxisDefaultsMajorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartAxisDefaultsMajorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartAxisDefaultsMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartAxisDefaultsMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartAxisDefaultsPlotBand {
color?: string;
from?: number;
opacity?: number;
to?: number;
}
interface ChartAxisDefaultsTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartAxisDefaultsTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartAxisDefaultsTitlePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartAxisDefaultsTitle {
background?: string;
border?: ChartAxisDefaultsTitleBorder;
color?: string;
font?: string;
margin?: ChartAxisDefaultsTitleMargin;
padding?: ChartAxisDefaultsTitlePadding;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
visual?: Function;
}
interface ChartAxisDefaults {
background?: string;
color?: string;
crosshair?: ChartAxisDefaultsCrosshair;
labels?: ChartAxisDefaultsLabels;
line?: ChartAxisDefaultsLine;
majorGridLines?: ChartAxisDefaultsMajorGridLines;
majorTicks?: ChartAxisDefaultsMajorTicks;
minorGridLines?: ChartAxisDefaultsMinorGridLines;
minorTicks?: ChartAxisDefaultsMinorTicks;
narrowRange?: boolean;
pane?: string;
plotBands?: ChartAxisDefaultsPlotBand[];
reverse?: boolean;
startAngle?: number;
title?: ChartAxisDefaultsTitle;
visible?: boolean;
}
interface ChartCategoryAxisItemAutoBaseUnitSteps {
milliseconds?: any;
seconds?: any;
minutes?: any;
hours?: any;
days?: any;
weeks?: any;
months?: any;
years?: any;
}
interface ChartCategoryAxisItemCrosshairTooltipBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartCategoryAxisItemCrosshairTooltipPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartCategoryAxisItemCrosshairTooltip {
background?: string;
border?: ChartCategoryAxisItemCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: ChartCategoryAxisItemCrosshairTooltipPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartCategoryAxisItemCrosshair {
color?: string;
dashType?: string;
opacity?: number;
tooltip?: ChartCategoryAxisItemCrosshairTooltip;
visible?: boolean;
width?: number;
}
interface ChartCategoryAxisItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartCategoryAxisItemLabelsDateFormats {
days?: string;
hours?: string;
months?: string;
weeks?: string;
years?: string;
}
interface ChartCategoryAxisItemLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartCategoryAxisItemLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartCategoryAxisItemLabelsRotation {
align?: string;
angle?: number|string;
}
interface ChartCategoryAxisItemLabels {
background?: string;
border?: ChartCategoryAxisItemLabelsBorder;
color?: string;
culture?: string;
dateFormats?: ChartCategoryAxisItemLabelsDateFormats;
font?: string;
format?: string;
margin?: ChartCategoryAxisItemLabelsMargin;
mirror?: boolean;
padding?: ChartCategoryAxisItemLabelsPadding;
rotation?: string | number | ChartCategoryAxisItemLabelsRotation;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
visual?: Function;
}
interface ChartCategoryAxisItemLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface ChartCategoryAxisItemMajorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartCategoryAxisItemMajorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartCategoryAxisItemMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartCategoryAxisItemMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartCategoryAxisItemNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface ChartCategoryAxisItemNotesDataItemIcon {
background?: string;
border?: ChartCategoryAxisItemNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartCategoryAxisItemNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartCategoryAxisItemNotesDataItemLabel {
background?: string;
border?: ChartCategoryAxisItemNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface ChartCategoryAxisItemNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface ChartCategoryAxisItemNotesDataItem {
value?: any;
position?: string;
icon?: ChartCategoryAxisItemNotesDataItemIcon;
label?: ChartCategoryAxisItemNotesDataItemLabel;
line?: ChartCategoryAxisItemNotesDataItemLine;
}
interface ChartCategoryAxisItemNotesIconBorder {
color?: string;
width?: number;
}
interface ChartCategoryAxisItemNotesIcon {
background?: string;
border?: ChartCategoryAxisItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartCategoryAxisItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartCategoryAxisItemNotesLabel {
background?: string;
border?: ChartCategoryAxisItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface ChartCategoryAxisItemNotesLine {
dashType?: string;
width?: number;
color?: string;
length?: number;
}
interface ChartCategoryAxisItemNotes {
position?: string;
icon?: ChartCategoryAxisItemNotesIcon;
label?: ChartCategoryAxisItemNotesLabel;
line?: ChartCategoryAxisItemNotesLine;
data?: ChartCategoryAxisItemNotesDataItem[];
visual?: Function;
}
interface ChartCategoryAxisItemPlotBand {
color?: string;
from?: number;
opacity?: number;
to?: number;
}
interface ChartCategoryAxisItemSelectMousewheel {
reverse?: boolean;
zoom?: string;
}
interface ChartCategoryAxisItemSelect {
from?: any;
max?: any;
min?: any;
mousewheel?: ChartCategoryAxisItemSelectMousewheel;
to?: any;
}
interface ChartCategoryAxisItemTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartCategoryAxisItemTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartCategoryAxisItemTitlePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartCategoryAxisItemTitle {
background?: string;
border?: ChartCategoryAxisItemTitleBorder;
color?: string;
font?: string;
margin?: ChartCategoryAxisItemTitleMargin;
padding?: ChartCategoryAxisItemTitlePadding;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
visual?: Function;
}
interface ChartCategoryAxisItem {
autoBaseUnitSteps?: ChartCategoryAxisItemAutoBaseUnitSteps;
axisCrossingValue?: any|Date|any;
background?: string;
baseUnit?: string;
baseUnitStep?: any;
categories?: any;
color?: string;
crosshair?: ChartCategoryAxisItemCrosshair;
field?: string;
justified?: boolean;
labels?: ChartCategoryAxisItemLabels;
line?: ChartCategoryAxisItemLine;
majorGridLines?: ChartCategoryAxisItemMajorGridLines;
majorTicks?: ChartCategoryAxisItemMajorTicks;
max?: any;
maxDateGroups?: number;
maxDivisions?: number;
min?: any;
minorGridLines?: ChartCategoryAxisItemMinorGridLines;
minorTicks?: ChartCategoryAxisItemMinorTicks;
name?: string;
pane?: string;
plotBands?: ChartCategoryAxisItemPlotBand[];
reverse?: boolean;
roundToBaseUnit?: boolean;
select?: ChartCategoryAxisItemSelect;
startAngle?: number;
title?: ChartCategoryAxisItemTitle;
type?: string;
visible?: boolean;
weekStartDay?: number;
notes?: ChartCategoryAxisItemNotes;
}
interface ChartChartAreaBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartChartAreaMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartChartArea {
background?: string;
border?: ChartChartAreaBorder;
height?: number;
margin?: ChartChartAreaMargin;
opacity?: number;
width?: number;
}
interface ChartLegendBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartLegendInactiveItemsLabels {
color?: string;
font?: string;
template?: string|Function;
}
interface ChartLegendInactiveItems {
labels?: ChartLegendInactiveItemsLabels;
}
interface ChartLegendItem {
cursor?: string;
visual?: Function;
}
interface ChartLegendLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartLegendLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartLegendLabels {
color?: string;
font?: string;
margin?: ChartLegendLabelsMargin;
padding?: ChartLegendLabelsPadding;
template?: string|Function;
}
interface ChartLegendMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartLegendPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartLegend {
align?: string;
background?: string;
border?: ChartLegendBorder;
height?: number;
inactiveItems?: ChartLegendInactiveItems;
item?: ChartLegendItem;
labels?: ChartLegendLabels;
margin?: ChartLegendMargin;
offsetX?: number;
offsetY?: number;
orientation?: string;
padding?: ChartLegendPadding;
position?: string;
reverse?: boolean;
spacing?: number;
visible?: boolean;
width?: number;
}
interface ChartPaneBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartPaneMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartPanePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartPaneTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartPaneTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartPaneTitle {
background?: string;
border?: ChartPaneTitleBorder;
color?: string;
font?: string;
margin?: ChartPaneTitleMargin;
position?: string;
text?: string;
visible?: boolean;
visual?: Function;
}
interface ChartPane {
background?: string;
border?: ChartPaneBorder;
clip?: boolean;
height?: number;
margin?: ChartPaneMargin;
name?: string;
padding?: ChartPanePadding;
title?: string | ChartPaneTitle;
}
interface ChartPannable {
key?: string;
lock?: string;
}
interface ChartPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface ChartPdf {
author?: string;
creator?: string;
date?: Date;
forceProxy?: boolean;
fileName?: string;
keywords?: string;
landscape?: boolean;
margin?: ChartPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface ChartPlotAreaBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartPlotAreaMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartPlotAreaPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartPlotArea {
background?: string;
border?: ChartPlotAreaBorder;
margin?: ChartPlotAreaMargin;
opacity?: number;
padding?: ChartPlotAreaPadding;
}
interface ChartSeriesItemBorder {
color?: string|Function;
dashType?: string|Function;
opacity?: number|Function;
width?: number|Function;
}
interface ChartSeriesItemConnectors {
color?: string|Function;
padding?: number;
width?: number;
}
interface ChartSeriesItemErrorBarsLine {
width?: number;
dashType?: string;
}
interface ChartSeriesItemErrorBars {
value?: string|number|any|Function;
visual?: Function;
xValue?: string|number|any|Function;
yValue?: string|number|any|Function;
endCaps?: boolean;
color?: string;
line?: ChartSeriesItemErrorBarsLine;
}
interface ChartSeriesItemExtremesBorder {
color?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemExtremes {
background?: string|Function;
border?: Function | ChartSeriesItemExtremesBorder;
size?: number|Function;
type?: string|Function;
rotation?: number|Function;
}
interface ChartSeriesItemHighlightBorder {
color?: string;
opacity?: number;
width?: number;
}
interface ChartSeriesItemHighlightLine {
dashType?: string;
color?: string;
opacity?: number;
width?: number;
}
interface ChartSeriesItemHighlight {
border?: ChartSeriesItemHighlightBorder;
color?: string;
line?: ChartSeriesItemHighlightLine;
opacity?: number;
toggle?: Function;
visible?: boolean;
visual?: Function;
}
interface ChartSeriesItemLabelsBorder {
color?: string|Function;
dashType?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemLabelsFromBorder {
color?: string|Function;
dashType?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemLabelsFromMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesItemLabelsFromPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesItemLabelsFrom {
background?: string|Function;
border?: ChartSeriesItemLabelsFromBorder;
color?: string|Function;
font?: string|Function;
format?: string|Function;
margin?: ChartSeriesItemLabelsFromMargin;
padding?: ChartSeriesItemLabelsFromPadding;
position?: string|Function;
template?: string|Function;
visible?: boolean|Function;
}
interface ChartSeriesItemLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesItemLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesItemLabelsToBorder {
color?: string|Function;
dashType?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemLabelsToMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesItemLabelsToPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesItemLabelsTo {
background?: string|Function;
border?: ChartSeriesItemLabelsToBorder;
color?: string|Function;
font?: string|Function;
format?: string|Function;
margin?: ChartSeriesItemLabelsToMargin;
padding?: ChartSeriesItemLabelsToPadding;
position?: string|Function;
template?: string|Function;
visible?: boolean|Function;
}
interface ChartSeriesItemLabels {
align?: string;
background?: string|Function;
border?: ChartSeriesItemLabelsBorder;
color?: string|Function;
distance?: number;
font?: string|Function;
format?: string|Function;
margin?: ChartSeriesItemLabelsMargin;
padding?: ChartSeriesItemLabelsPadding;
position?: string|Function;
rotation?: string|number;
template?: string|Function;
visible?: boolean|Function;
visual?: Function;
from?: ChartSeriesItemLabelsFrom;
to?: ChartSeriesItemLabelsTo;
}
interface ChartSeriesItemLine {
color?: string;
opacity?: number;
width?: number;
style?: string;
}
interface ChartSeriesItemMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesItemMarkersBorder {
color?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemMarkersFromBorder {
color?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemMarkersFrom {
background?: string|Function;
border?: Function | ChartSeriesItemMarkersFromBorder;
size?: number|Function;
type?: string|Function;
visible?: boolean|Function;
visual?: Function;
rotation?: number|Function;
}
interface ChartSeriesItemMarkersToBorder {
color?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemMarkersTo {
background?: string|Function;
border?: Function | ChartSeriesItemMarkersToBorder;
size?: number|Function;
type?: string|Function;
visible?: boolean|Function;
visual?: Function;
rotation?: number|Function;
}
interface ChartSeriesItemMarkers {
background?: string|Function;
border?: Function | ChartSeriesItemMarkersBorder;
from?: ChartSeriesItemMarkersFrom;
size?: number|Function;
to?: ChartSeriesItemMarkersTo;
type?: string|Function;
visible?: boolean|Function;
visual?: Function;
rotation?: number|Function;
}
interface ChartSeriesItemNegativeValues {
color?: string;
visible?: boolean;
}
interface ChartSeriesItemNotesIconBorder {
color?: string;
width?: number;
}
interface ChartSeriesItemNotesIcon {
background?: string;
border?: ChartSeriesItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartSeriesItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartSeriesItemNotesLabel {
background?: string;
border?: ChartSeriesItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface ChartSeriesItemNotesLine {
dashType?: string;
width?: number;
color?: string;
length?: number;
}
interface ChartSeriesItemNotes {
position?: string;
icon?: ChartSeriesItemNotesIcon;
label?: ChartSeriesItemNotesLabel;
line?: ChartSeriesItemNotesLine;
visual?: Function;
}
interface ChartSeriesItemOutliersBorder {
color?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemOutliers {
background?: string|Function;
border?: Function | ChartSeriesItemOutliersBorder;
size?: number|Function;
type?: string|Function;
rotation?: number|Function;
}
interface ChartSeriesItemOverlay {
gradient?: string;
}
interface ChartSeriesItemStack {
type?: string;
group?: string;
}
interface ChartSeriesItemTargetBorder {
color?: string|Function;
dashType?: string|Function;
width?: number|Function;
}
interface ChartSeriesItemTargetLine {
width?: number|Function;
}
interface ChartSeriesItemTarget {
border?: Function | ChartSeriesItemTargetBorder;
color?: string|Function;
line?: ChartSeriesItemTargetLine;
}
interface ChartSeriesItemTooltipBorder {
color?: string;
width?: number;
}
interface ChartSeriesItemTooltipPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesItemTooltip {
background?: string;
border?: ChartSeriesItemTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: ChartSeriesItemTooltipPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartSeriesItem {
aggregate?: string|Function;
axis?: string;
border?: ChartSeriesItemBorder;
categoryAxis?: string;
categoryField?: string;
closeField?: string;
color?: string|Function;
colorField?: string;
connectors?: ChartSeriesItemConnectors;
currentField?: string;
dashType?: string;
data?: any;
downColor?: string|Function;
downColorField?: string;
segmentSpacing?: number;
summaryField?: string;
neckRatio?: number;
dynamicSlope?: boolean;
dynamicHeight?: boolean;
errorBars?: ChartSeriesItemErrorBars;
errorLowField?: string;
errorHighField?: string;
xErrorLowField?: string;
xErrorHighField?: string;
yErrorLowField?: string;
yErrorHighField?: string;
explodeField?: string;
field?: string;
fromField?: string;
toField?: string;
noteTextField?: string;
lowerField?: string;
q1Field?: string;
medianField?: string;
q3Field?: string;
upperField?: string;
meanField?: string;
outliersField?: string;
gap?: number;
highField?: string;
highlight?: ChartSeriesItemHighlight;
holeSize?: number;
labels?: ChartSeriesItemLabels;
line?: string | ChartSeriesItemLine;
lowField?: string;
margin?: ChartSeriesItemMargin;
markers?: ChartSeriesItemMarkers;
outliers?: ChartSeriesItemOutliers;
extremes?: ChartSeriesItemExtremes;
maxSize?: number;
minSize?: number;
missingValues?: string;
style?: string;
name?: string;
negativeColor?: string;
negativeValues?: ChartSeriesItemNegativeValues;
opacity?: number;
openField?: string;
overlay?: ChartSeriesItemOverlay;
padding?: number;
size?: number;
sizeField?: string;
spacing?: number;
stack?: boolean | string | ChartSeriesItemStack;
startAngle?: number;
target?: ChartSeriesItemTarget;
targetField?: string;
tooltip?: ChartSeriesItemTooltip;
type?: string;
visible?: boolean;
visibleInLegend?: boolean;
visibleInLegendField?: string;
visual?: Function;
width?: number;
xAxis?: string;
xField?: string;
yAxis?: string;
yField?: string;
notes?: ChartSeriesItemNotes;
zIndex?: number;
}
interface ChartSeriesDefaultsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartSeriesDefaultsLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartSeriesDefaultsLabelsFromBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartSeriesDefaultsLabelsFromMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesDefaultsLabelsFromPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesDefaultsLabelsFrom {
background?: string;
border?: ChartSeriesDefaultsLabelsFromBorder;
color?: string;
font?: string;
format?: string;
margin?: ChartSeriesDefaultsLabelsFromMargin;
padding?: ChartSeriesDefaultsLabelsFromPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartSeriesDefaultsLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesDefaultsLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesDefaultsLabelsToBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartSeriesDefaultsLabelsToMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesDefaultsLabelsToPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesDefaultsLabelsTo {
background?: string;
border?: ChartSeriesDefaultsLabelsToBorder;
color?: string;
font?: string;
format?: string;
margin?: ChartSeriesDefaultsLabelsToMargin;
padding?: ChartSeriesDefaultsLabelsToPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartSeriesDefaultsLabels {
background?: string;
border?: ChartSeriesDefaultsLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: ChartSeriesDefaultsLabelsMargin;
padding?: ChartSeriesDefaultsLabelsPadding;
rotation?: string|number;
template?: string|Function;
visible?: boolean;
visual?: Function;
from?: ChartSeriesDefaultsLabelsFrom;
to?: ChartSeriesDefaultsLabelsTo;
}
interface ChartSeriesDefaultsNotesIconBorder {
color?: string;
width?: number;
}
interface ChartSeriesDefaultsNotesIcon {
background?: string;
border?: ChartSeriesDefaultsNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartSeriesDefaultsNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartSeriesDefaultsNotesLabel {
background?: string;
border?: ChartSeriesDefaultsNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface ChartSeriesDefaultsNotesLine {
dashType?: string;
width?: number;
color?: string;
length?: number;
}
interface ChartSeriesDefaultsNotes {
icon?: ChartSeriesDefaultsNotesIcon;
label?: ChartSeriesDefaultsNotesLabel;
line?: ChartSeriesDefaultsNotesLine;
visual?: Function;
}
interface ChartSeriesDefaultsOverlay {
gradient?: string;
}
interface ChartSeriesDefaultsStack {
type?: string;
}
interface ChartSeriesDefaultsTooltipBorder {
color?: string;
width?: number;
}
interface ChartSeriesDefaultsTooltipPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartSeriesDefaultsTooltip {
background?: string;
border?: ChartSeriesDefaultsTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: ChartSeriesDefaultsTooltipPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartSeriesDefaults {
area?: any;
bar?: any;
border?: ChartSeriesDefaultsBorder;
bubble?: any;
candlestick?: any;
column?: any;
donut?: any;
gap?: number;
labels?: ChartSeriesDefaultsLabels;
line?: any;
ohlc?: any;
overlay?: ChartSeriesDefaultsOverlay;
pie?: any;
rangeArea?: any;
scatter?: any;
scatterLine?: any;
spacing?: number;
stack?: boolean | ChartSeriesDefaultsStack;
type?: string;
tooltip?: ChartSeriesDefaultsTooltip;
verticalArea?: any;
verticalLine?: any;
verticalRangeArea?: any;
visual?: Function;
notes?: ChartSeriesDefaultsNotes;
}
interface ChartTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartTitlePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartTitle {
align?: string;
background?: string;
border?: ChartTitleBorder;
color?: string;
font?: string;
margin?: ChartTitleMargin;
padding?: ChartTitlePadding;
position?: string;
text?: string;
visible?: boolean;
}
interface ChartTooltipBorder {
color?: string;
width?: number;
}
interface ChartTooltipPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartTooltip {
background?: string;
border?: ChartTooltipBorder;
color?: string;
font?: string;
format?: string;
opacity?: number;
padding?: ChartTooltipPadding;
shared?: boolean;
sharedTemplate?: string|Function;
template?: string|Function;
visible?: boolean;
}
interface ChartValueAxisItemCrosshairTooltipBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartValueAxisItemCrosshairTooltipPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartValueAxisItemCrosshairTooltip {
background?: string;
border?: ChartValueAxisItemCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: ChartValueAxisItemCrosshairTooltipPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartValueAxisItemCrosshair {
color?: string;
dashType?: string;
opacity?: number;
tooltip?: ChartValueAxisItemCrosshairTooltip;
visible?: boolean;
width?: number;
}
interface ChartValueAxisItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartValueAxisItemLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartValueAxisItemLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartValueAxisItemLabelsRotation {
align?: string;
angle?: number|string;
}
interface ChartValueAxisItemLabels {
background?: string;
border?: ChartValueAxisItemLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: ChartValueAxisItemLabelsMargin;
mirror?: boolean;
padding?: ChartValueAxisItemLabelsPadding;
rotation?: string | number | ChartValueAxisItemLabelsRotation;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
visual?: Function;
}
interface ChartValueAxisItemLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface ChartValueAxisItemMajorGridLines {
color?: string;
dashType?: string;
type?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartValueAxisItemMajorTicks {
color?: string;
size?: number;
visible?: boolean;
step?: number;
skip?: number;
}
interface ChartValueAxisItemMinorGridLines {
color?: string;
dashType?: string;
type?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartValueAxisItemMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartValueAxisItemNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface ChartValueAxisItemNotesDataItemIcon {
background?: string;
border?: ChartValueAxisItemNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartValueAxisItemNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartValueAxisItemNotesDataItemLabel {
background?: string;
border?: ChartValueAxisItemNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface ChartValueAxisItemNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface ChartValueAxisItemNotesDataItem {
value?: any;
position?: string;
icon?: ChartValueAxisItemNotesDataItemIcon;
label?: ChartValueAxisItemNotesDataItemLabel;
line?: ChartValueAxisItemNotesDataItemLine;
}
interface ChartValueAxisItemNotesIconBorder {
color?: string;
width?: number;
}
interface ChartValueAxisItemNotesIcon {
background?: string;
border?: ChartValueAxisItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartValueAxisItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartValueAxisItemNotesLabel {
background?: string;
border?: ChartValueAxisItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface ChartValueAxisItemNotesLine {
dashType?: string;
width?: number;
color?: string;
length?: number;
}
interface ChartValueAxisItemNotes {
position?: string;
icon?: ChartValueAxisItemNotesIcon;
label?: ChartValueAxisItemNotesLabel;
line?: ChartValueAxisItemNotesLine;
data?: ChartValueAxisItemNotesDataItem[];
visual?: Function;
}
interface ChartValueAxisItemPlotBand {
color?: string;
from?: number;
opacity?: number;
to?: number;
}
interface ChartValueAxisItemTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartValueAxisItemTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartValueAxisItemTitlePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartValueAxisItemTitle {
background?: string;
border?: ChartValueAxisItemTitleBorder;
color?: string;
font?: string;
margin?: ChartValueAxisItemTitleMargin;
padding?: ChartValueAxisItemTitlePadding;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
visual?: Function;
}
interface ChartValueAxisItem {
axisCrossingValue?: any|Date|any;
background?: string;
color?: string;
crosshair?: ChartValueAxisItemCrosshair;
labels?: ChartValueAxisItemLabels;
line?: ChartValueAxisItemLine;
majorGridLines?: ChartValueAxisItemMajorGridLines;
majorUnit?: number;
max?: number;
min?: number;
minorGridLines?: ChartValueAxisItemMinorGridLines;
majorTicks?: ChartValueAxisItemMajorTicks;
minorTicks?: ChartValueAxisItemMinorTicks;
minorUnit?: number;
name?: string;
narrowRange?: boolean;
pane?: string;
plotBands?: ChartValueAxisItemPlotBand[];
reverse?: boolean;
title?: ChartValueAxisItemTitle;
type?: string;
visible?: boolean;
notes?: ChartValueAxisItemNotes;
}
interface ChartXAxisItemCrosshairTooltipBorder {
color?: string;
dashType?: string;
width?: number; | bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartXAxisItemCrosshairTooltip {
background?: string;
border?: ChartXAxisItemCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: ChartXAxisItemCrosshairTooltipPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartXAxisItemCrosshair {
color?: string;
dashType?: string;
opacity?: number;
tooltip?: ChartXAxisItemCrosshairTooltip;
visible?: boolean;
width?: number;
}
interface ChartXAxisItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartXAxisItemLabelsDateFormats {
days?: string;
hours?: string;
months?: string;
weeks?: string;
years?: string;
}
interface ChartXAxisItemLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartXAxisItemLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartXAxisItemLabelsRotation {
align?: string;
angle?: number|string;
}
interface ChartXAxisItemLabels {
background?: string;
border?: ChartXAxisItemLabelsBorder;
color?: string;
culture?: string;
dateFormats?: ChartXAxisItemLabelsDateFormats;
font?: string;
format?: string;
margin?: ChartXAxisItemLabelsMargin;
mirror?: boolean;
padding?: ChartXAxisItemLabelsPadding;
rotation?: string | number | ChartXAxisItemLabelsRotation;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
visual?: Function;
}
interface ChartXAxisItemLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface ChartXAxisItemMajorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartXAxisItemMajorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartXAxisItemMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartXAxisItemMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartXAxisItemNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface ChartXAxisItemNotesDataItemIcon {
background?: string;
border?: ChartXAxisItemNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartXAxisItemNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartXAxisItemNotesDataItemLabel {
background?: string;
border?: ChartXAxisItemNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface ChartXAxisItemNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface ChartXAxisItemNotesDataItem {
value?: any;
position?: string;
icon?: ChartXAxisItemNotesDataItemIcon;
label?: ChartXAxisItemNotesDataItemLabel;
line?: ChartXAxisItemNotesDataItemLine;
}
interface ChartXAxisItemNotesIconBorder {
color?: string;
width?: number;
}
interface ChartXAxisItemNotesIcon {
background?: string;
border?: ChartXAxisItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartXAxisItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartXAxisItemNotesLabel {
background?: string;
border?: ChartXAxisItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface ChartXAxisItemNotesLine {
dashType?: string;
width?: number;
color?: string;
length?: number;
}
interface ChartXAxisItemNotes {
position?: string;
icon?: ChartXAxisItemNotesIcon;
label?: ChartXAxisItemNotesLabel;
line?: ChartXAxisItemNotesLine;
data?: ChartXAxisItemNotesDataItem[];
visual?: Function;
}
interface ChartXAxisItemPlotBand {
color?: string;
from?: number;
opacity?: number;
to?: number;
}
interface ChartXAxisItemTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartXAxisItemTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartXAxisItemTitlePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartXAxisItemTitle {
background?: string;
border?: ChartXAxisItemTitleBorder;
color?: string;
font?: string;
margin?: ChartXAxisItemTitleMargin;
padding?: ChartXAxisItemTitlePadding;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
visual?: Function;
}
interface ChartXAxisItem {
axisCrossingValue?: any|Date|any;
background?: string;
baseUnit?: string;
color?: string;
crosshair?: ChartXAxisItemCrosshair;
labels?: ChartXAxisItemLabels;
line?: ChartXAxisItemLine;
majorGridLines?: ChartXAxisItemMajorGridLines;
minorGridLines?: ChartXAxisItemMinorGridLines;
minorTicks?: ChartXAxisItemMinorTicks;
majorTicks?: ChartXAxisItemMajorTicks;
majorUnit?: number;
max?: any;
min?: any;
minorUnit?: number;
name?: string;
narrowRange?: boolean;
pane?: string;
plotBands?: ChartXAxisItemPlotBand[];
reverse?: boolean;
startAngle?: number;
title?: ChartXAxisItemTitle;
type?: string;
visible?: boolean;
notes?: ChartXAxisItemNotes;
}
interface ChartYAxisItemCrosshairTooltipBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartYAxisItemCrosshairTooltipPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartYAxisItemCrosshairTooltip {
background?: string;
border?: ChartYAxisItemCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: ChartYAxisItemCrosshairTooltipPadding;
template?: string|Function;
visible?: boolean;
}
interface ChartYAxisItemCrosshair {
color?: string;
dashType?: string;
opacity?: number;
tooltip?: ChartYAxisItemCrosshairTooltip;
visible?: boolean;
width?: number;
}
interface ChartYAxisItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartYAxisItemLabelsDateFormats {
days?: string;
hours?: string;
months?: string;
weeks?: string;
years?: string;
}
interface ChartYAxisItemLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartYAxisItemLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartYAxisItemLabelsRotation {
align?: string;
angle?: number;
}
interface ChartYAxisItemLabels {
background?: string;
border?: ChartYAxisItemLabelsBorder;
color?: string;
culture?: string;
dateFormats?: ChartYAxisItemLabelsDateFormats;
font?: string;
format?: string;
margin?: ChartYAxisItemLabelsMargin;
mirror?: boolean;
padding?: ChartYAxisItemLabelsPadding;
rotation?: number |ChartYAxisItemLabelsRotation;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
visual?: Function;
}
interface ChartYAxisItemLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface ChartYAxisItemMajorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartYAxisItemMajorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartYAxisItemMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartYAxisItemMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface ChartYAxisItemNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface ChartYAxisItemNotesDataItemIcon {
background?: string;
border?: ChartYAxisItemNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartYAxisItemNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartYAxisItemNotesDataItemLabel {
background?: string;
border?: ChartYAxisItemNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface ChartYAxisItemNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface ChartYAxisItemNotesDataItem {
value?: any;
position?: string;
icon?: ChartYAxisItemNotesDataItemIcon;
label?: ChartYAxisItemNotesDataItemLabel;
line?: ChartYAxisItemNotesDataItemLine;
}
interface ChartYAxisItemNotesIconBorder {
color?: string;
width?: number;
}
interface ChartYAxisItemNotesIcon {
background?: string;
border?: ChartYAxisItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface ChartYAxisItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartYAxisItemNotesLabel {
background?: string;
border?: ChartYAxisItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface ChartYAxisItemNotesLine {
dashType?: string;
width?: number;
color?: string;
length?: number;
}
interface ChartYAxisItemNotes {
position?: string;
icon?: ChartYAxisItemNotesIcon;
label?: ChartYAxisItemNotesLabel;
line?: ChartYAxisItemNotesLine;
data?: ChartYAxisItemNotesDataItem[];
visual?: Function;
}
interface ChartYAxisItemPlotBand {
color?: string;
from?: number;
opacity?: number;
to?: number;
}
interface ChartYAxisItemTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface ChartYAxisItemTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartYAxisItemTitlePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface ChartYAxisItemTitle {
background?: string;
border?: ChartYAxisItemTitleBorder;
color?: string;
font?: string;
margin?: ChartYAxisItemTitleMargin;
padding?: ChartYAxisItemTitlePadding;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
visual?: Function;
}
interface ChartYAxisItem {
axisCrossingValue?: any|Date|any;
background?: string;
baseUnit?: string;
color?: string;
crosshair?: ChartYAxisItemCrosshair;
labels?: ChartYAxisItemLabels;
line?: ChartYAxisItemLine;
majorGridLines?: ChartYAxisItemMajorGridLines;
minorGridLines?: ChartYAxisItemMinorGridLines;
minorTicks?: ChartYAxisItemMinorTicks;
majorTicks?: ChartYAxisItemMajorTicks;
majorUnit?: number;
max?: any;
min?: any;
minorUnit?: number;
name?: string;
narrowRange?: boolean;
pane?: string;
plotBands?: ChartYAxisItemPlotBand[];
reverse?: boolean;
title?: ChartYAxisItemTitle;
type?: string;
visible?: boolean;
notes?: ChartYAxisItemNotes;
}
interface ChartZoomableMousewheel {
lock?: string;
}
interface ChartZoomableSelection {
key?: string;
lock?: string;
}
interface ChartZoomable {
mousewheel?: boolean | ChartZoomableMousewheel;
selection?: boolean | ChartZoomableSelection;
}
interface ChartExportImageOptions {
width?: string;
height?: string;
cors?: string;
}
interface ChartExportSVGOptions {
raw?: boolean;
}
interface ChartToggleHighlightOptions {
series?: string;
category?: string;
}
interface ChartSeriesClickEventSeries {
type?: string;
name?: string;
data?: any;
}
interface ChartSeriesHoverEventSeries {
type?: string;
name?: string;
data?: any;
}
interface ChartSeriesOverEventSeries {
type?: string;
name?: string;
data?: any;
}
interface ChartSeriesLeaveEventSeries {
type?: string;
name?: string;
data?: any;
}
interface ChartOptions {
name?: string;
autoBind?: boolean;
axisDefaults?: ChartAxisDefaults;
categoryAxis?: ChartCategoryAxisItem | ChartCategoryAxisItem[];
chartArea?: ChartChartArea;
dataSource?: any|any|kendo.data.DataSource;
legend?: ChartLegend;
panes?: ChartPane[];
pannable?: boolean | ChartPannable;
pdf?: ChartPdf;
persistSeriesVisibility?: boolean;
plotArea?: ChartPlotArea;
renderAs?: string;
series?: ChartSeriesItem[];
seriesColors?: any;
seriesDefaults?: ChartSeriesDefaults;
theme?: string;
title?: string | ChartTitle;
tooltip?: ChartTooltip;
transitions?: boolean;
valueAxis?: ChartValueAxisItem | ChartValueAxisItem[];
xAxis?: ChartXAxisItem | ChartXAxisItem[];
yAxis?: ChartYAxisItem | ChartYAxisItem[];
zoomable?: boolean | ChartZoomable;
axisLabelClick?(e: ChartAxisLabelClickEvent): void;
dataBound?(e: ChartDataBoundEvent): void;
drag?(e: ChartDragEvent): void;
dragEnd?(e: ChartDragEndEvent): void;
dragStart?(e: ChartDragStartEvent): void;
legendItemClick?(e: ChartLegendItemClickEvent): void;
legendItemHover?(e: ChartLegendItemHoverEvent): void;
legendItemLeave?(e: ChartLegendItemLeaveEvent): void;
noteClick?(e: ChartNoteClickEvent): void;
noteHover?(e: ChartNoteHoverEvent): void;
noteLeave?(e: ChartNoteLeaveEvent): void;
paneRender?(e: ChartPaneRenderEvent): void;
plotAreaClick?(e: ChartPlotAreaClickEvent): void;
plotAreaHover?(e: ChartPlotAreaHoverEvent): void;
plotAreaLeave?(e: ChartPlotAreaLeaveEvent): void;
render?(e: ChartRenderEvent): void;
select?(e: ChartSelectEvent): void;
selectEnd?(e: ChartSelectEndEvent): void;
selectStart?(e: ChartSelectStartEvent): void;
seriesClick?(e: ChartSeriesClickEvent): void;
seriesHover?(e: ChartSeriesHoverEvent): void;
seriesOver?(e: ChartSeriesOverEvent): void;
seriesLeave?(e: ChartSeriesLeaveEvent): void;
zoom?(e: ChartZoomEvent): void;
zoomEnd?(e: ChartZoomEndEvent): void;
zoomStart?(e: ChartZoomStartEvent): void;
}
interface ChartEvent {
sender: Chart;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ChartAxisLabelClickEvent extends ChartEvent {
axis?: any;
dataItem?: any;
element?: any;
index?: any;
text?: string;
value?: any;
}
interface ChartDataBoundEvent extends ChartEvent {
}
interface ChartDragEvent extends ChartEvent {
axisRanges?: any;
originalEvent?: any;
}
interface ChartDragEndEvent extends ChartEvent {
axisRanges?: any;
originalEvent?: any;
}
interface ChartDragStartEvent extends ChartEvent {
axisRanges?: any;
originalEvent?: any;
}
interface ChartLegendItemClickEvent extends ChartEvent {
pointIndex?: number;
series?: any;
seriesIndex?: number;
text?: string;
element?: any;
}
interface ChartLegendItemHoverEvent extends ChartEvent {
element?: any;
pointIndex?: number;
series?: any;
seriesIndex?: number;
text?: string;
}
interface ChartLegendItemLeaveEvent extends ChartEvent {
element?: any;
pointIndex?: number;
series?: any;
seriesIndex?: number;
text?: string;
}
interface ChartNoteClickEvent extends ChartEvent {
category?: any;
dataItem?: any;
element?: any;
series?: any;
value?: any;
visual?: any;
}
interface ChartNoteHoverEvent extends ChartEvent {
category?: any;
dataItem?: any;
element?: any;
series?: any;
value?: any;
visual?: any;
}
interface ChartNoteLeaveEvent extends ChartEvent {
category?: any;
dataItem?: any;
element?: any;
series?: any;
value?: any;
visual?: any;
}
interface ChartPaneRenderEvent extends ChartEvent {
pane?: kendo.dataviz.ChartPane;
name?: string;
index?: number;
}
interface ChartPlotAreaClickEvent extends ChartEvent {
category?: any;
element?: any;
originalEvent?: any;
value?: any;
x?: any;
y?: any;
}
interface ChartPlotAreaHoverEvent extends ChartEvent {
category?: any;
element?: any;
originalEvent?: any;
value?: any;
x?: any;
y?: any;
}
interface ChartPlotAreaLeaveEvent extends ChartEvent {
}
interface ChartRenderEvent extends ChartEvent {
}
interface ChartSelectEvent extends ChartEvent {
axis?: any;
from?: any;
to?: any;
}
interface ChartSelectEndEvent extends ChartEvent {
axis?: any;
from?: any;
to?: any;
}
interface ChartSelectStartEvent extends ChartEvent {
axis?: any;
from?: any;
to?: any;
}
interface ChartSeriesClickEvent extends ChartEvent {
category?: any;
dataItem?: any;
element?: any;
originalEvent?: any;
percentage?: any;
series?: ChartSeriesClickEventSeries;
stackValue?: any;
value?: any;
}
interface ChartSeriesHoverEvent extends ChartEvent {
category?: any;
categoryPoints?: any;
dataItem?: any;
element?: any;
originalEvent?: any;
percentage?: any;
series?: ChartSeriesHoverEventSeries;
stackValue?: any;
value?: any;
}
interface ChartSeriesOverEvent extends ChartEvent {
category?: any;
dataItem?: any;
element?: any;
originalEvent?: any;
percentage?: any;
series?: ChartSeriesOverEventSeries;
stackValue?: any;
value?: any;
}
interface ChartSeriesLeaveEvent extends ChartEvent {
category?: any;
dataItem?: any;
element?: any;
originalEvent?: any;
percentage?: any;
series?: ChartSeriesLeaveEventSeries;
stackValue?: any;
value?: any;
}
interface ChartZoomEvent extends ChartEvent {
axisRanges?: any;
delta?: number;
originalEvent?: any;
}
interface ChartZoomEndEvent extends ChartEvent {
axisRanges?: any;
originalEvent?: any;
}
interface ChartZoomStartEvent extends ChartEvent {
axisRanges?: any;
originalEvent?: any;
}
class Diagram extends kendo.ui.Widget {
static fn: Diagram;
options: DiagramOptions;
dataSource: kendo.data.DataSource;
connections: kendo.dataviz.diagram.Connection[];
connectionsDataSource: kendo.data.DataSource;
shapes: kendo.dataviz.diagram.Shape[];
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Diagram;
constructor(element: Element, options?: DiagramOptions);
addConnection(connection: any, undoable: boolean): void;
addShape(obj: any, undoable: boolean): kendo.dataviz.diagram.Shape;
alignShapes(direction: string): void;
boundingBox(items: any): kendo.dataviz.diagram.Rect;
bringIntoView(obj: any, options: any): void;
cancelEdit(): void;
clear(): void;
connect(source: any, target: any, options: any): void;
connected(source: any, target: any): void;
copy(): void;
createConnection(item: any): void;
createShape(item: any): void;
cut(): void;
destroy(): void;
documentToModel(point: any): any;
documentToView(point: any): any;
edit(item: any): void;
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
focus(): void;
getConnectionByModelId(id: string): kendo.dataviz.diagram.Connection;
getConnectionByModelId(id: number): kendo.dataviz.diagram.Connection;
getConnectionByModelUid(uid: string): kendo.dataviz.diagram.Connection;
getShapeById(id: string): any;
getShapeByModelId(id: string): kendo.dataviz.diagram.Shape;
getShapeByModelId(id: number): kendo.dataviz.diagram.Shape;
getShapeByModelUid(uid: string): kendo.dataviz.diagram.Shape;
layerToModel(point: any): any;
layout(options: any): void;
load(json: string): void;
modelToDocument(point: any): any;
modelToLayer(point: any): any;
modelToView(point: any): any;
pan(pan: any): void;
paste(): void;
redo(): void;
remove(items: any, undoable: boolean): void;
resize(): void;
save(): void;
saveAsPdf(): JQueryPromise<any>;
saveEdit(): void;
select(): any;
select(elements: kendo.dataviz.diagram.Connection, options: any): void;
select(elements: kendo.dataviz.diagram.Shape, options: any): void;
select(elements: any, options: any): void;
selectAll(): void;
selectArea(rect: kendo.dataviz.diagram.Rect): void;
setConnectionsDataSource(dataSource: kendo.data.DataSource): void;
setDataSource(dataSource: kendo.data.DataSource): void;
toBack(items: any, undoable: boolean): void;
toFront(items: any, undoable: boolean): void;
transformPoint(p: any): void;
transformRect(r: any): void;
undo(): void;
viewToDocument(point: kendo.dataviz.diagram.Point): kendo.dataviz.diagram.Point;
viewToModel(point: kendo.dataviz.diagram.Point): kendo.dataviz.diagram.Point;
viewport(): kendo.dataviz.diagram.Rect;
zoom(): number;
zoom(zoom: number, point: kendo.dataviz.diagram.Point): void;
}
interface DiagramConnectionDefaultsContent {
color?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
fontWeight?: string;
template?: string|Function;
text?: string;
visual?: Function;
}
interface DiagramConnectionDefaultsEditableTool {
name?: string;
}
interface DiagramConnectionDefaultsEditable {
drag?: boolean;
remove?: boolean;
tools?: DiagramConnectionDefaultsEditableTool[];
}
interface DiagramConnectionDefaultsEndCapFill {
color?: string;
}
interface DiagramConnectionDefaultsEndCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramConnectionDefaultsEndCap {
fill?: string | DiagramConnectionDefaultsEndCapFill;
stroke?: string | DiagramConnectionDefaultsEndCapStroke;
type?: string;
}
interface DiagramConnectionDefaultsHoverStroke {
color?: string;
}
interface DiagramConnectionDefaultsHover {
stroke?: DiagramConnectionDefaultsHoverStroke;
}
interface DiagramConnectionDefaultsSelectionHandlesFill {
color?: string;
}
interface DiagramConnectionDefaultsSelectionHandlesStroke {
color?: string;
}
interface DiagramConnectionDefaultsSelectionHandles {
fill?: string | DiagramConnectionDefaultsSelectionHandlesFill;
stroke?: DiagramConnectionDefaultsSelectionHandlesStroke;
width?: number;
height?: number;
}
interface DiagramConnectionDefaultsSelection {
handles?: DiagramConnectionDefaultsSelectionHandles;
}
interface DiagramConnectionDefaultsStartCapFill {
color?: string;
}
interface DiagramConnectionDefaultsStartCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramConnectionDefaultsStartCap {
fill?: string | DiagramConnectionDefaultsStartCapFill;
stroke?: string | DiagramConnectionDefaultsStartCapStroke;
type?: string;
}
interface DiagramConnectionDefaultsStroke {
color?: string;
width?: number;
}
interface DiagramConnectionDefaults {
content?: DiagramConnectionDefaultsContent;
editable?: boolean | DiagramConnectionDefaultsEditable;
endCap?: string | DiagramConnectionDefaultsEndCap;
fromConnector?: string;
hover?: DiagramConnectionDefaultsHover;
selectable?: boolean;
selection?: DiagramConnectionDefaultsSelection;
startCap?: string | DiagramConnectionDefaultsStartCap;
stroke?: DiagramConnectionDefaultsStroke;
toConnector?: string;
type?: string;
}
interface DiagramConnectionContent {
color?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
fontWeight?: string;
template?: string|Function;
text?: string;
visual?: Function;
}
interface DiagramConnectionEditableTool {
name?: string;
}
interface DiagramConnectionEditable {
tools?: DiagramConnectionEditableTool[];
}
interface DiagramConnectionEndCapFill {
color?: string;
}
interface DiagramConnectionEndCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramConnectionEndCap {
fill?: string | DiagramConnectionEndCapFill;
stroke?: string | DiagramConnectionEndCapStroke;
type?: string;
}
interface DiagramConnectionFrom {
x?: number;
y?: number;
}
interface DiagramConnectionHoverStroke {
color?: string;
}
interface DiagramConnectionHover {
stroke?: DiagramConnectionHoverStroke;
}
interface DiagramConnectionPoint {
x?: number;
y?: number;
}
interface DiagramConnectionSelectionHandlesFill {
color?: string;
}
interface DiagramConnectionSelectionHandlesStroke {
color?: string;
}
interface DiagramConnectionSelectionHandles {
fill?: string | DiagramConnectionSelectionHandlesFill;
stroke?: DiagramConnectionSelectionHandlesStroke;
width?: number;
height?: number;
}
interface DiagramConnectionSelection {
handles?: DiagramConnectionSelectionHandles;
}
interface DiagramConnectionStartCapFill {
color?: string;
}
interface DiagramConnectionStartCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramConnectionStartCap {
fill?: string | DiagramConnectionStartCapFill;
stroke?: string | DiagramConnectionStartCapStroke;
type?: string;
}
interface DiagramConnectionStroke {
color?: string;
width?: number;
}
interface DiagramConnectionTo {
x?: number;
y?: number;
}
interface DiagramConnection {
content?: DiagramConnectionContent;
editable?: boolean | DiagramConnectionEditable;
endCap?: string | DiagramConnectionEndCap;
from?: string | DiagramConnectionFrom;
fromConnector?: string;
hover?: DiagramConnectionHover;
points?: DiagramConnectionPoint[];
selection?: DiagramConnectionSelection;
startCap?: string | DiagramConnectionStartCap;
stroke?: DiagramConnectionStroke;
to?: string | DiagramConnectionTo;
toConnector?: string;
type?: string;
}
interface DiagramEditableDragSnap {
size?: number;
}
interface DiagramEditableDrag {
snap?: boolean | DiagramEditableDragSnap;
}
interface DiagramEditableResizeHandlesFill {
color?: string;
opacity?: number;
}
interface DiagramEditableResizeHandlesHoverFill {
color?: string;
opacity?: number;
}
interface DiagramEditableResizeHandlesHoverStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramEditableResizeHandlesHover {
fill?: string | DiagramEditableResizeHandlesHoverFill;
stroke?: DiagramEditableResizeHandlesHoverStroke;
}
interface DiagramEditableResizeHandlesStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramEditableResizeHandles {
fill?: string | DiagramEditableResizeHandlesFill;
height?: number;
hover?: DiagramEditableResizeHandlesHover;
stroke?: DiagramEditableResizeHandlesStroke;
width?: number;
}
interface DiagramEditableResize {
handles?: DiagramEditableResizeHandles;
}
interface DiagramEditableRotateFill {
color?: string;
opacity?: number;
}
interface DiagramEditableRotateStroke {
color?: string;
width?: number;
}
interface DiagramEditableRotate {
fill?: DiagramEditableRotateFill;
stroke?: DiagramEditableRotateStroke;
}
interface DiagramEditableTool {
name?: string;
step?: number;
}
interface DiagramEditable {
connectionTemplate?: string|Function;
drag?: boolean | DiagramEditableDrag;
remove?: boolean;
resize?: boolean | DiagramEditableResize;
rotate?: boolean | DiagramEditableRotate;
shapeTemplate?: string|Function;
tools?: DiagramEditableTool[];
}
interface DiagramLayoutGrid {
componentSpacingX?: number;
componentSpacingY?: number;
offsetX?: number;
offsetY?: number;
width?: number;
}
interface DiagramLayout {
endRadialAngle?: number;
grid?: DiagramLayoutGrid;
horizontalSeparation?: number;
iterations?: number;
layerSeparation?: number;
nodeDistance?: number;
radialFirstLevelSeparation?: number;
radialSeparation?: number;
startRadialAngle?: number;
subtype?: string;
tipOverTreeStartLevel?: number;
type?: string;
underneathHorizontalOffset?: number;
underneathVerticalSeparation?: number;
underneathVerticalTopOffset?: number;
verticalSeparation?: number;
}
interface DiagramPannable {
key?: string;
}
interface DiagramPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface DiagramPdf {
author?: string;
creator?: string;
date?: Date;
fileName?: string;
forceProxy?: boolean;
keywords?: string;
landscape?: boolean;
margin?: DiagramPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface DiagramSelectableStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramSelectable {
key?: string;
multiple?: boolean;
stroke?: DiagramSelectableStroke;
}
interface DiagramShapeDefaultsConnectorDefaultsFill {
color?: string;
opacity?: number;
}
interface DiagramShapeDefaultsConnectorDefaultsHoverFill {
color?: string;
opacity?: number;
}
interface DiagramShapeDefaultsConnectorDefaultsHoverStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeDefaultsConnectorDefaultsHover {
fill?: string | DiagramShapeDefaultsConnectorDefaultsHoverFill;
stroke?: string | DiagramShapeDefaultsConnectorDefaultsHoverStroke;
}
interface DiagramShapeDefaultsConnectorDefaultsStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeDefaultsConnectorDefaults {
width?: number;
height?: number;
hover?: DiagramShapeDefaultsConnectorDefaultsHover;
fill?: string | DiagramShapeDefaultsConnectorDefaultsFill;
stroke?: string | DiagramShapeDefaultsConnectorDefaultsStroke;
}
interface DiagramShapeDefaultsConnectorFill {
color?: string;
opacity?: number;
}
interface DiagramShapeDefaultsConnectorHoverFill {
color?: string;
opacity?: number;
}
interface DiagramShapeDefaultsConnectorHoverStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeDefaultsConnectorHover {
fill?: string | DiagramShapeDefaultsConnectorHoverFill;
stroke?: string | DiagramShapeDefaultsConnectorHoverStroke;
}
interface DiagramShapeDefaultsConnectorStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeDefaultsConnector {
name?: string;
position?: Function;
width?: number;
height?: number;
hover?: DiagramShapeDefaultsConnectorHover;
fill?: string | DiagramShapeDefaultsConnectorFill;
stroke?: string | DiagramShapeDefaultsConnectorStroke;
}
interface DiagramShapeDefaultsContent {
align?: string;
color?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
fontWeight?: string;
template?: string|Function;
text?: string;
}
interface DiagramShapeDefaultsEditableTool {
name?: string;
step?: number;
}
interface DiagramShapeDefaultsEditable {
connect?: boolean;
drag?: boolean;
remove?: boolean;
tools?: DiagramShapeDefaultsEditableTool[];
}
interface DiagramShapeDefaultsFillGradientStop {
offset?: number;
color?: string;
opacity?: number;
}
interface DiagramShapeDefaultsFillGradient {
type?: string;
center?: any;
radius?: number;
start?: any;
end?: any;
stops?: DiagramShapeDefaultsFillGradientStop[];
}
interface DiagramShapeDefaultsFill {
color?: string;
opacity?: number;
gradient?: DiagramShapeDefaultsFillGradient;
}
interface DiagramShapeDefaultsHoverFill {
color?: string;
opacity?: number;
}
interface DiagramShapeDefaultsHover {
fill?: string | DiagramShapeDefaultsHoverFill;
}
interface DiagramShapeDefaultsRotation {
angle?: number;
}
interface DiagramShapeDefaultsStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeDefaults {
connectors?: DiagramShapeDefaultsConnector[];
connectorDefaults?: DiagramShapeDefaultsConnectorDefaults;
content?: DiagramShapeDefaultsContent;
editable?: boolean | DiagramShapeDefaultsEditable;
fill?: string | DiagramShapeDefaultsFill;
height?: number;
hover?: DiagramShapeDefaultsHover;
minHeight?: number;
minWidth?: number;
path?: string;
rotation?: DiagramShapeDefaultsRotation;
selectable?: boolean;
source?: string;
stroke?: DiagramShapeDefaultsStroke;
type?: string;
visual?: Function;
width?: number;
x?: number;
y?: number;
}
interface DiagramShapeConnectorDefaultsFill {
color?: string;
opacity?: number;
}
interface DiagramShapeConnectorDefaultsHoverFill {
color?: string;
opacity?: number;
}
interface DiagramShapeConnectorDefaultsHoverStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeConnectorDefaultsHover {
fill?: string | DiagramShapeConnectorDefaultsHoverFill;
stroke?: string | DiagramShapeConnectorDefaultsHoverStroke;
}
interface DiagramShapeConnectorDefaultsStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeConnectorDefaults {
width?: number;
height?: number;
hover?: DiagramShapeConnectorDefaultsHover;
fill?: string | DiagramShapeConnectorDefaultsFill;
stroke?: string | DiagramShapeConnectorDefaultsStroke;
}
interface DiagramShapeConnectorFill {
color?: string;
opacity?: number;
}
interface DiagramShapeConnectorHoverFill {
color?: string;
opacity?: number;
}
interface DiagramShapeConnectorHoverStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeConnectorHover {
fill?: string | DiagramShapeConnectorHoverFill;
stroke?: string | DiagramShapeConnectorHoverStroke;
}
interface DiagramShapeConnectorStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShapeConnector {
description?: string;
name?: string;
position?: Function;
width?: number;
height?: number;
hover?: DiagramShapeConnectorHover;
fill?: string | DiagramShapeConnectorFill;
stroke?: string | DiagramShapeConnectorStroke;
}
interface DiagramShapeContent {
align?: string;
color?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
fontWeight?: string;
template?: string|Function;
text?: string;
}
interface DiagramShapeEditableTool {
name?: string;
step?: number;
}
interface DiagramShapeEditable {
connect?: boolean;
tools?: DiagramShapeEditableTool[];
}
interface DiagramShapeFillGradientStop {
offset?: number;
color?: string;
opacity?: number;
}
interface DiagramShapeFillGradient {
type?: string;
center?: any;
radius?: number;
start?: any;
end?: any;
stops?: DiagramShapeFillGradientStop[];
}
interface DiagramShapeFill {
color?: string;
opacity?: number;
gradient?: DiagramShapeFillGradient;
}
interface DiagramShapeHoverFill {
color?: string;
opacity?: number;
}
interface DiagramShapeHover {
fill?: string | DiagramShapeHoverFill;
}
interface DiagramShapeRotation {
angle?: number;
}
interface DiagramShapeStroke {
color?: string;
dashType?: string;
width?: number;
}
interface DiagramShape {
connectors?: DiagramShapeConnector[];
connectorDefaults?: DiagramShapeConnectorDefaults;
content?: DiagramShapeContent;
editable?: boolean | DiagramShapeEditable;
fill?: string | DiagramShapeFill;
height?: number;
hover?: DiagramShapeHover;
id?: string;
minHeight?: number;
minWidth?: number;
path?: string;
rotation?: DiagramShapeRotation;
source?: string;
stroke?: DiagramShapeStroke;
type?: string;
visual?: Function;
width?: number;
x?: number;
y?: number;
}
interface DiagramExportImageOptions {
width?: string;
height?: string;
cors?: string;
}
interface DiagramExportSVGOptions {
raw?: boolean;
}
interface DiagramSelectOptions {
addToSelection?: boolean;
}
interface DiagramOptions {
name?: string;
autoBind?: boolean;
connectionDefaults?: DiagramConnectionDefaults;
connections?: DiagramConnection[];
connectionsDataSource?: any|any|kendo.data.DataSource;
dataSource?: any|any|kendo.data.DataSource;
editable?: boolean | DiagramEditable;
layout?: DiagramLayout;
pannable?: boolean | DiagramPannable;
pdf?: DiagramPdf;
selectable?: boolean | DiagramSelectable;
shapeDefaults?: DiagramShapeDefaults;
shapes?: DiagramShape[];
template?: string|Function;
theme?: string;
zoom?: number;
zoomMax?: number;
zoomMin?: number;
zoomRate?: number;
add?(e: DiagramAddEvent): void;
cancel?(e: DiagramCancelEvent): void;
change?(e: DiagramChangeEvent): void;
click?(e: DiagramClickEvent): void;
dataBound?(e: DiagramDataBoundEvent): void;
drag?(e: DiagramDragEvent): void;
dragEnd?(e: DiagramDragEndEvent): void;
dragStart?(e: DiagramDragStartEvent): void;
edit?(e: DiagramEditEvent): void;
itemBoundsChange?(e: DiagramItemBoundsChangeEvent): void;
itemRotate?(e: DiagramItemRotateEvent): void;
mouseEnter?(e: DiagramMouseEnterEvent): void;
mouseLeave?(e: DiagramMouseLeaveEvent): void;
pan?(e: DiagramPanEvent): void;
remove?(e: DiagramRemoveEvent): void;
save?(e: DiagramSaveEvent): void;
select?(e: DiagramSelectEvent): void;
toolBarClick?(e: DiagramToolBarClickEvent): void;
zoomEnd?(e: DiagramZoomEndEvent): void;
zoomStart?(e: DiagramZoomStartEvent): void;
}
interface DiagramEvent {
sender: Diagram;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DiagramAddEvent extends DiagramEvent {
connection?: kendo.dataviz.diagram.Connection;
shape?: kendo.dataviz.diagram.Shape;
}
interface DiagramCancelEvent extends DiagramEvent {
container?: JQuery;
connection?: kendo.data.Model;
shape?: kendo.data.Model;
}
interface DiagramChangeEvent extends DiagramEvent {
added?: any;
removed?: any;
}
interface DiagramClickEvent extends DiagramEvent {
item?: any;
meta?: any;
point?: kendo.dataviz.diagram.Point;
}
interface DiagramDataBoundEvent extends DiagramEvent {
}
interface DiagramDragEvent extends DiagramEvent {
connectionHandle?: string;
connections?: any;
shapes?: any;
}
interface DiagramDragEndEvent extends DiagramEvent {
connectionHandle?: string;
connections?: any;
shapes?: any;
}
interface DiagramDragStartEvent extends DiagramEvent {
connectionHandle?: string;
connections?: any;
shapes?: any;
}
interface DiagramEditEvent extends DiagramEvent {
container?: JQuery;
connection?: kendo.data.Model;
shape?: kendo.data.Model;
}
interface DiagramItemBoundsChangeEvent extends DiagramEvent {
bounds?: kendo.dataviz.diagram.Rect;
item?: kendo.dataviz.diagram.Shape;
}
interface DiagramItemRotateEvent extends DiagramEvent {
item?: kendo.dataviz.diagram.Shape;
}
interface DiagramMouseEnterEvent extends DiagramEvent {
item?: any;
}
interface DiagramMouseLeaveEvent extends DiagramEvent {
item?: any;
}
interface DiagramPanEvent extends DiagramEvent {
pan?: kendo.dataviz.diagram.Point;
}
interface DiagramRemoveEvent extends DiagramEvent {
connection?: kendo.dataviz.diagram.Connection;
shape?: kendo.dataviz.diagram.Shape;
}
interface DiagramSaveEvent extends DiagramEvent {
container?: JQuery;
connection?: kendo.data.Model;
shape?: kendo.data.Model;
}
interface DiagramSelectEvent extends DiagramEvent {
selected?: any;
deselected?: any;
}
interface DiagramToolBarClickEvent extends DiagramEvent {
action?: string;
shapes?: any;
connections?: any;
target?: JQuery;
}
interface DiagramZoomEndEvent extends DiagramEvent {
point?: kendo.dataviz.diagram.Point;
zoom?: number;
}
interface DiagramZoomStartEvent extends DiagramEvent {
point?: kendo.dataviz.diagram.Point;
zoom?: number;
}
class LinearGauge extends kendo.ui.Widget {
static fn: LinearGauge;
options: LinearGaugeOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): LinearGauge;
constructor(element: Element, options?: LinearGaugeOptions);
allValues(values: any): any;
destroy(): void;
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
redraw(): void;
resize(force?: boolean): void;
setOptions(options: any): void;
svg(): void;
imageDataURL(): string;
value(): void;
}
interface LinearGaugeGaugeAreaBorder {
color?: string;
dashType?: string;
width?: number;
}
interface LinearGaugeGaugeAreaMargin {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface LinearGaugeGaugeArea {
background?: string;
border?: LinearGaugeGaugeAreaBorder;
height?: number;
margin?: LinearGaugeGaugeAreaMargin;
width?: number;
}
interface LinearGaugePointerItemBorder {
color?: string;
dashType?: string;
width?: number;
}
interface LinearGaugePointerItemTrackBorder {
color?: string;
dashType?: string;
width?: number;
}
interface LinearGaugePointerItemTrack {
border?: LinearGaugePointerItemTrackBorder;
color?: string;
opacity?: number;
size?: number;
visible?: boolean;
}
interface LinearGaugePointerItem {
border?: LinearGaugePointerItemBorder;
color?: string;
margin?: number|any;
opacity?: number;
shape?: string;
size?: number;
track?: LinearGaugePointerItemTrack;
value?: number;
}
interface LinearGaugeScaleLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface LinearGaugeScaleLabelsMargin {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface LinearGaugeScaleLabelsPadding {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface LinearGaugeScaleLabels {
background?: string;
border?: LinearGaugeScaleLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: LinearGaugeScaleLabelsMargin;
padding?: LinearGaugeScaleLabelsPadding;
template?: string|Function;
visible?: boolean;
}
interface LinearGaugeScaleLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface LinearGaugeScaleMajorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
}
interface LinearGaugeScaleMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
}
interface LinearGaugeScaleRange {
from?: number;
to?: number;
opacity?: number;
color?: string;
}
interface LinearGaugeScale {
line?: LinearGaugeScaleLine;
labels?: LinearGaugeScaleLabels;
majorTicks?: LinearGaugeScaleMajorTicks;
majorUnit?: number;
max?: number;
min?: number;
minorTicks?: LinearGaugeScaleMinorTicks;
minorUnit?: number;
mirror?: boolean;
ranges?: LinearGaugeScaleRange[];
rangePlaceholderColor?: string;
rangeSize?: number;
reverse?: boolean;
vertical?: boolean;
}
interface LinearGaugeExportImageOptions {
width?: string;
height?: string;
}
interface LinearGaugeExportSVGOptions {
raw?: boolean;
}
interface LinearGaugeOptions {
name?: string;
gaugeArea?: LinearGaugeGaugeArea;
pointer?: LinearGaugePointerItem[];
renderAs?: string;
scale?: LinearGaugeScale;
theme?: string;
transitions?: boolean;
}
interface LinearGaugeEvent {
sender: LinearGauge;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Map extends kendo.ui.Widget {
static fn: Map;
options: MapOptions;
layers: any;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Map;
constructor(element: Element, options?: MapOptions);
center(): kendo.dataviz.map.Location;
center(center: any): void;
center(center: kendo.dataviz.map.Location): void;
destroy(): void;
eventOffset(e: any): kendo.geometry.Point;
eventOffset(e: JQueryEventObject): kendo.geometry.Point;
eventToLayer(e: any): kendo.geometry.Point;
eventToLayer(e: JQueryEventObject): kendo.geometry.Point;
eventToLocation(e: any): kendo.geometry.Point;
eventToLocation(e: JQueryEventObject): kendo.geometry.Point;
eventToView(e: any): kendo.geometry.Point;
eventToView(e: JQueryEventObject): kendo.geometry.Point;
extent(): kendo.dataviz.map.Extent;
extent(extent: kendo.dataviz.map.Extent): void;
layerToLocation(point: any, zoom: number): kendo.dataviz.map.Location;
layerToLocation(point: kendo.geometry.Point, zoom: number): kendo.dataviz.map.Location;
locationToLayer(location: any, zoom: number): kendo.geometry.Point;
locationToLayer(location: kendo.dataviz.map.Location, zoom: number): kendo.geometry.Point;
locationToView(location: any): kendo.geometry.Point;
locationToView(location: kendo.dataviz.map.Location): kendo.geometry.Point;
resize(force?: boolean): void;
setOptions(options: any): void;
viewSize(): any;
viewToLocation(point: any, zoom: number): kendo.dataviz.map.Location;
viewToLocation(point: kendo.geometry.Point, zoom: number): kendo.dataviz.map.Location;
zoom(): number;
zoom(level: number): void;
}
interface MapControlsAttribution {
position?: string;
}
interface MapControlsNavigator {
position?: string;
}
interface MapControlsZoom {
position?: string;
}
interface MapControls {
attribution?: boolean | MapControlsAttribution;
navigator?: boolean | MapControlsNavigator;
zoom?: boolean | MapControlsZoom;
}
interface MapLayerDefaultsBing {
attribution?: string;
opacity?: number;
key?: string;
imagerySet?: string;
culture?: string;
}
interface MapLayerDefaultsBubbleStyleFill {
color?: string;
opacity?: number;
}
interface MapLayerDefaultsBubbleStyleStroke {
color?: string;
dashType?: string;
opacity?: number;
width?: number;
}
interface MapLayerDefaultsBubbleStyle {
fill?: MapLayerDefaultsBubbleStyleFill;
stroke?: MapLayerDefaultsBubbleStyleStroke;
}
interface MapLayerDefaultsBubble {
attribution?: string;
opacity?: number;
maxSize?: number;
minSize?: number;
style?: MapLayerDefaultsBubbleStyle;
symbol?: string|Function;
}
interface MapLayerDefaultsMarkerTooltipAnimationClose {
effects?: string;
duration?: number;
}
interface MapLayerDefaultsMarkerTooltipAnimationOpen {
effects?: string;
duration?: number;
}
interface MapLayerDefaultsMarkerTooltipAnimation {
close?: MapLayerDefaultsMarkerTooltipAnimationClose;
open?: MapLayerDefaultsMarkerTooltipAnimationOpen;
}
interface MapLayerDefaultsMarkerTooltipContent {
url?: string;
}
interface MapLayerDefaultsMarkerTooltip {
autoHide?: boolean;
animation?: MapLayerDefaultsMarkerTooltipAnimation;
content?: string | Function | MapLayerDefaultsMarkerTooltipContent;
template?: string;
callout?: boolean;
iframe?: boolean;
height?: number;
width?: number;
position?: string;
showAfter?: number;
showOn?: string;
}
interface MapLayerDefaultsMarker {
shape?: string;
tooltip?: MapLayerDefaultsMarkerTooltip;
opacity?: number;
}
interface MapLayerDefaultsShapeStyleFill {
color?: string;
opacity?: number;
}
interface MapLayerDefaultsShapeStyleStroke {
color?: string;
dashType?: string;
opacity?: number;
width?: number;
}
interface MapLayerDefaultsShapeStyle {
fill?: MapLayerDefaultsShapeStyleFill;
stroke?: MapLayerDefaultsShapeStyleStroke;
}
interface MapLayerDefaultsShape {
attribution?: string;
opacity?: number;
style?: MapLayerDefaultsShapeStyle;
}
interface MapLayerDefaultsTile {
urlTemplate?: string;
attribution?: string;
subdomains?: any;
opacity?: number;
}
interface MapLayerDefaults {
marker?: MapLayerDefaultsMarker;
shape?: MapLayerDefaultsShape;
bubble?: MapLayerDefaultsBubble;
tileSize?: number;
tile?: MapLayerDefaultsTile;
bing?: MapLayerDefaultsBing;
}
interface MapLayerStyleFill {
color?: string;
opacity?: number;
}
interface MapLayerStyleStroke {
color?: string;
dashType?: number;
opacity?: number;
width?: number;
}
interface MapLayerStyle {
fill?: MapLayerStyleFill;
stroke?: MapLayerStyleStroke;
}
interface MapLayerTooltipAnimationClose {
effects?: string;
duration?: number;
}
interface MapLayerTooltipAnimationOpen {
effects?: string;
duration?: number;
}
interface MapLayerTooltipAnimation {
close?: MapLayerTooltipAnimationClose;
open?: MapLayerTooltipAnimationOpen;
}
interface MapLayerTooltipContent {
url?: string;
}
interface MapLayerTooltip {
autoHide?: boolean;
animation?: MapLayerTooltipAnimation;
content?: string | Function | MapLayerTooltipContent;
template?: string;
callout?: boolean;
iframe?: boolean;
height?: number;
width?: number;
position?: string;
showAfter?: number;
showOn?: string;
}
interface MapLayer {
attribution?: string;
autoBind?: boolean;
dataSource?: any|any|kendo.data.DataSource;
extent?: any|kendo.dataviz.map.Extent;
key?: string;
imagerySet?: string;
culture?: string;
locationField?: string;
shape?: string;
tileSize?: number;
titleField?: string;
tooltip?: MapLayerTooltip;
maxSize?: number;
minSize?: number;
maxZoom?: number;
minZoom?: number;
opacity?: number;
subdomains?: any;
symbol?: string|Function;
type?: string;
style?: MapLayerStyle;
urlTemplate?: string;
valueField?: string;
zIndex?: number;
}
interface MapMarkerDefaultsTooltipAnimationClose {
effects?: string;
duration?: number;
}
interface MapMarkerDefaultsTooltipAnimationOpen {
effects?: string;
duration?: number;
}
interface MapMarkerDefaultsTooltipAnimation {
close?: MapMarkerDefaultsTooltipAnimationClose;
open?: MapMarkerDefaultsTooltipAnimationOpen;
}
interface MapMarkerDefaultsTooltipContent {
url?: string;
}
interface MapMarkerDefaultsTooltip {
autoHide?: boolean;
animation?: MapMarkerDefaultsTooltipAnimation;
content?: string | Function | MapMarkerDefaultsTooltipContent;
template?: string;
callout?: boolean;
iframe?: boolean;
height?: number;
width?: number;
position?: string;
showAfter?: number;
showOn?: string;
}
interface MapMarkerDefaults {
shape?: string;
tooltip?: MapMarkerDefaultsTooltip;
}
interface MapMarkerTooltipAnimationClose {
effects?: string;
duration?: number;
}
interface MapMarkerTooltipAnimationOpen {
effects?: string;
duration?: number;
}
interface MapMarkerTooltipAnimation {
close?: MapMarkerTooltipAnimationClose;
open?: MapMarkerTooltipAnimationOpen;
}
interface MapMarkerTooltipContent {
url?: string;
}
interface MapMarkerTooltip {
autoHide?: boolean;
animation?: MapMarkerTooltipAnimation;
content?: string | Function | MapMarkerTooltipContent;
template?: string;
callout?: boolean;
iframe?: boolean;
height?: number;
width?: number;
position?: string;
showAfter?: number;
showOn?: string;
}
interface MapMarker {
location?: any|kendo.dataviz.map.Location;
shape?: string;
title?: string;
tooltip?: MapMarkerTooltip;
}
interface MapOptions {
name?: string;
center?: any|kendo.dataviz.map.Location;
controls?: MapControls;
layerDefaults?: MapLayerDefaults;
layers?: MapLayer[];
markerDefaults?: MapMarkerDefaults;
markers?: MapMarker[];
minZoom?: number;
maxZoom?: number;
minSize?: number;
pannable?: boolean;
wraparound?: boolean;
zoom?: number;
zoomable?: boolean;
beforeReset?(e: MapBeforeResetEvent): void;
click?(e: MapClickEvent): void;
markerActivate?(e: MapMarkerActivateEvent): void;
markerCreated?(e: MapMarkerCreatedEvent): void;
markerClick?(e: MapMarkerClickEvent): void;
pan?(e: MapPanEvent): void;
panEnd?(e: MapPanEndEvent): void;
reset?(e: MapResetEvent): void;
shapeClick?(e: MapShapeClickEvent): void;
shapeCreated?(e: MapShapeCreatedEvent): void;
shapeFeatureCreated?(e: MapShapeFeatureCreatedEvent): void;
shapeMouseEnter?(e: MapShapeMouseEnterEvent): void;
shapeMouseLeave?(e: MapShapeMouseLeaveEvent): void;
zoomStart?(e: MapZoomStartEvent): void;
zoomEnd?(e: MapZoomEndEvent): void;
}
interface MapEvent {
sender: Map;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface MapBeforeResetEvent extends MapEvent {
}
interface MapClickEvent extends MapEvent {
location?: kendo.dataviz.map.Location;
originalEvent?: any;
}
interface MapMarkerActivateEvent extends MapEvent {
marker?: kendo.dataviz.map.Marker;
layer?: kendo.dataviz.map.Marker;
}
interface MapMarkerCreatedEvent extends MapEvent {
marker?: kendo.dataviz.map.Marker;
layer?: kendo.dataviz.map.Marker;
}
interface MapMarkerClickEvent extends MapEvent {
marker?: kendo.dataviz.map.Marker;
layer?: kendo.dataviz.map.Marker;
}
interface MapPanEvent extends MapEvent {
origin?: kendo.dataviz.map.Location;
center?: kendo.dataviz.map.Location;
originalEvent?: any;
}
interface MapPanEndEvent extends MapEvent {
origin?: kendo.dataviz.map.Location;
center?: kendo.dataviz.map.Location;
originalEvent?: any;
}
interface MapResetEvent extends MapEvent {
}
interface MapShapeClickEvent extends MapEvent {
layer?: kendo.dataviz.map.layer.Shape;
shape?: kendo.drawing.Element;
originalEvent?: any;
}
interface MapShapeCreatedEvent extends MapEvent {
layer?: kendo.dataviz.map.layer.Shape;
shape?: kendo.drawing.Element;
originalEvent?: any;
}
interface MapShapeFeatureCreatedEvent extends MapEvent {
dataItem?: any;
layer?: kendo.dataviz.map.layer.Shape;
group?: kendo.drawing.Group;
properties?: any;
}
interface MapShapeMouseEnterEvent extends MapEvent {
layer?: kendo.dataviz.map.layer.Shape;
shape?: kendo.drawing.Element;
originalEvent?: any;
}
interface MapShapeMouseLeaveEvent extends MapEvent {
layer?: kendo.dataviz.map.layer.Shape;
shape?: kendo.drawing.Element;
originalEvent?: any;
}
interface MapZoomStartEvent extends MapEvent {
originalEvent?: any;
}
interface MapZoomEndEvent extends MapEvent {
originalEvent?: any;
}
class QRCode extends kendo.ui.Widget {
static fn: QRCode;
options: QRCodeOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): QRCode;
constructor(element: Element, options?: QRCodeOptions);
destroy(): void;
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
imageDataURL(): string;
redraw(): void;
resize(force?: boolean): void;
setOptions(options: any): void;
svg(): string;
value(options: string): void;
value(options: number): void;
}
interface QRCodeBorder {
color?: string;
width?: number;
}
interface QRCodeExportImageOptions {
width?: string;
height?: string;
}
interface QRCodeExportSVGOptions {
raw?: boolean;
}
interface QRCodeOptions {
name?: string;
background?: string;
border?: QRCodeBorder;
color?: string;
encoding?: string;
errorCorrection?: string;
padding?: number;
renderAs?: string;
size?: number|string;
value?: number|string;
}
interface QRCodeEvent {
sender: QRCode;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class RadialGauge extends kendo.ui.Widget {
static fn: RadialGauge;
options: RadialGaugeOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): RadialGauge;
constructor(element: Element, options?: RadialGaugeOptions);
allValues(values?: any): any;
destroy(): void;
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
redraw(): void;
resize(force?: boolean): void;
setOptions(options: any): void;
svg(): void;
imageDataURL(): string;
value(): void;
}
interface RadialGaugeGaugeAreaBorder {
color?: string;
dashType?: string;
opacity?: number;
width?: number;
}
interface RadialGaugeGaugeAreaMargin {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface RadialGaugeGaugeArea {
background?: string;
border?: RadialGaugeGaugeAreaBorder;
height?: number;
margin?: RadialGaugeGaugeAreaMargin;
width?: number;
}
interface RadialGaugePointerItemCap {
color?: string;
size?: number;
}
interface RadialGaugePointerItem {
cap?: RadialGaugePointerItemCap;
color?: string;
length?: number;
value?: number;
}
interface RadialGaugeScaleLabelsBorder {
color?: string;
dashType?: string;
opacity?: number;
width?: number;
}
interface RadialGaugeScaleLabelsMargin {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface RadialGaugeScaleLabelsPadding {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
interface RadialGaugeScaleLabels {
background?: string;
border?: RadialGaugeScaleLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: RadialGaugeScaleLabelsMargin;
padding?: RadialGaugeScaleLabelsPadding;
position?: string;
template?: string|Function;
visible?: boolean;
}
interface RadialGaugeScaleMajorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
}
interface RadialGaugeScaleMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
}
interface RadialGaugeScaleRange {
from?: number;
to?: number;
opacity?: number;
color?: string;
}
interface RadialGaugeScale {
endAngle?: number;
labels?: RadialGaugeScaleLabels;
majorTicks?: RadialGaugeScaleMajorTicks;
majorUnit?: number;
max?: number;
min?: number;
minorTicks?: RadialGaugeScaleMinorTicks;
minorUnit?: number;
ranges?: RadialGaugeScaleRange[];
rangePlaceholderColor?: string;
rangeSize?: number;
rangeDistance?: number;
reverse?: boolean;
startAngle?: number;
}
interface RadialGaugeExportImageOptions {
width?: string;
height?: string;
}
interface RadialGaugeExportSVGOptions {
raw?: boolean;
}
interface RadialGaugeOptions {
name?: string;
gaugeArea?: RadialGaugeGaugeArea;
pointer?: RadialGaugePointerItem[];
renderAs?: string;
scale?: RadialGaugeScale;
theme?: string;
transitions?: boolean;
}
interface RadialGaugeEvent {
sender: RadialGauge;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Sparkline extends kendo.ui.Widget {
static fn: Sparkline;
options: SparklineOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Sparkline;
constructor(element: Element, options?: SparklineOptions);
destroy(): void;
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
refresh(): void;
setDataSource(dataSource: kendo.data.DataSource): void;
setOptions(options: any): void;
svg(): string;
imageDataURL(): string;
}
interface SparklineCategoryAxisItemCrosshairTooltipBorder {
color?: string;
width?: number;
}
interface SparklineCategoryAxisItemCrosshairTooltip {
background?: string;
border?: SparklineCategoryAxisItemCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface SparklineCategoryAxisItemCrosshair {
color?: string;
width?: number;
opacity?: number;
dashType?: number;
visible?: boolean;
tooltip?: SparklineCategoryAxisItemCrosshairTooltip;
}
interface SparklineCategoryAxisItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineCategoryAxisItemLabels {
background?: string;
border?: SparklineCategoryAxisItemLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: number|any;
mirror?: boolean;
padding?: number|any;
rotation?: number;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
culture?: string;
dateFormats?: any;
}
interface SparklineCategoryAxisItemLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface SparklineCategoryAxisItemMajorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface SparklineCategoryAxisItemMajorTicks {
size?: number;
visible?: boolean;
color?: string;
width?: number;
step?: number;
skip?: number;
}
interface SparklineCategoryAxisItemMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface SparklineCategoryAxisItemMinorTicks {
size?: number;
visible?: boolean;
color?: string;
width?: number;
step?: number;
skip?: number;
}
interface SparklineCategoryAxisItemNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface SparklineCategoryAxisItemNotesDataItemIcon {
background?: string;
border?: SparklineCategoryAxisItemNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface SparklineCategoryAxisItemNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineCategoryAxisItemNotesDataItemLabel {
background?: string;
border?: SparklineCategoryAxisItemNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface SparklineCategoryAxisItemNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface SparklineCategoryAxisItemNotesDataItem {
value?: any;
position?: string;
icon?: SparklineCategoryAxisItemNotesDataItemIcon;
label?: SparklineCategoryAxisItemNotesDataItemLabel;
line?: SparklineCategoryAxisItemNotesDataItemLine;
}
interface SparklineCategoryAxisItemNotesIconBorder {
color?: string;
width?: number;
}
interface SparklineCategoryAxisItemNotesIcon {
background?: string;
border?: SparklineCategoryAxisItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface SparklineCategoryAxisItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineCategoryAxisItemNotesLabel {
background?: string;
border?: SparklineCategoryAxisItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface SparklineCategoryAxisItemNotesLine {
width?: number;
color?: string;
length?: number;
}
interface SparklineCategoryAxisItemNotes {
position?: string;
icon?: SparklineCategoryAxisItemNotesIcon;
label?: SparklineCategoryAxisItemNotesLabel;
line?: SparklineCategoryAxisItemNotesLine;
data?: SparklineCategoryAxisItemNotesDataItem[];
}
interface SparklineCategoryAxisItemPlotBand {
from?: number;
to?: number;
color?: string;
opacity?: number;
}
interface SparklineCategoryAxisItemTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineCategoryAxisItemTitle {
background?: string;
border?: SparklineCategoryAxisItemTitleBorder;
color?: string;
font?: string;
margin?: number|any;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
}
interface SparklineCategoryAxisItem {
axisCrossingValue?: any|Date|any;
categories?: any;
color?: string;
field?: string;
justified?: boolean;
labels?: SparklineCategoryAxisItemLabels;
line?: SparklineCategoryAxisItemLine;
majorGridLines?: SparklineCategoryAxisItemMajorGridLines;
majorTicks?: SparklineCategoryAxisItemMajorTicks;
minorGridLines?: SparklineCategoryAxisItemMinorGridLines;
minorTicks?: SparklineCategoryAxisItemMinorTicks;
name?: string;
plotBands?: SparklineCategoryAxisItemPlotBand[];
reverse?: boolean;
title?: SparklineCategoryAxisItemTitle;
type?: string;
autoBaseUnitSteps?: any;
baseUnit?: string;
baseUnitStep?: any;
max?: any;
min?: any;
roundToBaseUnit?: boolean;
weekStartDay?: number;
maxDateGroups?: number;
maxDivisions?: number;
visible?: boolean;
crosshair?: SparklineCategoryAxisItemCrosshair;
notes?: SparklineCategoryAxisItemNotes;
}
interface SparklineChartAreaBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineChartArea {
background?: string;
opacity?: number;
border?: SparklineChartAreaBorder;
height?: number;
margin?: number|any;
width?: number;
}
interface SparklinePlotAreaBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklinePlotArea {
background?: string;
opacity?: number;
border?: SparklinePlotAreaBorder;
margin?: number|any;
}
interface SparklineSeriesItemBorder {
color?: string|Function;
dashType?: string|Function;
opacity?: number|Function;
width?: number|Function;
}
interface SparklineSeriesItemConnectors {
color?: string;
padding?: number;
width?: number;
}
interface SparklineSeriesItemHighlightBorder {
width?: number;
color?: string;
opacity?: number;
}
interface SparklineSeriesItemHighlight {
border?: SparklineSeriesItemHighlightBorder;
color?: string;
opacity?: number;
visible?: boolean;
}
interface SparklineSeriesItemLabelsBorder {
color?: string|Function;
dashType?: string|Function;
width?: number|Function;
}
interface SparklineSeriesItemLabels {
align?: string;
background?: string|Function;
border?: SparklineSeriesItemLabelsBorder;
color?: string|Function;
distance?: number;
font?: string|Function;
format?: string|Function;
margin?: number|any;
padding?: number|any;
position?: string|Function;
template?: string|Function;
visible?: boolean|Function;
}
interface SparklineSeriesItemLine {
color?: string;
opacity?: number;
width?: string;
style?: string;
}
interface SparklineSeriesItemMarkersBorder {
color?: string|Function;
width?: number|Function;
}
interface SparklineSeriesItemMarkers {
background?: string|Function;
border?: Function | SparklineSeriesItemMarkersBorder;
size?: number|Function;
type?: string|Function;
visible?: boolean|Function;
rotation?: number|Function;
}
interface SparklineSeriesItemNotesIconBorder {
color?: string;
width?: number;
}
interface SparklineSeriesItemNotesIcon {
background?: string;
border?: SparklineSeriesItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface SparklineSeriesItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineSeriesItemNotesLabel {
background?: string;
border?: SparklineSeriesItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface SparklineSeriesItemNotesLine {
width?: number;
color?: string;
length?: number;
}
interface SparklineSeriesItemNotes {
position?: string;
icon?: SparklineSeriesItemNotesIcon;
label?: SparklineSeriesItemNotesLabel;
line?: SparklineSeriesItemNotesLine;
}
interface SparklineSeriesItemOverlay {
gradient?: string;
}
interface SparklineSeriesItemStack {
type?: string;
group?: string;
}
interface SparklineSeriesItemTargetBorder {
color?: string|Function;
dashType?: string|Function;
width?: number;
}
interface SparklineSeriesItemTargetLine {
width?: any|Function;
}
interface SparklineSeriesItemTarget {
line?: SparklineSeriesItemTargetLine;
color?: string|Function;
border?: Function | SparklineSeriesItemTargetBorder;
}
interface SparklineSeriesItemTooltipBorder {
color?: string;
width?: number;
}
interface SparklineSeriesItemTooltip {
background?: string;
border?: SparklineSeriesItemTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface SparklineSeriesItem {
type?: string;
dashType?: string;
data?: any;
explodeField?: string;
currentField?: string;
targetField?: string;
field?: string;
name?: string;
highlight?: SparklineSeriesItemHighlight;
aggregate?: string|Function;
axis?: string;
border?: SparklineSeriesItemBorder;
categoryField?: string;
color?: string|Function;
colorField?: string;
connectors?: SparklineSeriesItemConnectors;
gap?: number;
labels?: SparklineSeriesItemLabels;
line?: string | SparklineSeriesItemLine;
markers?: SparklineSeriesItemMarkers;
missingValues?: string;
style?: string;
negativeColor?: string;
opacity?: number;
overlay?: SparklineSeriesItemOverlay;
padding?: number;
size?: number;
startAngle?: number;
spacing?: number;
stack?: boolean | string | SparklineSeriesItemStack;
tooltip?: SparklineSeriesItemTooltip;
width?: number;
target?: SparklineSeriesItemTarget;
notes?: SparklineSeriesItemNotes;
zIndex?: number;
}
interface SparklineSeriesDefaultsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineSeriesDefaultsLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineSeriesDefaultsLabels {
background?: string;
border?: SparklineSeriesDefaultsLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: number|any;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface SparklineSeriesDefaultsStack {
type?: string;
}
interface SparklineSeriesDefaultsTooltipBorder {
color?: string;
width?: number;
}
interface SparklineSeriesDefaultsTooltip {
background?: string;
border?: SparklineSeriesDefaultsTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface SparklineSeriesDefaults {
area?: any;
bar?: any;
border?: SparklineSeriesDefaultsBorder;
column?: any;
gap?: number;
labels?: SparklineSeriesDefaultsLabels;
line?: any;
overlay?: any;
pie?: any;
spacing?: number;
stack?: boolean | SparklineSeriesDefaultsStack;
type?: string;
tooltip?: SparklineSeriesDefaultsTooltip;
}
interface SparklineTooltipBorder {
color?: string;
width?: number;
}
interface SparklineTooltip {
background?: string;
border?: SparklineTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
shared?: boolean;
sharedTemplate?: string;
}
interface SparklineValueAxisItemCrosshairTooltipBorder {
color?: string;
width?: number;
}
interface SparklineValueAxisItemCrosshairTooltip {
background?: string;
border?: SparklineValueAxisItemCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface SparklineValueAxisItemCrosshair {
color?: string;
width?: number;
opacity?: number;
dashType?: number;
visible?: boolean;
tooltip?: SparklineValueAxisItemCrosshairTooltip;
}
interface SparklineValueAxisItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineValueAxisItemLabels {
background?: string;
border?: SparklineValueAxisItemLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: number|any;
mirror?: boolean;
padding?: number|any;
rotation?: number;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
}
interface SparklineValueAxisItemLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface SparklineValueAxisItemMajorGridLines {
color?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface SparklineValueAxisItemMajorTicks {
size?: number;
visible?: boolean;
color?: string;
width?: number;
step?: number;
skip?: number;
}
interface SparklineValueAxisItemMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface SparklineValueAxisItemMinorTicks {
size?: number;
color?: string;
width?: number;
visible?: boolean;
step?: number;
skip?: number;
}
interface SparklineValueAxisItemNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface SparklineValueAxisItemNotesDataItemIcon {
background?: string;
border?: SparklineValueAxisItemNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface SparklineValueAxisItemNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineValueAxisItemNotesDataItemLabel {
background?: string;
border?: SparklineValueAxisItemNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface SparklineValueAxisItemNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface SparklineValueAxisItemNotesDataItem {
value?: any;
position?: string;
icon?: SparklineValueAxisItemNotesDataItemIcon;
label?: SparklineValueAxisItemNotesDataItemLabel;
line?: SparklineValueAxisItemNotesDataItemLine;
}
interface SparklineValueAxisItemNotesIconBorder {
color?: string;
width?: number;
}
interface SparklineValueAxisItemNotesIcon {
background?: string;
border?: SparklineValueAxisItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface SparklineValueAxisItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineValueAxisItemNotesLabel {
background?: string;
border?: SparklineValueAxisItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface SparklineValueAxisItemNotesLine {
width?: number;
color?: string;
length?: number;
}
interface SparklineValueAxisItemNotes {
position?: string;
icon?: SparklineValueAxisItemNotesIcon;
label?: SparklineValueAxisItemNotesLabel;
line?: SparklineValueAxisItemNotesLine;
data?: SparklineValueAxisItemNotesDataItem[];
}
interface SparklineValueAxisItemPlotBand {
from?: number;
to?: number;
color?: string;
opacity?: number;
}
interface SparklineValueAxisItemTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface SparklineValueAxisItemTitle {
background?: string;
border?: SparklineValueAxisItemTitleBorder;
color?: string;
font?: string;
margin?: number|any;
padding?: number|any;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
}
interface SparklineValueAxisItem {
axisCrossingValue?: any|Date|any;
color?: string;
labels?: SparklineValueAxisItemLabels;
line?: SparklineValueAxisItemLine;
majorGridLines?: SparklineValueAxisItemMajorGridLines;
majorTicks?: SparklineValueAxisItemMajorTicks;
majorUnit?: number;
max?: number;
min?: number;
minorGridLines?: SparklineValueAxisItemMinorGridLines;
minorTicks?: SparklineValueAxisItemMinorTicks;
minorUnit?: number;
name?: any;
narrowRange?: boolean;
plotBands?: SparklineValueAxisItemPlotBand[];
reverse?: boolean;
title?: SparklineValueAxisItemTitle;
visible?: boolean;
crosshair?: SparklineValueAxisItemCrosshair;
notes?: SparklineValueAxisItemNotes;
}
interface SparklineExportImageOptions {
width?: string;
height?: string;
}
interface SparklineExportSVGOptions {
raw?: boolean;
}
interface SparklineSeriesClickEventSeries {
type?: string;
name?: string;
data?: any;
}
interface SparklineSeriesHoverEventSeries {
type?: string;
name?: string;
data?: any;
}
interface SparklineSeriesOverEventSeries {
type?: string;
name?: string;
data?: any;
}
interface SparklineSeriesLeaveEventSeries {
type?: string;
name?: string;
data?: any;
}
interface SparklineOptions {
name?: string;
axisDefaults?: any;
categoryAxis?: SparklineCategoryAxisItem | SparklineCategoryAxisItem[];
chartArea?: SparklineChartArea;
data?: any;
dataSource?: any;
autoBind?: boolean;
plotArea?: SparklinePlotArea;
pointWidth?: number;
renderAs?: string;
series?: SparklineSeriesItem[];
seriesColors?: any;
seriesDefaults?: SparklineSeriesDefaults;
theme?: string;
tooltip?: SparklineTooltip;
transitions?: boolean;
type?: string;
valueAxis?: SparklineValueAxisItem | SparklineValueAxisItem[];
axisLabelClick?(e: SparklineAxisLabelClickEvent): void;
dataBound?(e: SparklineEvent): void;
dragStart?(e: SparklineDragStartEvent): void;
drag?(e: SparklineDragEvent): void;
dragEnd?(e: SparklineDragEndEvent): void;
paneRender?(e: SparklinePaneRenderEvent): void;
plotAreaClick?(e: SparklinePlotAreaClickEvent): void;
plotAreaHover?(e: SparklinePlotAreaHoverEvent): void;
plotAreaLeave?(e: SparklinePlotAreaLeaveEvent): void;
seriesClick?(e: SparklineSeriesClickEvent): void;
seriesHover?(e: SparklineSeriesHoverEvent): void;
seriesOver?(e: SparklineSeriesOverEvent): void;
seriesLeave?(e: SparklineSeriesLeaveEvent): void;
zoomStart?(e: SparklineZoomStartEvent): void;
zoom?(e: SparklineZoomEvent): void;
zoomEnd?(e: SparklineZoomEndEvent): void;
}
interface SparklineEvent {
sender: Sparkline;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SparklineAxisLabelClickEvent extends SparklineEvent {
axis?: any;
value?: any;
text?: any;
index?: any;
dataItem?: any;
element?: any;
}
interface SparklineDragStartEvent extends SparklineEvent {
axisRanges?: any;
originalEvent?: any;
}
interface SparklineDragEvent extends SparklineEvent {
axisRanges?: any;
originalEvent?: any;
}
interface SparklineDragEndEvent extends SparklineEvent {
axisRanges?: any;
originalEvent?: any;
}
interface SparklinePaneRenderEvent extends SparklineEvent {
pane?: kendo.dataviz.ChartPane;
name?: string;
index?: number;
}
interface SparklinePlotAreaClickEvent extends SparklineEvent {
value?: any;
category?: any;
element?: any;
x?: any;
y?: any;
}
interface SparklinePlotAreaHoverEvent extends SparklineEvent {
category?: any;
element?: any;
originalEvent?: any;
value?: any;
}
interface SparklinePlotAreaLeaveEvent extends SparklineEvent {
}
interface SparklineSeriesClickEvent extends SparklineEvent {
value?: any;
category?: any;
series?: SparklineSeriesClickEventSeries;
dataItem?: any;
element?: any;
percentage?: any;
}
interface SparklineSeriesHoverEvent extends SparklineEvent {
value?: any;
category?: any;
series?: SparklineSeriesHoverEventSeries;
dataItem?: any;
element?: any;
percentage?: any;
}
interface SparklineSeriesOverEvent extends SparklineEvent {
category?: any;
dataItem?: any;
element?: any;
originalEvent?: any;
percentage?: any;
series?: SparklineSeriesOverEventSeries;
stackValue?: any;
value?: any;
}
interface SparklineSeriesLeaveEvent extends SparklineEvent {
category?: any;
dataItem?: any;
element?: any;
originalEvent?: any;
percentage?: any;
series?: SparklineSeriesLeaveEventSeries;
stackValue?: any;
value?: any;
}
interface SparklineZoomStartEvent extends SparklineEvent {
axisRanges?: any;
originalEvent?: any;
}
interface SparklineZoomEvent extends SparklineEvent {
axisRanges?: any;
delta?: number;
originalEvent?: any;
}
interface SparklineZoomEndEvent extends SparklineEvent {
axisRanges?: any;
originalEvent?: any;
}
class StockChart extends kendo.ui.Widget {
static fn: StockChart;
options: StockChartOptions;
dataSource: kendo.data.DataSource;
navigator: kendo.dataviz.Navigator;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): StockChart;
constructor(element: Element, options?: StockChartOptions);
destroy(): void;
exportImage(options: any): JQueryPromise<any>;
exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise<any>;
exportSVG(options: any): JQueryPromise<any>;
redraw(): void;
refresh(): void;
resize(force?: boolean): void;
setDataSource(dataSource: kendo.data.DataSource): void;
setOptions(options: any): void;
svg(): string;
imageDataURL(): string;
}
interface StockChartCategoryAxisItemAutoBaseUnitSteps {
days?: any;
hours?: any;
minutes?: any;
months?: any;
weeks?: any;
years?: any;
}
interface StockChartCategoryAxisItemCrosshairTooltipBorder {
color?: string;
width?: number;
}
interface StockChartCategoryAxisItemCrosshairTooltip {
background?: string;
border?: StockChartCategoryAxisItemCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface StockChartCategoryAxisItemCrosshair {
color?: string;
width?: number;
opacity?: number;
dashType?: number;
visible?: boolean;
tooltip?: StockChartCategoryAxisItemCrosshairTooltip;
}
interface StockChartCategoryAxisItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartCategoryAxisItemLabels {
background?: string;
border?: StockChartCategoryAxisItemLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: number|any;
mirror?: boolean;
padding?: number|any;
rotation?: number;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
culture?: string;
dateFormats?: any;
}
interface StockChartCategoryAxisItemLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface StockChartCategoryAxisItemMajorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface StockChartCategoryAxisItemMajorTicks {
color?: string;
size?: number;
width?: number;
visible?: boolean;
step?: number;
skip?: number;
}
interface StockChartCategoryAxisItemMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface StockChartCategoryAxisItemMinorTicks {
size?: number;
visible?: boolean;
color?: string;
width?: number;
step?: number;
skip?: number;
}
interface StockChartCategoryAxisItemNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface StockChartCategoryAxisItemNotesDataItemIcon {
background?: string;
border?: StockChartCategoryAxisItemNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface StockChartCategoryAxisItemNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartCategoryAxisItemNotesDataItemLabel {
background?: string;
border?: StockChartCategoryAxisItemNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface StockChartCategoryAxisItemNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface StockChartCategoryAxisItemNotesDataItem {
value?: any;
position?: string;
icon?: StockChartCategoryAxisItemNotesDataItemIcon;
label?: StockChartCategoryAxisItemNotesDataItemLabel;
line?: StockChartCategoryAxisItemNotesDataItemLine;
}
interface StockChartCategoryAxisItemNotesIconBorder {
color?: string;
width?: number;
}
interface StockChartCategoryAxisItemNotesIcon {
background?: string;
border?: StockChartCategoryAxisItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface StockChartCategoryAxisItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartCategoryAxisItemNotesLabel {
background?: string;
border?: StockChartCategoryAxisItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface StockChartCategoryAxisItemNotesLine {
width?: number;
color?: string;
length?: number;
}
interface StockChartCategoryAxisItemNotes {
position?: string;
icon?: StockChartCategoryAxisItemNotesIcon;
label?: StockChartCategoryAxisItemNotesLabel;
line?: StockChartCategoryAxisItemNotesLine;
data?: StockChartCategoryAxisItemNotesDataItem[];
}
interface StockChartCategoryAxisItemPlotBand {
from?: number;
to?: number;
color?: string;
opacity?: number;
}
interface StockChartCategoryAxisItemSelectMousewheel {
reverse?: boolean;
zoom?: string;
}
interface StockChartCategoryAxisItemSelect {
from?: string|Date;
to?: string|Date;
min?: any;
max?: any;
mousewheel?: StockChartCategoryAxisItemSelectMousewheel;
}
interface StockChartCategoryAxisItemTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartCategoryAxisItemTitle {
background?: string;
border?: StockChartCategoryAxisItemTitleBorder;
color?: string;
font?: string;
margin?: number|any;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
}
interface StockChartCategoryAxisItem {
axisCrossingValue?: any|Date|any;
categories?: any;
color?: string;
field?: string;
justified?: boolean;
labels?: StockChartCategoryAxisItemLabels;
line?: StockChartCategoryAxisItemLine;
majorGridLines?: StockChartCategoryAxisItemMajorGridLines;
majorTicks?: StockChartCategoryAxisItemMajorTicks;
minorGridLines?: StockChartCategoryAxisItemMinorGridLines;
minorTicks?: StockChartCategoryAxisItemMinorTicks;
name?: string;
pane?: string;
plotBands?: StockChartCategoryAxisItemPlotBand[];
reverse?: boolean;
select?: StockChartCategoryAxisItemSelect;
title?: StockChartCategoryAxisItemTitle;
type?: string;
autoBaseUnitSteps?: StockChartCategoryAxisItemAutoBaseUnitSteps;
background?: string;
baseUnit?: string;
baseUnitStep?: any;
max?: any;
min?: any;
roundToBaseUnit?: boolean;
weekStartDay?: number;
maxDateGroups?: number;
maxDivisions?: number;
visible?: boolean;
crosshair?: StockChartCategoryAxisItemCrosshair;
notes?: StockChartCategoryAxisItemNotes;
}
interface StockChartChartAreaBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartChartArea {
background?: string;
opacity?: number;
border?: StockChartChartAreaBorder;
height?: number;
margin?: number|any;
width?: number;
}
interface StockChartLegendBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartLegendInactiveItemsLabels {
color?: string;
font?: string;
template?: string;
}
interface StockChartLegendInactiveItemsMarkers {
color?: string;
}
interface StockChartLegendInactiveItems {
labels?: StockChartLegendInactiveItemsLabels;
markers?: StockChartLegendInactiveItemsMarkers;
}
interface StockChartLegendItem {
cursor?: string;
visual?: Function;
}
interface StockChartLegendLabels {
color?: string;
font?: string;
template?: string;
}
interface StockChartLegend {
background?: string;
border?: StockChartLegendBorder;
item?: StockChartLegendItem;
labels?: StockChartLegendLabels;
margin?: number|any;
offsetX?: number;
offsetY?: number;
padding?: number|any;
position?: string;
reverse?: boolean;
visible?: boolean;
inactiveItems?: StockChartLegendInactiveItems;
}
interface StockChartNavigatorCategoryAxisAutoBaseUnitSteps {
seconds?: any;
minutes?: any;
hours?: any;
days?: any;
weeks?: any;
months?: any;
years?: any;
}
interface StockChartNavigatorCategoryAxisCrosshairTooltipBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorCategoryAxisCrosshairTooltipPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface StockChartNavigatorCategoryAxisCrosshairTooltip {
background?: string;
border?: StockChartNavigatorCategoryAxisCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: StockChartNavigatorCategoryAxisCrosshairTooltipPadding;
template?: string|Function;
visible?: boolean;
}
interface StockChartNavigatorCategoryAxisCrosshair {
color?: string;
opacity?: number;
tooltip?: StockChartNavigatorCategoryAxisCrosshairTooltip;
visible?: boolean;
width?: number;
}
interface StockChartNavigatorCategoryAxisLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorCategoryAxisLabelsDateFormats {
days?: string;
hours?: string;
months?: string;
weeks?: string;
years?: string;
}
interface StockChartNavigatorCategoryAxisLabelsMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface StockChartNavigatorCategoryAxisLabelsPadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface StockChartNavigatorCategoryAxisLabels {
background?: string;
border?: StockChartNavigatorCategoryAxisLabelsBorder;
color?: string;
culture?: string;
dateFormats?: StockChartNavigatorCategoryAxisLabelsDateFormats;
font?: string;
format?: string;
margin?: StockChartNavigatorCategoryAxisLabelsMargin;
mirror?: boolean;
padding?: StockChartNavigatorCategoryAxisLabelsPadding;
rotation?: number;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
}
interface StockChartNavigatorCategoryAxisLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface StockChartNavigatorCategoryAxisMajorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface StockChartNavigatorCategoryAxisMajorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface StockChartNavigatorCategoryAxisMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface StockChartNavigatorCategoryAxisMinorTicks {
color?: string;
size?: number;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface StockChartNavigatorCategoryAxisNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface StockChartNavigatorCategoryAxisNotesDataItemIcon {
background?: string;
border?: StockChartNavigatorCategoryAxisNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface StockChartNavigatorCategoryAxisNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorCategoryAxisNotesDataItemLabel {
background?: string;
border?: StockChartNavigatorCategoryAxisNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface StockChartNavigatorCategoryAxisNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface StockChartNavigatorCategoryAxisNotesDataItem {
value?: any;
position?: string;
icon?: StockChartNavigatorCategoryAxisNotesDataItemIcon;
label?: StockChartNavigatorCategoryAxisNotesDataItemLabel;
line?: StockChartNavigatorCategoryAxisNotesDataItemLine;
}
interface StockChartNavigatorCategoryAxisNotesIconBorder {
color?: string;
width?: number;
}
interface StockChartNavigatorCategoryAxisNotesIcon {
background?: string;
border?: StockChartNavigatorCategoryAxisNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface StockChartNavigatorCategoryAxisNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorCategoryAxisNotesLabel {
background?: string;
border?: StockChartNavigatorCategoryAxisNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface StockChartNavigatorCategoryAxisNotesLine {
width?: number;
color?: string;
length?: number;
}
interface StockChartNavigatorCategoryAxisNotes {
position?: string;
icon?: StockChartNavigatorCategoryAxisNotesIcon;
label?: StockChartNavigatorCategoryAxisNotesLabel;
line?: StockChartNavigatorCategoryAxisNotesLine;
data?: StockChartNavigatorCategoryAxisNotesDataItem[];
}
interface StockChartNavigatorCategoryAxisPlotBand {
color?: string;
from?: number;
opacity?: number;
to?: number;
}
interface StockChartNavigatorCategoryAxisTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorCategoryAxisTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface StockChartNavigatorCategoryAxisTitlePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface StockChartNavigatorCategoryAxisTitle {
background?: string;
border?: StockChartNavigatorCategoryAxisTitleBorder;
color?: string;
font?: string;
margin?: StockChartNavigatorCategoryAxisTitleMargin;
padding?: StockChartNavigatorCategoryAxisTitlePadding;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
}
interface StockChartNavigatorCategoryAxis {
autoBaseUnitSteps?: StockChartNavigatorCategoryAxisAutoBaseUnitSteps;
axisCrossingValue?: any|Date|any;
background?: string;
baseUnit?: string;
baseUnitStep?: any;
categories?: any;
color?: string;
crosshair?: StockChartNavigatorCategoryAxisCrosshair;
field?: string;
justified?: boolean;
labels?: StockChartNavigatorCategoryAxisLabels;
line?: StockChartNavigatorCategoryAxisLine;
majorGridLines?: StockChartNavigatorCategoryAxisMajorGridLines;
majorTicks?: StockChartNavigatorCategoryAxisMajorTicks;
max?: any;
maxDateGroups?: number;
min?: any;
minorGridLines?: StockChartNavigatorCategoryAxisMinorGridLines;
minorTicks?: StockChartNavigatorCategoryAxisMinorTicks;
plotBands?: StockChartNavigatorCategoryAxisPlotBand[];
reverse?: boolean;
roundToBaseUnit?: boolean;
title?: StockChartNavigatorCategoryAxisTitle;
visible?: boolean;
weekStartDay?: number;
notes?: StockChartNavigatorCategoryAxisNotes;
}
interface StockChartNavigatorHint {
visible?: boolean;
template?: string|Function;
format?: string;
}
interface StockChartNavigatorPaneBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorPaneMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface StockChartNavigatorPanePadding {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface StockChartNavigatorPaneTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorPaneTitleMargin {
bottom?: number;
left?: number;
right?: number;
top?: number;
}
interface StockChartNavigatorPaneTitle {
background?: string;
border?: StockChartNavigatorPaneTitleBorder;
color?: string;
font?: string;
margin?: StockChartNavigatorPaneTitleMargin;
position?: string;
text?: string;
visible?: boolean;
}
interface StockChartNavigatorPane {
background?: string;
border?: StockChartNavigatorPaneBorder;
height?: number;
margin?: StockChartNavigatorPaneMargin;
name?: string;
padding?: StockChartNavigatorPanePadding;
title?: string | StockChartNavigatorPaneTitle;
}
interface StockChartNavigatorSelectMousewheel {
reverse?: boolean;
zoom?: string;
}
interface StockChartNavigatorSelect {
from?: Date;
mousewheel?: boolean | StockChartNavigatorSelectMousewheel;
to?: Date;
}
interface StockChartNavigatorSeriesItemBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorSeriesItemHighlightBorder {
width?: number;
color?: string;
opacity?: number;
}
interface StockChartNavigatorSeriesItemHighlightLine {
width?: number;
color?: string;
opacity?: number;
}
interface StockChartNavigatorSeriesItemHighlight {
border?: StockChartNavigatorSeriesItemHighlightBorder;
color?: string;
line?: StockChartNavigatorSeriesItemHighlightLine;
opacity?: number;
visible?: boolean;
}
interface StockChartNavigatorSeriesItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartNavigatorSeriesItemLabels {
background?: string;
border?: StockChartNavigatorSeriesItemLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: number|any;
padding?: number|any;
position?: string;
template?: string|Function;
visible?: boolean;
}
interface StockChartNavigatorSeriesItemLine {
color?: string;
opacity?: number;
width?: string;
}
interface StockChartNavigatorSeriesItemMarkersBorder {
color?: string;
width?: number;
}
interface StockChartNavigatorSeriesItemMarkers {
background?: string;
border?: StockChartNavigatorSeriesItemMarkersBorder;
rotation?: number|Function;
size?: number;
type?: string;
visible?: boolean;
}
interface StockChartNavigatorSeriesItemOverlay {
gradient?: string;
}
interface StockChartNavigatorSeriesItemStack {
type?: string;
group?: string;
}
interface StockChartNavigatorSeriesItemTooltipBorder {
color?: string;
width?: number;
}
interface StockChartNavigatorSeriesItemTooltip {
background?: string;
border?: StockChartNavigatorSeriesItemTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface StockChartNavigatorSeriesItem {
type?: string;
dashType?: string;
data?: any;
highField?: string;
field?: string;
categoryField?: string;
name?: string;
highlight?: StockChartNavigatorSeriesItemHighlight;
aggregate?: string|Function;
axis?: string;
border?: StockChartNavigatorSeriesItemBorder;
closeField?: string;
color?: string;
colorField?: string;
downColor?: string;
downColorField?: string;
gap?: number;
labels?: StockChartNavigatorSeriesItemLabels;
line?: string | StockChartNavigatorSeriesItemLine;
lowField?: string;
markers?: StockChartNavigatorSeriesItemMarkers;
missingValues?: string;
style?: string;
opacity?: number;
openField?: string;
overlay?: StockChartNavigatorSeriesItemOverlay;
spacing?: number;
stack?: boolean | string | StockChartNavigatorSeriesItemStack;
tooltip?: StockChartNavigatorSeriesItemTooltip;
width?: number;
}
interface StockChartNavigator {
categoryAxis?: StockChartNavigatorCategoryAxis;
dataSource?: any;
autoBind?: boolean;
dateField?: string;
pane?: StockChartNavigatorPane;
series?: StockChartNavigatorSeriesItem[];
select?: StockChartNavigatorSelect;
hint?: StockChartNavigatorHint;
visible?: boolean;
}
interface StockChartPaneBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartPaneTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartPaneTitle {
background?: string;
border?: StockChartPaneTitleBorder;
color?: string;
font?: string;
margin?: number|any;
position?: string;
text?: string;
visible?: boolean;
}
interface StockChartPane {
name?: string;
margin?: number|any;
padding?: number|any;
background?: string;
border?: StockChartPaneBorder;
clip?: boolean;
height?: number;
title?: string | StockChartPaneTitle;
}
interface StockChartPdfMargin {
bottom?: number|string;
left?: number|string;
right?: number|string;
top?: number|string;
}
interface StockChartPdf {
author?: string;
creator?: string;
date?: Date;
forceProxy?: boolean;
fileName?: string;
keywords?: string;
landscape?: boolean;
margin?: StockChartPdfMargin;
paperSize?: string|any;
proxyURL?: string;
proxyTarget?: string;
subject?: string;
title?: string;
}
interface StockChartPlotAreaBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartPlotArea {
background?: string;
opacity?: number;
border?: StockChartPlotAreaBorder;
margin?: number|any;
}
interface StockChartSeriesItemBorder {
color?: string|Function;
dashType?: string|Function;
opacity?: number|Function;
width?: number|Function;
}
interface StockChartSeriesItemHighlightBorder {
width?: number;
color?: string;
opacity?: number;
}
interface StockChartSeriesItemHighlightLine {
width?: number;
color?: string;
opacity?: number;
}
interface StockChartSeriesItemHighlight {
visible?: boolean;
border?: StockChartSeriesItemHighlightBorder;
color?: string;
line?: StockChartSeriesItemHighlightLine;
opacity?: number;
}
interface StockChartSeriesItemLabelsBorder {
color?: string|Function;
dashType?: string|Function;
width?: number|Function;
}
interface StockChartSeriesItemLabels {
background?: string|Function;
border?: StockChartSeriesItemLabelsBorder;
color?: string|Function;
font?: string|Function;
format?: string|Function;
margin?: number|any;
padding?: number|any;
position?: string|Function;
template?: string|Function;
visible?: boolean|Function;
}
interface StockChartSeriesItemLine {
color?: string;
opacity?: number;
width?: string;
style?: string;
}
interface StockChartSeriesItemMarkersBorder {
color?: string|Function;
width?: number|Function;
}
interface StockChartSeriesItemMarkers {
background?: string|Function;
border?: Function | StockChartSeriesItemMarkersBorder;
size?: number|Function;
rotation?: number|Function;
type?: string|Function;
visible?: boolean|Function;
}
interface StockChartSeriesItemNotesIconBorder {
color?: string;
width?: number;
}
interface StockChartSeriesItemNotesIcon {
background?: string;
border?: StockChartSeriesItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface StockChartSeriesItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartSeriesItemNotesLabel {
background?: string;
border?: StockChartSeriesItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface StockChartSeriesItemNotesLine {
width?: number;
color?: string;
length?: number;
}
interface StockChartSeriesItemNotes {
position?: string;
icon?: StockChartSeriesItemNotesIcon;
label?: StockChartSeriesItemNotesLabel;
line?: StockChartSeriesItemNotesLine;
}
interface StockChartSeriesItemOverlay {
gradient?: string;
}
interface StockChartSeriesItemStack {
type?: string;
group?: string;
}
interface StockChartSeriesItemTargetBorder {
color?: string|Function;
dashType?: string|Function;
width?: number|Function;
}
interface StockChartSeriesItemTargetLine {
width?: any|Function;
}
interface StockChartSeriesItemTarget {
line?: StockChartSeriesItemTargetLine;
color?: string|Function;
border?: Function | StockChartSeriesItemTargetBorder;
}
interface StockChartSeriesItemTooltipBorder {
color?: string;
width?: number;
}
interface StockChartSeriesItemTooltip {
background?: string;
border?: StockChartSeriesItemTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface StockChartSeriesItem {
type?: string;
dashType?: string;
data?: any;
highField?: string;
field?: string;
categoryField?: string;
currentField?: string;
targetField?: string;
name?: string;
highlight?: StockChartSeriesItemHighlight;
aggregate?: string|Function;
axis?: string;
border?: StockChartSeriesItemBorder;
closeField?: string;
color?: string|Function;
colorField?: string;
downColor?: string|Function;
downColorField?: string;
gap?: number;
labels?: StockChartSeriesItemLabels;
line?: string | StockChartSeriesItemLine;
lowField?: string;
markers?: StockChartSeriesItemMarkers;
missingValues?: string;
style?: string;
negativeColor?: string;
opacity?: number;
openField?: string;
overlay?: StockChartSeriesItemOverlay;
spacing?: number;
stack?: boolean | string | StockChartSeriesItemStack;
tooltip?: StockChartSeriesItemTooltip;
visibleInLegend?: boolean;
width?: number;
target?: StockChartSeriesItemTarget;
notes?: StockChartSeriesItemNotes;
zIndex?: number;
}
interface StockChartSeriesDefaultsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartSeriesDefaultsLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartSeriesDefaultsLabels {
background?: string;
border?: StockChartSeriesDefaultsLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: number|any;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface StockChartSeriesDefaultsStack {
type?: string;
}
interface StockChartSeriesDefaultsTooltipBorder {
color?: string;
width?: number;
}
interface StockChartSeriesDefaultsTooltip {
background?: string;
border?: StockChartSeriesDefaultsTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface StockChartSeriesDefaults {
area?: any;
candlestick?: any;
ohlc?: any;
border?: StockChartSeriesDefaultsBorder;
column?: any;
gap?: number;
labels?: StockChartSeriesDefaultsLabels;
line?: any;
overlay?: any;
pie?: any;
spacing?: number;
stack?: boolean | StockChartSeriesDefaultsStack;
type?: string;
tooltip?: StockChartSeriesDefaultsTooltip;
}
interface StockChartTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartTitle {
align?: string;
background?: string;
border?: StockChartTitleBorder;
font?: string;
color?: string;
margin?: number|any;
padding?: number|any;
position?: string;
text?: string;
visible?: boolean;
}
interface StockChartTooltipBorder {
color?: string;
width?: number;
}
interface StockChartTooltip {
background?: string;
border?: StockChartTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
shared?: boolean;
sharedTemplate?: string;
}
interface StockChartValueAxisItemCrosshairTooltipBorder {
color?: string;
width?: number;
}
interface StockChartValueAxisItemCrosshairTooltip {
background?: string;
border?: StockChartValueAxisItemCrosshairTooltipBorder;
color?: string;
font?: string;
format?: string;
padding?: number|any;
template?: string|Function;
visible?: boolean;
}
interface StockChartValueAxisItemCrosshair {
color?: string;
width?: number;
opacity?: number;
dashType?: number;
visible?: boolean;
tooltip?: StockChartValueAxisItemCrosshairTooltip;
}
interface StockChartValueAxisItemLabelsBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartValueAxisItemLabels {
background?: string;
border?: StockChartValueAxisItemLabelsBorder;
color?: string;
font?: string;
format?: string;
margin?: number|any;
mirror?: boolean;
padding?: number|any;
rotation?: number;
skip?: number;
step?: number;
template?: string|Function;
visible?: boolean;
}
interface StockChartValueAxisItemLine {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
}
interface StockChartValueAxisItemMajorGridLines {
color?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface StockChartValueAxisItemMajorTicks {
size?: number;
visible?: boolean;
color?: string;
width?: number;
step?: number;
skip?: number;
}
interface StockChartValueAxisItemMinorGridLines {
color?: string;
dashType?: string;
visible?: boolean;
width?: number;
step?: number;
skip?: number;
}
interface StockChartValueAxisItemMinorTicks {
size?: number;
color?: string;
width?: number;
visible?: boolean;
step?: number;
skip?: number;
}
interface StockChartValueAxisItemNotesDataItemIconBorder {
color?: string;
width?: number;
}
interface StockChartValueAxisItemNotesDataItemIcon {
background?: string;
border?: StockChartValueAxisItemNotesDataItemIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface StockChartValueAxisItemNotesDataItemLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartValueAxisItemNotesDataItemLabel {
background?: string;
border?: StockChartValueAxisItemNotesDataItemLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
text?: string;
position?: string;
}
interface StockChartValueAxisItemNotesDataItemLine {
width?: number;
color?: string;
length?: number;
}
interface StockChartValueAxisItemNotesDataItem {
value?: any;
position?: string;
icon?: StockChartValueAxisItemNotesDataItemIcon;
label?: StockChartValueAxisItemNotesDataItemLabel;
line?: StockChartValueAxisItemNotesDataItemLine;
}
interface StockChartValueAxisItemNotesIconBorder {
color?: string;
width?: number;
}
interface StockChartValueAxisItemNotesIcon {
background?: string;
border?: StockChartValueAxisItemNotesIconBorder;
size?: number;
type?: string;
visible?: boolean;
}
interface StockChartValueAxisItemNotesLabelBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartValueAxisItemNotesLabel {
background?: string;
border?: StockChartValueAxisItemNotesLabelBorder;
color?: string;
font?: string;
template?: string|Function;
visible?: boolean;
rotation?: number;
format?: string;
position?: string;
}
interface StockChartValueAxisItemNotesLine {
width?: number;
color?: string;
length?: number;
}
interface StockChartValueAxisItemNotes {
position?: string;
icon?: StockChartValueAxisItemNotesIcon;
label?: StockChartValueAxisItemNotesLabel;
line?: StockChartValueAxisItemNotesLine;
data?: StockChartValueAxisItemNotesDataItem[];
}
interface StockChartValueAxisItemPlotBand {
from?: number;
to?: number;
color?: string;
opacity?: number;
}
interface StockChartValueAxisItemTitleBorder {
color?: string;
dashType?: string;
width?: number;
}
interface StockChartValueAxisItemTitle {
background?: string;
border?: StockChartValueAxisItemTitleBorder;
color?: string;
font?: string;
margin?: number|any;
padding?: number|any;
position?: string;
rotation?: number;
text?: string;
visible?: boolean;
}
interface StockChartValueAxisItem {
axisCrossingValue?: any|Date|any;
background?: string;
color?: string;
labels?: StockChartValueAxisItemLabels;
line?: StockChartValueAxisItemLine;
majorGridLines?: StockChartValueAxisItemMajorGridLines;
majorTicks?: StockChartValueAxisItemMajorTicks;
majorUnit?: number;
max?: number;
min?: number;
minorGridLines?: StockChartValueAxisItemMinorGridLines;
minorTicks?: StockChartValueAxisItemMinorTicks;
minorUnit?: number;
name?: any;
narrowRange?: boolean;
pane?: string;
plotBands?: StockChartValueAxisItemPlotBand[];
reverse?: boolean;
title?: StockChartValueAxisItemTitle;
visible?: boolean;
crosshair?: StockChartValueAxisItemCrosshair;
notes?: StockChartValueAxisItemNotes;
}
interface StockChartExportImageOptions {
width?: string;
height?: string;
}
interface StockChartExportSVGOptions {
raw?: boolean;
}
interface StockChartSeriesClickEventSeries {
type?: string;
name?: string;
data?: any;
}
interface StockChartSeriesHoverEventSeries {
type?: string;
name?: string;
data?: any;
}
interface StockChartSeriesOverEventSeries {
type?: string;
name?: string;
data?: any;
}
interface StockChartSeriesLeaveEventSeries {
type?: string;
name?: string;
data?: any;
}
interface StockChartOptions {
name?: string;
dateField?: string;
navigator?: StockChartNavigator;
axisDefaults?: any;
categoryAxis?: StockChartCategoryAxisItem | StockChartCategoryAxisItem[];
chartArea?: StockChartChartArea;
dataSource?: any;
autoBind?: boolean;
legend?: StockChartLegend;
panes?: StockChartPane[];
pdf?: StockChartPdf;
persistSeriesVisibility?: boolean;
plotArea?: StockChartPlotArea;
renderAs?: string;
series?: StockChartSeriesItem[];
seriesColors?: any;
seriesDefaults?: StockChartSeriesDefaults;
theme?: string;
title?: StockChartTitle;
tooltip?: StockChartTooltip;
transitions?: boolean;
valueAxis?: StockChartValueAxisItem | StockChartValueAxisItem[];
axisLabelClick?(e: StockChartAxisLabelClickEvent): void;
dataBound?(e: StockChartEvent): void;
dragStart?(e: StockChartDragStartEvent): void;
drag?(e: StockChartDragEvent): void;
dragEnd?(e: StockChartDragEndEvent): void;
legendItemClick?(e: StockChartLegendItemClickEvent): void;
legendItemHover?(e: StockChartLegendItemHoverEvent): void;
legendItemLeave?(e: StockChartLegendItemLeaveEvent): void;
noteClick?(e: StockChartNoteClickEvent): void;
noteHover?(e: StockChartNoteHoverEvent): void;
noteLeave?(e: StockChartNoteLeaveEvent): void;
paneRender?(e: StockChartPaneRenderEvent): void;
plotAreaClick?(e: StockChartPlotAreaClickEvent): void;
plotAreaHover?(e: StockChartPlotAreaHoverEvent): void;
plotAreaLeave?(e: StockChartPlotAreaLeaveEvent): void;
render?(e: StockChartRenderEvent): void;
select?(e: StockChartSelectEvent): void;
selectEnd?(e: StockChartSelectEndEvent): void;
selectStart?(e: StockChartSelectStartEvent): void;
seriesClick?(e: StockChartSeriesClickEvent): void;
seriesHover?(e: StockChartSeriesHoverEvent): void;
seriesOver?(e: StockChartSeriesOverEvent): void;
seriesLeave?(e: StockChartSeriesLeaveEvent): void;
zoomStart?(e: StockChartZoomStartEvent): void;
zoom?(e: StockChartZoomEvent): void;
zoomEnd?(e: StockChartZoomEndEvent): void;
}
interface StockChartEvent {
sender: StockChart;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface StockChartAxisLabelClickEvent extends StockChartEvent {
axis?: any;
value?: any;
text?: any;
index?: any;
dataItem?: any;
element?: any;
}
interface StockChartDragStartEvent extends StockChartEvent {
axisRanges?: any;
originalEvent?: any;
}
interface StockChartDragEvent extends StockChartEvent {
axisRanges?: any;
originalEvent?: any;
}
interface StockChartDragEndEvent extends StockChartEvent {
axisRanges?: any;
originalEvent?: any;
}
interface StockChartLegendItemClickEvent extends StockChartEvent {
text?: string;
series?: any;
seriesIndex?: number;
pointIndex?: number;
element?: any;
}
interface StockChartLegendItemHoverEvent extends StockChartEvent {
text?: string;
series?: any;
seriesIndex?: number;
pointIndex?: number;
element?: any;
}
interface StockChartLegendItemLeaveEvent extends StockChartEvent {
element?: any;
pointIndex?: number;
series?: any;
seriesIndex?: number;
text?: string;
}
interface StockChartNoteClickEvent extends StockChartEvent {
category?: any;
element?: any;
value?: any;
series?: any;
dataItem?: any;
}
interface StockChartNoteHoverEvent extends StockChartEvent {
category?: any;
element?: any;
value?: any;
series?: any;
dataItem?: any;
}
interface StockChartNoteLeaveEvent extends StockChartEvent {
category?: any;
dataItem?: any;
element?: any;
series?: any;
value?: any;
visual?: any;
}
interface StockChartPaneRenderEvent extends StockChartEvent {
pane?: kendo.dataviz.ui.StockChart;
name?: string;
index?: number;
}
interface StockChartPlotAreaClickEvent extends StockChartEvent {
value?: any;
category?: any;
element?: any;
x?: any;
y?: any;
}
interface StockChartPlotAreaHoverEvent extends StockChartEvent {
category?: any;
element?: any;
originalEvent?: any;
value?: any;
x?: any;
y?: any;
}
interface StockChartPlotAreaLeaveEvent extends StockChartEvent {
}
interface StockChartRenderEvent extends StockChartEvent {
}
interface StockChartSelectEvent extends StockChartEvent {
axis?: any;
from?: Date;
to?: Date;
}
interface StockChartSelectEndEvent extends StockChartEvent {
axis?: any;
from?: Date;
to?: Date;
}
interface StockChartSelectStartEvent extends StockChartEvent {
axis?: any;
from?: Date;
to?: Date;
}
interface StockChartSeriesClickEvent extends StockChartEvent {
value?: any;
category?: any;
series?: StockChartSeriesClickEventSeries;
dataItem?: any;
element?: any;
percentage?: any;
}
interface StockChartSeriesHoverEvent extends StockChartEvent {
value?: any;
category?: any;
series?: StockChartSeriesHoverEventSeries;
dataItem?: any;
element?: any;
percentage?: any;
}
interface StockChartSeriesOverEvent extends StockChartEvent {
category?: any;
dataItem?: any;
element?: any;
originalEvent?: any;
percentage?: any;
series?: StockChartSeriesOverEventSeries;
stackValue?: any;
value?: any;
}
interface StockChartSeriesLeaveEvent extends StockChartEvent {
category?: any;
dataItem?: any;
element?: any;
originalEvent?: any;
percentage?: any;
series?: StockChartSeriesLeaveEventSeries;
stackValue?: any;
value?: any;
}
interface StockChartZoomStartEvent extends StockChartEvent {
axisRanges?: any;
originalEvent?: any;
}
interface StockChartZoomEvent extends StockChartEvent {
axisRanges?: any;
delta?: number;
originalEvent?: any;
}
interface StockChartZoomEndEvent extends StockChartEvent {
axisRanges?: any;
originalEvent?: any;
}
class TreeMap extends kendo.ui.Widget {
static fn: TreeMap;
options: TreeMapOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): TreeMap;
constructor(element: Element, options?: TreeMapOptions);
}
interface TreeMapOptions {
name?: string;
dataSource?: any|any|kendo.data.HierarchicalDataSource;
autoBind?: boolean;
type?: string;
theme?: string;
valueField?: string;
colorField?: string;
textField?: string;
template?: string|Function;
colors?: any;
itemCreated?(e: TreeMapItemCreatedEvent): void;
dataBound?(e: TreeMapDataBoundEvent): void;
}
interface TreeMapEvent {
sender: TreeMap;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TreeMapItemCreatedEvent extends TreeMapEvent {
element?: JQuery|Element;
}
interface TreeMapDataBoundEvent extends TreeMapEvent {
}
}
declare namespace kendo.dataviz.map {
class BingLayer extends kendo.dataviz.map.TileLayer {
options: BingLayerOptions;
map: kendo.dataviz.ui.Map;
constructor(map: kendo.dataviz.ui.Map, options?: BingLayerOptions);
show(): void;
hide(): void;
imagerySet(): void;
}
interface BingLayerOptions {
name?: string;
baseUrl?: string;
imagerySet?: string;
}
interface BingLayerEvent {
sender: BingLayer;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Extent extends kendo.Class {
options: ExtentOptions;
nw: kendo.dataviz.map.Location;
se: kendo.dataviz.map.Location;
constructor(nw: kendo.dataviz.map.Location|any, se: kendo.dataviz.map.Location|any);
static create(a: kendo.dataviz.map.Location, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent;
static create(a: kendo.dataviz.map.Location, b?: any): kendo.dataviz.map.Extent;
static create(a: any, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent;
static create(a: any, b?: any): kendo.dataviz.map.Extent;
contains(location: kendo.dataviz.map.Location): boolean;
containsAny(locations: any): boolean;
center(): kendo.dataviz.map.Location;
include(location: kendo.dataviz.map.Location): void;
includeAll(locations: any): void;
edges(): any;
toArray(): any;
overlaps(extent: kendo.dataviz.map.Extent): boolean;
}
interface ExtentOptions {
name?: string;
}
interface ExtentEvent {
sender: Extent;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Layer extends kendo.Class {
options: LayerOptions;
map: kendo.dataviz.ui.Map;
constructor(map: kendo.dataviz.ui.Map, options?: LayerOptions);
show(): void;
hide(): void;
}
interface LayerOptions {
name?: string;
}
interface LayerEvent {
sender: Layer;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Location extends kendo.Class {
options: LocationOptions;
lat: number;
lng: number;
constructor(lat: number, lng: number);
static create(lat: number, lng?: number): kendo.dataviz.map.Location;
static create(lat: any, lng?: number): kendo.dataviz.map.Location;
static create(lat: kendo.dataviz.map.Location, lng?: number): kendo.dataviz.map.Location;
static fromLngLat(lnglat: any): kendo.dataviz.map.Location;
static fromLatLng(lnglat: any): kendo.dataviz.map.Location;
clone(): kendo.dataviz.map.Location;
destination(destination: kendo.dataviz.map.Location, bearing: number): number;
distanceTo(distance: number, bearing: number): kendo.dataviz.map.Location;
equals(location: kendo.dataviz.map.Location): boolean;
round(digits: number): kendo.dataviz.map.Location;
toArray(): any;
toString(): string;
wrap(): kendo.dataviz.map.Location;
}
interface LocationOptions {
name?: string;
}
interface LocationEvent {
sender: Location;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Marker extends Observable {
options: MarkerOptions;
constructor(options?: MarkerOptions);
location(): kendo.dataviz.map.Location;
location(location: any): void;
location(location: kendo.dataviz.map.Location): void;
}
interface MarkerTooltipAnimationClose {
effects?: string;
duration?: number;
}
interface MarkerTooltipAnimationOpen {
effects?: string;
duration?: number;
}
interface MarkerTooltipAnimation {
close?: MarkerTooltipAnimationClose;
open?: MarkerTooltipAnimationOpen;
}
interface MarkerTooltipContent {
url?: string;
}
interface MarkerTooltip {
autoHide?: boolean;
animation?: MarkerTooltipAnimation;
content?: string | Function | MarkerTooltipContent;
template?: string;
callout?: boolean;
iframe?: boolean;
height?: number;
width?: number;
position?: string;
showAfter?: number;
showOn?: string;
}
interface MarkerOptions {
name?: string;
location?: any|kendo.dataviz.map.Location;
shape?: string;
title?: string;
tooltip?: MarkerTooltip;
}
interface MarkerEvent {
sender: Marker;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class MarkerLayer extends kendo.dataviz.map.Layer {
options: MarkerLayerOptions;
map: kendo.dataviz.ui.Map;
items: any;
constructor(map: kendo.dataviz.ui.Map, options?: MarkerLayerOptions);
add(marker: kendo.dataviz.map.Marker): void;
clear(): void;
hide(): void;
remove(marker: kendo.dataviz.map.Marker): void;
setDataSource(dataSource: any): void;
show(): void;
}
interface MarkerLayerOptions {
name?: string;
}
interface MarkerLayerEvent {
sender: MarkerLayer;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ShapeLayer extends kendo.dataviz.map.Layer {
options: ShapeLayerOptions;
map: kendo.dataviz.ui.Map;
constructor(map: kendo.dataviz.ui.Map, options?: ShapeLayerOptions);
show(): void;
hide(): void;
setDataSource(): void;
}
interface ShapeLayerOptions {
name?: string;
}
interface ShapeLayerEvent {
sender: ShapeLayer;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class TileLayer extends kendo.dataviz.map.Layer {
options: TileLayerOptions;
map: kendo.dataviz.ui.Map;
constructor(map: kendo.dataviz.ui.Map, options?: TileLayerOptions);
show(): void;
hide(): void;
}
interface TileLayerOptions {
name?: string;
urlTemplate?: string;
subdomains?: any;
tileSize?: number;
}
interface TileLayerEvent {
sender: TileLayer;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
}
declare namespace kendo.dataviz {
class ChartAxis extends Observable {
options: ChartAxisOptions;
range(): any;
slot(from: string, to?: string, limit?: boolean): kendo.geometry.Rect;
slot(from: string, to?: number, limit?: boolean): kendo.geometry.Rect;
slot(from: string, to?: Date, limit?: boolean): kendo.geometry.Rect;
slot(from: number, to?: string, limit?: boolean): kendo.geometry.Rect;
slot(from: number, to?: number, limit?: boolean): kendo.geometry.Rect;
slot(from: number, to?: Date, limit?: boolean): kendo.geometry.Rect;
slot(from: Date, to?: string, limit?: boolean): kendo.geometry.Rect;
slot(from: Date, to?: number, limit?: boolean): kendo.geometry.Rect;
slot(from: Date, to?: Date, limit?: boolean): kendo.geometry.Rect;
value(point: kendo.geometry.Point): void;
valueRange(): void;
}
interface ChartAxisOptions {
name?: string;
}
interface ChartAxisEvent {
sender: ChartAxis;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ChartPane extends Observable {
options: ChartPaneOptions;
chartsVisual: kendo.drawing.Group;
visual: kendo.drawing.Group;
findAxisByName(name: string): kendo.dataviz.ChartAxis;
series(): any;
}
interface ChartPaneOptions {
name?: string;
}
interface ChartPaneEvent {
sender: ChartPane;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ChartPlotArea extends Observable {
options: ChartPlotAreaOptions;
backgroundVisual: kendo.drawing.MultiPath;
visual: kendo.drawing.Group;
}
interface ChartPlotAreaOptions {
name?: string;
}
interface ChartPlotAreaEvent {
sender: ChartPlotArea;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ChartPoint extends Observable {
options: ChartPointOptions;
category: string|Date|number;
dataItem: any;
percentage: number;
runningTotal: number;
total: number;
value: number;
visual: kendo.drawing.Element;
}
interface ChartPointOptions {
name?: string;
}
interface ChartPointEvent {
sender: ChartPoint;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ChartSeries extends Observable {
options: ChartSeriesOptions;
data(): any;
data(data: any): void;
findPoint(callback: Function): kendo.dataviz.ChartPoint;
points(): any;
points(filter: Function): void;
toggleHighlight(show: boolean, filter: Function): void;
toggleHighlight(show: boolean, filter: any): void;
toggleVisibility(show: boolean, filter: Function): void;
}
interface ChartSeriesOptions {
name?: string;
}
interface ChartSeriesEvent {
sender: ChartSeries;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Navigator extends kendo.Observable {
options: NavigatorOptions;
select(): any;
select(): void;
}
interface NavigatorOptions {
name?: string;
}
interface NavigatorEvent {
sender: Navigator;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
}
declare namespace kendo.dataviz.diagram {
class Circle extends Observable {
options: CircleOptions;
drawingElement: kendo.drawing.Circle;
constructor(options?: CircleOptions);
position(): void;
position(offset: kendo.dataviz.diagram.Point): void;
rotate(angle: number, center: kendo.dataviz.diagram.Point): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface CircleFillGradientStop {
offset?: number;
color?: string;
opacity?: number;
}
interface CircleFillGradient {
type?: string;
center?: any;
radius?: number;
start?: any;
end?: any;
stops?: CircleFillGradientStop[];
}
interface CircleFill {
color?: string;
opacity?: number;
gradient?: CircleFillGradient;
}
interface CircleStroke {
color?: string;
width?: number;
}
interface CircleOptions {
name?: string;
fill?: string | CircleFill;
stroke?: CircleStroke;
center?: any;
radius?: number;
}
interface CircleEvent {
sender: Circle;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Connection extends Observable {
options: ConnectionOptions;
dataItem: any;
from: kendo.dataviz.diagram.Shape;
sourceConnector: kendo.dataviz.diagram.Connector;
targetConnector: kendo.dataviz.diagram.Connector;
to: kendo.dataviz.diagram.Shape;
constructor(options?: ConnectionOptions);
source(): any;
source(source: kendo.dataviz.diagram.Shape): void;
source(source: kendo.dataviz.diagram.Point): void;
source(source: kendo.dataviz.diagram.Connector): void;
sourcePoint(): kendo.dataviz.diagram.Point;
target(): any;
target(target: kendo.dataviz.diagram.Shape): void;
target(target: kendo.dataviz.diagram.Point): void;
target(target: kendo.dataviz.diagram.Connector): void;
targetPoint(): kendo.dataviz.diagram.Point;
select(value: boolean): void;
type(): void;
type(value: string): void;
points(): any;
allPoints(): any;
redraw(options?: any): void;
}
interface ConnectionContent {
color?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
fontWeight?: string;
template?: string|Function;
text?: string;
visual?: Function;
}
interface ConnectionEndCapFill {
color?: string;
}
interface ConnectionEndCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface ConnectionEndCap {
fill?: string | ConnectionEndCapFill;
stroke?: string | ConnectionEndCapStroke;
type?: string;
}
interface ConnectionHoverStroke {
color?: string;
}
interface ConnectionHover {
stroke?: ConnectionHoverStroke;
}
interface ConnectionPoint {
x?: number;
y?: number;
}
interface ConnectionStartCapFill {
color?: string;
}
interface ConnectionStartCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface ConnectionStartCap {
fill?: string | ConnectionStartCapFill;
stroke?: string | ConnectionStartCapStroke;
type?: string;
}
interface ConnectionStroke {
color?: string;
}
interface ConnectionOptions {
name?: string;
content?: ConnectionContent;
fromConnector?: string;
fromX?: number;
fromY?: number;
stroke?: ConnectionStroke;
hover?: ConnectionHover;
startCap?: string | ConnectionStartCap;
endCap?: string | ConnectionEndCap;
points?: ConnectionPoint[];
selectable?: boolean;
toConnector?: string;
toX?: number;
toY?: number;
type?: string;
}
interface ConnectionEvent {
sender: Connection;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Connector extends Observable {
options: ConnectorOptions;
connections: any;
shape: kendo.dataviz.diagram.Shape;
constructor(options?: ConnectorOptions);
position(): kendo.dataviz.diagram.Point;
}
interface ConnectorFill {
color?: string;
opacity?: number;
}
interface ConnectorHoverFill {
color?: string;
opacity?: number;
}
interface ConnectorHoverStroke {
color?: string;
dashType?: string;
width?: number;
}
interface ConnectorHover {
fill?: string | ConnectorHoverFill;
stroke?: string | ConnectorHoverStroke;
}
interface ConnectorStroke {
color?: string;
dashType?: string;
width?: number;
}
interface ConnectorOptions {
name?: string;
width?: number;
height?: number;
hover?: ConnectorHover;
fill?: string | ConnectorFill;
stroke?: string | ConnectorStroke;
}
interface ConnectorEvent {
sender: Connector;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Group extends Observable {
options: GroupOptions;
drawingElement: kendo.drawing.Group;
constructor(options?: GroupOptions);
append(element: any): void;
clear(): void;
remove(element: any): void;
position(): void;
position(offset: kendo.dataviz.diagram.Point): void;
rotate(angle: number, center: kendo.dataviz.diagram.Point): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface GroupOptions {
name?: string;
x?: number;
y?: number;
}
interface GroupEvent {
sender: Group;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Image extends Observable {
options: ImageOptions;
drawingElement: kendo.drawing.Image;
constructor(options?: ImageOptions);
position(): void;
position(offset: kendo.dataviz.diagram.Point): void;
rotate(angle: number, center: kendo.dataviz.diagram.Point): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface ImageOptions {
name?: string;
height?: number;
width?: number;
x?: number;
y?: number;
source?: string;
}
interface ImageEvent {
sender: Image;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Layout extends Observable {
options: LayoutOptions;
drawingElement: kendo.drawing.Layout;
constructor(rect: kendo.dataviz.diagram.Rect, options?: LayoutOptions);
append(element: any): void;
clear(): void;
rect(): kendo.dataviz.diagram.Rect;
rect(rect: kendo.dataviz.diagram.Rect): void;
reflow(): void;
remove(element: any): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface LayoutOptions {
name?: string;
alignContent?: string;
alignItems?: string;
justifyContent?: string;
lineSpacing?: number;
spacing?: number;
orientation?: string;
wrap?: boolean;
}
interface LayoutEvent {
sender: Layout;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Line extends Observable {
options: LineOptions;
drawingElement: kendo.drawing.Path;
constructor(options?: LineOptions);
position(): void;
position(offset: kendo.dataviz.diagram.Point): void;
rotate(angle: number, center: kendo.dataviz.diagram.Point): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface LineStroke {
color?: string;
width?: number;
}
interface LineOptions {
name?: string;
stroke?: LineStroke;
from?: any;
to?: any;
}
interface LineEvent {
sender: Line;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Path extends Observable {
options: PathOptions;
drawingElement: kendo.drawing.Path;
constructor(options?: PathOptions);
data(): string;
data(path: string): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface PathEndCapFill {
color?: string;
opacity?: number;
}
interface PathEndCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface PathEndCap {
fill?: string | PathEndCapFill;
stroke?: string | PathEndCapStroke;
type?: string;
}
interface PathFillGradientStop {
offset?: number;
color?: string;
opacity?: number;
}
interface PathFillGradient {
type?: string;
center?: any;
radius?: number;
start?: any;
end?: any;
stops?: PathFillGradientStop[];
}
interface PathFill {
color?: string;
opacity?: number;
gradient?: PathFillGradient;
}
interface PathStartCapFill {
color?: string;
opacity?: number;
}
interface PathStartCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface PathStartCap {
fill?: string | PathStartCapFill;
stroke?: string | PathStartCapStroke;
type?: string;
}
interface PathStroke {
color?: string;
width?: number;
}
interface PathOptions {
name?: string;
data?: string;
endCap?: string | PathEndCap;
fill?: string | PathFill;
height?: number;
startCap?: string | PathStartCap;
stroke?: PathStroke;
width?: number;
x?: number;
y?: number;
}
interface PathEvent {
sender: Path;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Point extends Observable {
options: PointOptions;
x: number;
y: number;
constructor(x: number, y: number);
}
interface PointOptions {
name?: string;
}
interface PointEvent {
sender: Point;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Polyline extends Observable {
options: PolylineOptions;
drawingElement: kendo.drawing.Path;
constructor(options?: PolylineOptions);
points(): any;
points(points: any): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface PolylineEndCapFill {
color?: string;
opacity?: number;
}
interface PolylineEndCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface PolylineEndCap {
fill?: string | PolylineEndCapFill;
stroke?: string | PolylineEndCapStroke;
type?: string;
}
interface PolylineFillGradientStop {
offset?: number;
color?: string;
opacity?: number;
}
interface PolylineFillGradient {
type?: string;
center?: any;
radius?: number;
start?: any;
end?: any;
stops?: PolylineFillGradientStop[];
}
interface PolylineFill {
color?: string;
opacity?: number;
gradient?: PolylineFillGradient;
}
interface PolylineStartCapFill {
color?: string;
opacity?: number;
}
interface PolylineStartCapStroke {
color?: string;
dashType?: string;
width?: number;
}
interface PolylineStartCap {
fill?: string | PolylineStartCapFill;
stroke?: string | PolylineStartCapStroke;
type?: string;
}
interface PolylineStroke {
color?: string;
width?: number;
}
interface PolylineOptions {
name?: string;
endCap?: string | PolylineEndCap;
fill?: string | PolylineFill;
startCap?: string | PolylineStartCap;
stroke?: PolylineStroke;
}
interface PolylineEvent {
sender: Polyline;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Rect extends Observable {
options: RectOptions;
constructor(options?: RectOptions);
position(): void;
position(offset: kendo.dataviz.diagram.Point): void;
rotate(angle: number, center: kendo.dataviz.diagram.Point): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface RectOptions {
name?: string;
height?: number;
width?: number;
x?: number;
y?: number;
}
interface RectEvent {
sender: Rect;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Rectangle extends Observable {
options: RectangleOptions;
drawingElement: kendo.drawing.Path;
constructor(options?: RectangleOptions);
visible(): boolean;
visible(visible: boolean): void;
}
interface RectangleFillGradientStop {
offset?: number;
color?: string;
opacity?: number;
}
interface RectangleFillGradient {
type?: string;
center?: any;
radius?: number;
start?: any;
end?: any;
stops?: RectangleFillGradientStop[];
}
interface RectangleFill {
color?: string;
opacity?: number;
gradient?: RectangleFillGradient;
}
interface RectangleStroke {
color?: string;
width?: number;
}
interface RectangleOptions {
name?: string;
fill?: string | RectangleFill;
height?: number;
stroke?: RectangleStroke;
width?: number;
x?: number;
y?: number;
}
interface RectangleEvent {
sender: Rectangle;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Shape extends Observable {
options: ShapeOptions;
connectors: any;
dataItem: any;
shapeVisual: any;
visual: kendo.dataviz.diagram.Group;
constructor(options?: ShapeOptions);
position(): void;
position(point: kendo.dataviz.diagram.Point): void;
clone(): kendo.dataviz.diagram.Shape;
select(value: boolean): void;
connections(type: string): void;
getConnector(): void;
getPosition(side: string): void;
redraw(options: any): void;
redrawVisual(): void;
}
interface ShapeConnectorDefaultsFill {
color?: string;
opacity?: number;
}
interface ShapeConnectorDefaultsHoverFill {
color?: string;
opacity?: number;
}
interface ShapeConnectorDefaultsHoverStroke {
color?: string;
dashType?: string;
width?: number;
}
interface ShapeConnectorDefaultsHover {
fill?: string | ShapeConnectorDefaultsHoverFill;
stroke?: string | ShapeConnectorDefaultsHoverStroke;
}
interface ShapeConnectorDefaultsStroke {
color?: string;
dashType?: string;
width?: number;
}
interface ShapeConnectorDefaults {
width?: number;
height?: number;
hover?: ShapeConnectorDefaultsHover;
fill?: string | ShapeConnectorDefaultsFill;
stroke?: string | ShapeConnectorDefaultsStroke;
}
interface ShapeConnector {
name?: string;
description?: string;
position?: Function;
}
interface ShapeContent {
align?: string;
color?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
fontWeight?: string;
text?: string;
}
interface ShapeEditable {
connect?: boolean;
}
interface ShapeFillGradientStop {
offset?: number;
color?: string;
opacity?: number;
}
interface ShapeFillGradient {
type?: string;
center?: any;
radius?: number;
start?: any;
end?: any;
stops?: ShapeFillGradientStop[];
}
interface ShapeFill {
color?: string;
opacity?: number;
gradient?: ShapeFillGradient;
}
interface ShapeHoverFill {
color?: string;
opacity?: number;
}
interface ShapeHover {
fill?: string | ShapeHoverFill;
}
interface ShapeRotation {
angle?: number;
}
interface ShapeStroke {
color?: string;
width?: number;
dashType?: string;
}
interface ShapeOptions {
name?: string;
id?: string;
editable?: boolean | ShapeEditable;
path?: string;
stroke?: ShapeStroke;
type?: string;
x?: number;
y?: number;
minWidth?: number;
minHeight?: number;
width?: number;
height?: number;
fill?: string | ShapeFill;
hover?: ShapeHover;
connectors?: ShapeConnector[];
rotation?: ShapeRotation;
content?: ShapeContent;
selectable?: boolean;
visual?: Function;
connectorDefaults?: ShapeConnectorDefaults;
}
interface ShapeEvent {
sender: Shape;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class TextBlock extends Observable {
options: TextBlockOptions;
drawingElement: kendo.drawing.Text;
constructor(options?: TextBlockOptions);
content(): string;
content(content: string): void;
position(): void;
position(offset: kendo.dataviz.diagram.Point): void;
rotate(angle: number, center: kendo.dataviz.diagram.Point): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface TextBlockOptions {
name?: string;
color?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
fontWeight?: string;
height?: number;
text?: string;
width?: number;
x?: number;
y?: number;
}
interface TextBlockEvent {
sender: TextBlock;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
}
declare namespace kendo {
class Color extends Observable {
options: ColorOptions;
diff(): number;
equals(): boolean;
toHSV(): any;
toRGB(): any;
toBytes(): any;
toHex(): string;
toCss(): string;
toCssRgba(): string;
toDisplay(): string;
}
interface ColorOptions {
name?: string;
}
interface ColorEvent {
sender: Color;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
namespace date {
var MS_PER_DAY: number;
var MS_PER_HOUR: number;
var MS_PER_MINUTE: number;
function setDayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): void;
function dayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): Date;
function weekInYear(date: Date, weekStart?: number): number;
function getDate(date: Date): Date;
function isInDateRange(targetDate: Date, lowerLimitDate: Date, upperLimitDate: Date): boolean;
function isInTimeRange(targetDate: Date, lowerLimitDate: Date, upperLimitDate: Date): boolean;
function isToday(targetDate: Date): boolean;
function nextDay(targetDate: Date): Date;
function previousDay(targetDate: Date): Date;
function toUtcTime(targetDate: Date): number;
function setTime(targetDate: Date, millisecondsToAdd: number, ignoreDST: boolean): void;
function setHours(targetDate: Date, sourceDate: number): Date;
function addDays(targetDate: Date, numberOfDaysToAdd: number): Date;
function today(): Date;
function toInvariantTime(targetDate: Date): Date;
function firstDayOfMonth(targetDate: Date): Date;
function lastDayOfMonth(targetDate: Date): Date;
function getMilliseconds(targetDate: Date): number;
}
namespace drawing {
function align(elements: any, rect: kendo.geometry.Rect, alignment: string): void;
function drawDOM(element: JQuery, options: any): JQueryPromise<any>;
function exportImage(group: kendo.drawing.Group, options: any): JQueryPromise<any>;
function exportPDF(group: kendo.drawing.Group, options: kendo.drawing.PDFOptions): JQueryPromise<any>;
function exportSVG(group: kendo.drawing.Group, options: any): JQueryPromise<any>;
function fit(element: kendo.drawing.Element, rect: kendo.geometry.Rect): void;
function stack(elements: any): void;
function vAlign(elements: any, rect: kendo.geometry.Rect, alignment: string): void;
function vStack(elements: any): void;
function vWrap(elements: any, rect: kendo.geometry.Rect): any;
function wrap(elements: any, rect: kendo.geometry.Rect): any;
}
namespace effects {
function box(element: HTMLElement): any;
function fillScale(firstElement: HTMLElement, secondElement: HTMLElement): number;
function fitScale(firstElement: HTMLElement, secondElement: HTMLElement): number;
function transformOrigin(firstElement: HTMLElement, secondElement: HTMLElement): any;
}
function alert(text: string): void;
function antiForgeryTokens(): any;
function bind(element: string, viewModel: any, namespace?: any): void;
function bind(element: string, viewModel: kendo.data.ObservableObject, namespace?: any): void;
function bind(element: JQuery, viewModel: any, namespace?: any): void;
function bind(element: JQuery, viewModel: kendo.data.ObservableObject, namespace?: any): void;
function bind(element: Element, viewModel: any, namespace?: any): void;
function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void;
function confirm(text: string): JQueryPromise<any>;
function culture(culture: string): void;
function destroy(element: string): void;
function destroy(element: JQuery): void;
function destroy(element: Element): void;
function guid(): string;
function htmlEncode(value: string): string;
function observableHierarchy(array: any): void;
function parseDate(value: string, formats?: string, culture?: string): Date;
function parseDate(value: string, formats?: any, culture?: string): Date;
function parseExactDate(value: string, formats?: string, culture?: string): Date;
function parseExactDate(value: string, formats?: any, culture?: string): Date;
function parseFloat(value: string, culture?: string): number;
function parseInt(value: string, culture?: string): number;
function parseColor(color: string, noerror: boolean): kendo.Color;
function prompt(text: string, defaultValue: string): JQueryPromise<any>;
function proxyModelSetters(): void;
function proxyModelSetters(data: kendo.data.Model): void;
function resize(element: string, force: boolean): void;
function resize(element: JQuery, force: boolean): void;
function resize(element: Element, force: boolean): void;
function saveAs(options: any): void;
function stringify(value: any): string;
function throttle(fn: Function, timeout: number): Function;
function touchScroller(element: string): void;
function touchScroller(element: JQuery): void;
function touchScroller(element: Element): void;
function toString(value: Date, format: string, culture?: string): string;
function toString(value: number, format: string, culture?: string): string;
function unbind(element: string): void;
function unbind(element: JQuery): void;
function unbind(element: Element): void;
namespace pdf {
function defineFont(map: any): void;
}
namespace timezone {
function offset(utcTime: Date, timezone: string): number;
function offset(utcTime: number, timezone: string): number;
function convert(targetDate: Date, fromOffset: number, toOffset: number): Date;
function convert(targetDate: Date, fromOffset: number, toOffset: string): Date;
function convert(targetDate: Date, fromOffset: string, toOffset: number): Date;
function convert(targetDate: Date, fromOffset: string, toOffset: string): Date;
function apply(targetDate: Date, offset: number): Date;
function apply(targetDate: Date, offset: string): Date;
function remove(targetDate: Date, offset: number): Date;
function remove(targetDate: Date, offset: string): Date;
function abbr(targetDate: Date, timezone: string): string;
function toLocalDate(targetDate: Date): Date;
function toLocalDate(targetDate: number): Date;
}
}
declare namespace kendo.spreadsheet {
class CustomFilter extends Observable {
options: CustomFilterOptions;
init(options: any): void;
}
interface CustomFilterOptions {
name?: string;
}
interface CustomFilterEvent {
sender: CustomFilter;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class DynamicFilter extends Observable {
options: DynamicFilterOptions;
init(options: any): void;
}
interface DynamicFilterOptions {
name?: string;
}
interface DynamicFilterEvent {
sender: DynamicFilter;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Range extends Observable {
options: RangeOptions;
background(): string;
background(value?: string): void;
bold(): boolean;
bold(value?: boolean): void;
borderBottom(): any;
borderBottom(value?: any): void;
borderLeft(): any;
borderLeft(value?: any): void;
borderRight(): any;
borderRight(value?: any): void;
borderTop(): any;
borderTop(value?: any): void;
color(): string;
color(value?: string): void;
clear(options?: any): void;
clearFilter(indices: any): void;
clearFilter(indices: number): void;
editor(): string;
editor(value?: string): void;
enable(): boolean;
enable(value?: boolean): void;
fillFrom(srcRange: Range, direction?: number): void;
fillFrom(srcRange: string, direction?: number): void;
filter(filter: boolean): void;
filter(filter: any): void;
fontFamily(): string;
fontFamily(value?: string): void;
fontSize(): number;
fontSize(value?: number): void;
forEachCell(callback: Function): void;
format(): string;
format(format?: string): void;
formula(): string;
formula(formula?: string): void;
hasFilter(): boolean;
input(): any;
input(value?: string): void;
input(value?: number): void;
input(value?: Date): void;
isSortable(): boolean;
isFilterable(): boolean;
italic(): boolean;
italic(value?: boolean): void;
link(): string;
link(url?: string): void;
merge(): void;
select(): void;
sort(sort: number): void;
sort(sort: any): void;
textAlign(): string;
textAlign(value?: string): void;
unmerge(): void;
values(): any;
values(values: any): void;
validation(): any;
validation(value?: any): void;
value(): any;
value(value?: string): void;
value(value?: number): void;
value(value?: Date): void;
verticalAlign(): string;
verticalAlign(value?: string): void;
wrap(): boolean;
wrap(value?: boolean): void;
}
interface RangeOptions {
name?: string;
}
interface RangeEvent {
sender: Range;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Sheet extends Observable {
options: SheetOptions;
clearFilter(indexes: number): void;
clearFilter(indexes: any): void;
columnWidth(): void;
columnWidth(index: number, width?: number): void;
batch(callback: Function, changeEventArgs: any): void;
deleteColumn(index: number): void;
deleteRow(index: number): void;
fromJSON(data: any): void;
frozenColumns(): number;
frozenColumns(count?: number): void;
frozenRows(): number;
frozenRows(count?: number): void;
hideColumn(index: number): void;
hideRow(index: number): void;
insertColumn(index: number): void;
insertRow(index: number): void;
range(ref: string): kendo.spreadsheet.Range;
range(rowIndex: number, columnIndex: number, rowCount?: number, columnCount?: number): kendo.spreadsheet.Range;
rowHeight(): void;
rowHeight(index: number, width?: number): void;
selection(): kendo.spreadsheet.Range;
setDataSource(dataSource: kendo.data.DataSource, columns?: any): void;
showGridLines(): boolean;
showGridLines(showGridLines?: boolean): void;
toJSON(): void;
unhideColumn(index: number): void;
unhideRow(index: number): void;
}
interface SheetOptions {
name?: string;
change?(e: SheetChangeEvent): void;
}
interface SheetEvent {
sender: Sheet;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SheetChangeEvent extends SheetEvent {
}
class TopFilter extends Observable {
options: TopFilterOptions;
init(options: any): void;
}
interface TopFilterOptions {
name?: string;
}
interface TopFilterEvent {
sender: TopFilter;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ValueFilter extends Observable {
options: ValueFilterOptions;
init(options: any): void;
}
interface ValueFilterOptions {
name?: string;
}
interface ValueFilterEvent {
sender: ValueFilter;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
}
declare namespace kendo.mobile.ui {
class ActionSheet extends kendo.mobile.ui.Widget {
static fn: ActionSheet;
options: ActionSheetOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ActionSheet;
constructor(element: Element, options?: ActionSheetOptions);
close(): void;
destroy(): void;
open(target: JQuery, context: any): void;
}
interface ActionSheetPopup {
direction?: number|string;
height?: number|string;
width?: number|string;
}
interface ActionSheetOptions {
name?: string;
cancel?: string;
popup?: ActionSheetPopup;
type?: string;
close?(e: ActionSheetEvent): void;
open?(e: ActionSheetOpenEvent): void;
}
interface ActionSheetEvent {
sender: ActionSheet;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ActionSheetOpenEvent extends ActionSheetEvent {
target?: JQuery;
context?: JQuery;
}
class BackButton extends kendo.mobile.ui.Widget {
static fn: BackButton;
options: BackButtonOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): BackButton;
constructor(element: Element, options?: BackButtonOptions);
destroy(): void;
}
interface BackButtonOptions {
name?: string;
click?(e: BackButtonClickEvent): void;
}
interface BackButtonEvent {
sender: BackButton;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface BackButtonClickEvent extends BackButtonEvent {
target?: JQuery;
button?: JQuery;
}
class Button extends kendo.mobile.ui.Widget {
static fn: Button;
options: ButtonOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Button;
constructor(element: Element, options?: ButtonOptions);
badge(value: string): string;
badge(value: boolean): string;
destroy(): void;
enable(enable: boolean): void;
}
interface ButtonOptions {
name?: string;
badge?: string;
clickOn?: string;
enable?: boolean;
icon?: string;
click?(e: ButtonClickEvent): void;
}
interface ButtonEvent {
sender: Button;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ButtonClickEvent extends ButtonEvent {
target?: JQuery;
button?: JQuery;
}
class ButtonGroup extends kendo.mobile.ui.Widget {
static fn: ButtonGroup;
options: ButtonGroupOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ButtonGroup;
constructor(element: Element, options?: ButtonGroupOptions);
badge(button: string, value: string): string;
badge(button: string, value: boolean): string;
badge(button: number, value: string): string;
badge(button: number, value: boolean): string;
current(): JQuery;
destroy(): void;
enable(enable: boolean): void;
select(li: JQuery): void;
select(li: number): void;
}
interface ButtonGroupOptions {
name?: string;
enable?: boolean;
index?: number;
selectOn?: string;
select?(e: ButtonGroupSelectEvent): void;
}
interface ButtonGroupEvent {
sender: ButtonGroup;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ButtonGroupSelectEvent extends ButtonGroupEvent {
index?: number;
}
class Collapsible extends kendo.mobile.ui.Widget {
static fn: Collapsible;
options: CollapsibleOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Collapsible;
constructor(element: Element, options?: CollapsibleOptions);
collapse(instant: boolean): void;
destroy(): void;
expand(instant?: boolean): void;
resize(): void;
toggle(instant?: boolean): void;
}
interface CollapsibleOptions {
name?: string;
animation?: boolean;
collapsed?: boolean;
expandIcon?: string;
iconPosition?: string;
inset?: boolean;
collapse?(e: CollapsibleEvent): void;
expand?(e: CollapsibleEvent): void;
}
interface CollapsibleEvent {
sender: Collapsible;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class DetailButton extends kendo.mobile.ui.Widget {
static fn: DetailButton;
options: DetailButtonOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): DetailButton;
constructor(element: Element, options?: DetailButtonOptions);
destroy(): void;
}
interface DetailButtonOptions {
name?: string;
click?(e: DetailButtonClickEvent): void;
}
interface DetailButtonEvent {
sender: DetailButton;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DetailButtonClickEvent extends DetailButtonEvent {
target?: JQuery;
button?: JQuery;
}
class Drawer extends kendo.mobile.ui.Widget {
static fn: Drawer;
options: DrawerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Drawer;
constructor(element: Element, options?: DrawerOptions);
destroy(): void;
hide(): void;
show(): void;
}
interface DrawerOptions {
name?: string;
container?: JQuery;
position?: string;
swipeToOpen?: boolean;
swipeToOpenViews?: any;
title?: string;
views?: any;
afterHide?(e: DrawerAfterHideEvent): void;
beforeShow?(e: DrawerEvent): void;
hide?(e: DrawerHideEvent): void;
init?(e: DrawerInitEvent): void;
show?(e: DrawerShowEvent): void;
}
interface DrawerEvent {
sender: Drawer;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface DrawerAfterHideEvent extends DrawerEvent {
}
interface DrawerHideEvent extends DrawerEvent {
}
interface DrawerInitEvent extends DrawerEvent {
}
interface DrawerShowEvent extends DrawerEvent {
}
class Layout extends kendo.mobile.ui.Widget {
static fn: Layout;
options: LayoutOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Layout;
constructor(element: Element, options?: LayoutOptions);
}
interface LayoutOptions {
name?: string;
id?: string;
platform?: string;
hide?(e: LayoutHideEvent): void;
init?(e: LayoutInitEvent): void;
show?(e: LayoutShowEvent): void;
}
interface LayoutEvent {
sender: Layout;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface LayoutHideEvent extends LayoutEvent {
layout?: JQuery;
view?: JQuery;
}
interface LayoutInitEvent extends LayoutEvent {
layout?: JQuery;
}
interface LayoutShowEvent extends LayoutEvent {
layout?: JQuery;
view?: JQuery;
}
class ListView extends kendo.mobile.ui.Widget {
static fn: ListView;
options: ListViewOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ListView;
constructor(element: Element, options?: ListViewOptions);
append(dataItems: any): void;
prepend(dataItems: any): void;
replace(dataItems: any): void;
remove(dataItems: any): void;
setDataItem(item: JQuery, dataItem: kendo.data.Model): void;
destroy(): void;
items(): JQuery;
refresh(): void;
setDataSource(dataSource: kendo.data.DataSource): void;
}
interface ListViewFilterable {
placeholder?: string;
autoFilter?: boolean;
field?: string;
ignoreCase?: boolean;
operator?: string;
}
interface ListViewMessages {
loadMoreText?: string;
pullTemplate?: string;
refreshTemplate?: string;
releaseTemplate?: string;
}
interface ListViewOptions {
name?: string;
appendOnRefresh?: boolean;
autoBind?: boolean;
dataSource?: kendo.data.DataSource|any;
endlessScroll?: boolean;
fixedHeaders?: boolean;
headerTemplate?: string|Function;
loadMore?: boolean;
messages?: ListViewMessages;
pullToRefresh?: boolean;
pullParameters?: Function;
style?: string;
template?: string|Function;
type?: string;
filterable?: boolean | ListViewFilterable;
virtualViewSize?: number;
click?(e: ListViewClickEvent): void;
dataBound?(e: ListViewEvent): void;
dataBinding?(e: ListViewEvent): void;
itemChange?(e: ListViewEvent): void;
}
interface ListViewEvent {
sender: ListView;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ListViewClickEvent extends ListViewEvent {
item?: JQuery;
target?: JQuery;
dataItem?: any;
button?: kendo.mobile.ui.Button;
}
class Loader extends kendo.mobile.ui.Widget {
static fn: Loader;
options: LoaderOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Loader;
constructor(element: Element, options?: LoaderOptions);
hide(): void;
show(): void;
}
interface LoaderOptions {
name?: string;
}
interface LoaderEvent {
sender: Loader;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class ModalView extends kendo.mobile.ui.Widget {
static fn: ModalView;
options: ModalViewOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ModalView;
constructor(element: Element, options?: ModalViewOptions);
close(): void;
destroy(): void;
open(target?: JQuery): void;
}
interface ModalViewOptions {
name?: string;
height?: number;
modal?: boolean;
width?: number;
beforeOpen?(e: ModalViewBeforeOpenEvent): void;
close?(e: ModalViewCloseEvent): void;
init?(e: ModalViewInitEvent): void;
open?(e: ModalViewOpenEvent): void;
}
interface ModalViewEvent {
sender: ModalView;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ModalViewBeforeOpenEvent extends ModalViewEvent {
target?: JQuery;
}
interface ModalViewCloseEvent extends ModalViewEvent {
}
interface ModalViewInitEvent extends ModalViewEvent {
}
interface ModalViewOpenEvent extends ModalViewEvent {
target?: JQuery;
}
class NavBar extends kendo.mobile.ui.Widget {
static fn: NavBar;
options: NavBarOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): NavBar;
constructor(element: Element, options?: NavBarOptions);
destroy(): void;
title(value: string): void;
}
interface NavBarOptions {
name?: string;
}
interface NavBarEvent {
sender: NavBar;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Pane extends kendo.mobile.ui.Widget {
static fn: Pane;
options: PaneOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Pane;
constructor(element: Element, options?: PaneOptions);
destroy(): void;
hideLoading(): void;
navigate(url: string, transition: string): void;
replace(url: string, transition: string): void;
showLoading(): void;
view(): kendo.mobile.ui.View;
}
interface PaneOptions {
name?: string;
collapsible?: boolean;
initial?: string;
layout?: string;
loading?: string;
portraitWidth?: number;
transition?: string;
navigate?(e: PaneNavigateEvent): void;
viewShow?(e: PaneViewShowEvent): void;
}
interface PaneEvent {
sender: Pane;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface PaneNavigateEvent extends PaneEvent {
url?: JQuery;
}
interface PaneViewShowEvent extends PaneEvent {
view?: kendo.mobile.ui.View;
}
class PopOver extends kendo.mobile.ui.Widget {
static fn: PopOver;
options: PopOverOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): PopOver;
constructor(element: Element, options?: PopOverOptions);
close(): void;
destroy(): void;
open(target: JQuery): void;
}
interface PopOverPane {
initial?: string;
layout?: string;
loading?: string;
transition?: string;
}
interface PopOverPopup {
height?: number|string;
width?: number|string;
}
interface PopOverOptions {
name?: string;
pane?: PopOverPane;
popup?: PopOverPopup;
close?(e: PopOverCloseEvent): void;
open?(e: PopOverOpenEvent): void;
}
interface PopOverEvent {
sender: PopOver;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface PopOverCloseEvent extends PopOverEvent {
}
interface PopOverOpenEvent extends PopOverEvent {
target?: JQuery;
}
class ScrollView extends kendo.mobile.ui.Widget {
static fn: ScrollView;
options: ScrollViewOptions;
dataSource: kendo.data.DataSource;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): ScrollView;
constructor(element: Element, options?: ScrollViewOptions);
content(content: string): void;
content(content: JQuery): void;
destroy(): void;
next(): void;
prev(): void;
refresh(): void;
scrollTo(page: number, instant: boolean): void;
setDataSource(dataSource: kendo.data.DataSource): void;
value(dataItem: any): any;
}
interface ScrollViewOptions {
name?: string;
autoBind?: boolean;
bounceVelocityThreshold?: number;
contentHeight?: number|string;
dataSource?: kendo.data.DataSource|any;
duration?: number;
emptyTemplate?: string;
enablePager?: boolean;
itemsPerPage?: number;
page?: number;
pageSize?: number;
template?: string;
velocityThreshold?: number;
changing?(e: ScrollViewChangingEvent): void;
change?(e: ScrollViewChangeEvent): void;
refresh?(e: ScrollViewRefreshEvent): void;
}
interface ScrollViewEvent {
sender: ScrollView;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ScrollViewChangingEvent extends ScrollViewEvent {
currentPage?: number;
nextPage?: number;
}
interface ScrollViewChangeEvent extends ScrollViewEvent {
page?: number;
element?: JQuery;
data?: any;
}
interface ScrollViewRefreshEvent extends ScrollViewEvent {
pageCount?: number;
page?: number;
}
class Scroller extends kendo.mobile.ui.Widget {
static fn: Scroller;
options: ScrollerOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Scroller;
constructor(element: Element, options?: ScrollerOptions);
animatedScrollTo(x: number, y: number): void;
contentResized(): void;
destroy(): void;
disable(): void;
enable(): void;
height(): number;
pullHandled(): void;
reset(): void;
scrollHeight(): void;
scrollTo(x: number, y: number): void;
scrollWidth(): void;
zoomOut(): void;
}
interface ScrollerMessages {
pullTemplate?: string;
refreshTemplate?: string;
releaseTemplate?: string;
}
interface ScrollerOptions {
name?: string;
elastic?: boolean;
messages?: ScrollerMessages;
pullOffset?: number;
pullToRefresh?: boolean;
useNative?: boolean;
visibleScrollHints?: boolean;
zoom?: boolean;
pull?(e: ScrollerEvent): void;
resize?(e: ScrollerEvent): void;
scroll?(e: ScrollerScrollEvent): void;
}
interface ScrollerEvent {
sender: Scroller;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ScrollerScrollEvent extends ScrollerEvent {
scrollTop?: number;
scrollLeft?: number;
}
class SplitView extends kendo.mobile.ui.Widget {
static fn: SplitView;
options: SplitViewOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): SplitView;
constructor(element: Element, options?: SplitViewOptions);
destroy(): void;
expandPanes(): void;
collapsePanes(): void;
}
interface SplitViewOptions {
name?: string;
style?: string;
init?(e: SplitViewInitEvent): void;
show?(e: SplitViewShowEvent): void;
}
interface SplitViewEvent {
sender: SplitView;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SplitViewInitEvent extends SplitViewEvent {
view?: JQuery;
}
interface SplitViewShowEvent extends SplitViewEvent {
view?: JQuery;
}
class Switch extends kendo.mobile.ui.Widget {
static fn: Switch;
options: SwitchOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): Switch;
constructor(element: Element, options?: SwitchOptions);
check(): boolean;
check(check: boolean): void;
destroy(): void;
enable(enable: boolean): void;
refresh(): void;
toggle(): void;
}
interface SwitchOptions {
name?: string;
checked?: boolean;
enable?: boolean;
offLabel?: string;
onLabel?: string;
change?(e: SwitchChangeEvent): void;
}
interface SwitchEvent {
sender: Switch;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SwitchChangeEvent extends SwitchEvent {
checked?: any;
}
class TabStrip extends kendo.mobile.ui.Widget {
static fn: TabStrip;
options: TabStripOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): TabStrip;
constructor(element: Element, options?: TabStripOptions);
badge(tab: string, value: string): string;
badge(tab: string, value: boolean): string;
badge(tab: number, value: string): string;
badge(tab: number, value: boolean): string;
currentItem(): JQuery;
destroy(): void;
switchTo(url: string): void;
switchTo(url: number): void;
switchByFullUrl(url: string): void;
clear(): void;
}
interface TabStripOptions {
name?: string;
selectedIndex?: number;
select?(e: TabStripSelectEvent): void;
}
interface TabStripEvent {
sender: TabStrip;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TabStripSelectEvent extends TabStripEvent {
item?: JQuery;
}
class View extends kendo.mobile.ui.Widget {
static fn: View;
options: ViewOptions;
element: JQuery;
wrapper: JQuery;
static extend(proto: Object): View;
constructor(element: Element, options?: ViewOptions);
contentElement(): void;
destroy(): void;
enable(enable: boolean): void;
}
interface ViewOptions {
name?: string;
model?: string;
reload?: boolean;
scroller?: any;
stretch?: boolean;
title?: string;
useNativeScrolling?: boolean;
zoom?: boolean;
afterShow?(e: ViewAfterShowEvent): void;
beforeHide?(e: ViewBeforeHideEvent): void;
beforeShow?(e: ViewBeforeShowEvent): void;
hide?(e: ViewHideEvent): void;
init?(e: ViewInitEvent): void;
show?(e: ViewShowEvent): void;
transitionStart?(e: ViewTransitionStartEvent): void;
transitionEnd?(e: ViewTransitionEndEvent): void;
}
interface ViewEvent {
sender: View;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface ViewAfterShowEvent extends ViewEvent {
view?: kendo.mobile.ui.View;
}
interface ViewBeforeHideEvent extends ViewEvent {
view?: kendo.mobile.ui.View;
}
interface ViewBeforeShowEvent extends ViewEvent {
view?: kendo.mobile.ui.View;
}
interface ViewHideEvent extends ViewEvent {
view?: kendo.mobile.ui.View;
}
interface ViewInitEvent extends ViewEvent {
view?: kendo.mobile.ui.View;
}
interface ViewShowEvent extends ViewEvent {
view?: kendo.mobile.ui.View;
}
interface ViewTransitionStartEvent extends ViewEvent {
type?: string;
}
interface ViewTransitionEndEvent extends ViewEvent {
type?: string;
}
}
declare namespace kendo.ooxml {
class Workbook extends Observable {
options: WorkbookOptions;
sheets: WorkbookSheet[];
constructor(options?: WorkbookOptions);
toDataURL(): string;
toDataURLAsync(): JQueryPromise<any>;
}
interface WorkbookSheetColumn {
autoWidth?: boolean;
index?: number;
width?: number;
}
interface WorkbookSheetFilter {
from?: number;
to?: number;
}
interface WorkbookSheetFreezePane {
colSplit?: number;
rowSplit?: number;
}
interface WorkbookSheetRowCellBorderBottom {
color?: string;
size?: number;
}
interface WorkbookSheetRowCellBorderLeft {
color?: string;
size?: number;
}
interface WorkbookSheetRowCellBorderRight {
color?: string;
size?: number;
}
interface WorkbookSheetRowCellBorderTop {
color?: string;
size?: number;
}
interface WorkbookSheetRowCell {
background?: string;
borderBottom?: WorkbookSheetRowCellBorderBottom;
borderLeft?: WorkbookSheetRowCellBorderLeft;
borderTop?: WorkbookSheetRowCellBorderTop;
borderRight?: WorkbookSheetRowCellBorderRight;
bold?: boolean;
color?: string;
colSpan?: number;
fontFamily?: string;
fontName?: string;
fontSize?: number;
format?: string;
formula?: string;
hAlign?: string;
index?: any;
italic?: boolean;
rowSpan?: number;
textAlign?: string;
underline?: boolean;
wrap?: boolean;
vAlign?: string;
verticalAlign?: string;
value?: Date|number|string|boolean;
}
interface WorkbookSheetRow {
cells?: WorkbookSheetRowCell[];
index?: number;
height?: number;
}
interface WorkbookSheet {
columns?: WorkbookSheetColumn[];
freezePane?: WorkbookSheetFreezePane;
frozenColumns?: number;
frozenRows?: number;
filter?: WorkbookSheetFilter;
mergedCells?: any;
name?: string;
rows?: WorkbookSheetRow[];
showGridLines?: boolean;
title?: string;
}
interface WorkbookOptions {
name?: string;
creator?: string;
date?: Date;
sheets?: WorkbookSheet[];
}
interface WorkbookEvent {
sender: Workbook;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
}
declare namespace kendo.dataviz.drawing {
class Arc extends kendo.drawing.Element {
options: ArcOptions;
constructor(geometry: kendo.geometry.Arc, options?: ArcOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
geometry(): kendo.geometry.Arc;
geometry(value: kendo.geometry.Arc): void;
fill(color: string, opacity?: number): kendo.drawing.Arc;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Arc;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface ArcOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface ArcEvent {
sender: Arc;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Circle extends kendo.drawing.Element {
options: CircleOptions;
constructor(geometry: kendo.geometry.Circle, options?: CircleOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
geometry(): kendo.geometry.Circle;
geometry(value: kendo.geometry.Circle): void;
fill(color: string, opacity?: number): kendo.drawing.Circle;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Circle;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface CircleOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface CircleEvent {
sender: Circle;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Element extends kendo.Class {
options: ElementOptions;
parent: kendo.drawing.Group;
constructor(options?: ElementOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
opacity(): number;
opacity(opacity: number): void;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface ElementOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
opacity?: number;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface ElementEvent {
sender: Element;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface FillOptions {
color?: string;
opacity?: number;
}
class Gradient extends kendo.Class {
options: GradientOptions;
stops: any;
constructor(options?: GradientOptions);
addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop;
removeStop(stop: kendo.drawing.GradientStop): void;
}
interface GradientOptions {
name?: string;
stops?: any;
}
interface GradientEvent {
sender: Gradient;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class GradientStop extends kendo.Class {
options: GradientStopOptions;
constructor(options?: GradientStopOptions);
}
interface GradientStopOptions {
name?: string;
offset?: number;
color?: string;
opacity?: number;
}
interface GradientStopEvent {
sender: GradientStop;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Group extends kendo.drawing.Element {
options: GroupOptions;
children: any;
constructor(options?: GroupOptions);
append(element: kendo.drawing.Element): void;
clear(): void;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
insert(position: number, element: kendo.drawing.Element): void;
opacity(): number;
opacity(opacity: number): void;
remove(element: kendo.drawing.Element): void;
removeAt(index: number): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface GroupOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
opacity?: number;
pdf?: kendo.drawing.PDFOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface GroupEvent {
sender: Group;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Image extends kendo.drawing.Element {
options: ImageOptions;
constructor(src: string, rect: kendo.geometry.Rect);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
opacity(): number;
opacity(opacity: number): void;
src(): string;
src(value: string): void;
rect(): kendo.geometry.Rect;
rect(value: kendo.geometry.Rect): void;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface ImageOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
opacity?: number;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface ImageEvent {
sender: Image;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Layout extends kendo.drawing.Group {
options: LayoutOptions;
constructor(rect: kendo.geometry.Rect, options?: LayoutOptions);
rect(): kendo.geometry.Rect;
rect(rect: kendo.geometry.Rect): void;
reflow(): void;
}
interface LayoutOptions {
name?: string;
alignContent?: string;
alignItems?: string;
justifyContent?: string;
lineSpacing?: number;
spacing?: number;
orientation?: string;
wrap?: boolean;
}
interface LayoutEvent {
sender: Layout;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class LinearGradient extends kendo.drawing.Gradient {
options: LinearGradientOptions;
stops: any;
constructor(options?: LinearGradientOptions);
addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop;
end(): kendo.geometry.Point;
end(end: any): void;
end(end: kendo.geometry.Point): void;
start(): kendo.geometry.Point;
start(start: any): void;
start(start: kendo.geometry.Point): void;
removeStop(stop: kendo.drawing.GradientStop): void;
}
interface LinearGradientOptions {
name?: string;
stops?: any;
}
interface LinearGradientEvent {
sender: LinearGradient;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class MultiPath extends kendo.drawing.Element {
options: MultiPathOptions;
paths: any;
constructor(options?: MultiPathOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
close(): kendo.drawing.MultiPath;
containsPoint(point: kendo.geometry.Point): boolean;
curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.MultiPath;
curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath;
curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.MultiPath;
curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath;
curveTo(controlOut: kendo.geometry.Point, controlIn: any, endPoint: any): kendo.drawing.MultiPath;
curveTo(controlOut: kendo.geometry.Point, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath;
curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.MultiPath;
curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath;
fill(color: string, opacity?: number): kendo.drawing.MultiPath;
lineTo(x: number, y?: number): kendo.drawing.MultiPath;
lineTo(x: any, y?: number): kendo.drawing.MultiPath;
lineTo(x: kendo.geometry.Point, y?: number): kendo.drawing.MultiPath;
moveTo(x: number, y?: number): kendo.drawing.MultiPath;
moveTo(x: any, y?: number): kendo.drawing.MultiPath;
moveTo(x: kendo.geometry.Point, y?: number): kendo.drawing.MultiPath;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.MultiPath;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface MultiPathOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface MultiPathEvent {
sender: MultiPath;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class OptionsStore extends kendo.Class {
options: OptionsStoreOptions;
observer: any;
constructor(options?: OptionsStoreOptions);
get(field: string): any;
set(field: string, value: any): void;
}
interface OptionsStoreOptions {
name?: string;
}
interface OptionsStoreEvent {
sender: OptionsStore;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface PDFOptions {
creator?: string;
date?: Date;
imgDPI?: number;
keywords?: string;
landscape?: boolean;
margin?: any;
paperSize?: any;
subject?: string;
title?: string;
}
class Path extends kendo.drawing.Element {
options: PathOptions;
segments: any;
constructor(options?: PathOptions);
static fromArc(arc: kendo.geometry.Arc, options?: any): kendo.drawing.Path;
static fromPoints(points: any, options?: any): kendo.drawing.Path;
static fromRect(rect: kendo.geometry.Rect, options?: any): kendo.drawing.Path;
static parse(svgPath: string, options?: any): kendo.drawing.MultiPath;
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
close(): kendo.drawing.Path;
containsPoint(point: kendo.geometry.Point): boolean;
curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.Path;
curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.Path;
curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.Path;
curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: kendo.geometry.Point): kendo.drawing.Path;
curveTo(controlOut: kendo.geometry.Point, controlIn: any, endPoint: any): kendo.drawing.Path;
curveTo(controlOut: kendo.geometry.Point, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.Path;
curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.Path;
curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point, endPoint: kendo.geometry.Point): kendo.drawing.Path;
fill(color: string, opacity?: number): kendo.drawing.Path;
lineTo(x: number, y?: number): kendo.drawing.Path;
lineTo(x: any, y?: number): kendo.drawing.Path;
lineTo(x: kendo.geometry.Point, y?: number): kendo.drawing.Path;
moveTo(x: number, y?: number): kendo.drawing.Path;
moveTo(x: any, y?: number): kendo.drawing.Path;
moveTo(x: kendo.geometry.Point, y?: number): kendo.drawing.Path;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Path;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface PathOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface PathEvent {
sender: Path;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class RadialGradient extends kendo.drawing.Gradient {
options: RadialGradientOptions;
stops: any;
constructor(options?: RadialGradientOptions);
addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop;
center(): kendo.geometry.Point;
center(center: any): void;
center(center: kendo.geometry.Point): void;
radius(): number;
radius(value: number): void;
removeStop(stop: kendo.drawing.GradientStop): void;
}
interface RadialGradientOptions {
name?: string;
center?: any|kendo.geometry.Point;
radius?: number;
stops?: any;
}
interface RadialGradientEvent {
sender: RadialGradient;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Rect extends kendo.drawing.Element {
options: RectOptions;
constructor(geometry: kendo.geometry.Rect, options?: RectOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
geometry(): kendo.geometry.Rect;
geometry(value: kendo.geometry.Rect): void;
fill(color: string, opacity?: number): kendo.drawing.Rect;
opacity(): number;
opacity(opacity: number): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Rect;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface RectOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface RectEvent {
sender: Rect;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Segment extends kendo.Class {
options: SegmentOptions;
constructor(anchor: kendo.geometry.Point, controlIn: kendo.geometry.Point, controlOut: kendo.geometry.Point);
anchor(): kendo.geometry.Point;
anchor(value: kendo.geometry.Point): void;
controlIn(): kendo.geometry.Point;
controlIn(value: kendo.geometry.Point): void;
controlOut(): kendo.geometry.Point;
controlOut(value: kendo.geometry.Point): void;
}
interface SegmentOptions {
name?: string;
}
interface SegmentEvent {
sender: Segment;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface StrokeOptions {
color?: string;
dashType?: string;
lineCap?: string;
lineJoin?: string;
opacity?: number;
width?: number;
}
class Surface extends kendo.Observable {
options: SurfaceOptions;
constructor(options?: SurfaceOptions);
static create(element: JQuery, options?: any): kendo.drawing.Surface;
static create(element: Element, options?: any): kendo.drawing.Surface;
element: JQuery;
clear(): void;
draw(element: kendo.drawing.Element): void;
eventTarget(e: any): kendo.drawing.Element;
hideTooltip(): void;
resize(force?: boolean): void;
showTooltip(element: kendo.drawing.Element, options?: any): void;
}
interface SurfaceTooltipAnimationClose {
effects?: string;
duration?: number;
}
interface SurfaceTooltipAnimationOpen {
effects?: string;
duration?: number;
}
interface SurfaceTooltipAnimation {
close?: SurfaceTooltipAnimationClose;
open?: SurfaceTooltipAnimationOpen;
}
interface SurfaceTooltip {
animation?: boolean | SurfaceTooltipAnimation;
appendTo?: string|JQuery;
}
interface SurfaceOptions {
name?: string;
type?: string;
height?: string;
width?: string;
tooltip?: SurfaceTooltip;
click?(e: SurfaceClickEvent): void;
mouseenter?(e: SurfaceMouseenterEvent): void;
mouseleave?(e: SurfaceMouseleaveEvent): void;
tooltipClose?(e: SurfaceTooltipCloseEvent): void;
tooltipOpen?(e: SurfaceTooltipOpenEvent): void;
}
interface SurfaceEvent {
sender: Surface;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface SurfaceClickEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
originalEvent?: any;
}
interface SurfaceMouseenterEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
originalEvent?: any;
}
interface SurfaceMouseleaveEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
originalEvent?: any;
}
interface SurfaceTooltipCloseEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
target?: kendo.drawing.Element;
}
interface SurfaceTooltipOpenEvent extends SurfaceEvent {
element?: kendo.drawing.Element;
target?: kendo.drawing.Element;
}
class Text extends kendo.drawing.Element {
options: TextOptions;
constructor(content: string, position: kendo.geometry.Point, options?: TextOptions);
bbox(): kendo.geometry.Rect;
clip(): kendo.drawing.Path;
clip(clip: kendo.drawing.Path): void;
clippedBBox(): kendo.geometry.Rect;
containsPoint(point: kendo.geometry.Point): boolean;
content(): string;
content(value: string): void;
fill(color: string, opacity?: number): kendo.drawing.Text;
opacity(): number;
opacity(opacity: number): void;
position(): kendo.geometry.Point;
position(value: kendo.geometry.Point): void;
stroke(color: string, width?: number, opacity?: number): kendo.drawing.Text;
transform(): kendo.geometry.Transformation;
transform(transform: kendo.geometry.Transformation): void;
visible(): boolean;
visible(visible: boolean): void;
}
interface TextOptions {
name?: string;
clip?: kendo.drawing.Path;
cursor?: string;
fill?: kendo.drawing.FillOptions;
font?: string;
opacity?: number;
stroke?: kendo.drawing.StrokeOptions;
tooltip?: kendo.drawing.TooltipOptions;
transform?: kendo.geometry.Transformation;
visible?: boolean;
}
interface TextEvent {
sender: Text;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
interface TooltipOptions {
autoHide?: boolean;
content?: string|Function;
position?: string;
height?: number|string;
hideDelay?: number;
offset?: number;
shared?: boolean;
showAfter?: number;
showOn?: string;
width?: number|string;
}
}
declare namespace kendo.dataviz.geometry {
class Arc extends Observable {
options: ArcOptions;
anticlockwise: boolean;
center: kendo.geometry.Point;
endAngle: number;
radiusX: number;
radiusY: number;
startAngle: number;
constructor(center: any|kendo.geometry.Point, options?: ArcOptions);
bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect;
getAnticlockwise(): boolean;
getCenter(): kendo.geometry.Point;
getEndAngle(): number;
getRadiusX(): number;
getRadiusY(): number;
getStartAngle(): number;
pointAt(angle: number): kendo.geometry.Point;
setAnticlockwise(value: boolean): kendo.geometry.Arc;
setCenter(value: kendo.geometry.Point): kendo.geometry.Arc;
setEndAngle(value: number): kendo.geometry.Arc;
setRadiusX(value: number): kendo.geometry.Arc;
setRadiusY(value: number): kendo.geometry.Arc;
setStartAngle(value: number): kendo.geometry.Arc;
}
interface ArcOptions {
name?: string;
}
interface ArcEvent {
sender: Arc;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Circle extends Observable {
options: CircleOptions;
center: kendo.geometry.Point;
radius: number;
constructor(center: any|kendo.geometry.Point, radius: number);
bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect;
clone(): kendo.geometry.Circle;
equals(other: kendo.geometry.Circle): boolean;
getCenter(): kendo.geometry.Point;
getRadius(): number;
pointAt(angle: number): kendo.geometry.Point;
setCenter(value: kendo.geometry.Point): kendo.geometry.Point;
setCenter(value: any): kendo.geometry.Point;
setRadius(value: number): kendo.geometry.Circle;
}
interface CircleOptions {
name?: string;
}
interface CircleEvent {
sender: Circle;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Matrix extends Observable {
options: MatrixOptions;
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix;
static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix;
static translate(x: number, y: number): kendo.geometry.Matrix;
static unit(): kendo.geometry.Matrix;
clone(): kendo.geometry.Matrix;
equals(other: kendo.geometry.Matrix): boolean;
round(digits: number): kendo.geometry.Matrix;
multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix;
toArray(digits: number): any;
toString(digits: number, separator: string): string;
}
interface MatrixOptions {
name?: string;
}
interface MatrixEvent {
sender: Matrix;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Point extends Observable {
options: PointOptions;
x: number;
y: number;
constructor(x: number, y: number);
static create(x: number, y: number): kendo.geometry.Point;
static create(x: any, y: number): kendo.geometry.Point;
static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point;
static min(): kendo.geometry.Point;
static max(): kendo.geometry.Point;
static minPoint(): kendo.geometry.Point;
static maxPoint(): kendo.geometry.Point;
clone(): kendo.geometry.Point;
distanceTo(point: kendo.geometry.Point): number;
equals(other: kendo.geometry.Point): boolean;
getX(): number;
getY(): number;
move(x: number, y: number): kendo.geometry.Point;
rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point;
rotate(angle: number, center: any): kendo.geometry.Point;
round(digits: number): kendo.geometry.Point;
scale(scaleX: number, scaleY: number): kendo.geometry.Point;
scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point;
setX(value: number): kendo.geometry.Point;
setY(value: number): kendo.geometry.Point;
toArray(digits: number): any;
toString(digits: number, separator: string): string;
transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point;
transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point;
translate(dx: number, dy: number): kendo.geometry.Point;
translateWith(vector: kendo.geometry.Point): kendo.geometry.Point;
translateWith(vector: any): kendo.geometry.Point;
}
interface PointOptions {
name?: string;
}
interface PointEvent {
sender: Point;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Rect extends Observable {
options: RectOptions;
origin: kendo.geometry.Point;
size: kendo.geometry.Size;
constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any);
static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect;
static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect;
bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect;
bottomLeft(): kendo.geometry.Point;
bottomRight(): kendo.geometry.Point;
center(): kendo.geometry.Point;
clone(): kendo.geometry.Rect;
equals(other: kendo.geometry.Rect): boolean;
getOrigin(): kendo.geometry.Point;
getSize(): kendo.geometry.Size;
height(): number;
setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect;
setOrigin(value: any): kendo.geometry.Rect;
setSize(value: kendo.geometry.Size): kendo.geometry.Rect;
setSize(value: any): kendo.geometry.Rect;
topLeft(): kendo.geometry.Point;
topRight(): kendo.geometry.Point;
width(): number;
}
interface RectOptions {
name?: string;
}
interface RectEvent {
sender: Rect;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Size extends Observable {
options: SizeOptions;
width: number;
height: number;
static create(width: number, height: number): kendo.geometry.Size;
static create(width: any, height: number): kendo.geometry.Size;
static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size;
clone(): kendo.geometry.Size;
equals(other: kendo.geometry.Size): boolean;
getWidth(): number;
getHeight(): number;
setWidth(value: number): kendo.geometry.Size;
setHeight(value: number): kendo.geometry.Size;
}
interface SizeOptions {
name?: string;
}
interface SizeEvent {
sender: Size;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
class Transformation extends Observable {
options: TransformationOptions;
clone(): kendo.geometry.Transformation;
equals(other: kendo.geometry.Transformation): boolean;
matrix(): kendo.geometry.Matrix;
multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation;
rotate(angle: number, center: any): kendo.geometry.Transformation;
rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation;
scale(scaleX: number, scaleY: number): kendo.geometry.Transformation;
translate(x: number, y: number): kendo.geometry.Transformation;
}
interface TransformationOptions {
name?: string;
}
interface TransformationEvent {
sender: Transformation;
preventDefault: Function;
isDefaultPrevented(): boolean;
}
}
interface HTMLElement {
kendoBindingTarget: kendo.data.BindingTarget;
}
interface JQueryAjaxSettings {
}
interface JQueryXHR {
}
interface JQueryEventObject {
}
interface JQueryPromise<T> {
}
interface JQuery {
data(key: any): any;
kendoAlert(): JQuery;
kendoAlert(options: kendo.ui.AlertOptions): JQuery;
data(key: "kendoAlert"): kendo.ui.Alert;
kendoArcGauge(): JQuery;
kendoArcGauge(options: kendo.dataviz.ui.ArcGaugeOptions): JQuery;
data(key: "kendoArcGauge"): kendo.dataviz.ui.ArcGauge;
kendoAutoComplete(): JQuery;
kendoAutoComplete(options: kendo.ui.AutoCompleteOptions): JQuery;
data(key: "kendoAutoComplete"): kendo.ui.AutoComplete;
kendoBarcode(): JQuery;
kendoBarcode(options: kendo.dataviz.ui.BarcodeOptions): JQuery;
data(key: "kendoBarcode"): kendo.dataviz.ui.Barcode;
kendoButton(): JQuery;
kendoButton(options: kendo.ui.ButtonOptions): JQuery;
data(key: "kendoButton"): kendo.ui.Button;
kendoButtonGroup(): JQuery;
kendoButtonGroup(options: kendo.ui.ButtonGroupOptions): JQuery;
data(key: "kendoButtonGroup"): kendo.ui.ButtonGroup;
kendoCalendar(): JQuery;
kendoCalendar(options: kendo.ui.CalendarOptions): JQuery;
data(key: "kendoCalendar"): kendo.ui.Calendar;
kendoChart(): JQuery;
kendoChart(options: kendo.dataviz.ui.ChartOptions): JQuery;
data(key: "kendoChart"): kendo.dataviz.ui.Chart;
kendoChat(): JQuery;
kendoChat(options: kendo.ui.ChatOptions): JQuery;
data(key: "kendoChat"): kendo.ui.Chat;
kendoColorPalette(): JQuery;
kendoColorPalette(options: kendo.ui.ColorPaletteOptions): JQuery;
data(key: "kendoColorPalette"): kendo.ui.ColorPalette;
kendoColorPicker(): JQuery;
kendoColorPicker(options: kendo.ui.ColorPickerOptions): JQuery;
data(key: "kendoColorPicker"): kendo.ui.ColorPicker;
kendoComboBox(): JQuery;
kendoComboBox(options: kendo.ui.ComboBoxOptions): JQuery;
data(key: "kendoComboBox"): kendo.ui.ComboBox;
kendoConfirm(): JQuery;
kendoConfirm(options: kendo.ui.ConfirmOptions): JQuery;
data(key: "kendoConfirm"): kendo.ui.Confirm;
kendoContextMenu(): JQuery;
kendoContextMenu(options: kendo.ui.ContextMenuOptions): JQuery;
data(key: "kendoContextMenu"): kendo.ui.ContextMenu;
kendoDateInput(): JQuery;
kendoDateInput(options: kendo.ui.DateInputOptions): JQuery;
data(key: "kendoDateInput"): kendo.ui.DateInput;
kendoDatePicker(): JQuery;
kendoDatePicker(options: kendo.ui.DatePickerOptions): JQuery;
data(key: "kendoDatePicker"): kendo.ui.DatePicker;
kendoDateRangePicker(): JQuery;
kendoDateRangePicker(options: kendo.ui.DateRangePickerOptions): JQuery;
data(key: "kendoDateRangePicker"): kendo.ui.DateRangePicker;
kendoDateTimePicker(): JQuery;
kendoDateTimePicker(options: kendo.ui.DateTimePickerOptions): JQuery;
data(key: "kendoDateTimePicker"): kendo.ui.DateTimePicker;
kendoDiagram(): JQuery;
kendoDiagram(options: kendo.dataviz.ui.DiagramOptions): JQuery;
data(key: "kendoDiagram"): kendo.dataviz.ui.Diagram;
kendoDialog(): JQuery;
kendoDialog(options: kendo.ui.DialogOptions): JQuery;
data(key: "kendoDialog"): kendo.ui.Dialog;
kendoDraggable(): JQuery;
kendoDraggable(options: kendo.ui.DraggableOptions): JQuery;
data(key: "kendoDraggable"): kendo.ui.Draggable;
kendoDropDownList(): JQuery;
kendoDropDownList(options: kendo.ui.DropDownListOptions): JQuery;
data(key: "kendoDropDownList"): kendo.ui.DropDownList;
kendoDropDownTree(): JQuery;
kendoDropDownTree(options: kendo.ui.DropDownTreeOptions): JQuery;
data(key: "kendoDropDownTree"): kendo.ui.DropDownTree;
kendoDropTarget(): JQuery;
kendoDropTarget(options: kendo.ui.DropTargetOptions): JQuery;
data(key: "kendoDropTarget"): kendo.ui.DropTarget;
kendoDropTargetArea(): JQuery;
kendoDropTargetArea(options: kendo.ui.DropTargetAreaOptions): JQuery;
data(key: "kendoDropTargetArea"): kendo.ui.DropTargetArea;
kendoEditor(): JQuery;
kendoEditor(options: kendo.ui.EditorOptions): JQuery;
data(key: "kendoEditor"): kendo.ui.Editor;
kendoFilterMenu(): JQuery;
kendoFilterMenu(options: kendo.ui.FilterMenuOptions): JQuery;
data(key: "kendoFilterMenu"): kendo.ui.FilterMenu;
kendoFlatColorPicker(): JQuery;
kendoFlatColorPicker(options: kendo.ui.FlatColorPickerOptions): JQuery;
data(key: "kendoFlatColorPicker"): kendo.ui.FlatColorPicker;
kendoGantt(): JQuery;
kendoGantt(options: kendo.ui.GanttOptions): JQuery;
data(key: "kendoGantt"): kendo.ui.Gantt;
kendoGrid(): JQuery;
kendoGrid(options: kendo.ui.GridOptions): JQuery;
data(key: "kendoGrid"): kendo.ui.Grid;
kendoLinearGauge(): JQuery;
kendoLinearGauge(options: kendo.dataviz.ui.LinearGaugeOptions): JQuery;
data(key: "kendoLinearGauge"): kendo.dataviz.ui.LinearGauge;
kendoListBox(): JQuery;
kendoListBox(options: kendo.ui.ListBoxOptions): JQuery;
data(key: "kendoListBox"): kendo.ui.ListBox;
kendoListView(): JQuery;
kendoListView(options: kendo.ui.ListViewOptions): JQuery;
data(key: "kendoListView"): kendo.ui.ListView;
kendoMap(): JQuery;
kendoMap(options: kendo.dataviz.ui.MapOptions): JQuery;
data(key: "kendoMap"): kendo.dataviz.ui.Map;
kendoMaskedTextBox(): JQuery;
kendoMaskedTextBox(options: kendo.ui.MaskedTextBoxOptions): JQuery;
data(key: "kendoMaskedTextBox"): kendo.ui.MaskedTextBox;
kendoMediaPlayer(): JQuery;
kendoMediaPlayer(options: kendo.ui.MediaPlayerOptions): JQuery;
data(key: "kendoMediaPlayer"): kendo.ui.MediaPlayer;
kendoMenu(): JQuery;
kendoMenu(options: kendo.ui.MenuOptions): JQuery;
data(key: "kendoMenu"): kendo.ui.Menu;
kendoMobileActionSheet(): JQuery;
kendoMobileActionSheet(options: kendo.mobile.ui.ActionSheetOptions): JQuery;
data(key: "kendoMobileActionSheet"): kendo.mobile.ui.ActionSheet;
kendoMobileBackButton(): JQuery;
kendoMobileBackButton(options: kendo.mobile.ui.BackButtonOptions): JQuery;
data(key: "kendoMobileBackButton"): kendo.mobile.ui.BackButton;
kendoMobileButton(): JQuery;
kendoMobileButton(options: kendo.mobile.ui.ButtonOptions): JQuery;
data(key: "kendoMobileButton"): kendo.mobile.ui.Button;
kendoMobileButtonGroup(): JQuery;
kendoMobileButtonGroup(options: kendo.mobile.ui.ButtonGroupOptions): JQuery;
data(key: "kendoMobileButtonGroup"): kendo.mobile.ui.ButtonGroup;
kendoMobileCollapsible(): JQuery;
kendoMobileCollapsible(options: kendo.mobile.ui.CollapsibleOptions): JQuery;
data(key: "kendoMobileCollapsible"): kendo.mobile.ui.Collapsible;
kendoMobileDetailButton(): JQuery;
kendoMobileDetailButton(options: kendo.mobile.ui.DetailButtonOptions): JQuery;
data(key: "kendoMobileDetailButton"): kendo.mobile.ui.DetailButton;
kendoMobileDrawer(): JQuery;
kendoMobileDrawer(options: kendo.mobile.ui.DrawerOptions): JQuery;
data(key: "kendoMobileDrawer"): kendo.mobile.ui.Drawer;
kendoMobileLayout(): JQuery;
kendoMobileLayout(options: kendo.mobile.ui.LayoutOptions): JQuery;
data(key: "kendoMobileLayout"): kendo.mobile.ui.Layout;
kendoMobileListView(): JQuery;
kendoMobileListView(options: kendo.mobile.ui.ListViewOptions): JQuery;
data(key: "kendoMobileListView"): kendo.mobile.ui.ListView;
kendoMobileLoader(): JQuery;
kendoMobileLoader(options: kendo.mobile.ui.LoaderOptions): JQuery;
data(key: "kendoMobileLoader"): kendo.mobile.ui.Loader;
kendoMobileModalView(): JQuery;
kendoMobileModalView(options: kendo.mobile.ui.ModalViewOptions): JQuery;
data(key: "kendoMobileModalView"): kendo.mobile.ui.ModalView;
kendoMobileNavBar(): JQuery;
kendoMobileNavBar(options: kendo.mobile.ui.NavBarOptions): JQuery;
data(key: "kendoMobileNavBar"): kendo.mobile.ui.NavBar;
kendoMobilePane(): JQuery;
kendoMobilePane(options: kendo.mobile.ui.PaneOptions): JQuery;
data(key: "kendoMobilePane"): kendo.mobile.ui.Pane;
kendoMobilePopOver(): JQuery;
kendoMobilePopOver(options: kendo.mobile.ui.PopOverOptions): JQuery;
data(key: "kendoMobilePopOver"): kendo.mobile.ui.PopOver;
kendoMobileScrollView(): JQuery;
kendoMobileScrollView(options: kendo.mobile.ui.ScrollViewOptions): JQuery;
data(key: "kendoMobileScrollView"): kendo.mobile.ui.ScrollView;
kendoMobileScroller(): JQuery;
kendoMobileScroller(options: kendo.mobile.ui.ScrollerOptions): JQuery;
data(key: "kendoMobileScroller"): kendo.mobile.ui.Scroller;
kendoMobileSplitView(): JQuery;
kendoMobileSplitView(options: kendo.mobile.ui.SplitViewOptions): JQuery;
data(key: "kendoMobileSplitView"): kendo.mobile.ui.SplitView;
kendoMobileSwitch(): JQuery;
kendoMobileSwitch(options: kendo.mobile.ui.SwitchOptions): JQuery;
data(key: "kendoMobileSwitch"): kendo.mobile.ui.Switch;
kendoMobileTabStrip(): JQuery;
kendoMobileTabStrip(options: kendo.mobile.ui.TabStripOptions): JQuery;
data(key: "kendoMobileTabStrip"): kendo.mobile.ui.TabStrip;
kendoMobileView(): JQuery;
kendoMobileView(options: kendo.mobile.ui.ViewOptions): JQuery;
data(key: "kendoMobileView"): kendo.mobile.ui.View;
kendoMultiColumnComboBox(): JQuery;
kendoMultiColumnComboBox(options: kendo.ui.MultiColumnComboBoxOptions): JQuery;
data(key: "kendoMultiColumnComboBox"): kendo.ui.MultiColumnComboBox;
kendoMultiSelect(): JQuery;
kendoMultiSelect(options: kendo.ui.MultiSelectOptions): JQuery;
data(key: "kendoMultiSelect"): kendo.ui.MultiSelect;
kendoMultiViewCalendar(): JQuery;
kendoMultiViewCalendar(options: kendo.ui.MultiViewCalendarOptions): JQuery;
data(key: "kendoMultiViewCalendar"): kendo.ui.MultiViewCalendar;
kendoNotification(): JQuery;
kendoNotification(options: kendo.ui.NotificationOptions): JQuery;
data(key: "kendoNotification"): kendo.ui.Notification;
kendoNumericTextBox(): JQuery;
kendoNumericTextBox(options: kendo.ui.NumericTextBoxOptions): JQuery;
data(key: "kendoNumericTextBox"): kendo.ui.NumericTextBox;
kendoPager(): JQuery;
kendoPager(options: kendo.ui.PagerOptions): JQuery;
data(key: "kendoPager"): kendo.ui.Pager;
kendoPanelBar(): JQuery;
kendoPanelBar(options: kendo.ui.PanelBarOptions): JQuery;
data(key: "kendoPanelBar"): kendo.ui.PanelBar;
kendoPivotConfigurator(): JQuery;
kendoPivotConfigurator(options: kendo.ui.PivotConfiguratorOptions): JQuery;
data(key: "kendoPivotConfigurator"): kendo.ui.PivotConfigurator;
kendoPivotGrid(): JQuery;
kendoPivotGrid(options: kendo.ui.PivotGridOptions): JQuery;
data(key: "kendoPivotGrid"): kendo.ui.PivotGrid;
kendoPopup(): JQuery;
kendoPopup(options: kendo.ui.PopupOptions): JQuery;
data(key: "kendoPopup"): kendo.ui.Popup;
kendoProgressBar(): JQuery;
kendoProgressBar(options: kendo.ui.ProgressBarOptions): JQuery;
data(key: "kendoProgressBar"): kendo.ui.ProgressBar;
kendoPrompt(): JQuery;
kendoPrompt(options: kendo.ui.PromptOptions): JQuery;
data(key: "kendoPrompt"): kendo.ui.Prompt;
kendoQRCode(): JQuery;
kendoQRCode(options: kendo.dataviz.ui.QRCodeOptions): JQuery;
data(key: "kendoQRCode"): kendo.dataviz.ui.QRCode;
kendoRadialGauge(): JQuery;
kendoRadialGauge(options: kendo.dataviz.ui.RadialGaugeOptions): JQuery;
data(key: "kendoRadialGauge"): kendo.dataviz.ui.RadialGauge;
kendoRangeSlider(): JQuery;
kendoRangeSlider(options: kendo.ui.RangeSliderOptions): JQuery;
data(key: "kendoRangeSlider"): kendo.ui.RangeSlider;
kendoResponsivePanel(): JQuery;
kendoResponsivePanel(options: kendo.ui.ResponsivePanelOptions): JQuery;
data(key: "kendoResponsivePanel"): kendo.ui.ResponsivePanel;
kendoScheduler(): JQuery;
kendoScheduler(options: kendo.ui.SchedulerOptions): JQuery;
data(key: "kendoScheduler"): kendo.ui.Scheduler;
kendoScrollView(): JQuery;
kendoScrollView(options: kendo.ui.ScrollViewOptions): JQuery;
data(key: "kendoScrollView"): kendo.ui.ScrollView;
kendoSlider(): JQuery;
kendoSlider(options: kendo.ui.SliderOptions): JQuery;
data(key: "kendoSlider"): kendo.ui.Slider;
kendoSortable(): JQuery;
kendoSortable(options: kendo.ui.SortableOptions): JQuery;
data(key: "kendoSortable"): kendo.ui.Sortable;
kendoSparkline(): JQuery;
kendoSparkline(options: kendo.dataviz.ui.SparklineOptions): JQuery;
data(key: "kendoSparkline"): kendo.dataviz.ui.Sparkline;
kendoSplitter(): JQuery;
kendoSplitter(options: kendo.ui.SplitterOptions): JQuery;
data(key: "kendoSplitter"): kendo.ui.Splitter;
kendoSpreadsheet(): JQuery;
kendoSpreadsheet(options: kendo.ui.SpreadsheetOptions): JQuery;
data(key: "kendoSpreadsheet"): kendo.ui.Spreadsheet;
kendoStockChart(): JQuery;
kendoStockChart(options: kendo.dataviz.ui.StockChartOptions): JQuery;
data(key: "kendoStockChart"): kendo.dataviz.ui.StockChart;
kendoSwitch(): JQuery;
kendoSwitch(options: kendo.ui.SwitchOptions): JQuery;
data(key: "kendoSwitch"): kendo.ui.Switch;
kendoTabStrip(): JQuery;
kendoTabStrip(options: kendo.ui.TabStripOptions): JQuery;
data(key: "kendoTabStrip"): kendo.ui.TabStrip;
kendoTimePicker(): JQuery;
kendoTimePicker(options: kendo.ui.TimePickerOptions): JQuery;
data(key: "kendoTimePicker"): kendo.ui.TimePicker;
kendoToolBar(): JQuery;
kendoToolBar(options: kendo.ui.ToolBarOptions): JQuery;
data(key: "kendoToolBar"): kendo.ui.ToolBar;
kendoTooltip(): JQuery;
kendoTooltip(options: kendo.ui.TooltipOptions): JQuery;
data(key: "kendoTooltip"): kendo.ui.Tooltip;
kendoTouch(): JQuery;
kendoTouch(options: kendo.ui.TouchOptions): JQuery;
data(key: "kendoTouch"): kendo.ui.Touch;
kendoTreeList(): JQuery;
kendoTreeList(options: kendo.ui.TreeListOptions): JQuery;
data(key: "kendoTreeList"): kendo.ui.TreeList;
kendoTreeMap(): JQuery;
kendoTreeMap(options: kendo.dataviz.ui.TreeMapOptions): JQuery;
data(key: "kendoTreeMap"): kendo.dataviz.ui.TreeMap;
kendoTreeView(): JQuery;
kendoTreeView(options: kendo.ui.TreeViewOptions): JQuery;
data(key: "kendoTreeView"): kendo.ui.TreeView;
kendoUpload(): JQuery;
kendoUpload(options: kendo.ui.UploadOptions): JQuery;
data(key: "kendoUpload"): kendo.ui.Upload;
kendoValidator(): JQuery;
kendoValidator(options: kendo.ui.ValidatorOptions): JQuery;
data(key: "kendoValidator"): kendo.ui.Validator;
kendoWindow(): JQuery;
kendoWindow(options: kendo.ui.WindowOptions): JQuery;
data(key: "kendoWindow"): kendo.ui.Window;
} | }
interface ChartXAxisItemCrosshairTooltipPadding { |
test_nest.py | """
Collection of tests for unified general functions
"""
# global
import copy
import pytest
# local
import ivy
import ivy.functional.backends.numpy
# Helpers #
# --------#
def _snai(n, idx, v):
if len(idx) == 1:
n[idx[0]] = v
else:
_snai(n[idx[0]], idx[1:], v)
def _mnai(n, idx, fn):
if len(idx) == 1:
n[idx[0]] = fn(n[idx[0]])
else:
_mnai(n[idx[0]], idx[1:], fn)
# Tests #
# ------#
# index_nest
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": (((2,), (4,)), ((6,), (8,)))}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0), ("b", "c", 1, 0)]
)
def test_index_nest(nest, index, device, call):
ret = ivy.index_nest(nest, index)
true_ret = nest
for i in index:
true_ret = true_ret[i]
assert ret == true_ret
# set_nest_at_index
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0), ("b", "c", 1, 0)]
)
@pytest.mark.parametrize("value", [1])
def test_set_nest_at_index(nest, index, value, device, call):
|
# map_nest_at_index
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"index", [("a", 0, 0), ("a", 1, 0), ("b", "c", 0, 0, 0), ("b", "c", 1, 0, 0)]
)
@pytest.mark.parametrize("fn", [lambda x: x + 2, lambda x: x**2])
def test_map_nest_at_index(nest, index, fn, device, call):
nest_copy = copy.deepcopy(nest)
ivy.map_nest_at_index(nest, index, fn)
_mnai(nest_copy, index, fn)
assert nest == nest_copy
# multi_index_nest
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": (((2,), (4,)), ((6,), (8,)))}}]
)
@pytest.mark.parametrize(
"multi_indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0), ("b", "c", 1, 0))]
)
def test_multi_index_nest(nest, multi_indices, device, call):
rets = ivy.multi_index_nest(nest, multi_indices)
true_rets = list()
for indices in multi_indices:
true_ret = nest
for i in indices:
true_ret = true_ret[i]
true_rets.append(true_ret)
assert rets == true_rets
# set_nest_at_indices
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0), ("b", "c", 1, 0))]
)
@pytest.mark.parametrize("values", [(1, 2)])
def test_set_nest_at_indices(nest, indices, values, device, call):
nest_copy = copy.deepcopy(nest)
ivy.set_nest_at_indices(nest, indices, values)
def snais(n, idxs, vs):
[_snai(n, index, value) for index, value in zip(idxs, vs)]
snais(nest_copy, indices, values)
assert nest == nest_copy
# map_nest_at_indices
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
@pytest.mark.parametrize(
"indices", [(("a", 0, 0), ("a", 1, 0)), (("b", "c", 0, 0, 0), ("b", "c", 1, 0, 0))]
)
@pytest.mark.parametrize("fn", [lambda x: x + 2, lambda x: x**2])
def test_map_nest_at_indices(nest, indices, fn, device, call):
nest_copy = copy.deepcopy(nest)
ivy.map_nest_at_indices(nest, indices, fn)
def mnais(n, idxs, vs):
[_mnai(n, index, fn) for index in idxs]
mnais(nest_copy, indices, fn)
assert nest == nest_copy
# nested_indices_where
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_nested_indices_where(nest, device, call):
indices = ivy.nested_indices_where(nest, lambda x: x < 5)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 1, 0]
assert indices[2] == ["b", "c", 0, 0, 0]
assert indices[3] == ["b", "c", 0, 1, 0]
# nested_indices_where_w_nest_checks
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_nested_indices_where_w_nest_checks(nest, device, call):
indices = ivy.nested_indices_where(
nest, lambda x: isinstance(x, list) or (isinstance(x, int) and x < 5), True
)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 0]
assert indices[2] == ["a", 1, 0]
assert indices[3] == ["a", 1]
assert indices[4] == ["a"]
assert indices[5] == ["b", "c", 0, 0, 0]
assert indices[6] == ["b", "c", 0, 0]
assert indices[7] == ["b", "c", 0, 1, 0]
assert indices[8] == ["b", "c", 0, 1]
assert indices[9] == ["b", "c", 0]
assert indices[10] == ["b", "c", 1, 0]
assert indices[11] == ["b", "c", 1, 1]
assert indices[12] == ["b", "c", 1]
assert indices[13] == ["b", "c"]
# all_nested_indices
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_all_nested_indices(nest, device, call):
indices = ivy.all_nested_indices(nest)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 1, 0]
assert indices[2] == ["b", "c", 0, 0, 0]
assert indices[3] == ["b", "c", 0, 1, 0]
assert indices[4] == ["b", "c", 1, 0, 0]
assert indices[5] == ["b", "c", 1, 1, 0]
# all_nested_indices_w_nest_checks
@pytest.mark.parametrize(
"nest", [{"a": [[0], [1]], "b": {"c": [[[2], [4]], [[6], [8]]]}}]
)
def test_all_nested_indices_w_nest_checks(nest, device, call):
indices = ivy.all_nested_indices(nest, True)
assert indices[0] == ["a", 0, 0]
assert indices[1] == ["a", 0]
assert indices[2] == ["a", 1, 0]
assert indices[3] == ["a", 1]
assert indices[4] == ["a"]
assert indices[5] == ["b", "c", 0, 0, 0]
assert indices[6] == ["b", "c", 0, 0]
assert indices[7] == ["b", "c", 0, 1, 0]
assert indices[8] == ["b", "c", 0, 1]
assert indices[9] == ["b", "c", 0]
assert indices[10] == ["b", "c", 1, 0, 0]
assert indices[11] == ["b", "c", 1, 0]
assert indices[12] == ["b", "c", 1, 1, 0]
assert indices[13] == ["b", "c", 1, 1]
assert indices[14] == ["b", "c", 1]
assert indices[15] == ["b", "c"]
assert indices[16] == ["b"]
# copy_nest
def test_copy_nest(device, call):
nest = {
"a": [ivy.array([0]), ivy.array([1])],
"b": {"c": [ivy.array([[2], [4]]), ivy.array([[6], [8]])]},
}
nest_copy = ivy.copy_nest(nest)
# copied nests
assert nest["a"] is not nest_copy["a"]
assert nest["b"] is not nest_copy["b"]
assert nest["b"]["c"] is not nest_copy["b"]["c"]
# non-copied arrays
assert nest["a"][0] is nest_copy["a"][0]
assert nest["a"][1] is nest_copy["a"][1]
assert nest["b"]["c"][0] is nest_copy["b"]["c"][0]
assert nest["b"]["c"][1] is nest_copy["b"]["c"][1]
| nest_copy = copy.deepcopy(nest)
ivy.set_nest_at_index(nest, index, value)
_snai(nest_copy, index, value)
assert nest == nest_copy |
cliProcessMain.js | /*!--------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
(function(){
var e=["require","exports","vs/platform/instantiation/common/instantiation","vs/base/common/types","vs/nls!vs/code/node/cliProcessMain","path","vs/base/common/objects","vs/platform/log/common/log","vs/nls","vs/base/common/event","vs/base/common/strings","vs/base/common/lifecycle","vs/base/node/pfs","vs/platform/configuration/common/configuration","vs/platform/registry/common/platform","vs/platform/configuration/common/configurationRegistry","vs/base/common/platform","vs/platform/environment/common/environment","vs/platform/extensionManagement/common/extensionManagementUtil","vs/base/common/arrays","vs/platform/node/package","vs/base/common/async","vs/base/common/uri","vs/base/common/errors","fs","vs/base/common/paths","os","vs/platform/telemetry/common/telemetry","vs/platform/extensionManagement/common/extensionManagement","vs/platform/instantiation/common/serviceCollection","vs/base/common/network","vs/base/common/errorMessage","vs/platform/extensions/node/extensionValidator","vs/base/common/map","vs/base/node/request","vs/base/common/amd","vs/platform/node/product","vs/base/common/json","vs/platform/instantiation/common/descriptors","vs/base/node/extfs","vs/platform/configuration/common/configurationModels","vs/platform/request/node/request","vs/platform/extensionManagement/node/extensionManagementUtil","vs/base/common/uuid","vs/platform/node/zip","semver","vs/platform/extensions/common/extensions","vs/base/common/collections","vs/base/node/config","vs/platform/extensionManagement/node/extensionsManifestCache","vs/base/common/mime","vs/platform/instantiation/common/graph","vs/platform/download/common/download","vs/base/common/labels","vs/base/common/glob","vs/base/common/decorators","vs/base/common/assert","vs/platform/instantiation/common/instantiationService","vs/platform/request/node/requestService","vs/nls!vs/base/common/errorMessage","vs/platform/log/node/spdlogService","vs/base/node/paths","vs/base/common/date","vs/platform/environment/node/environmentService","vs/base/node/proxy","vs/nls!vs/platform/configuration/common/configurationRegistry","vs/nls!vs/platform/extensionManagement/common/extensionManagement","vs/nls!vs/platform/extensionManagement/node/extensionManagementService","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/nls!vs/platform/extensionManagement/node/extensionManagementUtil","vs/nls!vs/platform/extensions/node/extensionValidator","vs/nls!vs/platform/node/zip","vs/platform/configuration/node/configuration","vs/platform/configuration/node/configurationService","vs/nls!vs/platform/request/node/request","vs/platform/state/common/state","vs/platform/state/node/stateService","vs/nls!vs/platform/telemetry/common/telemetryService","vs/platform/telemetry/common/telemetryService","vs/platform/telemetry/common/telemetryUtils","vs/platform/telemetry/node/appInsightsAppender","vs/platform/extensionManagement/node/extensionManagementService","vs/platform/telemetry/node/commonProperties","url","vs/platform/extensionManagement/common/extensionNls","vs/platform/extensionManagement/node/extensionLifecycle","vs/platform/extensionManagement/node/extensionGalleryService","yazl","yauzl","applicationinsights","crypto","zlib","child_process","vs/base/common/cancellation","vs/base/common/resources","vs/code/node/cliProcessMain"],t=function(t){
for(var n=[],r=0,i=t.length;r<i;r++)n[r]=e[t[r]];return n};define(e[56],t([0,1]),function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ok=function(e,t){if(!e||null===e)throw new Error(t?"Assertion failed ("+t+")":"Assertion Failed")}}),define(e[47],t([0,1]),function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.prototype.hasOwnProperty;t.values=function(e){var t=[];for(var r in e)n.call(e,r)&&t.push(e[r]);return t},t.size=function(e){var t=0;for(var r in e)n.call(e,r)&&(t+=1);return t},t.first=function(e){for(var t in e)if(n.call(e,t))return e[t]},t.forEach=function(e,t){var r=function(r){if(n.call(e,r)&&!1===t({key:r,value:e[r]},function(){delete e[r]}))return{value:void 0}};for(var i in e){var o=r(i);if("object"==typeof o)return o.value}},t.groupBy=function(e,t){for(var n=Object.create(null),r=0,i=e;r<i.length;r++){var o=i[r],s=t(o),a=n[s];a||(a=n[s]=[]),a.push(o)}return n},t.fromMap=function(e){var t=Object.create(null)
;return e&&e.forEach(function(e,n){t[n]=e}),t}}),define(e[55],t([0,1]),function(e,t){"use strict";function n(e){return function(t,n,r){var i=null,o=null;if("function"==typeof r.value?(i="value",o=r.value):"function"==typeof r.get&&(i="get",o=r.get),!o)throw new Error("not supported");r[i]=e(o,n)}}Object.defineProperty(t,"__esModule",{value:!0}),t.createDecorator=n,t.memoize=function(e,t,n){var r=null,i=null;if("function"==typeof n.value?(r="value",0!==(i=n.value).length&&console.warn("Memoize should only be used in functions with zero parameters")):"function"==typeof n.get&&(r="get",i=n.get),!i)throw new Error("not supported");var o="$memoize$"+t;n[r]=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[o]}},t.debounce=function(e,t,r){return n(function(n,i){var o="$debounce$"+i,s="$debounce$result$"+i;return function(){
for(var i=this,a=[],u=0;u<arguments.length;u++)a[u]=arguments[u];this[s]||(this[s]=r?r():void 0),clearTimeout(this[o]),t&&(this[s]=t.apply(void 0,[this[s]].concat(a)),a=[this[s]]),this[o]=setTimeout(function(){n.apply(i,a),i[s]=r?r():void 0},e)}})}}),define(e[37],t([0,1]),function(e,t){"use strict";function n(e,t){function n(t,n){for(var r=0,i=0;r<t||!n;){var o=e.charCodeAt(a);if(o>=48&&o<=57)i=16*i+o-48;else if(o>=65&&o<=70)i=16*i+o-65+10;else{if(!(o>=97&&o<=102))break;i=16*i+o-97+10}a++,r++}return r<t&&(i=-1),i}function s(){if(c="",p=0,l=a,a>=u)return l=u,f=17;var t=e.charCodeAt(a);if(r(t)){do{a++,c+=String.fromCharCode(t),t=e.charCodeAt(a)}while(r(t));return f=15}if(i(t))return a++,c+=String.fromCharCode(t),13===t&&10===e.charCodeAt(a)&&(a++,c+="\n"),f=14;switch(t){case 123:return a++,f=1;case 125:return a++,f=2;case 91:return a++,f=3;case 93:return a++,f=4;case 58:return a++,f=6;case 44:return a++,f=5;case 34:return a++,c=function(){for(var t="",r=a;;){if(a>=u){t+=e.substring(r,a),p=2;break}
var o=e.charCodeAt(a);if(34===o){t+=e.substring(r,a),a++;break}if(92!==o){if(o>=0&&o<=31){if(i(o)){t+=e.substring(r,a),p=2;break}p=6}a++}else{if(t+=e.substring(r,a),++a>=u){p=2;break}switch(o=e.charCodeAt(a++)){case 34:t+='"';break;case 92:t+="\\";break;case 47:t+="/";break;case 98:t+="\b";break;case 102:t+="\f";break;case 110:t+="\n";break;case 114:t+="\r";break;case 116:t+="\t";break;case 117:var s=n(4,!0);s>=0?t+=String.fromCharCode(s):p=4;break;default:p=5}r=a}}return t}(),f=10;case 47:var s=a-1;if(47===e.charCodeAt(a+1)){for(a+=2;a<u&&!i(e.charCodeAt(a));)a++;return c=e.substring(s,a),f=12}if(42===e.charCodeAt(a+1)){a+=2;for(var d=u-1,h=!1;a<d;){if(42===e.charCodeAt(a)&&47===e.charCodeAt(a+1)){a+=2,h=!0;break}a++}return h||(a++,p=1),c=e.substring(s,a),f=13}return c+=String.fromCharCode(t),a++,f=16;case 45:if(c+=String.fromCharCode(t),++a===u||!o(e.charCodeAt(a)))return f=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return c+=function(){var t=a
;if(48===e.charCodeAt(a))a++;else for(a++;a<e.length&&o(e.charCodeAt(a));)a++;if(a<e.length&&46===e.charCodeAt(a)){if(!(++a<e.length&&o(e.charCodeAt(a))))return p=3,e.substring(t,a);for(a++;a<e.length&&o(e.charCodeAt(a));)a++}var n=a;if(a<e.length&&(69===e.charCodeAt(a)||101===e.charCodeAt(a)))if((++a<e.length&&43===e.charCodeAt(a)||45===e.charCodeAt(a))&&a++,a<e.length&&o(e.charCodeAt(a))){for(a++;a<e.length&&o(e.charCodeAt(a));)a++;n=a}else p=3;return e.substring(t,n)}(),f=11;default:for(;a<u&&function(e){if(r(e)||i(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}(t);)a++,t=e.charCodeAt(a);if(l!==a){switch(c=e.substring(l,a)){case"true":return f=8;case"false":return f=9;case"null":return f=7}return f=16}return c+=String.fromCharCode(t),a++,f=16}}void 0===t&&(t=!1);var a=0,u=e.length,c="",l=0,f=16,p=0;return{setPosition:function(e){a=e,c="",l=0,f=16,p=0},getPosition:function(){return a},scan:t?function(){var e;do{e=s()}while(e>=12&&e<=15);return e}:s,
getToken:function(){return f},getTokenValue:function(){return c},getTokenOffset:function(){return l},getTokenLength:function(){return a-l},getTokenError:function(){return p}}}function r(e){return 32===e||9===e||11===e||12===e||160===e||5760===e||e>=8192&&e<=8203||8239===e||8287===e||12288===e||65279===e}function i(e){return 10===e||13===e||8232===e||8233===e}function o(e){return e>=48&&e<=57}function s(e){if(!e.parent||!e.parent.children)return[];var t=s(e.parent);if("property"===e.parent.type){var n=e.parent.children[0].value;t.push(n)}else if("array"===e.parent.type){var r=e.parent.children.indexOf(e);-1!==r&&t.push(r)}return t}function a(e){switch(e.type){case"array":return e.children.map(a);case"object":for(var t=Object.create(null),n=0,r=e.children;n<r.length;n++){var i=r[n],o=i.children[1];o&&(t[i.children[0].value]=a(o))}return t;case"null":case"string":case"number":case"boolean":return e.value;default:return}}function u(e,t,n){return void 0===n&&(n=!1),
t>=e.offset&&t<e.offset+e.length||n&&t===e.offset+e.length}function c(e,t,n){if(void 0===n&&(n=!1),u(e,t,n)){var r=e.children;if(Array.isArray(r))for(var i=0;i<r.length&&r[i].offset<=t;i++){var o=c(r[i],t,n);if(o)return o}return e}}function l(e,t,r){function i(e){return e?function(){return e(f.getTokenOffset(),f.getTokenLength())}:function(){return!0}}function o(e){return e?function(t){return e(t,f.getTokenOffset(),f.getTokenLength())}:function(){return!0}}function s(){for(;;){var e=f.scan();switch(f.getTokenError()){case 4:a(14);break;case 5:a(15);break;case 3:a(13);break;case 1:x||a(11);break;case 2:a(12);break;case 6:a(16)}switch(e){case 12:case 13:x?a(10):E();break;case 16:a(1);break;case 15:case 14:break;default:return e}}}function a(e,t,n){if(void 0===t&&(t=[]),void 0===n&&(n=[]),S(e),t.length+n.length>0)for(var r=f.getToken();17!==r;){if(-1!==t.indexOf(r)){s();break}if(-1!==n.indexOf(r))break;r=s()}}function u(e){var t=f.getTokenValue();return e?y(t):h(t),s(),!0}function c(){
return 10!==f.getToken()?(a(3,[],[2,5]),!1):(u(!1),6===f.getToken()?(b(":"),s(),l()||a(4,[],[2,5])):a(5,[],[2,5]),!0)}function l(){switch(f.getToken()){case 3:return function(){v(),s();for(var e=!1;4!==f.getToken()&&17!==f.getToken();){if(5===f.getToken()){if(e||a(4,[],[]),b(","),s(),4===f.getToken()&&C)break}else e&&a(6,[],[]);l()||a(4,[],[4,5]),e=!0}return m(),4!==f.getToken()?a(8,[4],[]):s(),!0}();case 1:return function(){d(),s();for(var e=!1;2!==f.getToken()&&17!==f.getToken();){if(5===f.getToken()){if(e||a(4,[],[]),b(","),s(),2===f.getToken()&&C)break}else e&&a(6,[],[]);c()||a(4,[],[2,5]),e=!0}return g(),2!==f.getToken()?a(7,[2],[]):s(),!0}();case 10:return u(!0);default:return function(){switch(f.getToken()){case 11:var e=0;try{"number"!=typeof(e=JSON.parse(f.getTokenValue()))&&(a(2),e=0)}catch(e){a(2)}y(e);break;case 7:y(null);break;case 8:y(!0);break;case 9:y(!1);break;default:return!1}return s(),!0}()}}void 0===r&&(r=p.DEFAULT)
;var f=n(e,!1),d=i(t.onObjectBegin),h=o(t.onObjectProperty),g=i(t.onObjectEnd),v=i(t.onArrayBegin),m=i(t.onArrayEnd),y=o(t.onLiteralValue),b=o(t.onSeparator),E=i(t.onComment),S=o(t.onError),x=r&&r.disallowComments,C=r&&r.allowTrailingComma;return s(),17===f.getToken()||(l()?(17!==f.getToken()&&a(9,[],[]),!0):(a(4,[],[]),!1))}function f(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string";default:return"null"}}Object.defineProperty(t,"__esModule",{value:!0});!function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"}(t.ScanError||(t.ScanError={}));!function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",
e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"}(t.SyntaxKind||(t.SyntaxKind={}));!function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",
e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"}(t.ParseErrorCode||(t.ParseErrorCode={}));var p;!function(e){e.DEFAULT={allowTrailingComma:!0}}(p=t.ParseOptions||(t.ParseOptions={})),t.createScanner=n;var d;!function(e){e[e.nullCharacter=0]="nullCharacter",e[e.maxAsciiCharacter=127]="maxAsciiCharacter",e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.lineSeparator=8232]="lineSeparator",e[e.paragraphSeparator=8233]="paragraphSeparator",e[e.nextLine=133]="nextLine",e[e.space=32]="space",e[e.nonBreakingSpace=160]="nonBreakingSpace",e[e.enQuad=8192]="enQuad",e[e.emQuad=8193]="emQuad",e[e.enSpace=8194]="enSpace",e[e.emSpace=8195]="emSpace",e[e.threePerEmSpace=8196]="threePerEmSpace",e[e.fourPerEmSpace=8197]="fourPerEmSpace",
e[e.sixPerEmSpace=8198]="sixPerEmSpace",e[e.figureSpace=8199]="figureSpace",e[e.punctuationSpace=8200]="punctuationSpace",e[e.thinSpace=8201]="thinSpace",e[e.hairSpace=8202]="hairSpace",e[e.zeroWidthSpace=8203]="zeroWidthSpace",e[e.narrowNoBreakSpace=8239]="narrowNoBreakSpace",e[e.ideographicSpace=12288]="ideographicSpace",e[e.mathematicalSpace=8287]="mathematicalSpace",e[e.ogham=5760]="ogham",e[e._=95]="_",e[e.$=36]="$",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",
e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.ampersand=38]="ampersand",e[e.asterisk=42]="asterisk",e[e.at=64]="at",e[e.backslash=92]="backslash",e[e.bar=124]="bar",e[e.caret=94]="caret",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.closeParen=41]="closeParen",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.equals=61]="equals",e[e.exclamation=33]="exclamation",e[e.greaterThan=62]="greaterThan",e[e.lessThan=60]="lessThan",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.openParen=40]="openParen",e[e.percent=37]="percent",e[e.plus=43]="plus",e[e.question=63]="question",e[e.semicolon=59]="semicolon",
e[e.singleQuote=39]="singleQuote",e[e.slash=47]="slash",e[e.tilde=126]="tilde",e[e.backspace=8]="backspace",e[e.formFeed=12]="formFeed",e[e.byteOrderMark=65279]="byteOrderMark",e[e.tab=9]="tab",e[e.verticalTab=11]="verticalTab"}(d||(d={})),t.getLocation=function(e,t){function n(e,t,n,r){s.value=e,s.offset=t,s.length=n,s.type=r,s.colonOffset=void 0,o=s}var r=[],i=new Object,o=void 0,s={value:{},offset:0,length:0,type:"object",parent:void 0},a=!1;try{l(e,{onObjectBegin:function(e,n){if(t<=e)throw i;o=void 0,a=t>e,r.push("")},onObjectProperty:function(e,o,s){if(t<o)throw i;if(n(e,o,s,"property"),r[r.length-1]=e,t<=o+s)throw i},onObjectEnd:function(e,n){if(t<=e)throw i;o=void 0,r.pop()},onArrayBegin:function(e,n){if(t<=e)throw i;o=void 0,r.push(0)},onArrayEnd:function(e,n){if(t<=e)throw i;o=void 0,r.pop()},onLiteralValue:function(e,r,o){if(t<r)throw i;if(n(e,r,o,f(e)),t<=r+o)throw i},onSeparator:function(e,n,s){if(t<=n)throw i;if(":"===e&&o&&"property"===o.type)o.colonOffset=n,a=!1,o=void 0;else if(","===e){
var u=r[r.length-1];"number"==typeof u?r[r.length-1]=u+1:(a=!0,r[r.length-1]=""),o=void 0}}})}catch(e){if(e!==i)throw e}return{path:r,previousNode:o,isAtPropertyKey:a,matches:function(e){for(var t=0,n=0;t<e.length&&n<r.length;n++)if(e[t]===r[n]||"*"===e[t])t++;else if("**"!==e[t])return!1;return t===e.length}}},t.parse=function(e,t,n){function r(e){Array.isArray(o)?o.push(e):i&&(o[i]=e)}void 0===t&&(t=[]),void 0===n&&(n=p.DEFAULT);var i=null,o=[],s=[];return l(e,{onObjectBegin:function(){var e={};r(e),s.push(o),o=e,i=null},onObjectProperty:function(e){i=e},onObjectEnd:function(){o=s.pop()},onArrayBegin:function(){var e=[];r(e),s.push(o),o=e,i=null},onArrayEnd:function(){o=s.pop()},onLiteralValue:r,onError:function(e,n,r){t.push({error:e,offset:n,length:r})}},n),o[0]},t.parseTree=function(e,t,n){function r(e){"property"===o.type&&(o.length=e-o.offset,o=o.parent)}function i(e){return o.children.push(e),e}void 0===t&&(t=[]),void 0===n&&(n=p.DEFAULT);var o={type:"array",offset:-1,length:-1,children:[],
parent:void 0};l(e,{onObjectBegin:function(e){o=i({type:"object",offset:e,length:-1,parent:o,children:[]})},onObjectProperty:function(e,t,n){(o=i({type:"property",offset:t,length:-1,parent:o,children:[]})).children.push({type:"string",value:e,offset:t,length:n,parent:o})},onObjectEnd:function(e,t){o.length=e+t-o.offset,o=o.parent,r(e+t)},onArrayBegin:function(e,t){o=i({type:"array",offset:e,length:-1,parent:o,children:[]})},onArrayEnd:function(e,t){o.length=e+t-o.offset,o=o.parent,r(e+t)},onLiteralValue:function(e,t,n){i({type:f(e),offset:t,length:n,parent:o,value:e}),r(t+n)},onSeparator:function(e,t,n){"property"===o.type&&(":"===e?o.colonOffset=t:","===e&&r(t))},onError:function(e,n,r){t.push({error:e,offset:n,length:r})}},n);var s=o.children[0];return s&&delete s.parent,s},t.findNodeAtLocation=function(e,t){if(e){for(var n=e,r=0,i=t;r<i.length;r++){var o=i[r];if("string"==typeof o){if("object"!==n.type||!Array.isArray(n.children))return;for(var s=!1,a=0,u=n.children;a<u.length;a++){var c=u[a]
;if(Array.isArray(c.children)&&c.children[0].value===o){n=c.children[1],s=!0;break}}if(!s)return}else{var l=o;if("array"!==n.type||l<0||!Array.isArray(n.children)||l>=n.children.length)return;n=n.children[l]}}return n}},t.getNodePath=s,t.getNodeValue=a,t.contains=u,t.findNodeAtOffset=c,t.visit=l,t.stripComments=function(e,t){var r,i,o=n(e),s=[],a=0;do{switch(i=o.getPosition(),r=o.scan()){case 12:case 13:case 17:a!==i&&s.push(e.substring(a,i)),void 0!==t&&s.push(o.getTokenValue().replace(/[^\r\n]/g,t)),a=o.getPosition()}}while(17!==r);return s.join("")}}),define(e[62],t([0,1,10]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toLocalISOString=function(e){return e.getFullYear()+"-"+n.pad(e.getMonth()+1,2)+"-"+n.pad(e.getDate(),2)+"T"+n.pad(e.getHours(),2)+":"+n.pad(e.getMinutes(),2)+":"+n.pad(e.getSeconds(),2)+"."+(e.getMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"}}),define(e[54],t([0,1,19,10,25,33,21]),function(e,t,n,r,i,o,s){"use strict";function a(e){switch(e){case 0:
return"";case 1:return S+"*?";default:return"(?:"+E+"|"+S+"+"+E+"|"+E+S+"+)*?"}}function u(e,t){if(!e)return[];for(var n,r=[],i=!1,o=!1,s="",a=0;a<e.length;a++){switch(n=e[a]){case t:if(!i&&!o){r.push(s),s="";continue}break;case"{":i=!0;break;case"}":i=!1;break;case"[":o=!0;break;case"]":o=!1}s+=n}return s&&r.push(s),r}function c(e){if(!e)return"";var t="",n=u(e,b);if(n.every(function(e){return e===y}))t=".*";else{var i=!1;n.forEach(function(e,o){if(e!==y){for(var s,l=!1,f="",p=!1,d="",h=0;h<e.length;h++)if("}"!==(s=e[h])&&l)f+=s;else if(!p||"]"===s&&d)switch(s){case"{":l=!0;continue;case"[":p=!0;continue;case"}":var g="(?:"+u(f,",").map(function(e){return c(e)}).join("|")+")";t+=g,l=!1,f="";break;case"]":t+="["+d+"]",p=!1,d="";break;case"?":t+=S;continue;case"*":t+=a(1);continue;default:t+=r.escapeRegExpCharacters(s)}else{d+="-"===s?s:"^"!==s&&"!"!==s||d?s===b?"":r.escapeRegExpCharacters(s):"^"}o<n.length-1&&(n[o+1]!==y||o+2<n.length)&&(t+=E),i=!1}else i||(t+=a(2),i=!0)})}return t}function l(e,t){
if(!e)return T;var i;i="string"!=typeof e?e.pattern:e;var o=(i=i.trim())+"_"+!!t.trimForExclusions,s=k.get(o);if(s)return f(s,e);var a;if(C.test(i)){var u=i.substr(4);s=function(e,t){return e&&r.endsWith(e,u)?i:null}}else s=(a=P.exec(p(i,t)))?function(e,t){var n="/"+e,i="\\"+e,o=function(o,s){return o?s?s===e?t:null:o===e||r.endsWith(o,n)||r.endsWith(o,i)?t:null:null},s=[e];return o.basenames=s,o.patterns=[t],o.allBasenames=s,o}(a[1],i):(t.trimForExclusions?w:_).test(i)?function(e,t){var r=m(e.slice(1,-1).split(",").map(function(e){return l(e,t)}).filter(function(e){return e!==T}),e),i=r.length;if(!i)return T;if(1===i)return r[0];var o=function(t,n){for(var i=0,o=r.length;i<o;i++)if(r[i](t,n))return e;return null},s=n.first(r,function(e){return!!e.allBasenames});s&&(o.allBasenames=s.allBasenames);var a=r.reduce(function(e,t){return t.allPaths?e.concat(t.allPaths):e},[]);a.length&&(o.allPaths=a);return o}(i,t):(a=I.exec(p(i,t)))?d(a[1].substr(1),i,!0):(a=O.exec(p(i,t)))?d(a[1],i,!1):function(e){try{
var t=new RegExp("^"+c(e)+"$");return function(n,r){return t.lastIndex=0,n&&t.test(n)?e:null}}catch(e){return T}}(i);return k.set(o,s),f(s,e)}function f(e,t){return"string"==typeof t?e:function(n,r){return i.isEqualOrParent(n,t.base)?e(t.pathToRelative(t.base,n),r):null}}function p(e,t){return t.trimForExclusions&&r.endsWith(e,"/**")?e.substr(0,e.length-2):e}function d(e,t,n){var o=i.nativeSep!==i.sep?e.replace(x,i.nativeSep):e,s=i.nativeSep+o,a=n?function(e,n){return e&&(e===o||r.endsWith(e,s))?t:null}:function(e,n){return e&&e===o?t:null};return a.allPaths=[(n?"*/":"./")+e],a}function h(e,t){if(void 0===t&&(t={}),!e)return j;if("string"==typeof e||v(e)){var r=l(e,t);if(r===T)return j;var o=function(e,t){return!!r(e,t)};return r.allBasenames&&(o.allBasenames=r.allBasenames),r.allPaths&&(o.allPaths=r.allPaths),o}return function(e,t){var r=m(Object.getOwnPropertyNames(e).map(function(n){return function(e,t,n){if(!1===t)return T;var r=l(e,n);if(r===T)return T;if("boolean"==typeof t)return r;if(t){var i=t.when
;if("string"==typeof i){var o=function(t,n,o,a){if(!a||!r(t,n))return null;var u=i.replace("$(basename)",o),c=a(u);return s.isThenable(c)?c.then(function(t){return t?e:null}):c?e:null};return o.requiresSiblings=!0,o}}return r}(n,e[n],t)}).filter(function(e){return e!==T})),o=r.length;if(!o)return T;if(!r.some(function(e){return!!e.requiresSiblings})){if(1===o)return r[0];var a=function(e,t){for(var n=0,i=r.length;n<i;n++){var o=r[n](e,t);if(o)return o}return null},u=n.first(r,function(e){return!!e.allBasenames});u&&(a.allBasenames=u.allBasenames);var c=r.reduce(function(e,t){return t.allPaths?e.concat(t.allPaths):e},[]);return c.length&&(a.allPaths=c),a}var f=function(e,t,n){for(var o=void 0,s=0,a=r.length;s<a;s++){var u=r[s];u.requiresSiblings&&n&&(t||(t=i.basename(e)),o||(o=t.substr(0,t.length-i.extname(e).length)));var c=u(e,t,o,n);if(c)return c}return null},p=n.first(r,function(e){return!!e.allBasenames});p&&(f.allBasenames=p.allBasenames);var d=r.reduce(function(e,t){
return t.allPaths?e.concat(t.allPaths):e},[]);d.length&&(f.allPaths=d);return f}(e,t)}function g(e){for(var t={},n=0,r=e;n<r.length;n++){t[r[n]]=!0}return t}function v(e){var t=e;return t&&"string"==typeof t.base&&"string"==typeof t.pattern&&"function"==typeof t.pathToRelative}function m(e,t){var n=e.filter(function(e){return!!e.basenames});if(n.length<2)return e;var r,i=n.reduce(function(e,t){var n=t.basenames;return n?e.concat(n):e},[]);if(t){r=[];for(var o=0,s=i.length;o<s;o++)r.push(t)}else r=n.reduce(function(e,t){var n=t.patterns;return n?e.concat(n):e},[]);var a=function(e,t){if(!e)return null;if(!t){var n=void 0;for(n=e.length;n>0;n--){var o=e.charCodeAt(n-1);if(47===o||92===o)break}t=e.substr(n)}var s=i.indexOf(t);return-1!==s?r[s]:null};a.basenames=i,a.patterns=r,a.allBasenames=i;var u=e.filter(function(e){return!e.basenames});return u.push(a),u}Object.defineProperty(t,"__esModule",{value:!0}),t.getEmptyExpression=function(){return Object.create(null)}
;var y="**",b="/",E="[/\\\\]",S="[^/\\\\]",x=/\//g;t.splitGlobAware=u;var C=/^\*\*\/\*\.[\w\.-]+$/,P=/^\*\*\/([\w\.-]+)\/?$/,_=/^{\*\*\/[\*\.]?[\w\.-]+\/?(,\*\*\/[\*\.]?[\w\.-]+\/?)*}$/,w=/^{\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?(,\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?)*}$/,I=/^\*\*((\/[\w\.-]+)+)\/?$/,O=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,k=new o.LRUCache(1e4),j=function(){return!1},T=function(){return null};t.match=function(e,t,n){return!(!e||!t)&&h(e)(t,void 0,n)},t.parse=h,t.hasSiblingPromiseFn=function(e){if(e){var t;return function(n){return t||(t=(e()||Promise.resolve([])).then(function(e){return e?g(e):{}})),t.then(function(e){return!!e[n]})}}},t.hasSiblingFn=function(e){if(e){var t;return function(n){if(!t){var r=e();t=r?g(r):{}}return!!t[n]}}},t.isRelativePattern=v,t.parseToAsync=function(e,t){var n=h(e,t);return function(e,t,r){var i=n(e,t,r);return s.isThenable(i)?i:Promise.resolve(i)}},t.getBasenameTerms=function(e){return e.allBasenames||[]},t.getPathTerms=function(e){return e.allPaths||[]}}),
define(e[50],t([0,1,25,10,19,54]),function(e,t,n,r,i,o){"use strict";function s(e,t){void 0===t&&(t=!1);var r=function(e){return{id:e.id,mime:e.mime,filename:e.filename,extension:e.extension,filepattern:e.filepattern,firstline:e.firstline,userConfigured:e.userConfigured,filenameLowercase:e.filename?e.filename.toLowerCase():void 0,extensionLowercase:e.extension?e.extension.toLowerCase():void 0,filepatternLowercase:e.filepattern?e.filepattern.toLowerCase():void 0,filepatternOnPath:!!e.filepattern&&e.filepattern.indexOf(n.sep)>=0}}(e);l.push(r),r.userConfigured?p.push(r):f.push(r),t&&!r.userConfigured&&l.forEach(function(e){e.mime===r.mime||e.userConfigured||(r.extension&&e.extension===r.extension&&console.warn("Overwriting extension <<"+r.extension+">> to now point to mime <<"+r.mime+">>"),r.filename&&e.filename===r.filename&&console.warn("Overwriting filename <<"+r.filename+">> to now point to mime <<"+r.mime+">>"),
r.filepattern&&e.filepattern===r.filepattern&&console.warn("Overwriting filepattern <<"+r.filepattern+">> to now point to mime <<"+r.mime+">>"),r.firstline&&e.firstline===r.firstline&&console.warn("Overwriting firstline <<"+r.firstline+">> to now point to mime <<"+r.mime+">>"))})}function a(e,i){if(!e)return[t.MIME_UNKNOWN];e=e.toLowerCase();var o=n.basename(e),s=u(e,o,p);if(s)return[s,t.MIME_TEXT];var a=u(e,o,f);if(a)return[a,t.MIME_TEXT];if(i){var c=function(e){r.startsWithUTF8BOM(e)&&(e=e.substr(1));if(e.length>0)for(var t=0;t<l.length;++t){var n=l[t];if(n.firstline){var i=e.match(n.firstline);if(i&&i.length>0)return n.mime}}return null}(i);if(c)return[c,t.MIME_TEXT]}return[t.MIME_UNKNOWN]}function u(e,t,n){for(var i=null,s=null,a=null,u=n.length-1;u>=0;u--){var c=n[u];if(t===c.filenameLowercase){i=c;break}if(c.filepattern&&(!s||c.filepattern.length>s.filepattern.length)){var l=c.filepatternOnPath?e:t;o.match(c.filepatternLowercase,l)&&(s=c)}
c.extension&&(!a||c.extension.length>a.extension.length)&&r.endsWith(t,c.extensionLowercase)&&(a=c)}return i?i.mime:s?s.mime:a?a.mime:null}function c(e){return!e||("string"==typeof e?e===t.MIME_BINARY||e===t.MIME_TEXT||e===t.MIME_UNKNOWN:1===e.length&&c(e[0]))}Object.defineProperty(t,"__esModule",{value:!0}),t.MIME_TEXT="text/plain",t.MIME_BINARY="application/octet-stream",t.MIME_UNKNOWN="application/unknown";var l=[],f=[],p=[];t.registerTextMime=s,t.clearTextMimes=function(e){e?(l=l.filter(function(e){return!e.userConfigured}),p=[]):(l=[],f=[],p=[])},t.guessMimeTypes=a,t.isUnspecific=c,t.suggestFilename=function(e,t){var n=l.filter(function(t){return!t.userConfigured&&t.extension&&t.id===e}).map(function(e){return e.extension}),o=i.coalesce(n).filter(function(e){return r.startsWith(e,".")});return o.length>0?t+o[0]:n[0]||t};var d={".bmp":"image/bmp",".gif":"image/gif",".jpg":"image/jpg",".jpeg":"image/jpg",".jpe":"image/jpg",".png":"image/png",".tiff":"image/tiff",".tif":"image/tiff",".ico":"image/x-icon",
".tga":"image/x-tga",".psd":"image/vnd.adobe.photoshop",".webp":"image/webp",".mid":"audio/midi",".midi":"audio/midi",".mp4a":"audio/mp4",".mpga":"audio/mpeg",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".m2a":"audio/mpeg",".m3a":"audio/mpeg",".oga":"audio/ogg",".ogg":"audio/ogg",".spx":"audio/ogg",".aac":"audio/x-aac",".wav":"audio/x-wav",".wma":"audio/x-ms-wma",".mp4":"video/mp4",".mp4v":"video/mp4",".mpg4":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpe":"video/mpeg",".m1v":"video/mpeg",".m2v":"video/mpeg",".ogv":"video/ogg",".qt":"video/quicktime",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".mk3d":"video/x-matroska",".mks":"video/x-matroska",".wmv":"video/x-ms-wmv",".flv":"video/x-flv",".avi":"video/x-msvideo",".movie":"video/x-sgi-movie"};t.getMediaMime=function(e){var t=n.extname(e);return d[t.toLowerCase()]}}),define(e[53],t([0,1,22,25,10,30,16,94]),function(e,t,n,r,i,o,s,a){"use strict";function u(e){return!(!s.isWindows||!e||":"!==e[1])}
function c(e){return u(e)?e.charAt(0).toUpperCase()+e.slice(1):e}function l(e,t){if(s.isWindows||!e||!t)return e;var n=f.original===t?f.normalized:void 0;return n||(n=""+i.rtrim(t,r.sep)+r.sep,f={original:t,normalized:n}),(s.isLinux?i.startsWith(e,n):i.startsWithIgnoreCase(e,n))&&(e="~/"+e.substr(n.length)),e}Object.defineProperty(t,"__esModule",{value:!0}),t.getPathLabel=function(e,t,f){if("string"==typeof e&&(e=n.URI.file(e)),f){var p=f.getWorkspaceFolder(e);if(p){var d=f.getWorkspace().folders.length>1,h=void 0;if(h=a.isEqual(p.uri,e,!s.isLinux)?"":r.normalize(i.ltrim(e.path.substr(p.uri.path.length),r.sep),!0),d){var g=p&&p.name?p.name:r.basename(p.uri.fsPath);h=h?g+" • "+h:g}return h}}if(e.scheme!==o.Schemas.file&&e.scheme!==o.Schemas.untitled)return e.with({query:null,fragment:null}).toString(!0);if(u(e.fsPath))return r.normalize(c(e.fsPath),!0);var v=r.normalize(e.fsPath,!0);return!s.isWindows&&t&&(v=l(v,t.userHome)),v},t.getBaseLabel=function(e){if(e){"string"==typeof e&&(e=n.URI.file(e))
;var t=r.basename(e.path)||(e.scheme===o.Schemas.file?e.fsPath:e.path);return u(t)?c(t):t}},t.normalizeDriveLetter=c;var f=Object.create(null);t.tildify=l,t.untildify=function(e,t){return e.replace(/^~($|\/|\\)/,t+"$1")};var p="…",d="\\\\",h="~";t.shorten=function(e){for(var t=new Array(e.length),n=!1,o=0;o<e.length;o++){var s=e[o];if(""!==s)if(s){n=!0;var a="";0===s.indexOf(d)?(a=s.substr(0,s.indexOf(d)+d.length),s=s.substr(s.indexOf(d)+d.length)):0===s.indexOf(r.nativeSep)?(a=s.substr(0,s.indexOf(r.nativeSep)+r.nativeSep.length),s=s.substr(s.indexOf(r.nativeSep)+r.nativeSep.length)):0===s.indexOf(h)&&(a=s.substr(0,s.indexOf(h)+h.length),s=s.substr(s.indexOf(h)+h.length));for(var u=s.split(r.nativeSep),c=1;n&&c<=u.length;c++)for(var l=u.length-c;n&&l>=0;l--){n=!1;for(var f=u.slice(l,l+c).join(r.nativeSep),g=0;!n&&g<e.length;g++)if(g!==o&&e[g]&&e[g].indexOf(f)>-1){var v=l+c===u.length,m=l>0&&e[g].indexOf(r.nativeSep)>-1?r.nativeSep+f:f,y=i.endsWith(e[g],m);n=!v||y}if(!n){var b=""
;(i.endsWith(u[0],":")||""!==a)&&(1===l&&(l=0,c++,f=u[0]+r.nativeSep+f),l>0&&(b=u[0]+r.nativeSep),b=a+b),l>0&&(b=b+p+r.nativeSep),b+=f,l+c<u.length&&(b=b+r.nativeSep+p),t[o]=b}}n&&(t[o]=s)}else t[o]=s;else t[o]="."+r.nativeSep}return t};var g;!function(e){e[e.TEXT=0]="TEXT",e[e.VARIABLE=1]="VARIABLE",e[e.SEPARATOR=2]="SEPARATOR"}(g||(g={})),t.template=function(e,t){void 0===t&&(t=Object.create(null));for(var n,r=[],i=!1,o="",s=0;s<e.length;s++)if("$"===(n=e[s])||i&&"{"===n)o&&r.push({value:o,type:g.TEXT}),o="",i=!0;else if("}"===n&&i){var a=t[o];if("string"==typeof a)a.length&&r.push({value:a,type:g.VARIABLE});else if(a){var u=r[r.length-1];u&&u.type===g.SEPARATOR||r.push({value:a.label,type:g.SEPARATOR})}o="",i=!1}else o+=n;return o&&!i&&r.push({value:o,type:g.TEXT}),r.filter(function(e,t){return e.type!==g.SEPARATOR||[r[t-1],r[t+1]].every(function(e){return e&&(e.type===g.VARIABLE||e.type===g.TEXT)&&e.value.length>0})}).map(function(e){return e.value}).join("")},t.mnemonicMenuLabel=function(e,t){
return s.isMacintosh||t?e.replace(/\(&&\w\)|&&/g,""):e.replace(/&&/g,"&")},t.mnemonicButtonLabel=function(e){return s.isMacintosh?e.replace(/\(&&\w\)|&&/g,""):s.isWindows?e.replace(/&&|&/g,function(e){return"&"===e?"&&":"&"}):e.replace(/&&/g,"_")},t.unmnemonicLabel=function(e){return e.replace(/&/g,"&&")}}),define(e[61],t([0,1,35]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n.getPathFromAmdModule(e,"paths"),i=e.__$__nodeRequire(r);t.getAppDataPath=i.getAppDataPath,t.getDefaultUserDataPath=i.getDefaultUserDataPath});var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e) | try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}u((r=r.apply(e,t||[])).next())})},r=this&&this.__generator||function(e,t){function n(n){return function(s){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,
i&&(o=2&n[0]?i.return:n[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,n[1])).done)return o;switch(i=0,o&&(n=[2&n[0],o.value]),n[0]){case 0:case 1:o=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,i=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(o=a.trys,!(o=o.length>0&&o[o.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!o||n[1]>o[0]&&n[1]<o[3])){a.label=n[1];break}if(6===n[0]&&a.label<o[1]){a.label=o[1],o=n;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(n);break}o[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}catch(e){n=[6,e],i=0}finally{r=o=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,s])}}var r,i,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s};define(e[64],t([0,1,83,3]),function(e,t,i,o){"use strict";function s(t,s){return void 0===s&&(s={}),
n(this,void 0,void 0,function(){var n,a,u,c,l,f;return r(this,function(r){switch(r.label){case 0:return n=i.parse(t),(a=s.proxyUrl||function(e){return"http:"===e.protocol?process.env.HTTP_PROXY||process.env.http_proxy||null:"https:"===e.protocol?process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||null:null}(n))?(u=i.parse(a),/^https?:$/.test(u.protocol||"")?(c={host:u.hostname||"",port:Number(u.port),auth:u.auth,rejectUnauthorized:!o.isBoolean(s.strictSSL)||s.strictSSL},"http:"!==n.protocol?[3,2]:[4,new Promise(function(t,n){e(["http-proxy-agent"],t,n)})]):[2,null]):[2,null];case 1:return f=r.sent(),[3,4];case 2:return[4,new Promise(function(t,n){e(["https-proxy-agent"],t,n)})];case 3:f=r.sent(),r.label=4;case 4:return l=f,[2,new l(c)]}})})}Object.defineProperty(t,"__esModule",{value:!0}),t.getProxyAgent=s}),define(e[48],t([0,1,24,5,6,11,9,37,39,16]),function(e,t,n,r,i,o,s,a,u,c){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var l=function(){
function e(e,t){void 0===t&&(t={defaultConfig:Object.create(null),onError:function(e){return console.error(e)}}),this._path=e,this.options=t,this.disposables=[],this.configName=r.basename(this._path),this._onDidUpdateConfiguration=new s.Emitter,this.disposables.push(this._onDidUpdateConfiguration),this.registerWatcher(),this.initAsync()}return Object.defineProperty(e.prototype,"path",{get:function(){return this._path},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasParseErrors",{get:function(){return this.parseErrors&&this.parseErrors.length>0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDidUpdateConfiguration",{get:function(){return this._onDidUpdateConfiguration.event},enumerable:!0,configurable:!0}),e.prototype.initAsync=function(){var e=this;this.loadAsync(function(t){e.loaded||e.updateCache(t),e.options.initCallback&&e.options.initCallback(e.getConfig())})},e.prototype.updateCache=function(e){this.cache=e,this.loaded=!0},e.prototype.loadSync=function(){try{
return this.parse(n.readFileSync(this._path).toString())}catch(e){return this.options.defaultConfig}},e.prototype.loadAsync=function(e){var t=this;n.readFile(this._path,function(n,r){return e(n?t.options.defaultConfig:t.parse(r.toString()))})},e.prototype.parse=function(e){try{return this.parseErrors=[],(this.options.parse?this.options.parse(e,this.parseErrors):a.parse(e,this.parseErrors))||this.options.defaultConfig}catch(e){return this.options.defaultConfig}},e.prototype.registerWatcher=function(){var e=this,t=r.dirname(this._path);this.watch(t,!0),n.lstat(this._path,function(t,r){t||r.isDirectory()||r.isSymbolicLink()&&n.readlink(e._path,function(t,n){t||e.watch(n,!1)})})},e.prototype.watch=function(e,t){var n=this;this.disposed||this.disposables.push(u.watch(e,function(e,r){return n.onConfigFileChange(e,r,t)},function(e){return n.options.onError(e)}))},e.prototype.onConfigFileChange=function(e,t,n){var i=this;n&&(c.isWindows&&t&&t!==this.configName&&(t=r.basename(t)),
t!==this.configName)||(this.timeoutHandle&&(global.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.timeoutHandle=global.setTimeout(function(){return i.reload()},this.options.changeBufferDelay||0))},e.prototype.reload=function(e){var t=this;this.loadAsync(function(n){if(i.equals(n,t.cache)||(t.updateCache(n),t._onDidUpdateConfiguration.fire({config:t.cache})),e)return e(n)})},e.prototype.getConfig=function(){return this.ensureLoaded(),this.cache},e.prototype.ensureLoaded=function(){this.loaded||this.updateCache(this.loadSync())},e.prototype.dispose=function(){this.disposed=!0,this.disposables=o.dispose(this.disposables)},e}();t.ConfigWatcher=l}),define(e[59],t([8,4]),function(e,t){return e.create("vs/base/common/errorMessage",t)}),define(e[31],t([0,1,59,3,19]),function(e,t,n,r,i){"use strict";function o(e,t){return e.message?t&&(e.stack||e.stacktrace)?n.localize(0,null,s(e),e.stack||e.stacktrace):s(e):n.localize(1,null)}function s(e){
return"string"==typeof e.code&&"number"==typeof e.errno&&"string"==typeof e.syscall?n.localize(2,null,e.message):e.message}function a(e,t){if(void 0===e&&(e=null),void 0===t&&(t=!1),!e)return n.localize(3,null);if(Array.isArray(e)){var s=i.coalesce(e),u=a(s[0],t);return s.length>1?n.localize(4,null,u,s.length):u}if(r.isString(e))return e;if(e.detail){var c=e.detail;if(c.error)return o(c.error,t);if(c.exception)return o(c.exception,t)}return e.stack?o(e,t):e.message?e.message:n.localize(5,null)}Object.defineProperty(t,"__esModule",{value:!0}),t.toErrorMessage=a}),define(e[65],t([8,4]),function(e,t){return e.create("vs/platform/configuration/common/configurationRegistry",t)}),define(e[66],t([8,4]),function(e,t){return e.create("vs/platform/extensionManagement/common/extensionManagement",t)}),define(e[67],t([8,4]),function(e,t){return e.create("vs/platform/extensionManagement/node/extensionManagementService",t)}),define(e[69],t([8,4]),function(e,t){
return e.create("vs/platform/extensionManagement/node/extensionManagementUtil",t)}),define(e[70],t([8,4]),function(e,t){return e.create("vs/platform/extensions/node/extensionValidator",t)}),define(e[71],t([8,4]),function(e,t){return e.create("vs/platform/node/zip",t)}),define(e[74],t([8,4]),function(e,t){return e.create("vs/platform/request/node/request",t)}),define(e[77],t([8,4]),function(e,t){return e.create("vs/platform/telemetry/common/telemetryService",t)});var i=this&&this.__assign||function(){return(i=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e}).apply(this,arguments)};define(e[18],t([0,1,10]),function(e,t,n){"use strict";function r(e,t){return e.uuid&&t.uuid?e.uuid===t.uuid:e.id===t.id||0===n.compareIgnoreCase(e.id,t.id)}function o(e){return e.toLocaleLowerCase()}function s(e,t){return e.toLocaleLowerCase()+"."+t.toLocaleLowerCase()}function a(e){
return e.manifest?s(e.manifest.publisher,e.manifest.name):e.identifier.id}Object.defineProperty(t,"__esModule",{value:!0}),t.areSameExtensions=r,t.adoptToGalleryExtensionId=o,t.getGalleryExtensionId=s,t.getGalleryExtensionIdFromLocal=a,t.LOCAL_EXTENSION_ID_REGEX=/^([^.]+\..+)-(\d+\.\d+\.\d+(-.*)?)$/,t.getIdFromLocalExtensionId=function(e){var n=t.LOCAL_EXTENSION_ID_REGEX.exec(e);return o(n&&n[1]?n[1]:e)},t.getLocalExtensionId=function(e,t){return e+"-"+t},t.groupByExtension=function(e,t){for(var n=[],i=function(e){for(var i=0,o=n;i<o.length;i++){var s=o[i];if(s.some(function(n){return r(t(n),t(e))}))return s}return null},o=0,s=e;o<s.length;o++){var a=s[o],u=i(a);u?u.push(a):n.push([a])}return n},t.getLocalExtensionTelemetryData=function(e){return{id:a(e),name:e.manifest.name,galleryId:null,publisherId:e.metadata?e.metadata.publisherId:null,publisherName:e.manifest.publisher,publisherDisplayName:e.metadata?e.metadata.publisherDisplayName:null,
dependencies:e.manifest.extensionDependencies&&e.manifest.extensionDependencies.length>0}},t.getGalleryExtensionTelemetryData=function(e){return i({id:e.identifier.id,name:e.name,galleryId:e.identifier.uuid,publisherId:e.publisherId,publisherName:e.publisher,publisherDisplayName:e.publisherDisplayName,dependencies:!!(e.properties.dependencies&&e.properties.dependencies.length>0)},e.telemetryData)},t.BetterMergeId="pprice.better-merge",t.getMaliciousExtensionsSet=function(e){for(var t=new Set,n=0,r=e;n<r.length;n++){var i=r[n];i.malicious&&t.add(i.id.id)}return t}}),define(e[84],t([0,1,6]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=/^%([\w\d.-]+)%$/i;t.localizeManifest=function(e,t){return n.cloneAndChange(e,function(e){if("string"==typeof e){var n=r.exec(e);if(n)return t[n[1]]||e}})}});var o=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){
for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();define(e[85],t([0,1,11,92,31,5,21,9,30,12]),function(e,t,i,s,a,u,c,l,f,p){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var d=function(e){function t(t,n){var r=e.call(this)||this;return r.environmentService=t,r.logService=n,r.processesLimiter=new c.Limiter(5),r}return o(t,e),t.prototype.postUninstall=function(e){return n(this,void 0,void 0,function(){var t,n=this;return r(this,function(r){switch(r.label){case 0:return(t=this.parseScript(e,"uninstall"))?(this.logService.info(e.identifier.id,"Running post uninstall script"),[4,this.processesLimiter.queue(function(){return n.runLifecycleHook(t.script,"uninstall",t.args,!0,e).then(function(){return n.logService.info(e.identifier.id,"Finished running post uninstall script")},function(t){
return n.logService.error(e.identifier.id,"Failed to run post uninstall script: "+t)})})]):[3,2];case 1:r.sent(),r.label=2;case 2:return[2,p.rimraf(this.getExtensionStoragePath(e)).then(void 0,function(e){return n.logService.error("Error while removing extension storage path",e)})]}})})},t.prototype.parseScript=function(e,t){var n="vscode:"+t;if(e.location.scheme===f.Schemas.file&&e.manifest&&e.manifest.scripts&&"string"==typeof e.manifest.scripts[n]){var r=e.manifest.scripts[n].split(" ");return r.length<2||"node"!==r[0]||!r[1]?(this.logService.warn(e.identifier.id,n+" should be a node script"),null):{script:u.posix.join(e.location.fsPath,r[1]),args:r.slice(2)||[]}}return null},t.prototype.runLifecycleHook=function(e,t,n,r,i){var o=this;return new Promise(function(s,u){var c,l=o.start(e,t,n,i),f=function(e){c&&(clearTimeout(c),c=null),e?u(e):s(void 0)};l.on("error",function(e){f(a.toErrorMessage(e)||"Unknown")}),l.on("exit",function(e,n){f(e?"post-"+t+" process exited with code "+e:void 0)}),
r&&(c=setTimeout(function(){c=null,l.kill(),u("timed out")},5e3))})},t.prototype.start=function(e,t,n,r){var i=this,o={silent:!0,execArgv:void 0},a=s.fork(e,["--type=extension-post-"+t].concat(n),o);a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8");var u=l.Event.fromNodeEventEmitter(a.stdout,"data"),c=l.Event.fromNodeEventEmitter(a.stderr,"data");u(function(e){return i.logService.info(r.identifier.id,"post-"+t,e)}),c(function(e){return i.logService.error(r.identifier.id,"post-"+t,e)});var f=l.Event.any(l.Event.map(u,function(e){return{data:"%c"+e,format:[""]}}),l.Event.map(c,function(e){return{data:"%c"+e,format:["color: red"]}}));return l.Event.debounce(f,function(e,t){return e?{data:e.data+t.data,format:e.format.concat(t.format)}:{data:t.data,format:t.format}},100)(function(e){console.group(r.identifier.id),console.log.apply(console,[e.data].concat(e.format)),console.groupEnd()}),a},t.prototype.getExtensionStoragePath=function(e){
return u.posix.join(this.environmentService.globalStorageHome,e.identifier.id.toLocaleLowerCase())},t}(i.Disposable);t.ExtensionsLifecycle=d}),define(e[46],t([0,1,18,10]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MANIFEST_CACHE_FOLDER="CachedExtensions",t.USER_MANIFEST_CACHE_FILE="user",t.BUILTIN_MANIFEST_CACHE_FILE="builtin";var i=new Set;i.add("msjsdiag.debugger-for-chrome"),t.isUIExtension=function(e,t){var r=n.getGalleryExtensionId(e.publisher,e.name),o=t.getValue("_workbench.uiExtensions")||[];if(o.length){if(-1!==o.indexOf(r))return!0;if(-1!==o.indexOf("-"+r))return!1}switch(e.extensionKind){case"ui":return!0;case"workspace":return!1;default:return i.has(r)||!e.main}};var o=function(){function e(e){this.value=e,this._lower=e.toLowerCase()}return e.equals=function(e,t){if(void 0===e||null===e)return void 0===t||null===t;if(void 0===t||null===t)return!1;if("string"==typeof e||"string"==typeof t){var n="string"==typeof e?e:e.value,i="string"==typeof t?t:t.value
;return r.equalsIgnoreCase(n,i)}return e._lower===t._lower},e.toKey=function(e){return"string"==typeof e?e.toLowerCase():e._lower},e}();t.CanonicalExtensionIdentifier=o}),define(e[49],t([0,1,11,5,46,12]),function(e,t,n,r,i,s){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=function(e){function t(t,n){var o=e.call(this)||this;return o.environmentService=t,o.extensionsManifestCache=r.join(o.environmentService.userDataPath,i.MANIFEST_CACHE_FOLDER,i.USER_MANIFEST_CACHE_FILE),o._register(n.onDidInstallExtension(function(e){return o.onDidInstallExtension(e)})),o._register(n.onDidUninstallExtension(function(e){return o.onDidUnInstallExtension(e)})),o}return o(t,e),t.prototype.onDidInstallExtension=function(e){e.error||this.invalidate()},t.prototype.onDidUnInstallExtension=function(e){e.error||this.invalidate()},t.prototype.invalidate=function(){s.del(this.extensionsManifestCache).then(function(){},function(){})},t}(n.Disposable);t.ExtensionsManifestCache=a}),define(e[38],t([0,1]),function(e,t){
"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){return function(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=!1),this.ctor=e,this.staticArguments=t,this.supportsDelayedInstantiation=n}}();t.SyncDescriptor=n,t.createSyncDescriptor=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return new n(e,t)}}),define(e[51],t([0,1,3,47]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this._hashFn=e,this._nodes=Object.create(null)}return e.prototype.roots=function(){var e=[];return r.forEach(this._nodes,function(t){n.isEmptyObject(t.value.outgoing)&&e.push(t.value)}),e},e.prototype.insertEdge=function(e,t){var n=this.lookupOrInsertNode(e),r=this.lookupOrInsertNode(t);n.outgoing[this._hashFn(t)]=r,r.incoming[this._hashFn(e)]=n},e.prototype.removeNode=function(e){var t=this._hashFn(e);delete this._nodes[t],r.forEach(this._nodes,function(e){delete e.value.outgoing[t],delete e.value.incoming[t]})},
e.prototype.lookupOrInsertNode=function(e){var t=this._hashFn(e),n=this._nodes[t];return n||(n=function(e){return{data:e,incoming:Object.create(null),outgoing:Object.create(null)}}(e),this._nodes[t]=n),n},e.prototype.lookup=function(e){return this._nodes[this._hashFn(e)]},e.prototype.isEmpty=function(){for(var e in this._nodes)return!1;return!0},e.prototype.toString=function(){var e=[];return r.forEach(this._nodes,function(t){e.push(t.key+", (incoming)["+Object.keys(t.value.incoming).join(", ")+"], (outgoing)["+Object.keys(t.value.outgoing).join(",")+"]")}),e.join("\n")},e}();t.Graph=i}),define(e[52],t([0,1,2]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IDownloadService=n.createDecorator("downloadService")}),define(e[17],t([0,1,2]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IEnvironmentService=n.createDecorator("environmentService")}),define(e[28],t([0,1,66,2]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{
value:!0}),t.EXTENSION_IDENTIFIER_PATTERN="^([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$",t.EXTENSION_IDENTIFIER_REGEX=new RegExp(t.EXTENSION_IDENTIFIER_PATTERN),t.isIExtensionIdentifier=function(e){return e&&"object"==typeof e&&"string"==typeof e.id&&(!e.uuid||"string"==typeof e.uuid)};!function(e){e[e.System=0]="System",e[e.User=1]="User"}(t.LocalExtensionType||(t.LocalExtensionType={})),t.IExtensionManagementService=r.createDecorator("extensionManagementService"),t.IExtensionGalleryService=r.createDecorator("extensionGalleryService");!function(e){e[e.NoneOrRelevance=0]="NoneOrRelevance",e[e.LastUpdatedDate=1]="LastUpdatedDate",e[e.Title=2]="Title",e[e.PublisherName=3]="PublisherName",e[e.InstallCount=4]="InstallCount",e[e.PublishedDate=5]="PublishedDate",e[e.AverageRating=6]="AverageRating",e[e.WeightedRating=12]="WeightedRating"}(t.SortBy||(t.SortBy={}));!function(e){e[e.Default=0]="Default",e[e.Ascending=1]="Ascending",e[e.Descending=2]="Descending"}(t.SortOrder||(t.SortOrder={}))
;!function(e){e.Uninstall="uninstall"}(t.StatisticType||(t.StatisticType={}));!function(e){e[e.None=0]="None",e[e.Install=1]="Install",e[e.Update=2]="Update"}(t.InstallOperation||(t.InstallOperation={})),t.INSTALL_ERROR_MALICIOUS="malicious",t.INSTALL_ERROR_INCOMPATIBLE="incompatible",t.IExtensionManagementServerService=r.createDecorator("extensionManagementServerService");!function(e){e[e.Disabled=0]="Disabled",e[e.WorkspaceDisabled=1]="WorkspaceDisabled",e[e.Enabled=2]="Enabled",e[e.WorkspaceEnabled=3]="WorkspaceEnabled"}(t.EnablementState||(t.EnablementState={})),t.IExtensionEnablementService=r.createDecorator("extensionEnablementService"),t.IExtensionTipsService=r.createDecorator("extensionTipsService");!function(e){e[e.Workspace=0]="Workspace",e[e.File=1]="File",e[e.Executable=2]="Executable",e[e.DynamicWorkspace=3]="DynamicWorkspace",e[e.Experimental=4]="Experimental"}(t.ExtensionRecommendationReason||(t.ExtensionRecommendationReason={})),t.ExtensionsLabel=n.localize(0,null),
t.ExtensionsChannelId="extensions",t.PreferencesLabel=n.localize(1,null)}),define(e[29],t([0,1]),function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._entries=new Map;for(var n=0,r=e;n<r.length;n++){var i=r[n],o=i[0],s=i[1];this.set(o,s)}}return e.prototype.set=function(e,t){var n=this._entries.get(e);return this._entries.set(e,t),n},e.prototype.forEach=function(e){this._entries.forEach(function(t,n){return e(n,t)})},e.prototype.has=function(e){return this._entries.has(e)},e.prototype.get=function(e){return this._entries.get(e)},e}();t.ServiceCollection=n}),define(e[57],t([0,1,23,3,51,38,2,29]),function(e,t,n,r,i,s,a,u){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var c=function(){function e(e,t,n){void 0===e&&(e=new u.ServiceCollection),void 0===t&&(t=!1),this._services=e,this._strict=t,this._parent=n,this._services.set(a.IInstantiationService,this)}
return e.prototype.createChild=function(t){return new e(t,this._strict,this)},e.prototype.invokeFunction=function(e){for(var t=this,r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];var o=f.traceInvocation(e),s=!1;try{var u={get:function(e,r){if(s)throw n.illegalState("service accessor is only valid during the invocation of its target method");var i=t._getOrCreateServiceInstance(e,o);if(!i&&r!==a.optional)throw new Error("[invokeFunction] unknown service '"+e+"'");return i}};return e.apply(void 0,[u].concat(r))}finally{s=!0,o.stop()}},e.prototype.createInstance=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r,i;return e instanceof s.SyncDescriptor?(r=f.traceCreation(e.ctor),i=this._createInstance(e.ctor,e.staticArguments.concat(t),r)):(r=f.traceCreation(e),i=this._createInstance(e,t,r)),r.stop(),i},e.prototype._createInstance=function(e,t,n){void 0===t&&(t=[]);for(var i=a._util.getServiceDependencies(e).sort(function(e,t){return e.index-t.index}),o=[],s=0,u=i;s<u.length;s++){
var c=u[s],l=this._getOrCreateServiceInstance(c.id,n);if(!l&&this._strict&&!c.optional)throw new Error("[createInstance] "+e.name+" depends on UNKNOWN service "+c.id+".");o.push(l)}var f=i.length>0?i[0].index:t.length;if(t.length!==f){console.warn("[createInstance] First service dependency of "+e.name+" at position "+(f+1)+" conflicts with "+t.length+" static arguments");var p=f-t.length;t=p>0?t.concat(new Array(p)):t.slice(0,f)}return r.create.apply(null,[e].concat(t,o))},e.prototype._setServiceInstance=function(e,t){if(this._services.get(e)instanceof s.SyncDescriptor)this._services.set(e,t);else{if(!this._parent)throw new Error("illegalState - setting UNKNOWN service instance");this._parent._setServiceInstance(e,t)}},e.prototype._getServiceInstanceOrDescriptor=function(e){var t=this._services.get(e);return!t&&this._parent?this._parent._getServiceInstanceOrDescriptor(e):t},e.prototype._getOrCreateServiceInstance=function(e,t){var n=this._getServiceInstanceOrDescriptor(e)
;return n instanceof s.SyncDescriptor?this._createAndCacheServiceInstance(e,n,t.branch(e,!0)):(t.branch(e,!1),n)},e.prototype._createAndCacheServiceInstance=function(e,t,n){function r(){var e=new Error("[createInstance] cyclic dependency between services");throw e.message=o.toString(),e}for(var o=new i.Graph(function(e){return e.id.toString()}),u=0,c=[{id:e,desc:t,_trace:n}];c.length;){var l=c.pop();o.lookupOrInsertNode(l),u++>100&&r();for(var f=0,p=a._util.getServiceDependencies(l.desc.ctor);f<p.length;f++){var d=p[f],h=this._getServiceInstanceOrDescriptor(d.id);if(h||d.optional||console.warn("[createInstance] "+e+" depends on "+d.id+" which is NOT registered."),h instanceof s.SyncDescriptor){var g={id:d.id,desc:h,_trace:l._trace.branch(d.id,!0)};o.insertEdge(l,g),c.push(g)}}}for(;;){var v=o.roots();if(0===v.length){o.isEmpty()||r();break}for(var m=0,y=v;m<y.length;m++){var b=y[m].data,E=this._createServiceInstanceWithOwner(b.id,b.desc.ctor,b.desc.staticArguments,b.desc.supportsDelayedInstantiation,b._trace)
;this._setServiceInstance(b.id,E),o.removeNode(b)}}return this._getServiceInstanceOrDescriptor(e)},e.prototype._createServiceInstanceWithOwner=function(e,t,n,r,i){if(void 0===n&&(n=[]),this._services.get(e)instanceof s.SyncDescriptor)return this._createServiceInstance(t,n,r,i);if(this._parent)return this._parent._createServiceInstanceWithOwner(e,t,n,r,i);throw new Error("illegalState - creating UNKNOWN service instance")},e.prototype._createServiceInstance=function(e,t,n,r){return void 0===t&&(t=[]),this._createInstance(e,t,r)},e}();t.InstantiationService=c;var l;!function(e){e[e.Creation=0]="Creation",e[e.Invocation=1]="Invocation",e[e.Branch=2]="Branch"}(l||(l={}));var f=function(){function e(e,t){this.type=e,this.name=t,this._start=Date.now(),this._dep=[]}return e.traceInvocation=function(t){return e._None},e.traceCreation=function(t){return e._None},e.prototype.branch=function(t,n){var r=new e(2,t.toString());return this._dep.push([t,n,r]),r},e.prototype.stop=function(){function t(e,n){
for(var i=[],o=new Array(e+1).join("\t"),s=0,a=n._dep;s<a.length;s++){var u=a[s],c=u[0],l=u[1],f=u[2];if(l&&f){r=!0,i.push(o+"CREATES -> "+c);var p=t(e+1,f);p&&i.push(p)}else i.push(o+"uses -> "+c)}return i.join("\n")}var n=Date.now()-this._start;e._totals+=n;var r=!1,i=[(0===this.type?"CREATE":"CALL")+" "+this.name,""+t(1,this),"DONE, took "+n.toFixed(2)+"ms (grand total "+e._totals.toFixed(2)+"ms)"];(n>2||r)&&console.log(i.join("\n"))},e._None=new(function(e){function t(){return e.call(this,-1,null)||this}return o(t,e),t.prototype.stop=function(){},t.prototype.branch=function(){return this},t}(e)),e._totals=0,e}()}),define(e[7],t([0,1,2,11,16,9]),function(e,t,n,r,i,s){"use strict";function a(){return(new Date).toISOString()}Object.defineProperty(t,"__esModule",{value:!0}),t.ILogService=n.createDecorator("logService");var u;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.Off=6]="Off"
}(u=t.LogLevel||(t.LogLevel={})),t.DEFAULT_LOG_LEVEL=u.Info;var c=function(e){function n(){var n=null!==e&&e.apply(this,arguments)||this;return n.level=t.DEFAULT_LOG_LEVEL,n._onDidChangeLogLevel=n._register(new s.Emitter),n.onDidChangeLogLevel=n._onDidChangeLogLevel.event,n}return o(n,e),n.prototype.setLevel=function(e){this.level!==e&&(this.level=e,this._onDidChangeLogLevel.fire(this.level))},n.prototype.getLevel=function(){return this.level},n}(r.Disposable);t.AbstractLogService=c;var l=function(e){function n(n){void 0===n&&(n=t.DEFAULT_LOG_LEVEL);var r=e.call(this)||this;return r.setLevel(n),r.useColors=!i.isWindows,r}return o(n,e),n.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Trace&&(this.useColors?console.log.apply(console,["[90m[main "+a()+"][0m",e].concat(t)):console.log.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]
;this.getLevel()<=u.Debug&&(this.useColors?console.log.apply(console,["[90m[main "+a()+"][0m",e].concat(t)):console.log.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Info&&(this.useColors?console.log.apply(console,["[90m[main "+a()+"][0m",e].concat(t)):console.log.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.warn=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Warning&&(this.useColors?console.warn.apply(console,["[93m[main "+a()+"][0m",e].concat(t)):console.warn.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Error&&(this.useColors?console.error.apply(console,["[91m[main "+a()+"][0m",e].concat(t)):console.error.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.critical=function(e){
for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Critical&&(this.useColors?console.error.apply(console,["[90m[main "+a()+"][0m",e].concat(t)):console.error.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.dispose=function(){},n}(c);t.ConsoleLogMainService=l;var f=function(e){function n(n){void 0===n&&(n=t.DEFAULT_LOG_LEVEL);var r=e.call(this)||this;return r.setLevel(n),r}return o(n,e),n.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Trace&&console.log.apply(console,["%cTRACE","color: #888",e].concat(t))},n.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Debug&&console.log.apply(console,["%cDEBUG","background: #eee; color: #888",e].concat(t))},n.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Info&&console.log.apply(console,["%c INFO","color: #33f",e].concat(t))},n.prototype.warn=function(e){
for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Warning&&console.log.apply(console,["%c WARN","color: #993",e].concat(t))},n.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Error&&console.log.apply(console,["%c ERR","color: #f33",e].concat(t))},n.prototype.critical=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Critical&&console.log.apply(console,["%cCRITI","background: #f33; color: white",e].concat(t))},n.prototype.dispose=function(){},n}(c);t.ConsoleLogService=f;var p=function(e){function t(t){var n=e.call(this)||this;return n.logServices=t,t.length&&n.setLevel(t[0].getLevel()),n}return o(t,e),t.prototype.setLevel=function(t){for(var n=0,r=this.logServices;n<r.length;n++){r[n].setLevel(t)}e.prototype.setLevel.call(this,t)},t.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r]
;o.trace.apply(o,[e].concat(t))}},t.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.debug.apply(o,[e].concat(t))}},t.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.info.apply(o,[e].concat(t))}},t.prototype.warn=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.warn.apply(o,[e].concat(t))}},t.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.error.apply(o,[e].concat(t))}},t.prototype.critical=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.critical.apply(o,[e].concat(t))}},t.prototype.dispose=function(){for(var e=0,t=this.logServices;e<t.length;e++){
t[e].dispose()}},t}(c);t.MultiplexLogService=p;var d=function(e){function t(t){var n=e.call(this)||this;return n.logService=t,n._register(t),n}return o(t,e),Object.defineProperty(t.prototype,"onDidChangeLogLevel",{get:function(){return this.logService.onDidChangeLogLevel},enumerable:!0,configurable:!0}),t.prototype.setLevel=function(e){this.logService.setLevel(e)},t.prototype.getLevel=function(){return this.logService.getLevel()},t.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).trace.apply(r,[e].concat(t))},t.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).debug.apply(r,[e].concat(t))},t.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).info.apply(r,[e].concat(t))},t.prototype.warn=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).warn.apply(r,[e].concat(t))},
t.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).error.apply(r,[e].concat(t))},t.prototype.critical=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).critical.apply(r,[e].concat(t))},t}(r.Disposable);t.DelegatedLogService=d;var h=function(){function e(){this.onDidChangeLogLevel=(new s.Emitter).event}return e.prototype.setLevel=function(e){},e.prototype.getLevel=function(){return u.Info},e.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.warn=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.critical=function(e){
for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.dispose=function(){},e}();t.NullLogService=h,t.getLogLevel=function(e){if(e.verbose)return u.Trace;if("string"==typeof e.args.log)switch(e.args.log.toLowerCase()){case"trace":return u.Trace;case"debug":return u.Debug;case"info":return u.Info;case"warn":return u.Warning;case"error":return u.Error;case"critical":return u.Critical;case"off":return u.Off}return t.DEFAULT_LOG_LEVEL}}),define(e[60],t([0,1,5,7]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createSpdLogService=function(t,o,s){try{var a=e.__$__nodeRequire("spdlog");a.setAsyncMode(8192,500);var u=n.join(s,t+".log"),c=new a.RotatingLogger(t,u,5242880,6);return c.setLevel(0),new i(c,o)}catch(e){console.error(e)}return new r.NullLogService},t.createRotatingLogger=function(t,n,r,i){return new(e.__$__nodeRequire("spdlog").RotatingLogger)(t,n,r,i)};var i=function(e){function t(t,n){void 0===n&&(n=r.LogLevel.Error);var i=e.call(this)||this
;return i.logger=t,i.setLevel(n),i}return o(t,e),t.prototype.trace=function(){this.getLevel()<=r.LogLevel.Trace&&this.logger.trace(this.format(arguments))},t.prototype.debug=function(){this.getLevel()<=r.LogLevel.Debug&&this.logger.debug(this.format(arguments))},t.prototype.info=function(){this.getLevel()<=r.LogLevel.Info&&this.logger.info(this.format(arguments))},t.prototype.warn=function(){this.getLevel()<=r.LogLevel.Warning&&this.logger.warn(this.format(arguments))},t.prototype.error=function(){if(this.getLevel()<=r.LogLevel.Error){var e=arguments[0];if(e instanceof Error){var t=Array.prototype.slice.call(arguments);t[0]=e.stack,this.logger.error(this.format(t))}else this.logger.error(this.format(arguments))}},t.prototype.critical=function(){this.getLevel()<=r.LogLevel.Critical&&this.logger.critical(this.format(arguments))},t.prototype.dispose=function(){this.logger.drop()},t.prototype.format=function(e){for(var t="",n=0;n<e.length;n++){var r=e[n];if("object"==typeof r)try{r=JSON.stringify(r)}catch(e){}
t+=(n>0?" ":"")+r}return t},t}(r.AbstractLogService)}),define(e[32],t([0,1,70,20]),function(e,t,n,r){"use strict";function i(e){return"*"===(e=e.trim())||c.test(e)}function o(e){if(!i(e))return null;if("*"===(e=e.trim()))return{hasCaret:!1,hasGreaterEquals:!1,majorBase:0,majorMustEqual:!1,minorBase:0,minorMustEqual:!1,patchBase:0,patchMustEqual:!1,preRelease:null};var t=e.match(c);return t?{hasCaret:"^"===t[1],hasGreaterEquals:">="===t[1],majorBase:"x"===t[2]?0:parseInt(t[2],10),majorMustEqual:"x"!==t[2],minorBase:"x"===t[4]?0:parseInt(t[4],10),minorMustEqual:"x"!==t[4],patchBase:"x"===t[6]?0:parseInt(t[6],10),patchMustEqual:"x"!==t[6],preRelease:t[8]||null}:null}function s(e){if(!e)return null;var t=e.majorBase,n=e.majorMustEqual,r=e.minorBase,i=e.minorMustEqual,o=e.patchBase,s=e.patchMustEqual;return e.hasCaret&&(0===t?s=!1:(i=!1,s=!1)),{majorBase:t,majorMustEqual:n,minorBase:r,minorMustEqual:i,patchBase:o,patchMustEqual:s,isMinimum:e.hasGreaterEquals}}function a(e,t){var n;n="string"==typeof e?s(o(e)):e
;var r;if(r="string"==typeof t?s(o(t)):t,!n||!r)return!1;var i=n.majorBase,a=n.minorBase,u=n.patchBase,c=r.majorBase,l=r.minorBase,f=r.patchBase,p=r.majorMustEqual,d=r.minorMustEqual,h=r.patchMustEqual;return r.isMinimum?i>c||!(i<c)&&(a>l||!(a<l)&&u>=f):(1!==i||0!==c||p&&d&&h||(c=1,l=0,f=0,p=!0,d=!1,h=!1),!(i<c)&&(i>c?!p:!(a<l)&&(a>l?!d:!(u<f)&&(!(u>f)||!h))))}function u(e,t,r){void 0===r&&(r=[]);var i=s(o(t));if(!i)return r.push(n.localize(0,null,t)),!1;if(0===i.majorBase){if(!i.majorMustEqual||!i.minorMustEqual)return r.push(n.localize(1,null,t)),!1}else if(!i.majorMustEqual)return r.push(n.localize(2,null,t)),!1;return!!a(e,i)||(r.push(n.localize(3,null,e,t)),!1)}Object.defineProperty(t,"__esModule",{value:!0});var c=/^(\^|>=)?((\d+)|x)\.((\d+)|x)\.((\d+)|x)(\-.*)?$/;t.isValidVersionStr=i,t.parseVersion=o,t.normalizeVersion=s,t.isValidVersion=a,t.isValidExtensionVersion=function(e,t,n){return!(!t.isBuiltin&&void 0!==t.main)||u(e,t.engines.vscode,n)},t.isEngineValid=function(e){
return"*"===e||u(r.default.version,e)},t.isVersionValid=u});var s=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};define(e[63],t([0,1,90,61,26,5,55,20,36,62,16,35,22]),function(e,t,n,r,i,o,a,u,c,l,f,p,d){"use strict";function h(e,t){return f.isWindows?function(e,t){return"\\\\.\\pipe\\"+n.createHash("md5").update(e).digest("hex")+"-"+u.default.version+"-"+t+"-sock"}(e,t):function(e,t){if(E){var r=n.createHash("md5").update(e).digest("hex").substr(0,8);return o.join(E,"vscode-"+r+"-"+u.default.version+"-"+t+".sock")}return o.join(e,u.default.version+"-"+t+".sock")}(e,t)}function g(e,t){return m(e.debugPluginHost,e.debugBrkPluginHost,5870,t,e.debugId)}function v(e,t){return m(e.debugSearch,e.debugBrkSearch,5876,t)}
function m(e,t,n,r,i){var o=t||e,s=Number(o)||(r?null:n);return{port:s,break:!!s&&Boolean(!!t),debugId:i}}function y(e,t){if(e){var n=o.resolve(e);return o.normalize(e)===n?n:o.resolve(t.env.VSCODE_CWD||t.cwd(),e)}}function b(e,t){return y(e["user-data-dir"],t)||o.resolve(r.getDefaultUserDataPath(t.platform))}Object.defineProperty(t,"__esModule",{value:!0});var E=process.env.XDG_RUNTIME_DIR,S=function(){function t(e,t){if(this._args=e,this._execPath=t,!process.env.VSCODE_LOGS){var n=l.toLocalISOString(new Date).replace(/-|:|\.\d+Z$/g,"");process.env.VSCODE_LOGS=o.join(this.userDataPath,"logs",n)}this.logsPath=process.env.VSCODE_LOGS}return Object.defineProperty(t.prototype,"args",{get:function(){return this._args},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appRoot",{get:function(){return o.dirname(p.getPathFromAmdModule(e,""))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"execPath",{get:function(){return this._execPath},enumerable:!0,configurable:!0}),
Object.defineProperty(t.prototype,"cliPath",{get:function(){return function(e,t,n){return f.isWindows?n?o.join(o.dirname(e),"bin",c.default.applicationName+".cmd"):o.join(t,"scripts","code-cli.bat"):f.isLinux?n?o.join(o.dirname(e),"bin",""+c.default.applicationName):o.join(t,"scripts","code-cli.sh"):n?o.join(t,"bin","code"):o.join(t,"scripts","code-cli.sh")}(this.execPath,this.appRoot,this.isBuilt)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"userHome",{get:function(){return i.homedir()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"userDataPath",{get:function(){var e=process.env.VSCODE_PORTABLE;return e?o.join(e,"user-data"):b(this._args,process)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appNameLong",{get:function(){return c.default.nameLong},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appQuality",{get:function(){return c.default.quality},enumerable:!0,configurable:!0}),
Object.defineProperty(t.prototype,"appSettingsHome",{get:function(){return o.join(this.userDataPath,"User")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appSettingsPath",{get:function(){return o.join(this.appSettingsHome,"settings.json")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalStorageHome",{get:function(){return o.join(this.appSettingsHome,"globalStorage")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"workspaceStorageHome",{get:function(){return o.join(this.appSettingsHome,"workspaceStorage")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"settingsSearchBuildId",{get:function(){return c.default.settingsSearchBuildId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"settingsSearchUrl",{get:function(){return c.default.settingsSearchUrl},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appKeybindingsPath",{get:function(){return o.join(this.appSettingsHome,"keybindings.json")},
enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isExtensionDevelopment",{get:function(){return!!this._args.extensionDevelopmentPath},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"backupHome",{get:function(){return o.join(this.userDataPath,"Backups")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"backupWorkspacesPath",{get:function(){return o.join(this.backupHome,"workspaces.json")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"workspacesHome",{get:function(){return o.join(this.userDataPath,"Workspaces")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"installSourcePath",{get:function(){return o.join(this.userDataPath,"installSource")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"builtinExtensionsPath",{get:function(){var t=y(this._args["builtin-extensions-dir"],process);return t||o.normalize(o.join(p.getPathFromAmdModule(e,""),"..","extensions"))},enumerable:!0,configurable:!0}),
Object.defineProperty(t.prototype,"extensionsPath",{get:function(){var e=y(this._args["extensions-dir"],process);if(e)return e;var t=process.env.VSCODE_EXTENSIONS;if(t)return t;var n=process.env.VSCODE_PORTABLE;return n?o.join(n,"extensions"):o.join(this.userHome,c.default.dataFolderName,"extensions")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"extensionDevelopmentLocationURI",{get:function(){var e=this._args.extensionDevelopmentPath;if(e)return/^[^:/?#]+?:\/\//.test(e)?d.URI.parse(e):d.URI.file(o.normalize(e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"extensionTestsPath",{get:function(){return this._args.extensionTestsPath?o.normalize(this._args.extensionTestsPath):this._args.extensionTestsPath},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disableExtensions",{get:function(){if(this._args["disable-extensions"])return!0;var e=this._args["disable-extension"];if(e){if("string"==typeof e)return[e];if(Array.isArray(e)&&e.length>0)return e}
return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipGettingStarted",{get:function(){return!!this._args["skip-getting-started"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipReleaseNotes",{get:function(){return!!this._args["skip-release-notes"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipAddToRecentlyOpened",{get:function(){return!!this._args["skip-add-to-recently-opened"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"debugExtensionHost",{get:function(){return g(this._args,this.isBuilt)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"debugSearch",{get:function(){return v(this._args,this.isBuilt)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBuilt",{get:function(){return!process.env.VSCODE_DEV},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"verbose",{get:function(){return!!this._args.verbose},enumerable:!0,configurable:!0}),
Object.defineProperty(t.prototype,"log",{get:function(){return this._args.log},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wait",{get:function(){return!!this._args.wait},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"logExtensionHostCommunication",{get:function(){return!!this._args.logExtensionHostCommunication},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"performance",{get:function(){return!!this._args.performance},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"status",{get:function(){return!!this._args.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mainIPCHandle",{get:function(){return h(this.userDataPath,"main")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sharedIPCHandle",{get:function(){return h(this.userDataPath,"shared")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nodeCachedDataDir",{get:function(){
return process.env.VSCODE_NODE_CACHED_DATA_DIR||void 0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disableUpdates",{get:function(){return!!this._args["disable-updates"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disableCrashReporter",{get:function(){return!!this._args["disable-crash-reporter"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"driverHandle",{get:function(){return this._args.driver},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"driverVerbose",{get:function(){return!!this._args["driver-verbose"]},enumerable:!0,configurable:!0}),s([a.memoize],t.prototype,"appRoot",null),s([a.memoize],t.prototype,"cliPath",null),s([a.memoize],t.prototype,"userHome",null),s([a.memoize],t.prototype,"userDataPath",null),s([a.memoize],t.prototype,"appSettingsHome",null),s([a.memoize],t.prototype,"appSettingsPath",null),s([a.memoize],t.prototype,"globalStorageHome",null),s([a.memoize],t.prototype,"workspaceStorageHome",null),
s([a.memoize],t.prototype,"settingsSearchBuildId",null),s([a.memoize],t.prototype,"settingsSearchUrl",null),s([a.memoize],t.prototype,"appKeybindingsPath",null),s([a.memoize],t.prototype,"isExtensionDevelopment",null),s([a.memoize],t.prototype,"backupHome",null),s([a.memoize],t.prototype,"backupWorkspacesPath",null),s([a.memoize],t.prototype,"workspacesHome",null),s([a.memoize],t.prototype,"installSourcePath",null),s([a.memoize],t.prototype,"builtinExtensionsPath",null),s([a.memoize],t.prototype,"extensionsPath",null),s([a.memoize],t.prototype,"extensionDevelopmentLocationURI",null),s([a.memoize],t.prototype,"extensionTestsPath",null),s([a.memoize],t.prototype,"debugExtensionHost",null),s([a.memoize],t.prototype,"debugSearch",null),s([a.memoize],t.prototype,"mainIPCHandle",null),s([a.memoize],t.prototype,"sharedIPCHandle",null),s([a.memoize],t.prototype,"nodeCachedDataDir",null),t}();t.EnvironmentService=S,t.parseExtensionHostPort=g,t.parseSearchPort=v,t.parseDebugPort=m,t.parseUserDataDir=b}),
define(e[14],t([0,1,3,56]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){this.data={}}return e.prototype.add=function(e,t){r.ok(n.isString(e)),r.ok(n.isObject(t)),r.ok(!this.data.hasOwnProperty(e),"There is already an extension with this id"),this.data[e]=t},e.prototype.knows=function(e){return this.data.hasOwnProperty(e)},e.prototype.as=function(e){return this.data[e]||null},e}();t.Registry=new i}),define(e[68],t([0,1,14,9]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Extensions={JSONContribution:"base.contributions.json"};var i=new(function(){function e(){this._onDidChangeSchema=new r.Emitter,this.onDidChangeSchema=this._onDidChangeSchema.event,this.schemasById={}}return e.prototype.registerSchema=function(e,t){this.schemasById[function(e){return e.length>0&&"#"===e.charAt(e.length-1)?e.substring(0,e.length-1):e}(e)]=t,this._onDidChangeSchema.fire(e)},e.prototype.notifySchemaChanged=function(e){
this._onDidChangeSchema.fire(e)},e.prototype.getSchemaContributions=function(){return{schemas:this.schemasById}},e}());n.Registry.add(t.Extensions.JSONContribution,i)}),define(e[15],t([0,1,65,9,14,3,10,68]),function(e,t,n,r,i,o,s,a){"use strict";function u(e){switch(Array.isArray(e)?e[0]:e){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};default:return null}}function c(e){return t.OVERRIDE_PROPERTY_PATTERN.test(e)?n.localize(3,null,e):void 0!==g.getConfigurationProperties()[e]?n.localize(4,null,e):null}Object.defineProperty(t,"__esModule",{value:!0}),t.Extensions={Configuration:"base.contributions.configuration"};!function(e){e[e.APPLICATION=1]="APPLICATION",e[e.WINDOW=2]="WINDOW",e[e.RESOURCE=3]="RESOURCE"}(t.ConfigurationScope||(t.ConfigurationScope={})),t.allSettings={properties:{},patternProperties:{}},t.applicationSettings={properties:{},patternProperties:{}},t.windowSettings={properties:{},patternProperties:{}},
t.resourceSettings={properties:{},patternProperties:{}},t.editorConfigurationSchemaId="vscode://schemas/settings/editor";var l=i.Registry.as(a.Extensions.JSONContribution),f=function(){function e(){this.overrideIdentifiers=[],this._onDidSchemaChange=new r.Emitter,this.onDidSchemaChange=this._onDidSchemaChange.event,this._onDidRegisterConfiguration=new r.Emitter,this.onDidRegisterConfiguration=this._onDidRegisterConfiguration.event,this.configurationContributors=[],this.editorConfigurationSchema={properties:{},patternProperties:{},additionalProperties:!1,errorMessage:"Unknown editor configuration setting"},this.configurationProperties={},this.excludedConfigurationProperties={},this.computeOverridePropertyPattern(),l.registerSchema(t.editorConfigurationSchemaId,this.editorConfigurationSchema)}return e.prototype.registerConfiguration=function(e,t){void 0===t&&(t=!0),this.registerConfigurations([e],[],t)},e.prototype.registerConfigurations=function(e,t,n){var r=this;void 0===n&&(n=!0)
;var i=this.toConfiguration(t);i&&e.push(i);var o=[];e.forEach(function(e){o.push.apply(o,r.validateAndRegisterProperties(e,n)),r.configurationContributors.push(e),r.registerJSONConfiguration(e),r.updateSchemaForOverrideSettingsConfiguration(e)}),this._onDidRegisterConfiguration.fire(o)},e.prototype.notifyConfigurationSchemaUpdated=function(e){l.notifySchemaChanged(t.editorConfigurationSchemaId)},e.prototype.registerOverrideIdentifiers=function(e){var t;(t=this.overrideIdentifiers).push.apply(t,e),this.updateOverridePropertyPatternKey()},e.prototype.toConfiguration=function(e){for(var r={id:"defaultOverrides",title:n.localize(0,null),properties:{}},i=0,o=e;i<o.length;i++){var s=o[i];for(var a in s.defaults){var u=s.defaults[a];t.OVERRIDE_PROPERTY_PATTERN.test(a)&&"object"==typeof u&&(r.properties[a]={type:"object",default:u,description:n.localize(1,null,a),$ref:t.editorConfigurationSchemaId})}}return Object.keys(r.properties).length?r:null},e.prototype.validateAndRegisterProperties=function(e,n,r,i){
void 0===n&&(n=!0),void 0===r&&(r=2),void 0===i&&(i=!1),r=o.isUndefinedOrNull(e.scope)?r:e.scope,i=e.overridable||i;var s=[],a=e.properties;if(a)for(var l in a){var f=void 0;if(n&&(f=c(l)))console.warn(f),delete a[l];else{var p=a[l],d=p.default;o.isUndefined(d)&&(p.default=u(p.type)),i&&(p.overridable=!0),t.OVERRIDE_PROPERTY_PATTERN.test(l)?p.scope=void 0:p.scope=o.isUndefinedOrNull(p.scope)?r:p.scope,!a[l].hasOwnProperty("included")||a[l].included?(this.configurationProperties[l]=a[l],s.push(l)):(this.excludedConfigurationProperties[l]=a[l],delete a[l])}}var h=e.allOf;if(h)for(var g=0,v=h;g<v.length;g++){var m=v[g];s.push.apply(s,this.validateAndRegisterProperties(m,n,r,i))}return s},e.prototype.getConfigurations=function(){return this.configurationContributors},e.prototype.getConfigurationProperties=function(){return this.configurationProperties},e.prototype.getExcludedConfigurationProperties=function(){return this.excludedConfigurationProperties},e.prototype.registerJSONConfiguration=function(e){
function n(e){var r=e.properties;if(r)for(var i in r)switch(t.allSettings.properties[i]=r[i],r[i].scope){case 1:t.applicationSettings.properties[i]=r[i];break;case 2:t.windowSettings.properties[i]=r[i];break;case 3:t.resourceSettings.properties[i]=r[i]}var o=e.allOf;o&&o.forEach(n)}n(e),this._onDidSchemaChange.fire()},e.prototype.updateSchemaForOverrideSettingsConfiguration=function(e){e.id!==p&&(this.update(e),l.registerSchema(t.editorConfigurationSchemaId,this.editorConfigurationSchema))},e.prototype.updateOverridePropertyPatternKey=function(){var e=t.allSettings.patternProperties[this.overridePropertyPattern];e||(e={type:"object",description:n.localize(2,null),errorMessage:"Unknown Identifier. Use language identifiers",$ref:t.editorConfigurationSchemaId}),delete t.allSettings.patternProperties[this.overridePropertyPattern],delete t.applicationSettings.patternProperties[this.overridePropertyPattern],delete t.windowSettings.patternProperties[this.overridePropertyPattern],
delete t.resourceSettings.patternProperties[this.overridePropertyPattern],this.computeOverridePropertyPattern(),t.allSettings.patternProperties[this.overridePropertyPattern]=e,t.applicationSettings.patternProperties[this.overridePropertyPattern]=e,t.windowSettings.patternProperties[this.overridePropertyPattern]=e,t.resourceSettings.patternProperties[this.overridePropertyPattern]=e,this._onDidSchemaChange.fire()},e.prototype.update=function(e){var t=this,n=e.properties;if(n)for(var r in n)n[r].overridable&&(this.editorConfigurationSchema.properties[r]=this.getConfigurationProperties()[r]);var i=e.allOf;i&&i.forEach(function(e){return t.update(e)})},e.prototype.computeOverridePropertyPattern=function(){this.overridePropertyPattern=this.overrideIdentifiers.length?h.replace("${0}",this.overrideIdentifiers.map(function(e){return s.createRegExp(e,!1).source}).join("|")):d},e}(),p="override",d="\\[.*\\]$",h="\\[(${0})\\]$";t.OVERRIDE_PROPERTY_PATTERN=new RegExp(d),t.getDefaultValue=u;var g=new f
;i.Registry.add(t.Extensions.Configuration,g),t.validateProperty=c,t.getScopes=function(){for(var e={},t=g.getConfigurationProperties(),n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];e[i]=t[i].scope}return e.launch=3,e.task=3,e}}),define(e[13],t([0,1,6,3,22,14,2,15]),function(e,t,n,r,i,o,s,a){"use strict";function u(e,t){var n=Object.create(null);for(var r in e)c(n,r,e[r],t);return n}function c(e,t,n,r){for(var i=t.split("."),o=i.pop(),s=e,a=0;a<i.length;a++){var u=i[a],c=s[u];switch(typeof c){case"undefined":c=s[u]=Object.create(null);break;case"object":break;default:return void r("Ignoring "+t+" as "+i.slice(0,a+1).join(".")+" is "+JSON.stringify(c))}s=c}"object"==typeof s?s[o]=n:r("Ignoring "+t+" as "+i.join(".")+" is "+JSON.stringify(s))}function l(e,t){var n=t.shift();if(0!==t.length){if(-1!==Object.keys(e).indexOf(n)){var r=e[n];"object"!=typeof r||Array.isArray(r)||(l(r,t),0===Object.keys(r).length&&delete e[n])}}else delete e[n]}function f(e,t,n){var r=function(e,t){for(var n=e,r=0;r<t.length;r++){
if("object"!=typeof n||null===n)return;n=n[t[r]]}return n}(e,t.split("."));return void 0===r?n:r}function p(e,t,n){Object.keys(t).forEach(function(i){i in e?r.isObject(e[i])&&r.isObject(t[i])?p(e[i],t[i],n):n&&(e[i]=t[i]):e[i]=t[i]})}function d(e){return e.substring(1,e.length-1)}Object.defineProperty(t,"__esModule",{value:!0}),t.IConfigurationService=s.createDecorator("configurationService"),t.isConfigurationOverrides=function(e){return e&&"object"==typeof e&&(!e.overrideIdentifier||"string"==typeof e.overrideIdentifier)&&(!e.resource||e.resource instanceof i.URI)};!function(e){e[e.USER=1]="USER",e[e.WORKSPACE=2]="WORKSPACE",e[e.WORKSPACE_FOLDER=3]="WORKSPACE_FOLDER",e[e.DEFAULT=4]="DEFAULT",e[e.MEMORY=5]="MEMORY"}(t.ConfigurationTarget||(t.ConfigurationTarget={})),t.ConfigurationTargetToString=function(e){switch(e){case 1:return"USER";case 2:return"WORKSPACE";case 3:return"WORKSPACE_FOLDER";case 4:return"DEFAULT";case 5:return"MEMORY"}},t.compare=function(e,t){for(var r=t.keys.filter(function(t){
return-1===e.keys.indexOf(t)}),i=e.keys.filter(function(e){return-1===t.keys.indexOf(e)}),o=[],s=0,a=e.keys;s<a.length;s++){var u=a[s],c=f(e.contents,u),l=f(t.contents,u);n.equals(c,l)||o.push(u)}return{added:r,removed:i,updated:o}},t.toOverrides=function(e,t){for(var n=[],r=o.Registry.as(a.Extensions.Configuration).getConfigurationProperties(),i=0,s=Object.keys(e);i<s.length;i++){var c=s[i];if(a.OVERRIDE_PROPERTY_PATTERN.test(c)){var l={};for(var f in e[c])r[f]&&r[f].overridable&&(l[f]=e[c][f]);n.push({identifiers:[d(c).trim()],contents:u(l,t)})}}return n},t.toValuesTree=u,t.addToValueTree=c,t.removeFromValueTree=function(e,t){l(e,t.split("."))},t.getConfigurationValue=f,t.merge=p,t.getConfigurationKeys=function(){var e=o.Registry.as(a.Extensions.Configuration).getConfigurationProperties();return Object.keys(e)},t.getDefaultValues=function(){var e=Object.create(null),t=o.Registry.as(a.Extensions.Configuration).getConfigurationProperties();for(var n in t)c(e,n,t[n].default,function(e){
return console.error("Conflict in default settings: "+e)});return e},t.overrideIdentifierFromKey=d,t.keyFromOverrideIdentifier=function(e){return"["+e+"]"}}),define(e[40],t([0,1,37,33,19,3,6,15,13]),function(e,t,n,r,i,s,a,u,c){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var l=function(){function e(e,t,n){void 0===e&&(e={}),void 0===t&&(t=[]),void 0===n&&(n=[]),this._contents=e,this._keys=t,this._overrides=n,this.isFrozen=!1}return Object.defineProperty(e.prototype,"contents",{get:function(){return this.checkAndFreeze(this._contents)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"overrides",{get:function(){return this.checkAndFreeze(this._overrides)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"keys",{get:function(){return this.checkAndFreeze(this._keys)},enumerable:!0,configurable:!0}),e.prototype.getValue=function(e){return e?c.getConfigurationValue(this.contents,e):this.contents},e.prototype.override=function(t){
var n=this.getContentsForOverrideIdentifer(t);if(!n||"object"!=typeof n||!Object.keys(n).length)return this;for(var r={},o=0,s=i.distinct(Object.keys(this.contents).concat(Object.keys(n)));o<s.length;o++){var u=s[o],c=this.contents[u],l=n[u];l&&("object"==typeof c&&"object"==typeof l?(c=a.deepClone(c),this.mergeContents(c,l)):c=l),r[u]=c}return new e(r)},e.prototype.merge=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var r=a.deepClone(this.contents),o=a.deepClone(this.overrides),s=this.keys.slice(),u=0,c=t;u<c.length;u++){var l=c[u];this.mergeContents(r,l.contents);for(var f=function(e){var t=o.filter(function(t){return i.equals(t.identifiers,e.identifiers)})[0];t?p.mergeContents(t.contents,e.contents):o.push(a.deepClone(e))},p=this,d=0,h=l.overrides;d<h.length;d++){f(h[d])}for(var g=0,v=l.keys;g<v.length;g++){var m=v[g];-1===s.indexOf(m)&&s.push(m)}}return new e(r,s,o)},e.prototype.freeze=function(){return this.isFrozen=!0,this},e.prototype.mergeContents=function(e,t){
for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];i in e&&s.isObject(e[i])&&s.isObject(t[i])?this.mergeContents(e[i],t[i]):e[i]=a.deepClone(t[i])}},e.prototype.checkAndFreeze=function(e){return this.isFrozen&&!Object.isFrozen(e)?a.deepFreeze(e):e},e.prototype.getContentsForOverrideIdentifer=function(e){for(var t=0,n=this.overrides;t<n.length;t++){var r=n[t];if(-1!==r.identifiers.indexOf(e))return r.contents}return null},e.prototype.toJSON=function(){return{contents:this.contents,overrides:this.overrides,keys:this.keys}},e.prototype.setValue=function(e,t){this.addKey(e),c.addToValueTree(this.contents,e,t,function(e){throw new Error(e)})},e.prototype.removeValue=function(e){this.removeKey(e)&&c.removeFromValueTree(this.contents,e)},e.prototype.addKey=function(e){for(var t=this.keys.length,n=0;n<t;n++)0===e.indexOf(this.keys[n])&&(t=n);this.keys.splice(t,1,e)},e.prototype.removeKey=function(e){var t=this.keys.indexOf(e);return-1!==t&&(this.keys.splice(t,1),!0)},e}();t.ConfigurationModel=l
;var f=function(e){function t(){for(var t=c.getDefaultValues(),n=c.getConfigurationKeys(),r=[],i=0,o=Object.keys(t);i<o.length;i++){var s=o[i];u.OVERRIDE_PROPERTY_PATTERN.test(s)&&r.push({identifiers:[c.overrideIdentifierFromKey(s).trim()],contents:c.toValuesTree(t[s],function(e){return console.error("Conflict in default settings file: "+e)})})}return e.call(this,t,n,r)||this}return o(t,e),t}(l);t.DefaultConfigurationModel=f;var p=function(){function e(e){this._name=e,this._configurationModel=null,this._parseErrors=[]}return Object.defineProperty(e.prototype,"configurationModel",{get:function(){return this._configurationModel||new l},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"errors",{get:function(){return this._parseErrors},enumerable:!0,configurable:!0}),e.prototype.parse=function(e){if(e){var t=this.parseContent(e),n=this.parseRaw(t);this._configurationModel=new l(n.contents,n.keys,n.overrides)}},e.prototype.parseContent=function(e){function t(e){
Array.isArray(o)?o.push(e):i&&(o[i]=e)}var r={},i=null,o=[],s=[],a=[],u={onObjectBegin:function(){var e={};t(e),s.push(o),o=e,i=null},onObjectProperty:function(e){i=e},onObjectEnd:function(){o=s.pop()},onArrayBegin:function(){var e=[];t(e),s.push(o),o=e,i=null},onArrayEnd:function(){o=s.pop()},onLiteralValue:t,onError:function(e,t,n){a.push({error:e,offset:t,length:n})}};if(e)try{n.visit(e,u),r=o[0]||{}}catch(e){console.error("Error while parsing settings file "+this._name+": "+e),this._parseErrors=[e]}return r},e.prototype.parseRaw=function(e){var t=this;return{contents:c.toValuesTree(e,function(e){return console.error("Conflict in settings file "+t._name+": "+e)}),keys:Object.keys(e),overrides:c.toOverrides(e,function(e){return console.error("Conflict in settings file "+t._name+": "+e)})}},e}();t.ConfigurationModelParser=p;var d=function(){function e(e,t,n,i,o,s,a){void 0===n&&(n=new l),void 0===i&&(i=new r.ResourceMap),void 0===o&&(o=new l),void 0===s&&(s=new r.ResourceMap),void 0===a&&(a=!0),
this._defaultConfiguration=e,this._userConfiguration=t,this._workspaceConfiguration=n,this._folderConfigurations=i,this._memoryConfiguration=o,this._memoryConfigurationByResource=s,this._freeze=a,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations=new r.ResourceMap}return e.prototype.getValue=function(e,t,n){return this.getConsolidateConfigurationModel(t,n).getValue(e)},e.prototype.updateValue=function(e,t,n){void 0===n&&(n={});var r;n.resource?(r=this._memoryConfigurationByResource.get(n.resource))||(r=new l,this._memoryConfigurationByResource.set(n.resource,r)):r=this._memoryConfiguration,void 0===t?r.removeValue(e):r.setValue(e,t),n.resource||(this._workspaceConsolidatedConfiguration=null)},e.prototype.inspect=function(e,t,n){var r=this.getConsolidateConfigurationModel(t,n),i=this.getFolderConfigurationModelForResource(t.resource,n),o=t.resource?this._memoryConfigurationByResource.get(t.resource)||this._memoryConfiguration:this._memoryConfiguration;return{
default:t.overrideIdentifier?this._defaultConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._defaultConfiguration.freeze().getValue(e),user:t.overrideIdentifier?this._userConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._userConfiguration.freeze().getValue(e),workspace:n?t.overrideIdentifier?this._workspaceConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._workspaceConfiguration.freeze().getValue(e):void 0,workspaceFolder:i?t.overrideIdentifier?i.freeze().override(t.overrideIdentifier).getValue(e):i.freeze().getValue(e):void 0,memory:t.overrideIdentifier?o.freeze().override(t.overrideIdentifier).getValue(e):o.freeze().getValue(e),value:r.getValue(e)}},e.prototype.keys=function(e){var t=this.getFolderConfigurationModelForResource(void 0,e);return{default:this._defaultConfiguration.freeze().keys,user:this._userConfiguration.freeze().keys,workspace:this._workspaceConfiguration.freeze().keys,workspaceFolder:t?t.freeze().keys:[]}},
e.prototype.updateDefaultConfiguration=function(e){this._defaultConfiguration=e,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()},e.prototype.updateUserConfiguration=function(e){this._userConfiguration=e,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()},e.prototype.updateWorkspaceConfiguration=function(e){this._workspaceConfiguration=e,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()},e.prototype.updateFolderConfiguration=function(e,t){this._folderConfigurations.set(e,t),this._foldersConsolidatedConfigurations.delete(e)},e.prototype.deleteFolderConfiguration=function(e){this.folders.delete(e),this._foldersConsolidatedConfigurations.delete(e)},Object.defineProperty(e.prototype,"defaults",{get:function(){return this._defaultConfiguration},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"user",{get:function(){return this._userConfiguration},enumerable:!0,
configurable:!0}),Object.defineProperty(e.prototype,"workspace",{get:function(){return this._workspaceConfiguration},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"folders",{get:function(){return this._folderConfigurations},enumerable:!0,configurable:!0}),e.prototype.getConsolidateConfigurationModel=function(e,t){var n=this.getConsolidatedConfigurationModelForResource(e,t);return e.overrideIdentifier?n.override(e.overrideIdentifier):n},e.prototype.getConsolidatedConfigurationModelForResource=function(e,t){var n=e.resource,r=this.getWorkspaceConsolidatedConfiguration();if(t&&n){var i=t.getFolder(n);i&&(r=this.getFolderConsolidatedConfiguration(i.uri)||r);var o=this._memoryConfigurationByResource.get(n);o&&(r=r.merge(o))}return r},e.prototype.getWorkspaceConsolidatedConfiguration=function(){return this._workspaceConsolidatedConfiguration||(this._workspaceConsolidatedConfiguration=this._defaultConfiguration.merge(this._userConfiguration,this._workspaceConfiguration,this._memoryConfiguration),
this._freeze&&(this._workspaceConfiguration=this._workspaceConfiguration.freeze())),this._workspaceConsolidatedConfiguration},e.prototype.getFolderConsolidatedConfiguration=function(e){var t=this._foldersConsolidatedConfigurations.get(e);if(!t){var n=this.getWorkspaceConsolidatedConfiguration(),r=this._folderConfigurations.get(e);r?(t=n.merge(r),this._freeze&&(t=t.freeze()),this._foldersConsolidatedConfigurations.set(e,t)):t=n}return t},e.prototype.getFolderConfigurationModelForResource=function(e,t){if(t&&e){var n=t.getFolder(e);if(n)return this._folderConfigurations.get(n.uri)}return null},e.prototype.toData=function(){var e=this;return{defaults:{contents:this._defaultConfiguration.contents,overrides:this._defaultConfiguration.overrides,keys:this._defaultConfiguration.keys},user:{contents:this._userConfiguration.contents,overrides:this._userConfiguration.overrides,keys:this._userConfiguration.keys},workspace:{contents:this._workspaceConfiguration.contents,overrides:this._workspaceConfiguration.overrides,
keys:this._workspaceConfiguration.keys},folders:this._folderConfigurations.keys().reduce(function(t,n){var r=e._folderConfigurations.get(n),i=r.contents,o=r.overrides,s=r.keys;return t[n.toString()]={contents:i,overrides:o,keys:s},t},Object.create({})),isComplete:!0}},e.prototype.allKeys=function(e){var t=this.keys(e),n=t.default.slice(),r=function(e){for(var t=0,r=e;t<r.length;t++){var i=r[t];-1===n.indexOf(i)&&n.push(i)}};r(t.user),r(t.workspace);for(var i=0,o=this.folders.keys();i<o.length;i++){var s=o[i];r(this.folders.get(s).keys)}return n},e}();t.Configuration=d;var h=function(){function e(){}return e.prototype.doesConfigurationContains=function(e,t){for(var n,r,i=e.contents,o=c.toValuesTree((n={},n[t]=!0,n),function(){});"object"==typeof o&&(r=Object.keys(o)[0]);){if(!(i=i[r]))return!1;o=o[r]}return!0},e.prototype.updateKeys=function(e,t,n){for(var r=0,i=t;r<i.length;r++){var o=i[r];e.setValue(o,{})}},e}();t.AbstractConfigurationChangeEvent=h;var g=function(e){function t(t,n){void 0===t&&(t=new l),
void 0===n&&(n=new r.ResourceMap);var i=e.call(this)||this;return i._changedConfiguration=t,i._changedConfigurationByResource=n,i}return o(t,e),Object.defineProperty(t.prototype,"changedConfiguration",{get:function(){return this._changedConfiguration},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"changedConfigurationByResource",{get:function(){return this._changedConfigurationByResource},enumerable:!0,configurable:!0}),t.prototype.change=function(e,n){if(e instanceof t){this._changedConfiguration=this._changedConfiguration.merge(e._changedConfiguration);for(var r=0,i=e._changedConfigurationByResource.keys();r<i.length;r++){var o=i[r],s=this.getOrSetChangedConfigurationForResource(o);s=s.merge(e._changedConfigurationByResource.get(o)),this._changedConfigurationByResource.set(o,s)}}else this.changeWithKeys(e,n);return this},t.prototype.telemetryData=function(e,t){return this._source=e,this._sourceConfig=t,this},Object.defineProperty(t.prototype,"affectedKeys",{get:function(){
var e=this._changedConfiguration.keys.slice();return this._changedConfigurationByResource.forEach(function(t){return e.push.apply(e,t.keys)}),i.distinct(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"source",{get:function(){return this._source},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sourceConfig",{get:function(){return this._sourceConfig},enumerable:!0,configurable:!0}),t.prototype.affectsConfiguration=function(e,t){var n=[this._changedConfiguration];if(t){var r=this._changedConfigurationByResource.get(t);r&&n.push(r)}else n.push.apply(n,this._changedConfigurationByResource.values());for(var i=0,o=n;i<o.length;i++){var s=o[i];if(this.doesConfigurationContains(s,e))return!0}return!1},t.prototype.changeWithKeys=function(e,t){var n=t?this.getOrSetChangedConfigurationForResource(t):this._changedConfiguration;this.updateKeys(n,e)},t.prototype.getOrSetChangedConfigurationForResource=function(e){var t=this._changedConfigurationByResource.get(e);return t||(t=new l,
this._changedConfigurationByResource.set(e,t)),t},t}(h);t.ConfigurationChangeEvent=g}),define(e[72],t([0,1,11,23,40,48,9]),function(e,t,n,r,i,s,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var u=function(e){function t(t){var n=e.call(this)||this;return n.settingsPath=t,n._onDidChangeConfiguration=n._register(new a.Emitter),n.onDidChangeConfiguration=n._onDidChangeConfiguration.event,n}return o(t,e),t.prototype.initialize=function(){var e=this;return this.initializePromise||(this.initializePromise=new Promise(function(t,n){e.userConfigModelWatcher=new s.ConfigWatcher(e.settingsPath,{changeBufferDelay:300,onError:function(e){return r.onUnexpectedError(e)},defaultConfig:new i.ConfigurationModelParser(e.settingsPath),parse:function(t,n){var r=new i.ConfigurationModelParser(e.settingsPath);return r.parse(t),r.errors.slice(),r},initCallback:function(){return t(void 0)}}),e._register(e.userConfigModelWatcher),e._register(e.userConfigModelWatcher.onDidUpdateConfiguration(function(){
return e._onDidChangeConfiguration.fire(e.userConfigModelWatcher.getConfig().configurationModel)}))})),this.initializePromise.then(function(){return e.userConfigModelWatcher.getConfig().configurationModel})},t.prototype.initializeSync=function(){return this.initialize(),this.userConfigModelWatcher.getConfig().configurationModel},t.prototype.reload=function(){var e=this;return this.initialize().then(function(){return new Promise(function(t){return e.userConfigModelWatcher.reload(function(e){return t(e.configurationModel)})})})},t}(n.Disposable);t.UserConfiguration=u});var a=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};define(e[73],t([0,1,14,15,11,13,40,9,17,72]),function(e,t,n,r,i,u,c,l,f,p){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var d=function(e){function t(t){var i=e.call(this)||this;i._onDidChangeConfiguration=i._register(new l.Emitter),i.onDidChangeConfiguration=i._onDidChangeConfiguration.event,
i.userConfiguration=i._register(new p.UserConfiguration(t.appSettingsPath));var o=new c.DefaultConfigurationModel,s=i.userConfiguration.initializeSync();return i._configuration=new c.Configuration(o,s),i._register(i.userConfiguration.onDidChangeConfiguration(function(e){return i.onDidChangeUserConfiguration(e)})),i._register(n.Registry.as(r.Extensions.Configuration).onDidRegisterConfiguration(function(e){return i.onDidRegisterConfiguration(e)})),i}return o(t,e),Object.defineProperty(t.prototype,"configuration",{get:function(){return this._configuration},enumerable:!0,configurable:!0}),t.prototype.getConfigurationData=function(){return this.configuration.toData()},t.prototype.getValue=function(e,t){var n="string"==typeof e?e:void 0,r=u.isConfigurationOverrides(e)?e:u.isConfigurationOverrides(t)?t:{};return this.configuration.getValue(n,r,null)},t.prototype.updateValue=function(e,t,n,r){return Promise.reject(new Error("not supported"))},t.prototype.inspect=function(e){
return this.configuration.inspect(e,{},null)},t.prototype.keys=function(){return this.configuration.keys(null)},t.prototype.reloadConfiguration=function(e){var t=this;return e?Promise.resolve(void 0):this.userConfiguration.reload().then(function(e){return t.onDidChangeUserConfiguration(e)})},t.prototype.onDidChangeUserConfiguration=function(e){var t=u.compare(this._configuration.user,e),n=t.added,r=t.updated,i=t.removed,o=n.concat(r,i);o.length&&(this._configuration.updateUserConfiguration(e),this.trigger(o,1))},t.prototype.onDidRegisterConfiguration=function(e){this._configuration.updateDefaultConfiguration(new c.DefaultConfigurationModel),this.trigger(e,4)},t.prototype.trigger=function(e,t){this._onDidChangeConfiguration.fire((new c.ConfigurationChangeEvent).change(e).telemetryData(t,this.getTargetConfiguration(t)))},t.prototype.getTargetConfiguration=function(e){switch(e){case 4:return this._configuration.defaults.contents;case 1:return this._configuration.user.contents}return{}},
t=s([a(0,f.IEnvironmentService)],t)}(i.Disposable);t.ConfigurationService=d}),define(e[41],t([0,1,74,2,15,14]),function(e,t,n,r,i,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IRequestService=r.createDecorator("requestService2"),o.Registry.as(i.Extensions.Configuration).registerConfiguration({id:"http",order:15,title:n.localize(0,null),type:"object",properties:{"http.proxy":{type:"string",pattern:"^https?://([^:]*(:[^@]*)?@)?([^:]+)(:\\d+)?/?$|^$",description:n.localize(1,null)},"http.proxyStrictSSL":{type:"boolean",default:!0,description:n.localize(2,null)},"http.proxyAuthorization":{type:["null","string"],default:null,description:n.localize(3,null)},"http.proxySupport":{type:"string",enum:["off","on","override"],enumDescriptions:[n.localize(4,null),n.localize(5,null),n.localize(6,null)],default:"override",description:n.localize(7,null)}}})}),define(e[75],t([0,1,2]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),
t.IStateService=n.createDecorator("stateService")}),define(e[76],t([0,1,5,24,17,39,3,7,12]),function(e,t,n,r,i,o,u,c,l){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var f=function(){function e(e,t){this.dbPath=e,this.onError=t,this._database=null,this.lastFlushedSerializedDatabase=null}return Object.defineProperty(e.prototype,"database",{get:function(){return this._database||(this._database=this.loadSync()),this._database},enumerable:!0,configurable:!0}),e.prototype.init=function(){var e=this;return l.readFile(this.dbPath).then(function(t){try{e.lastFlushedSerializedDatabase=t.toString(),e._database=JSON.parse(e.lastFlushedSerializedDatabase)}catch(t){e._database={}}},function(t){"ENOENT"!==t.code&&e.onError(t),e._database={}})},e.prototype.loadSync=function(){try{return this.lastFlushedSerializedDatabase=r.readFileSync(this.dbPath).toString(),JSON.parse(this.lastFlushedSerializedDatabase)}catch(e){return"ENOENT"!==e.code&&this.onError(e),{}}},e.prototype.getItem=function(e,t){
var n=this.database[e];return u.isUndefinedOrNull(n)?t:n},e.prototype.setItem=function(e,t){if(u.isUndefinedOrNull(t))return this.removeItem(e);("string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t||this.database[e]!==t)&&(this.database[e]=t,this.saveSync())},e.prototype.removeItem=function(e){u.isUndefined(this.database[e])||(this.database[e]=void 0,this.saveSync())},e.prototype.saveSync=function(){var e=JSON.stringify(this.database,null,4);if(e!==this.lastFlushedSerializedDatabase)try{o.writeFileAndFlushSync(this.dbPath,e),this.lastFlushedSerializedDatabase=e}catch(e){this.onError(e)}},e}();t.FileStorage=f;var p=function(){function e(t,r){this.fileStorage=new f(n.join(t.userDataPath,e.STATE_FILE),function(e){return r.error(e)})}return e.prototype.init=function(){return this.fileStorage.init()},e.prototype.getItem=function(e,t){return this.fileStorage.getItem(e,t)},e.prototype.setItem=function(e,t){this.fileStorage.setItem(e,t)},e.prototype.removeItem=function(e){this.fileStorage.removeItem(e)},
e.STATE_FILE="storage.json",e=s([a(0,i.IEnvironmentService),a(1,c.ILogService)],e)}();t.StateService=p}),define(e[27],t([0,1,2]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ITelemetryService=n.createDecorator("telemetryService")}),define(e[78],t([0,1,77,10,2,13,15,11,6,14]),function(e,t,n,r,i,o,u,c,l,f){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var p=function(){function e(e,t){this._configurationService=t,this._disposables=[],this._cleanupPatterns=[],this._appender=e.appender,this._commonProperties=e.commonProperties||Promise.resolve({}),this._piiPaths=e.piiPaths||[],this._userOptIn=!0,this._cleanupPatterns=[/file:\/\/\/.*?\/resources\/app\//gi];for(var n=0,i=this._piiPaths;n<i.length;n++){var o=i[n];this._cleanupPatterns.push(new RegExp(r.escapeRegExpCharacters(o),"gi"))}this._configurationService&&(this._updateUserOptIn(),this._configurationService.onDidChangeConfiguration(this._updateUserOptIn,this,this._disposables),this.publicLog("optInStatus",{
optIn:this._userOptIn}))}return e.prototype._updateUserOptIn=function(){var e=this._configurationService.getValue(d);this._userOptIn=e?e.enableTelemetry:this._userOptIn},Object.defineProperty(e.prototype,"isOptedIn",{get:function(){return this._userOptIn},enumerable:!0,configurable:!0}),e.prototype.getTelemetryInfo=function(){return this._commonProperties.then(function(e){return{sessionId:e.sessionID,instanceId:e["common.instanceId"],machineId:e["common.machineId"]}})},e.prototype.dispose=function(){this._disposables=c.dispose(this._disposables)},e.prototype.publicLog=function(e,t,n){var r=this;return this._userOptIn?this._commonProperties.then(function(i){t=l.mixin(t,i),t=l.cloneAndChange(t,function(e){if("string"==typeof e)return r._cleanupInfo(e,n)}),r._appender.log(e,t)},function(e){console.error(e)}):Promise.resolve(void 0)},e.prototype._cleanupInfo=function(e,t){var n=e;if(t){for(var r=[],i=0,o=this._cleanupPatterns;i<o.length;i++)for(d=o[i];;){var s=d.exec(e);if(!s)break;r.push([s.index,d.lastIndex])}
var a=/^[\\\/]?(node_modules|node_modules\.asar)[\\\/]/,u=/(file:\/\/)?([a-zA-Z]:(\\\\|\\|\/)|(\\\\|\\|\/))?([\w-\._]+(\\\\|\\|\/))+[\w-\._]*/g,c=0;n="";for(var l=function(){var t=u.exec(e);if(!t)return"break";!a.test(t[0])&&r.every(function(e){var n=e[0],r=e[1];return t.index<n||t.index>=r})&&(n+=e.substring(c,t.index)+"<REDACTED: user-file-path>",c=u.lastIndex)};;){if("break"===l())break}c<e.length&&(n+=e.substr(c))}for(var f=0,p=this._cleanupPatterns;f<p.length;f++){var d=p[f];n=n.replace(d,"")}return n},e.IDLE_START_EVENT_NAME="UserIdleStart",e.IDLE_STOP_EVENT_NAME="UserIdleStop",e=s([a(1,i.optional(o.IConfigurationService))],e)}();t.TelemetryService=p;var d="telemetry";f.Registry.as(u.Extensions.Configuration).registerConfiguration({id:d,order:110,type:"object",title:n.localize(0,null),properties:{"telemetry.enableTelemetry":{type:"boolean",description:n.localize(1,null),default:!0,tags:["usesOnlineServices"]}}})}),define(e[79],t([0,1,50,25,13,7]),function(e,t,n,r,i,o){"use strict";function u(e,t){
return t.onDidChangeConfiguration(function(t){4!==t.source&&(e.publicLog("updateConfiguration",{configurationSource:i.ConfigurationTargetToString(t.source),configurationKeys:function(e){if(!e)return[];var t=[];return c(t,"",e),t}(t.sourceConfig)}),e.publicLog("updateConfigurationValues",{configurationSource:i.ConfigurationTargetToString(t.source),configurationValues:function(e,t){if(!e)return[];return t.reduce(function(t,n){var r,i=n.split(".").reduce(function(e,t){return e&&"object"==typeof e?e[t]:void 0},e);return void 0!==i&&t.push((r={},r[n]=i,r)),t},[])}(t.sourceConfig,f)}))})}function c(e,t,n){n&&"object"==typeof n&&!Array.isArray(n)?Object.keys(n).forEach(function(r){return c(e,t?t+"."+r:r,n[r])}):e.push(t)}Object.defineProperty(t,"__esModule",{value:!0}),t.NullTelemetryService=new(function(){function e(){}return e.prototype.publicLog=function(e,t){return Promise.resolve(void 0)},e.prototype.getTelemetryInfo=function(){return Promise.resolve({instanceId:"someValue.instanceId",
sessionId:"someValue.sessionId",machineId:"someValue.machineId"})},e}()),t.combinedAppender=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return{log:function(t,n){return e.forEach(function(e){return e.log(t,n)})},dispose:function(){return Promise.all(e.map(function(e){return e.dispose()}))}}},t.NullAppender={log:function(){return null},dispose:function(){return Promise.resolve(null)}};var l=function(){function e(e){this._logService=e,this.commonPropertiesRegex=/^sessionID$|^version$|^timestamp$|^commitHash$|^common\./}return e.prototype.dispose=function(){return Promise.resolve(void 0)},e.prototype.log=function(e,t){var n=this,r={};Object.keys(t).forEach(function(e){n.commonPropertiesRegex.test(e)||(r[e]=t[e])}),this._logService.trace("telemetry/"+e,r)},e=s([a(0,o.ILogService)],e)}();t.LogAppender=l,t.telemetryURIDescriptor=function(e,t){var i=e&&e.fsPath;return i?{mimeType:n.guessMimeTypes(i).join(", "),scheme:e.scheme,ext:r.extname(i),path:t(i)}:{}}
;var f=["editor.fontFamily","editor.fontWeight","editor.fontSize","editor.lineHeight","editor.letterSpacing","editor.lineNumbers","editor.rulers","editor.wordSeparators","editor.tabSize","editor.insertSpaces","editor.detectIndentation","editor.roundedSelection","editor.scrollBeyondLastLine","editor.minimap.enabled","editor.minimap.side","editor.minimap.renderCharacters","editor.minimap.maxColumn","editor.find.seedSearchStringFromSelection","editor.find.autoFindInSelection","editor.wordWrap","editor.wordWrapColumn","editor.wrappingIndent","editor.mouseWheelScrollSensitivity","editor.multiCursorModifier","editor.quickSuggestions","editor.quickSuggestionsDelay","editor.parameterHints.enabled","editor.parameterHints.cycle","editor.autoClosingBrackets","editor.autoClosingQuotes","editor.autoSurround","editor.autoIndent","editor.formatOnType","editor.formatOnPaste","editor.suggestOnTriggerCharacters","editor.acceptSuggestionOnEnter","editor.acceptSuggestionOnCommitCharacter","editor.snippetSuggestions","editor.emptySelectionClipboard","editor.wordBasedSuggestions","editor.suggestSelection","editor.suggestFontSize","editor.suggestLineHeight","editor.tabCompletion","editor.selectionHighlight","editor.occurrencesHighlight","editor.overviewRulerLanes","editor.overviewRulerBorder","editor.cursorBlinking","editor.cursorSmoothCaretAnimation","editor.cursorStyle","editor.mouseWheelZoom","editor.fontLigatures","editor.hideCursorInOverviewRuler","editor.renderWhitespace","editor.renderControlCharacters","editor.renderIndentGuides","editor.renderLineHighlight","editor.codeLens","editor.folding","editor.showFoldingControls","editor.matchBrackets","editor.glyphMargin","editor.useTabStops","editor.trimAutoWhitespace","editor.stablePeek","editor.dragAndDrop","editor.formatOnSave","editor.colorDecorators","breadcrumbs.enabled","breadcrumbs.filePath","breadcrumbs.symbolPath","breadcrumbs.symbolSortOrder","breadcrumbs.useQuickPick","explorer.openEditors.visible","extensions.autoUpdate","files.associations","files.autoGuessEncoding","files.autoSave","files.autoSaveDelay","files.encoding","files.eol","files.hotExit","files.trimTrailingWhitespace","git.confirmSync","git.enabled","http.proxyStrictSSL","javascript.validate.enable","php.builtInCompletions.enable","php.validate.enable","php.validate.run","terminal.integrated.fontFamily","window.openFilesInNewWindow","window.restoreWindows","window.zoomLevel","workbench.editor.enablePreview","workbench.editor.enablePreviewFromQuickOpen","workbench.editor.showTabs","workbench.editor.highlightModifiedTabs","workbench.editor.swipeToNavigate","workbench.sideBar.location","workbench.startupEditor","workbench.statusBar.visible","workbench.welcome.enabled"]
;t.configurationTelemetry=u,t.keybindingsTelemetry=function(e,t){return t.onDidUpdateKeybindings(function(t){2===t.source&&t.keybindings&&e.publicLog("updateKeybindings",{bindings:t.keybindings.map(function(e){return{key:e.key,command:e.command,when:e.when,args:!!e.args||void 0}})})})}}),define(e[80],t([0,1,89,3,6,7]),function(e,t,n,r,i,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t,r,i){this._eventPrefix=e,this._defaultData=t,this._logService=i,this._defaultData||(this._defaultData=Object.create(null)),"string"==typeof r?this._aiClient=function(e){var t;return n.defaultClient?(t=new n.TelemetryClient(e)).channel.setUseDiskRetryCaching(!0):(n.setup(e).setAutoCollectRequests(!1).setAutoCollectPerformance(!1).setAutoCollectExceptions(!1).setAutoCollectDependencies(!1).setAutoDependencyCorrelation(!1).setAutoCollectConsole(!1).setInternalLogging(!1,!1).setUseDiskRetryCaching(!0).start(),t=n.defaultClient),
0===e.indexOf("AIF-")&&(t.config.endpointUrl="https://vortex.data.microsoft.com/collect/v1"),t}(r):"function"==typeof r&&(this._aiClient=r())}return e._getData=function(t){var n=Object.create(null),r=Object.create(null),i=Object.create(null);e._flaten(t,i);for(var o in i){var s=i[o=o.length>150?o.substr(o.length-149):o];"number"==typeof s?r[o]=s:"boolean"==typeof s?r[o]=s?1:0:"string"==typeof s?n[o]=s.substring(0,1023):void 0!==s&&null!==s&&(n[o]=s)}return{properties:n,measurements:r}},e._flaten=function(t,n,o,s){if(void 0===o&&(o=0),t)for(var a=0,u=Object.getOwnPropertyNames(t);a<u.length;a++){var c=u[a],l=t[c],f=s?s+c:c;Array.isArray(l)?n[f]=i.safeStringify(l):l instanceof Date?n[f]=l.toISOString():r.isObject(l)?o<2?e._flaten(l,n,o+1,f+"."):n[f]=i.safeStringify(l):n[f]=l}},e.prototype.log=function(t,n){this._aiClient&&(n=i.mixin(n,this._defaultData),n=e._getData(n),this._logService&&this._logService.trace("telemetry/"+t,n),this._aiClient.trackEvent({name:this._eventPrefix+"/"+t,properties:n.properties,
measurements:n.measurements}))},e.prototype.dispose=function(){var e=this;if(this._aiClient)return new Promise(function(t){e._aiClient.flush({callback:function(){e._aiClient=void 0,t(void 0)}})})},e=s([a(3,o.ILogService)],e)}();t.AppInsightsAppender=u}),define(e[82],t([0,1,16,26,43,12]),function(e,t,n,r,i,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveCommonProperties=function(e,t,s,a){var u=Object.create(null);u["common.machineId"]=s,u.sessionID=i.generateUuid()+Date.now(),u.commitHash=e,u.version=t,u["common.platformVersion"]=(r.release()||"").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/,"$1$2$3"),u["common.platform"]=n.PlatformToString(n.platform),u["common.nodePlatform"]=process.platform,u["common.nodeArch"]=process.arch;var c=0,l=Date.now();return Object.defineProperties(u,{timestamp:{get:function(){return new Date},enumerable:!0},"common.timesincesessionstart":{get:function(){return Date.now()-l},enumerable:!0},"common.sequence":{get:function(){return c++},enumerable:!0}}),
o.readFile(a,"utf8").then(function(e){return u["common.source"]=e.slice(0,30),u},function(e){return u})}}),define(e[44],t([0,1,71,5,24,21,12,88,87,9]),function(e,t,n,r,i,s,a,u,c,l){"use strict";function f(e,t,o,u,c){var f=s.createCancelablePromise(function(){return Promise.resolve()}),p=0;return l.Event.once(c.onCancellationRequested)(function(){u.debug(t,"Cancelled."),f.cancel(),e.close()}),new Promise(function(u,d){var g=new s.Sequencer,v=function(t){t.isCancellationRequested||(p++,e.readEntry())};e.once("error",d),e.once("close",function(){return f.then(function(){c.isCancellationRequested||e.entryCount===p?u():d(new h("Incomplete",new Error(n.localize(1,null,p,e.entryCount))))},d)}),e.readEntry(),e.on("entry",function(u){if(!c.isCancellationRequested)if(o.sourcePathRegex.test(u.fileName)){var p=u.fileName.replace(o.sourcePathRegex,"");if(/\/$/.test(p)){var h=r.join(t,p);f=s.createCancelablePromise(function(e){return a.mkdirp(h,void 0,e).then(function(){return v(e)}).then(void 0,d)})}else{
var m=s.ninvoke(e,e.openReadStream,u),y=function(e){var t=e.externalFileAttributes>>16||33188;return[448,56,7].map(function(e){return t&e}).reduce(function(e,t){return e+t},61440&t)}(u);f=s.createCancelablePromise(function(e){return g.queue(function(){return m.then(function(o){return function(e,t,o,s,u,c){var f=r.dirname(t),p=r.join(s,f);if(0!==p.indexOf(s))return Promise.reject(new Error(n.localize(0,null,t)));var d,h=r.join(s,t);return l.Event.once(c.onCancellationRequested)(function(){d&&d.destroy()}),Promise.resolve(a.mkdirp(p,void 0,c)).then(function(){return new Promise(function(t,n){if(!c.isCancellationRequested)try{(d=i.createWriteStream(h,{mode:o})).once("close",function(){return t()}),d.once("error",n),e.once("error",n),e.pipe(d)}catch(e){n(e)}})})}(o,p,y,t,0,e).then(function(){return v(e)})})}).then(null,d)})}}else v(c)})})}function p(e,t){return void 0===t&&(t=!1),s.nfcall(u.open,e,t?{lazyEntries:!0}:void 0).then(void 0,function(e){return Promise.reject(function(e){if(e instanceof h)return e
;var t=void 0;return/end of central directory record signature not found/.test(e.message)&&(t="CorruptZip"),new h(t,e)}(e))})}function d(e,t){return function(e,t){return p(e).then(function(e){return new Promise(function(r,i){e.on("entry",function(n){n.fileName===t&&s.ninvoke(e,e.openReadStream,n).then(function(e){return r(e)},function(e){return i(e)})}),e.once("close",function(){return i(new Error(n.localize(2,null,t)))})})})}(e,t).then(function(e){return new Promise(function(t,n){var r=[];e.once("error",n),e.on("data",function(e){return r.push(e)}),e.on("end",function(){return t(Buffer.concat(r))})})})}Object.defineProperty(t,"__esModule",{value:!0});var h=function(e){function t(t,n){var r=this,i=n.message;switch(t){case"CorruptZip":i="Corrupt ZIP: "+i}return r=e.call(this,i)||this,r.type=t,r.cause=n,r}return o(t,e),t}(Error);t.ExtractError=h,t.zip=function(e,t){return new Promise(function(n,r){var o=new c.ZipFile;t.forEach(function(e){
e.contents?o.addBuffer("string"==typeof e.contents?Buffer.from(e.contents,"utf8"):e.contents,e.path):e.localPath&&o.addFile(e.localPath,e.path)}),o.end();var s=i.createWriteStream(e);o.outputStream.pipe(s),o.outputStream.once("error",r),s.once("error",r),s.once("finish",function(){return n(e)})})},t.extract=function(e,t,n,r,i){void 0===n&&(n={});var o=new RegExp(n.sourcePath?"^"+n.sourcePath:""),s=p(e,!0);return n.overwrite&&(s=s.then(function(e){return a.rimraf(t).then(function(){return e})})),s.then(function(e){return f(e,t,{sourcePathRegex:o},r,i)})},t.buffer=d}),define(e[42],t([0,1,45,18,44,69]),function(e,t,n,r,i,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getIdAndVersionFromLocalExtensionId=function(e){var t=r.LOCAL_EXTENSION_ID_REGEX.exec(e);if(t&&t[1]&&t[2]){var i=n.valid(t[2]);if(i)return{id:r.adoptToGalleryExtensionId(t[1]),version:i}}return{id:r.adoptToGalleryExtensionId(e),version:null}},t.getManifest=function(e){return i.buffer(e,"extension/package.json").then(function(e){
try{return JSON.parse(e.toString("utf8"))}catch(e){throw new Error(o.localize(0,null))}})}}),define(e[81],t([0,1,67,5,12,6,11,19,44,28,18,84,17,21,9,45,22,20,16,7,49,85,31,27,32,26,43,52,2,30,35,42]),function(e,t,i,u,c,l,f,p,d,h,g,v,m,y,b,E,S,x,C,P,_,w,I,O,k,j,T,D,L,M,R,A){"use strict";function F(e){return new Promise(function(t,n){try{var r=JSON.parse(e),o=r.__metadata||null;delete r.__metadata,t({manifest:r,metadata:o})}catch(e){n(new Error(i.localize(0,null)))}})}function N(e,t){return g.getLocalExtensionId(e.identifier.id,t)}function U(e){return g.getLocalExtensionId(g.getGalleryExtensionId(e.publisher,e.name),e.version)}Object.defineProperty(t,"__esModule",{value:!0});var z=function(e){function t(t,n){var r=e.call(this,t)||this;return r.code=n,r}return o(t,e),t}(Error);t.ExtensionManagementError=z;var V=function(t){function V(e,n,r,i,o){var s=t.call(this)||this;return s.environmentService=e,s.galleryService=n,s.logService=r,s.downloadService=i,s.telemetryService=o,s.lastReportTimestamp=0,
s.installingExtensions=new Map,s.uninstallingExtensions=new Map,s._onInstallExtension=new b.Emitter,s.onInstallExtension=s._onInstallExtension.event,s._onDidInstallExtension=new b.Emitter,s.onDidInstallExtension=s._onDidInstallExtension.event,s._onUninstallExtension=new b.Emitter,s.onUninstallExtension=s._onUninstallExtension.event,s._onDidUninstallExtension=new b.Emitter,s.onDidUninstallExtension=s._onDidUninstallExtension.event,s._devSystemExtensionsPath=null,s._devSystemExtensionsFilePath=null,s.systemExtensionsPath=e.builtinExtensionsPath,s.extensionsPath=e.extensionsPath,s.uninstalledPath=u.join(s.extensionsPath,".obsolete"),s.uninstalledFileLimiter=new y.Queue,s.manifestCache=s._register(new _.ExtensionsManifestCache(e,s)),s.extensionLifecycle=s._register(new w.ExtensionsLifecycle(e,s.logService)),s._register(f.toDisposable(function(){s.installingExtensions.forEach(function(e){return e.cancel()}),s.uninstallingExtensions.forEach(function(e){return e.cancel()}),s.installingExtensions.clear(),
s.uninstallingExtensions.clear()})),s}return o(V,t),V.prototype.zip=function(e){return this.logService.trace("ExtensionManagementService#zip",e.identifier.id),this.collectFiles(e).then(function(e){return d.zip(u.join(j.tmpdir(),T.generateUuid()),e)}).then(function(e){return S.URI.file(e)})},V.prototype.unzip=function(e,t){return this.logService.trace("ExtensionManagementService#unzip",e.toString()),this.install(e,t)},V.prototype.collectFiles=function(e){var t=this,i=function(e){return n(t,void 0,void 0,function(){var t,n,o;return r(this,function(r){switch(r.label){case 0:return[4,c.readdir(e)];case 1:return t=r.sent(),t=t.map(function(t){return u.join(e,t)}),[4,Promise.all(t.map(function(e){return c.stat(e)}))];case 2:return n=r.sent(),o=Promise.resolve([]),n.forEach(function(e,n){var r=t[n];e.isFile()&&(o=o.then(function(e){return e.concat([r])})),e.isDirectory()&&(o=o.then(function(e){return i(r).then(function(t){return e.concat(t)})}))}),[2,o]}})})};return i(e.location.fsPath).then(function(t){
return t.map(function(t){return{path:"extension/"+u.relative(e.location.fsPath,t),localPath:t}})})},V.prototype.install=function(e,t){var n=this;return void 0===t&&(t=1),this.logService.trace("ExtensionManagementService#install",e.toString()),y.createCancelablePromise(function(r){return n.downloadVsix(e).then(function(e){var o=u.resolve(e.fsPath);return A.getManifest(o).then(function(e){var s={id:U(e)};return e.engines&&e.engines.vscode&&!k.isEngineValid(e.engines.vscode)?Promise.reject(new Error(i.localize(1,null,s.id,x.default.version))):n.removeIfExists(s.id).then(function(){var i={id:g.getGalleryExtensionId(e.publisher,e.name)};return n.getInstalled(1).then(function(t){var r=t.filter(function(t){return g.areSameExtensions(i,{id:g.getGalleryExtensionIdFromLocal(t)})&&E.gt(t.manifest.version,e.version)})[0];return r?n.uninstall(r,!0):void 0}).then(function(){return n.logService.info("Installing the extension:",s.id),n._onInstallExtension.fire({identifier:s,zipPath:o}),
n.getMetadata(g.getGalleryExtensionId(e.publisher,e.name)).then(function(e){return n.installFromZipPath(s,o,e,t,r)},function(e){return n.installFromZipPath(s,o,null,t,r)}).then(function(){return n.logService.info("Successfully installed the extension:",s.id),s},function(e){return n.logService.error("Failed to install the extension:",s.id,e.message),Promise.reject(e)})})},function(t){return Promise.reject(new Error(i.localize(2,null,e.displayName||e.name)))})})})})},V.prototype.downloadVsix=function(e){if(e.scheme===M.Schemas.file)return Promise.resolve(e);if(!this.downloadService)throw new Error("Download service is not available");var t=u.join(j.tmpdir(),T.generateUuid());return this.downloadService.download(e,t).then(function(){return S.URI.file(t)})},V.prototype.removeIfExists=function(e){var t=this;return this.getInstalled(1).then(function(t){return t.filter(function(t){return t.identifier.id===e})[0]}).then(function(e){return e?t.removeExtension(e,"existing"):void 0})},
V.prototype.installFromZipPath=function(e,t,n,r,i){var o=this;return this.toNonCancellablePromise(this.getInstalled().then(function(s){var a=o.getOperation({id:g.getIdFromLocalExtensionId(e.id),uuid:e.uuid},s);return o.installExtension({zipPath:t,id:e.id,metadata:n},r,i).then(function(e){return o.installDependenciesAndPackExtensions(e,null).then(function(){return e},function(t){return o.uninstall(e,!0).then(function(){return Promise.reject(t)},function(){return Promise.reject(t)})})}).then(function(n){return o._onDidInstallExtension.fire({identifier:e,zipPath:t,local:n,operation:a}),n},function(n){return o._onDidInstallExtension.fire({identifier:e,zipPath:t,operation:a,error:n}),Promise.reject(n)})}))},V.prototype.installFromGallery=function(e){return n(this,void 0,void 0,function(){var t,n,i,o,s,a,u,l,f,p,d,h,v,m=this;return r(this,function(r){switch(r.label){case 0:t=(new Date).getTime(),this.logService.info("Installing extension:",e.name),this._onInstallExtension.fire({identifier:e.identifier,gallery:e}),
n=function(e,n,r){m.logService.info("Extensions installed successfully:",e.identifier.id),m._onDidInstallExtension.fire({identifier:{id:N(e,e.version),uuid:e.identifier.uuid},gallery:e,local:r,operation:n}),m.reportTelemetry(m.getTelemetryEvent(n),g.getGalleryExtensionTelemetryData(e),(new Date).getTime()-t,void 0)},i=function(e,n,r){var i=r&&r.code?r.code:"unknown";m.logService.error("Failed to install extension:",e.identifier.id,r?r.message:i),m._onDidInstallExtension.fire({identifier:e.identifier,gallery:e,operation:n,error:i}),m.reportTelemetry(m.getTelemetryEvent(n),g.getGalleryExtensionTelemetryData(e),(new Date).getTime()-t,r),r instanceof Error&&(r.name=i)},r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.checkAndGetCompatibleVersion(e)];case 2:return e=r.sent(),[3,4];case 3:return o=r.sent(),i(e,1,o),[2,Promise.reject(o)];case 4:if(s=g.getLocalExtensionId(e.identifier.id,e.version),a=this.installingExtensions.get(s))return[3,10];u=1,a=y.createCancelablePromise(function(e){return l=e,
new Promise(function(e,t){f=e,p=t})}),this.installingExtensions.set(s,a),r.label=5;case 5:return r.trys.push([5,9,,10]),[4,this.getInstalled(1)];case 6:return d=r.sent(),(h=d.filter(function(t){return g.areSameExtensions(t.galleryIdentifier,e.identifier)})[0])?(u=2,E.gt(h.manifest.version,e.version)?[4,this.uninstall(h,!0)]:[3,8]):[3,8];case 7:r.sent(),r.label=8;case 8:return this.downloadInstallableExtension(e,u).then(function(e){return m.installExtension(e,1,l).then(function(t){return y.always(c.rimraf(e.zipPath),function(){return null}).then(function(){return t})})}).then(function(e){return m.installDependenciesAndPackExtensions(e,h).then(function(){return e},function(t){return m.uninstall(e,!0).then(function(){return Promise.reject(t)},function(){return Promise.reject(t)})})}).then(function(t){m.installingExtensions.delete(s),n(e,u,t),f(null)},function(t){m.installingExtensions.delete(s),i(e,u,t),p(t)}),[3,10];case 9:return v=r.sent(),this.installingExtensions.delete(s),i(e,u,v),[2,Promise.reject(v)]
;case 10:return[2,a]}})})},V.prototype.checkAndGetCompatibleVersion=function(e){return n(this,void 0,void 0,function(){var t;return r(this,function(n){switch(n.label){case 0:return[4,this.isMalicious(e)];case 1:return n.sent()?[2,Promise.reject(new z(i.localize(3,null),h.INSTALL_ERROR_MALICIOUS))]:[4,this.galleryService.loadCompatibleVersion(e)];case 2:return(t=n.sent())?[2,t]:[2,Promise.reject(new z(i.localize(4,null,e.identifier.id,x.default.version),h.INSTALL_ERROR_INCOMPATIBLE))]}})})},V.prototype.reinstallFromGallery=function(e){var t=this;return this.logService.trace("ExtensionManagementService#reinstallFromGallery",e.identifier.id),this.galleryService.isEnabled()?this.findGalleryExtension(e).then(function(n){return n?t.setUninstalled(e).then(function(){return t.removeUninstalledExtension(e).then(function(){return t.installFromGallery(n)},function(e){return Promise.reject(new Error(i.localize(6,null,I.toErrorMessage(e))))})}):Promise.reject(new Error(i.localize(7,null)))
}):Promise.reject(new Error(i.localize(5,null)))},V.prototype.getOperation=function(e,t){return t.some(function(t){return g.areSameExtensions({id:g.getGalleryExtensionIdFromLocal(t),uuid:t.identifier.uuid},e)})?2:1},V.prototype.getTelemetryEvent=function(e){return 2===e?"extensionGallery:update":"extensionGallery:install"},V.prototype.isMalicious=function(e){return this.getExtensionsReport().then(function(t){return g.getMaliciousExtensionsSet(t).has(e.identifier.id)})},V.prototype.downloadInstallableExtension=function(e,t){var n=this,r={id:e.identifier.uuid,publisherId:e.publisherId,publisherDisplayName:e.publisherDisplayName};return this.logService.trace("Started downloading extension:",e.name),this.galleryService.download(e,t).then(function(t){return n.logService.info("Downloaded extension:",e.name,t),A.getManifest(t).then(function(e){return{zipPath:t,id:U(e),metadata:r}},function(e){return Promise.reject(new z(n.joinErrors(e).message,"validating"))})},function(e){
return Promise.reject(new z(n.joinErrors(e).message,"downloading"))})},V.prototype.installExtension=function(e,t,n){var r=this;return this.unsetUninstalledAndGetLocal(e.id).then(function(i){return i||r.extractAndInstall(e,t,n)},function(e){return C.isMacintosh?Promise.reject(new z(i.localize(8,null),"unsetUninstalled")):Promise.reject(new z(i.localize(9,null),"unsetUninstalled"))})},V.prototype.unsetUninstalledAndGetLocal=function(e){var t=this;return this.isUninstalled(e).then(function(n){return n?(t.logService.trace("Removing the extension from uninstalled list:",e),t.unsetUninstalled(e).then(function(){return t.logService.info("Removed the extension from uninstalled list:",e),t.getInstalled(1)}).then(function(t){return t.filter(function(t){return t.identifier.id===e})[0]})):null})},V.prototype.extractAndInstall=function(e,t,n){var r=this,o=e.zipPath,s=e.id,a=e.metadata,l=1===t?this.extensionsPath:this.systemExtensionsPath,f=u.join(l,"."+s),p=u.join(l,s);return c.rimraf(p).then(function(){
return r.extractAndRename(s,o,f,p,n)},function(e){return Promise.reject(new z(i.localize(10,null,p,s),"deleting"))}).then(function(){return r.scanExtension(s,l,t)}).then(function(e){return e?(r.logService.info("Installation completed.",s),a?(e.metadata=a,r.saveMetadataForLocalExtension(e)):e):Promise.reject(i.localize(11,null,l))},function(e){return c.rimraf(p).then(function(){return Promise.reject(e)},function(){return Promise.reject(e)})})},V.prototype.extractAndRename=function(e,t,n,r,i){var o=this;return this.extract(e,t,n,i).then(function(){return o.rename(e,n,r,Date.now()+12e4).then(function(){return o.logService.info("Renamed to",r)},function(e){return o.logService.info("Rename failed. Deleting from extracted location",n),y.always(c.rimraf(n),function(){return null}).then(function(){return Promise.reject(e)})})})},V.prototype.extract=function(e,t,n,r){var i=this;return this.logService.trace("Started extracting the extension from "+t+" to "+n),c.rimraf(n).then(function(){return d.extract(t,n,{
sourcePath:"extension",overwrite:!0},i.logService,r).then(function(){return i.logService.info("Extracted extension to "+n+":",e)},function(e){return y.always(c.rimraf(n),function(){return null}).then(function(){return Promise.reject(new z(e.message,e instanceof d.ExtractError&&e.type?e.type:"extracting"))})})},function(e){return Promise.reject(new z(i.joinErrors(e).message,"deleting"))})},V.prototype.rename=function(e,t,n,r){var o=this;return c.rename(t,n).then(void 0,function(s){return C.isWindows&&s&&"EPERM"===s.code&&Date.now()<r?(o.logService.info("Failed renaming "+t+" to "+n+" with 'EPERM' error. Trying again..."),o.rename(e,t,n,r)):Promise.reject(new z(s.message||i.localize(12,null,t,n),s.code||"renaming"))})},V.prototype.installDependenciesAndPackExtensions=function(e,t){var n=this;if(this.galleryService.isEnabled()){var r=e.manifest.extensionDependencies||[];if(e.manifest.extensionPack)for(var i=function(e){t&&t.manifest.extensionPack&&t.manifest.extensionPack.some(function(t){
return g.areSameExtensions({id:t},{id:e})})||r.every(function(t){return!g.areSameExtensions({id:t},{id:e})})&&r.push(e)},o=0,s=e.manifest.extensionPack;o<s.length;o++){i(s[o])}if(r.length)return this.getInstalled().then(function(e){var t=r.filter(function(t){return!n.installingExtensions.has(g.adoptToGalleryExtensionId(t))&&e.every(function(e){var n=e.galleryIdentifier;return!g.areSameExtensions(n,{id:t})})});return t.length?n.galleryService.query({names:t,pageSize:r.length}).then(function(e){var t=e.firstPage;return Promise.all(t.map(function(e){return n.installFromGallery(e)})).then(function(){return null},function(e){return n.rollback(t).then(function(){return Promise.reject(e)},function(){return Promise.reject(e)})})}):null})}return Promise.resolve(void 0)},V.prototype.rollback=function(e){var t=this;return this.getInstalled(1).then(function(n){return Promise.all(n.filter(function(t){return e.some(function(e){return t.identifier.id===N(e,e.version)})}).map(function(e){return t.uninstall(e,!0)}))
}).then(function(){},function(){})},V.prototype.uninstall=function(e,t){var n=this;return void 0===t&&(t=!1),this.logService.trace("ExtensionManagementService#uninstall",e.identifier.id),this.toNonCancellablePromise(this.getInstalled(1).then(function(t){var r=t.filter(function(t){return t.manifest.publisher===e.manifest.publisher&&t.manifest.name===e.manifest.name});if(r.length){var o=r.map(function(e){return n.checkForDependenciesAndUninstall(e,t)});return Promise.all(o).then(function(){return null},function(e){return Promise.reject(n.joinErrors(e))})}return Promise.reject(new Error(i.localize(13,null,e.manifest.displayName||e.manifest.name)))}))},V.prototype.updateMetadata=function(e,t){var n=this;return this.logService.trace("ExtensionManagementService#updateMetadata",e.identifier.id),e.metadata=t,this.saveMetadataForLocalExtension(e).then(function(e){return n.manifestCache.invalidate(),e})},V.prototype.saveMetadataForLocalExtension=function(e){if(!e.metadata)return Promise.resolve(e)
;var t=u.join(this.extensionsPath,e.identifier.id,"package.json");return c.readFile(t,"utf8").then(function(e){return F(e)}).then(function(t){var n=t.manifest;return l.assign(n,{__metadata:e.metadata})}).then(function(e){return c.writeFile(t,JSON.stringify(e,null,"\t"))}).then(function(){return e})},V.prototype.getMetadata=function(e){return this.findGalleryExtensionByName(e).then(function(e){return e?{id:e.identifier.uuid,publisherDisplayName:e.publisherDisplayName,publisherId:e.publisherId}:null})},V.prototype.findGalleryExtension=function(e){var t=this;return e.identifier.uuid?this.findGalleryExtensionById(e.identifier.uuid).then(function(n){return n||t.findGalleryExtensionByName(g.getGalleryExtensionIdFromLocal(e))}):this.findGalleryExtensionByName(g.getGalleryExtensionIdFromLocal(e))},V.prototype.findGalleryExtensionById=function(e){return this.galleryService.query({ids:[e],pageSize:1}).then(function(e){return e.firstPage[0]})},V.prototype.findGalleryExtensionByName=function(e){
return this.galleryService.query({names:[e],pageSize:1}).then(function(e){return e.firstPage[0]})},V.prototype.joinErrors=function(e){var t=Array.isArray(e)?e:[e];return 1===t.length?t[0]instanceof Error?t[0]:new Error(t[0]):t.reduce(function(e,t){return new Error(e.message+(e.message?",":"")+(t instanceof Error?t.message:t))},new Error(""))},V.prototype.checkForDependenciesAndUninstall=function(e,t){var n=this;return this.preUninstallExtension(e).then(function(){var r=n.getAllPackExtensionsToUninstall(e,t);return r.length?n.uninstallExtensions(e,r,t):n.uninstallExtensions(e,[],t)}).then(function(){return n.postUninstallExtension(e)},function(t){return n.postUninstallExtension(e,new z(t instanceof Error?t.message:t,"local")),Promise.reject(t)})},V.prototype.uninstallExtensions=function(e,t,n){var r=this,i=this.getDependents(e,n);if(i.length){var o=i.filter(function(n){return e!==n&&-1===t.indexOf(n)});if(o.length)return Promise.reject(new Error(this.getDependentsErrorMessage(e,o)))}
return Promise.all([this.uninstallExtension(e)].concat(t.map(function(e){return r.doUninstall(e)}))).then(function(){})},V.prototype.getDependentsErrorMessage=function(e,t){return 1===t.length?i.localize(14,null,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name):2===t.length?i.localize(15,null,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name,t[1].manifest.displayName||t[1].manifest.name):i.localize(16,null,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name,t[1].manifest.displayName||t[1].manifest.name)},V.prototype.getAllPackExtensionsToUninstall=function(e,t,n){if(void 0===n&&(n=[]),-1!==n.indexOf(e))return[];n.push(e);var r=e.manifest.extensionPack?e.manifest.extensionPack:[];if(r.length){for(var i=t.filter(function(e){return r.some(function(t){return g.areSameExtensions({id:t},e.galleryIdentifier)})}),o=[],s=0,a=i;s<a.length;s++){var u=a[s];o.push.apply(o,this.getAllPackExtensionsToUninstall(u,t,n))}
return i.concat(o)}return[]},V.prototype.getDependents=function(e,t){return t.filter(function(t){return t.manifest.extensionDependencies&&t.manifest.extensionDependencies.some(function(t){return g.areSameExtensions({id:t},e.galleryIdentifier)})})},V.prototype.doUninstall=function(e){var t=this;return this.preUninstallExtension(e).then(function(){return t.uninstallExtension(e)}).then(function(){return t.postUninstallExtension(e)},function(n){return t.postUninstallExtension(e,new z(n instanceof Error?n.message:n,"local")),Promise.reject(n)})},V.prototype.preUninstallExtension=function(e){var t=this;return Promise.resolve(c.exists(e.location.fsPath)).then(function(e){return e?null:Promise.reject(new Error(i.localize(17,null)))}).then(function(){t.logService.info("Uninstalling extension:",e.identifier.id),t._onUninstallExtension.fire(e.identifier)})},V.prototype.uninstallExtension=function(e){var t=this,n=g.getGalleryExtensionIdFromLocal(e),r=this.uninstallingExtensions.get(n)
;return r||(r=y.createCancelablePromise(function(r){return t.scanUserExtensions(!1).then(function(r){return t.setUninstalled.apply(t,r.filter(function(t){return g.areSameExtensions({id:g.getGalleryExtensionIdFromLocal(t),uuid:t.identifier.uuid},{id:n,uuid:e.identifier.uuid})}))}).then(function(){t.uninstallingExtensions.delete(n)})}),this.uninstallingExtensions.set(n,r)),r},V.prototype.postUninstallExtension=function(e,t){return n(this,void 0,void 0,function(){var n;return r(this,function(r){switch(r.label){case 0:return t?(this.logService.error("Failed to uninstall extension:",e.identifier.id,t.message),[3,3]):[3,1];case 1:return this.logService.info("Successfully uninstalled extension:",e.identifier.id),e.identifier.uuid?[4,this.galleryService.reportStatistic(e.manifest.publisher,e.manifest.name,e.manifest.version,"uninstall")]:[3,3];case 2:r.sent(),r.label=3;case 3:return this.reportTelemetry("extensionGallery:uninstall",g.getLocalExtensionTelemetryData(e),void 0,t),
n=t?t instanceof z?t.code:"unknown":void 0,this._onDidUninstallExtension.fire({identifier:e.identifier,error:n}),[2]}})})},V.prototype.getInstalled=function(e){var t=this;void 0===e&&(e=null);var n=[];return null!==e&&0!==e||n.push(this.scanSystemExtensions().then(null,function(e){return Promise.reject(new z(t.joinErrors(e).message,"scanningSystem"))})),null!==e&&1!==e||n.push(this.scanUserExtensions(!0).then(null,function(e){return Promise.reject(new z(t.joinErrors(e).message,"scanningUser"))})),Promise.all(n).then(p.flatten,function(e){return Promise.reject(t.joinErrors(e))})},V.prototype.scanSystemExtensions=function(){var e=this;this.logService.trace("Started scanning system extensions");var t=this.scanExtensions(this.systemExtensionsPath,0).then(function(t){return e.logService.info("Scanned system extensions:",t.length),t});if(this.environmentService.isBuilt)return t;var n=this.getDevSystemExtensionsList().then(function(t){return t.length?e.scanExtensions(e.devSystemExtensionsPath,0).then(function(n){
return e.logService.info("Scanned dev system extensions:",n.length),n.filter(function(e){return t.some(function(t){return g.areSameExtensions(e.galleryIdentifier,{id:t})})})}):[]});return Promise.all([t,n]).then(function(e){var t=e[0],n=e[1];return t.concat(n)})},V.prototype.scanUserExtensions=function(e){var t=this;return this.logService.trace("Started scanning user extensions"),Promise.all([this.getUninstalledExtensions(),this.scanExtensions(this.extensionsPath,1)]).then(function(n){var r=n[0],i=n[1];if(i=i.filter(function(e){return!r[e.identifier.id]}),e){i=g.groupByExtension(i,function(e){return{id:g.getGalleryExtensionIdFromLocal(e),uuid:e.identifier.uuid}}).map(function(e){return e.sort(function(e,t){return E.rcompare(e.manifest.version,t.manifest.version)})[0]})}return t.logService.info("Scanned user extensions:",i.length),i})},V.prototype.scanExtensions=function(e,t){var n=this,r=new y.Limiter(10);return c.readdir(e).then(function(i){return Promise.all(i.map(function(i){return r.queue(function(){
return n.scanExtension(i,e,t)})}))}).then(function(e){return e.filter(function(e){return e&&e.identifier})})},V.prototype.scanExtension=function(e,t,n){if(1===n&&0===e.indexOf("."))return Promise.resolve(null);var r=u.join(t,e);return c.readdir(r).then(function(t){return function(e){var t=[c.readFile(u.join(e,"package.json"),"utf8").then(function(e){return F(e)}),c.readFile(u.join(e,"package.nls.json"),"utf8").then(void 0,function(e){return"ENOENT"!==e.code?Promise.reject(e):"{}"}).then(function(e){return JSON.parse(e)})];return Promise.all(t).then(function(e){var t=e[0],n=t.manifest,r=t.metadata,i=e[1];return{manifest:v.localizeManifest(n,i),metadata:r}})}(r).then(function(i){var o=i.manifest,s=i.metadata,a=t.filter(function(e){return/^readme(\.txt|\.md|)$/i.test(e)})[0],c=a?S.URI.file(u.join(r,a)).toString():null,l=t.filter(function(e){return/^changelog(\.txt|\.md|)$/i.test(e)})[0],f=l?S.URI.file(u.join(r,l)).toString():null
;o.extensionDependencies&&(o.extensionDependencies=o.extensionDependencies.map(function(e){return g.adoptToGalleryExtensionId(e)})),o.extensionPack&&(o.extensionPack=o.extensionPack.map(function(e){return g.adoptToGalleryExtensionId(e)}));var p={id:0===n?e:U(o),uuid:s?s.id:null},d={id:g.getGalleryExtensionId(o.publisher,o.name),uuid:p.uuid};return{type:n,identifier:p,galleryIdentifier:d,manifest:o,metadata:s,location:S.URI.file(r),readmeUrl:c,changelogUrl:f}})}).then(void 0,function(){return null})},V.prototype.removeDeprecatedExtensions=function(){var e=this;return this.removeUninstalledExtensions().then(function(){return e.removeOutdatedExtensions()})},V.prototype.removeUninstalledExtensions=function(){var e=this;return this.getUninstalledExtensions().then(function(t){return e.scanExtensions(e.extensionsPath,1).then(function(n){var r=n.filter(function(e){return t[e.identifier.id]});return Promise.all(r.map(function(t){return e.extensionLifecycle.postUninstall(t).then(function(){
return e.removeUninstalledExtension(t)})}))})}).then(function(){})},V.prototype.removeOutdatedExtensions=function(){var e=this;return this.scanExtensions(this.extensionsPath,1).then(function(t){var n=[],r=g.groupByExtension(t,function(e){return{id:g.getGalleryExtensionIdFromLocal(e),uuid:e.identifier.uuid}});return n.push.apply(n,p.flatten(r.map(function(e){return e.sort(function(e,t){return E.rcompare(e.manifest.version,t.manifest.version)}).slice(1)}))),Promise.all(n.map(function(t){return e.removeExtension(t,"outdated")}))}).then(function(){})},V.prototype.removeUninstalledExtension=function(e){var t=this;return this.removeExtension(e,"uninstalled").then(function(){return t.withUninstalledExtensions(function(t){return delete t[e.identifier.id]})}).then(function(){})},V.prototype.removeExtension=function(e,t){var n=this;return this.logService.trace("Deleting "+t+" extension from disk",e.identifier.id),c.rimraf(e.location.fsPath).then(function(){return n.logService.info("Deleted from disk",e.identifier.id)})
},V.prototype.isUninstalled=function(e){return this.filterUninstalled(e).then(function(e){return 1===e.length})},V.prototype.filterUninstalled=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.withUninstalledExtensions(function(t){for(var n=[],r=0,i=e;r<i.length;r++){var o=i[r];t[o]&&n.push(o)}return n})},V.prototype.setUninstalled=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.map(function(e){return e.identifier.id});return this.withUninstalledExtensions(function(e){return l.assign(e,n.reduce(function(e,t){return e[t]=!0,e},{}))})},V.prototype.unsetUninstalled=function(e){return this.withUninstalledExtensions(function(t){return delete t[e]})},V.prototype.getUninstalledExtensions=function(){return this.withUninstalledExtensions(function(e){return e})},V.prototype.withUninstalledExtensions=function(e){return n(this,void 0,void 0,function(){var t=this;return r(this,function(n){switch(n.label){case 0:
return[4,this.uninstalledFileLimiter.queue(function(){var n=null;return c.readFile(t.uninstalledPath,"utf8").then(void 0,function(e){return"ENOENT"===e.code?Promise.resolve("{}"):Promise.reject(e)}).then(function(e){try{return JSON.parse(e)}catch(e){return{}}}).then(function(t){return n=e(t),t}).then(function(e){if(0===Object.keys(e).length)return c.rimraf(t.uninstalledPath);var n=JSON.stringify(e);return c.writeFile(t.uninstalledPath,n)}).then(function(){return n})})];case 1:return[2,n.sent()]}})})},V.prototype.getExtensionsReport=function(){var e=(new Date).getTime();return(!this.reportedExtensions||e-this.lastReportTimestamp>3e5)&&(this.reportedExtensions=this.updateReportCache(),this.lastReportTimestamp=e),this.reportedExtensions},V.prototype.updateReportCache=function(){var e=this;return this.logService.trace("ExtensionManagementService.refreshReportedCache"),this.galleryService.getExtensionsReport().then(function(t){
return e.logService.trace("ExtensionManagementService.refreshReportedCache - got "+t.length+" reported extensions from service"),t},function(t){return e.logService.trace("ExtensionManagementService.refreshReportedCache - failed to get extension report"),[]})},Object.defineProperty(V.prototype,"devSystemExtensionsPath",{get:function(){return this._devSystemExtensionsPath||(this._devSystemExtensionsPath=u.normalize(u.join(R.getPathFromAmdModule(e,""),"..",".build","builtInExtensions"))),this._devSystemExtensionsPath},enumerable:!0,configurable:!0}),Object.defineProperty(V.prototype,"devSystemExtensionsFilePath",{get:function(){return this._devSystemExtensionsFilePath||(this._devSystemExtensionsFilePath=u.normalize(u.join(R.getPathFromAmdModule(e,""),"..","build","builtInExtensions.json"))),this._devSystemExtensionsFilePath},enumerable:!0,configurable:!0}),V.prototype.getDevSystemExtensionsList=function(){return c.readFile(this.devSystemExtensionsFilePath,"utf8").then(function(e){
return JSON.parse(e).map(function(e){return e.name})})},V.prototype.toNonCancellablePromise=function(e){return new Promise(function(t,n){return e.then(function(e){return t(e)},function(e){return n(e)})})},V.prototype.reportTelemetry=function(e,t,n,r){var i=r?r instanceof z?r.code:"unknown":void 0;this.telemetryService.publicLog(e,l.assign(t,{success:!r,duration:n,errorcode:i}))},V=s([a(0,m.IEnvironmentService),a(1,h.IExtensionGalleryService),a(2,P.ILogService),a(3,L.optional(D.IDownloadService)),a(4,O.ITelemetryService)],V)}(f.Disposable);t.ExtensionManagementService=V,t.getLocalExtensionIdFromGallery=N,t.getLocalExtensionIdFromManifest=U}),define(e[34],t([0,1,3,83,24,6,91,23]),function(e,t,i,o,s,a,u,c){"use strict";function l(t,s){var f;return(t.getRawRequest?Promise.resolve(t.getRawRequest(t)):Promise.resolve(function(t){return n(this,void 0,void 0,function(){var n,i,s;return r(this,function(r){switch(r.label){case 0:return"https:"!==(n=o.parse(t.url)).protocol?[3,2]:[4,new Promise(function(t,n){
e(["https"],t,n)})];case 1:return s=r.sent(),[3,4];case 2:return[4,new Promise(function(t,n){e(["http"],t,n)})];case 3:s=r.sent(),r.label=4;case 4:return i=s,[2,i.request]}})})}(t))).then(function(e){return new Promise(function(n,r){var p=o.parse(t.url),d={hostname:p.hostname,port:p.port?parseInt(p.port):"https:"===p.protocol?443:80,protocol:p.protocol,path:p.path,method:t.type||"GET",headers:t.headers,agent:t.agent,rejectUnauthorized:!i.isBoolean(t.strictSSL)||t.strictSSL};if(t.user&&t.password&&(d.auth=t.user+":"+t.password),(f=e(d,function(e){var o=i.isNumber(t.followRedirects)?t.followRedirects:3;if(e.statusCode&&e.statusCode>=300&&e.statusCode<400&&o>0&&e.headers.location)l(a.assign({},t,{url:e.headers.location,followRedirects:o-1}),s).then(n,r);else{var c=e;"gzip"===e.headers["content-encoding"]&&(c=c.pipe(u.createGunzip())),n({res:e,stream:c})}})).on("error",r),t.timeout&&f.setTimeout(t.timeout),t.data){if("string"!=typeof t.data)return void t.data.pipe(f);f.write(t.data)}f.end(),
s.onCancellationRequested(function(){f.abort(),r(c.canceled())})})})}function f(e){return e.res.statusCode&&e.res.statusCode>=200&&e.res.statusCode<300||1223===e.res.statusCode}function p(e){return 204===e.res.statusCode}Object.defineProperty(t,"__esModule",{value:!0}),t.request=l,t.download=function(e,t){return new Promise(function(n,r){var i=s.createWriteStream(e);i.once("finish",function(){return n(void 0)}),t.stream.once("error",r),t.stream.pipe(i)})},t.asText=function(e){return new Promise(function(t,n){if(!f(e))return n("Server returned "+e.res.statusCode);if(p(e))return t(null);var r=[];e.stream.on("data",function(e){return r.push(e)}),e.stream.on("end",function(){return t(r.join(""))}),e.stream.on("error",n)})},t.asJson=function(e){return new Promise(function(t,n){if(!f(e))return n("Server returned "+e.res.statusCode);if(p(e))return t(null);var r=[];e.stream.on("data",function(e){return r.push(e)}),e.stream.on("end",function(){try{t(JSON.parse(r.join("")))}catch(e){n(e)}}),e.stream.on("error",n)})}}),
define(e[86],t([0,1,26,5,19,23,18,6,41,27,34,20,36,32,17,12,39,43,33,93,7]),function(e,t,n,r,o,u,c,l,f,p,d,h,g,v,m,y,b,E,S,x,C){"use strict";function P(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return String(e.reduce(function(e,t){return e|t},0))}function _(e,t){var n=(e||[]).filter(function(e){return e.statisticName===t})[0];return n?n.value:0}function w(e,t){return e.files.filter(function(e){return e.assetType===t})[0]?{uri:e.assetUri+"/"+t,fallbackUri:e.fallbackAssetUri+"/"+t}:null}function I(e,t){var n=e.properties?e.properties.filter(function(e){return e.key===t}):[],r=n.length>0&&n[0].value;return r?r.split(",").map(function(e){return c.adoptToGalleryExtensionId(e)}):[]}function O(e){var t=e.properties?e.properties.filter(function(e){return e.key===M.Engine}):[];return t.length>0&&t[0].value||""}function k(t,n,r,i,o){var s={manifest:w(n,L.Manifest),readme:w(n,L.Details),changelog:w(n,L.Changelog),license:w(n,L.License),repository:function(e){if(e.properties){
var t=e.properties.filter(function(e){return e.key===L.Repository}),n=new RegExp("((git|ssh|http(s)?)|(git@[w.]+))(:(//)?)([w.@:/-~]+)(.git)(/)?"),r=t.filter(function(e){return n.test(e.value)})[0];return r?{uri:r.value,fallbackUri:r.value}:null}return w(e,L.Repository)}(n),download:function(e){return{uri:e.fallbackAssetUri+"/"+L.VSIX+"?redirect=true",fallbackUri:e.fallbackAssetUri+"/"+L.VSIX}}(n),icon:function(t){var n=w(t,L.Icon);if(n)return n;var r=e.toUrl("./media/defaultIcon.png");return{uri:r,fallbackUri:r}}(n),coreTranslations:function(e){return e.files.filter(function(e){return 0===e.assetType.indexOf("Microsoft.VisualStudio.Code.Translation.")}).reduce(function(t,n){return t[n.assetType.substring("Microsoft.VisualStudio.Code.Translation.".length)]=w(e,n.assetType),t},{})}(n)};return{identifier:{id:c.getGalleryExtensionId(t.publisher.publisherName,t.extensionName),uuid:t.extensionId},name:t.extensionName,version:n.version,date:n.lastUpdated,displayName:t.displayName,
publisherId:t.publisher.publisherId,publisher:t.publisher.publisherName,publisherDisplayName:t.publisher.displayName,description:t.shortDescription||"",installCount:_(t.statistics,"install")+_(t.statistics,"updateCount"),rating:_(t.statistics,"averagerating"),ratingCount:_(t.statistics,"ratingcount"),assets:s,properties:{dependencies:I(n,M.Dependency),extensionPack:I(n,M.ExtensionPack),engine:O(n),localizedLanguages:function(e){var t=e.properties?e.properties.filter(function(e){return e.key===M.LocalizedLanguages}):[],n=t.length>0&&t[0].value||"";return n?n.split(","):[]}(n)},telemetryData:{index:(i.pageNumber-1)*i.pageSize+r,searchText:i.searchText,querySource:o},preview:function(e){return-1!==e.indexOf("preview")}(t.flags)}}function j(e){var t=r.join(e.userDataPath,"machineid");return y.readFile(t,"utf8").then(function(e){return E.isUUID(e)?e:Promise.resolve(null)},function(){return Promise.resolve(null)}).then(function(e){if(!e){e=E.generateUuid();try{b.writeFileAndFlushSync(t,e)}catch(e){}}return{
"X-Market-Client-Id":"VSCode "+h.default.version,"User-Agent":"VSCode "+h.default.version,"X-Market-User-Id":e}})}Object.defineProperty(t,"__esModule",{value:!0});var T;!function(e){e[e.None=0]="None",e[e.IncludeVersions=1]="IncludeVersions",e[e.IncludeFiles=2]="IncludeFiles",e[e.IncludeCategoryAndTags=4]="IncludeCategoryAndTags",e[e.IncludeSharedAccounts=8]="IncludeSharedAccounts",e[e.IncludeVersionProperties=16]="IncludeVersionProperties",e[e.ExcludeNonValidated=32]="ExcludeNonValidated",e[e.IncludeInstallationTargets=64]="IncludeInstallationTargets",e[e.IncludeAssetUri=128]="IncludeAssetUri",e[e.IncludeStatistics=256]="IncludeStatistics",e[e.IncludeLatestVersionOnly=512]="IncludeLatestVersionOnly",e[e.Unpublished=4096]="Unpublished"}(T||(T={}));var D;!function(e){e[e.Tag=1]="Tag",e[e.ExtensionId=4]="ExtensionId",e[e.Category=5]="Category",e[e.ExtensionName=7]="ExtensionName",e[e.Target=8]="Target",e[e.Featured=9]="Featured",e[e.SearchText=10]="SearchText",e[e.ExcludeWithFlags=12]="ExcludeWithFlags"
}(D||(D={}));var L={Icon:"Microsoft.VisualStudio.Services.Icons.Default",Details:"Microsoft.VisualStudio.Services.Content.Details",Changelog:"Microsoft.VisualStudio.Services.Content.Changelog",Manifest:"Microsoft.VisualStudio.Code.Manifest",VSIX:"Microsoft.VisualStudio.Services.VSIXPackage",License:"Microsoft.VisualStudio.Services.Content.License",Repository:"Microsoft.VisualStudio.Services.Links.Source"},M={Dependency:"Microsoft.VisualStudio.Code.ExtensionDependencies",ExtensionPack:"Microsoft.VisualStudio.Code.ExtensionPack",Engine:"Microsoft.VisualStudio.Code.Engine",LocalizedLanguages:"Microsoft.VisualStudio.Code.LocalizedLanguages"},R={pageNumber:1,pageSize:10,sortBy:0,sortOrder:0,flags:T.None,criteria:[],assetTypes:[]},A=function(){function e(e){void 0===e&&(e=R),this.state=e}return Object.defineProperty(e.prototype,"pageNumber",{get:function(){return this.state.pageNumber},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pageSize",{get:function(){return this.state.pageSize},
enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"sortBy",{get:function(){return this.state.sortBy},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"sortOrder",{get:function(){return this.state.sortOrder},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"flags",{get:function(){return this.state.flags},enumerable:!0,configurable:!0}),e.prototype.withPage=function(t,n){return void 0===n&&(n=this.state.pageSize),new e(l.assign({},this.state,{pageNumber:t,pageSize:n}))},e.prototype.withFilter=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];var i=this.state.criteria.concat(n.map(function(e){return{filterType:t,value:e}}));return new e(l.assign({},this.state,{criteria:i}))},e.prototype.withSortBy=function(t){return new e(l.assign({},this.state,{sortBy:t}))},e.prototype.withSortOrder=function(t){return new e(l.assign({},this.state,{sortOrder:t}))},e.prototype.withFlags=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n]
;return new e(l.assign({},this.state,{flags:t.reduce(function(e,t){return e|t},0)}))},e.prototype.withAssetTypes=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e(l.assign({},this.state,{assetTypes:t}))},Object.defineProperty(e.prototype,"raw",{get:function(){var e=this.state,t=e.criteria,n=e.pageNumber,r=e.pageSize,i=e.sortBy,o=e.sortOrder,s=e.flags;return{filters:[{criteria:t,pageNumber:n,pageSize:r,sortBy:i,sortOrder:o}],assetTypes:e.assetTypes,flags:s}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"searchText",{get:function(){var e=this.state.criteria.filter(function(e){return e.filterType===D.SearchText})[0];return e&&e.value?e.value:""},enumerable:!0,configurable:!0}),e}(),F=function(){function e(e,t,n,r){this.requestService=e,this.logService=t,this.environmentService=n,this.telemetryService=r;var i=g.default.extensionsGallery;this.extensionsGalleryUrl=i&&i.serviceUrl,this.extensionsControlUrl=i&&i.controlUrl,
this.commonHeadersPromise=j(this.environmentService)}return e.prototype.api=function(e){return void 0===e&&(e=""),""+this.extensionsGalleryUrl+e},e.prototype.isEnabled=function(){return!!this.extensionsGalleryUrl},e.prototype.getExtension=function(e,t){var n=e.id,r=e.uuid,i=(new A).withFlags(T.IncludeAssetUri,T.IncludeStatistics,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,1).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished));return i=r?i.withFilter(D.ExtensionId,r):i.withFilter(D.ExtensionName,n),this.queryGallery(i,x.CancellationToken.None).then(function(e){var n=e.galleryExtensions;if(n.length){var r=n[0],o=t?r.versions.filter(function(e){return e.version===t})[0]:r.versions[0];if(o)return k(r,o,0,i)}return null})},e.prototype.query=function(e){var t=this;if(void 0===e&&(e={}),!this.isEnabled())return Promise.reject(new Error("No extension gallery service configured."))
;var n=e.names?"ids":e.text?"text":"all",r=e.text||"",i=l.getOrDefault(e,function(e){return e.pageSize},50);this.telemetryService.publicLog("galleryService:query",{type:n,text:r});var o=(new A).withFlags(T.IncludeLatestVersionOnly,T.IncludeAssetUri,T.IncludeStatistics,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,i).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished));return r?((r=(r=(r=r.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g,function(e,t,n){return o=o.withFilter(D.Category,n||t),""})).replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g,function(e,t,n){return o=o.withFilter(D.Tag,n||t),""})).trim())&&(r=r.length<200?r:r.substring(0,200),o=o.withFilter(D.SearchText,r)),o=o.withSortBy(0)):o=e.ids?o.withFilter.apply(o,[D.ExtensionId].concat(e.ids)):e.names?o.withFilter.apply(o,[D.ExtensionName].concat(e.names)):o.withSortBy(4),"number"==typeof e.sortBy&&(o=o.withSortBy(e.sortBy)),"number"==typeof e.sortOrder&&(o=o.withSortOrder(e.sortOrder)),
this.queryGallery(o,x.CancellationToken.None).then(function(n){var r=n.galleryExtensions,i=n.total;return{firstPage:r.map(function(t,n){return k(t,t.versions[0],n,o,e.source)}),total:i,pageSize:o.pageSize,getPage:function(n,r){if(r.isCancellationRequested)return Promise.reject(u.canceled());var i=o.withPage(n+1);return t.queryGallery(i,r).then(function(t){return t.galleryExtensions.map(function(t,n){return k(t,t.versions[0],n,i,e.source)})})}}})},e.prototype.queryGallery=function(e,t){var n=this;return this.isEnabled()?this.commonHeadersPromise.then(function(r){var i=JSON.stringify(e.raw),o=l.assign({},r,{"Content-Type":"application/json",Accept:"application/json;api-version=3.0-preview.1","Accept-Encoding":"gzip","Content-Length":i.length});return n.requestService.request({type:"POST",url:n.api("/extensionquery"),data:i,headers:o},t).then(function(e){return e.res.statusCode&&e.res.statusCode>=400&&e.res.statusCode<500?{galleryExtensions:[],total:0}:d.asJson(e).then(function(e){if(e){
var t=e.results[0],n=t.extensions,r=t.resultMetadata&&t.resultMetadata.filter(function(e){return"ResultCount"===e.metadataType})[0];return{galleryExtensions:n,total:r&&r.metadataItems.filter(function(e){return"TotalCount"===e.name})[0].count||0}}return{galleryExtensions:[],total:0}})})}):Promise.reject(new Error("No extension gallery service configured."))},e.prototype.reportStatistic=function(e,t,n,r){var o=this;return this.isEnabled()?this.commonHeadersPromise.then(function(s){var a=i({},s,{Accept:"*/*;api-version=4.0-preview.1"});return o.requestService.request({type:"POST",url:o.api("/publishers/"+e+"/extensions/"+t+"/"+n+"/stats?statType="+r),headers:a},x.CancellationToken.None).then(void 0,function(){})}):Promise.resolve(void 0)},e.prototype.download=function(e,t){var i=this;this.logService.trace("ExtensionGalleryService#download",e.identifier.id);var o=r.join(n.tmpdir(),E.generateUuid()),s=c.getGalleryExtensionTelemetryData(e),a=(new Date).getTime(),u=1===t?"install":2===t?"update":"",f=u?{
uri:e.assets.download.uri+"&"+u+"=true",fallbackUri:e.assets.download.fallbackUri+"?"+u+"=true"}:e.assets.download;return this.getAsset(f).then(function(e){return d.download(o,e)}).then(function(){return function(e){return i.telemetryService.publicLog("galleryService:downloadVSIX",l.assign(s,{duration:e}))}((new Date).getTime()-a)}).then(function(){return o})},e.prototype.getReadme=function(e,t){return e.assets.readme?this.getAsset(e.assets.readme,{},t).then(function(e){return d.asText(e)}).then(function(e){return e||""}):Promise.resolve("")},e.prototype.getManifest=function(e,t){return e.assets.manifest?this.getAsset(e.assets.manifest,{},t).then(d.asText).then(JSON.parse):Promise.resolve(null)},e.prototype.getCoreTranslation=function(e,t){var n=e.assets.coreTranslations[t.toUpperCase()];return n?this.getAsset(n).then(d.asText).then(JSON.parse):Promise.resolve(null)},e.prototype.getChangelog=function(e,t){return e.assets.changelog?this.getAsset(e.assets.changelog,{},t).then(function(e){return d.asText(e)
}).then(function(e){return e||""}):Promise.resolve("")},e.prototype.loadAllDependencies=function(e,t){return this.getDependenciesReccursively(e.map(function(e){return e.id}),[],t)},e.prototype.getAllVersions=function(e,t){var n=this,r=(new A).withFlags(T.IncludeVersions,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,1).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished));return r=e.identifier.uuid?r.withFilter(D.ExtensionId,e.identifier.uuid):r.withFilter(D.ExtensionName,e.identifier.id),this.queryGallery(r,x.CancellationToken.None).then(function(e){var r=e.galleryExtensions;return r.length?t?Promise.all(r[0].versions.map(function(e){return n.getEngine(e).then(function(t){return v.isEngineValid(t)?e:null})})).then(function(e){return e.filter(function(e){return!!e}).map(function(e){return{version:e.version,date:e.lastUpdated}})}):r[0].versions.map(function(e){return{version:e.version,date:e.lastUpdated}}):[]})},
e.prototype.loadCompatibleVersion=function(e,t){var n=this;if(void 0===t&&(t=e.version),e.version===t&&e.properties.engine&&v.isEngineValid(e.properties.engine))return Promise.resolve(e);var r=(new A).withFlags(T.IncludeVersions,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,1).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished)).withAssetTypes(L.Manifest,L.VSIX).withFilter(D.ExtensionId,e.identifier.uuid);return this.queryGallery(r,x.CancellationToken.None).then(function(e){var i=e.galleryExtensions[0];if(!i)return null;var o=n.getVersionsFrom(i.versions,t);return o.length?n.getLastValidExtensionVersion(i,o).then(function(e){return e?k(i,e,0,r):null}):null})},e.prototype.getVersionsFrom=function(e,t){if(e[0].version===t)return e;for(var n=[],r=null,i=0,o=e;i<o.length;i++){var s=o[i];r||s.version===t&&(r=s),r&&n.push(s)}return n},e.prototype.loadDependencies=function(e,t){var n;if(!e||0===e.length)return Promise.resolve([])
;var r=(n=(new A).withFlags(T.IncludeLatestVersionOnly,T.IncludeAssetUri,T.IncludeStatistics,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,e.length).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished)).withAssetTypes(L.Icon,L.License,L.Details,L.Manifest,L.VSIX)).withFilter.apply(n,[D.ExtensionName].concat(e));return this.queryGallery(r,t).then(function(e){for(var t=[],n=[],i=0;i<e.galleryExtensions.length;i++){var o=e.galleryExtensions[i];-1===n.indexOf(o.extensionId)&&(t.push(k(o,o.versions[0],i,r,"dependencies")),n.push(o.extensionId))}return t})},e.prototype.getDependenciesReccursively=function(t,n,r){var i=this;return t&&t.length&&(t=n.length?t.filter(function(t){return!e.hasExtensionByName(n,t)}):t).length?this.loadDependencies(t,r).then(function(t){for(var s=new Set,a=0,u=t;a<u.length;a++){var c=u[a];c.properties.dependencies&&c.properties.dependencies.forEach(function(e){return s.add(e)})}n=o.distinct(n.concat(t),function(e){
return e.identifier.uuid});var l=[];return s.forEach(function(t){return!e.hasExtensionByName(n,t)&&l.push(t)}),i.getDependenciesReccursively(l,n,r)}):Promise.resolve(n)},e.prototype.getAsset=function(e,t,n){var r=this;return void 0===t&&(t={}),void 0===n&&(n=x.CancellationToken.None),this.commonHeadersPromise.then(function(i){var o=l.assign({},i,t.headers||{});t=l.assign({},t,{type:"GET"},{headers:o});var s=e.uri,a=e.fallbackUri,c=l.assign({},t,{url:s});return r.requestService.request(c,n).then(function(e){return 200===e.res.statusCode?Promise.resolve(e):d.asText(e).then(function(t){return Promise.reject(new Error("Expected 200, got back "+e.res.statusCode+" instead.\n\n"+t))})}).then(void 0,function(e){if(u.isPromiseCanceledError(e))return Promise.reject(e);var i=u.getErrorMessage(e);r.telemetryService.publicLog("galleryService:requestError",{url:s,cdn:!0,message:i}),r.telemetryService.publicLog("galleryService:cdnFallback",{url:s,message:i});var o=l.assign({},t,{url:a})
;return r.requestService.request(o,n).then(void 0,function(e){if(u.isPromiseCanceledError(e))return Promise.reject(e);var t=u.getErrorMessage(e);return r.telemetryService.publicLog("galleryService:requestError",{url:a,cdn:!1,message:t}),Promise.reject(e)})})})},e.prototype.getLastValidExtensionVersion=function(e,t){var n=this.getLastValidExtensionVersionFromProperties(e,t);return n||this.getLastValidExtensionVersionReccursively(e,t)},e.prototype.getLastValidExtensionVersionFromProperties=function(e,t){for(var n=0,r=t;n<r.length;n++){var i=r[n],o=O(i);if(!o)return null;if(v.isEngineValid(o))return Promise.resolve(i)}return null},e.prototype.getEngine=function(e){var t=O(e);if(t)return Promise.resolve(t);var n=w(e,L.Manifest);if(!n)return Promise.reject("Manifest was not found");return this.getAsset(n,{headers:{"Accept-Encoding":"gzip"}}).then(function(e){return d.asJson(e)}).then(function(e){return e?e.engines.vscode:Promise.reject("Error while reading manifest")})},
e.prototype.getLastValidExtensionVersionReccursively=function(e,t){var n=this;if(!t.length)return Promise.resolve(null);var r=t[0];return this.getEngine(r).then(function(i){return v.isEngineValid(i)?(r.properties=r.properties||[],r.properties.push({key:M.Engine,value:i}),r):n.getLastValidExtensionVersionReccursively(e,t.slice(1))})},e.hasExtensionByName=function(e,t){for(var n=0,r=e;n<r.length;n++){var i=r[n];if(i.publisher+"."+i.name===t)return!0}return!1},e.prototype.getExtensionsReport=function(){return this.isEnabled()?this.extensionsControlUrl?this.requestService.request({type:"GET",url:this.extensionsControlUrl},x.CancellationToken.None).then(function(e){return 200!==e.res.statusCode?Promise.reject(new Error("Could not get extensions report.")):d.asJson(e).then(function(e){var t=new Map;if(e)for(var n=0,r=e.malicious;n<r.length;n++){var i=r[n],o=t.get(i)||{id:{id:i},malicious:!0,slow:!1};o.malicious=!0,t.set(i,o)}return Promise.resolve(S.values(t))})
}):Promise.resolve([]):Promise.reject(new Error("No extension gallery service configured."))},e=s([a(0,f.IRequestService),a(1,C.ILogService),a(2,m.IEnvironmentService),a(3,p.ITelemetryService)],e)}();t.ExtensionGalleryService=F,t.resolveMarketplaceHeaders=j}),define(e[58],t([0,1,6,34,64,13,7]),function(e,t,n,r,i,o,u){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var c=function(){function e(e,t){var n=this;this.logService=t,this.disposables=[],this.configure(e.getValue()),e.onDidChangeConfiguration(function(){return n.configure(e.getValue())},this,this.disposables)}return e.prototype.configure=function(e){this.proxyUrl=e.http&&e.http.proxy,this.strictSSL=!(!e.http||!e.http.proxyStrictSSL),this.authorization=e.http&&e.http.proxyAuthorization},e.prototype.request=function(e,t,o){var s=this;void 0===o&&(o=r.request),this.logService.trace("RequestService#request",e.url);var a=this.proxyUrl,u=this.strictSSL;return(e.agent?Promise.resolve(e.agent):Promise.resolve(i.getProxyAgent(e.url||"",{
proxyUrl:a,strictSSL:u}))).then(function(r){return e.agent=r,e.strictSSL=u,s.authorization&&(e.headers=n.assign(e.headers||{},{"Proxy-Authorization":s.authorization})),o(e,t)})},e=s([a(0,o.IConfigurationService),a(1,u.ILogService)],e)}();t.RequestService=c}),define(e[95],t([0,1,4,36,20,5,45,21,29,38,57,17,63,28,81,86,27,79,78,82,41,58,13,73,80,12,53,75,76,60,7,23,18,22,42]),function(e,t,i,o,u,c,l,f,p,d,h,g,v,m,y,b,E,S,x,C,P,_,w,I,O,k,j,T,D,L,M,R,A,F,N){"use strict";function U(e,t){return t?e.publisher+"."+e.name+"@"+e.version:e.publisher+"."+e.name}function z(e){var t=B.exec(e);return t&&t[1]?[A.adoptToGalleryExtensionId(t[1]),t[2]]:[A.adoptToGalleryExtensionId(e),void 0]}Object.defineProperty(t,"__esModule",{value:!0});var V=i.localize(2,null,"ms-vscode.csharp"),B=/^([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;t.getIdAndVersion=z;var q=function(){function e(e,t,n){this.environmentService=e,this.extensionManagementService=t,this.extensionGalleryService=n}return e.prototype.run=function(e){
return n(this,void 0,void 0,function(){var t,n,i;return r(this,function(r){switch(r.label){case 0:return e["install-source"]?[4,this.setInstallSource(e["install-source"])]:[3,2];case 1:return r.sent(),[3,8];case 2:return e["list-extensions"]?[4,this.listExtensions(!!e["show-versions"])]:[3,4];case 3:return r.sent(),[3,8];case 4:return e["install-extension"]?(n=e["install-extension"],t="string"==typeof n?[n]:n,[4,this.installExtension(t,e.force)]):[3,6];case 5:return r.sent(),[3,8];case 6:return e["uninstall-extension"]?(n=e["uninstall-extension"],i="string"==typeof n?[n]:n,[4,this.uninstallExtension(i)]):[3,8];case 7:r.sent(),r.label=8;case 8:return[2]}})})},e.prototype.setInstallSource=function(e){return k.writeFile(this.environmentService.installSourcePath,e.slice(0,30))},e.prototype.listExtensions=function(e){return n(this,void 0,void 0,function(){var t;return r(this,function(n){switch(n.label){case 0:return[4,this.extensionManagementService.getInstalled(1)];case 1:return(t=n.sent()).forEach(function(t){
return console.log(U(t.manifest,e))}),[2]}})})},e.prototype.installExtension=function(e,t){var n=this,r=e.filter(function(e){return/\.vsix$/i.test(e)}).map(function(e){return function(){var r=c.isAbsolute(e)?e:c.join(process.cwd(),e);return n.validate(r,t).then(function(e){return e?n.extensionManagementService.install(F.URI.file(r)).then(function(){console.log(i.localize(3,null,j.getBaseLabel(r)))},function(e){return R.isPromiseCanceledError(e)?(console.log(i.localize(4,null,j.getBaseLabel(r))),null):Promise.reject(e)}):null})}}),o=e.filter(function(e){return!/\.vsix$/i.test(e)}).map(function(e){return function(){var r=z(e),o=r[0],s=r[1];return n.extensionManagementService.getInstalled(1).then(function(e){return n.extensionGalleryService.getExtension({id:o},s).then(null,function(e){if(e.responseText)try{var t=JSON.parse(e.responseText);return Promise.reject(t.message)}catch(e){}return Promise.reject(e)}).then(function(r){if(!r)return Promise.reject(new Error(function(e){return i.localize(0,null,e)
}(s?o+"@"+s:o)+"\n"+V));var a=e.filter(function(e){return A.areSameExtensions({id:A.getGalleryExtensionIdFromLocal(e)},{id:o})})[0];return a?r.version!==a.manifest.version?s||t?(console.log(i.localize(5,null,o,r.version)),n.installFromGallery(o,r)):(console.log(i.localize(6,null,o,a.manifest.version,r.version)),Promise.resolve(null)):(console.log(i.localize(7,null,s?o+"@"+s:o)),Promise.resolve(null)):(console.log(i.localize(8,null,o)),n.installFromGallery(o,r))})})}});return f.sequence(r.concat(o))},e.prototype.validate=function(e,t){return n(this,void 0,void 0,function(){var n,o,s,a;return r(this,function(r){switch(r.label){case 0:return[4,N.getManifest(e)];case 1:if(!(n=r.sent()))throw new Error("Invalid vsix");return o={id:A.getGalleryExtensionId(n.publisher,n.name)},[4,this.extensionManagementService.getInstalled(1)];case 2:return s=r.sent(),(a=s.filter(function(e){return A.areSameExtensions(o,{id:A.getGalleryExtensionIdFromLocal(e)})&&l.gt(e.manifest.version,n.version)
})[0])&&!t?(console.log(i.localize(9,null,a.galleryIdentifier.id,a.manifest.version,n.version)),[2,!1]):[2,!0]}})})},e.prototype.installFromGallery=function(e,t){return n(this,void 0,void 0,function(){var n;return r(this,function(r){switch(r.label){case 0:console.log(i.localize(10,null)),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.extensionManagementService.installFromGallery(t)];case 2:return r.sent(),console.log(i.localize(11,null,e,t.version)),[3,4];case 3:if(n=r.sent(),!R.isPromiseCanceledError(n))throw n;return console.log(i.localize(12,null,e)),[3,4];case 4:return[2]}})})},e.prototype.uninstallExtension=function(e){var t=this;return f.sequence(e.map(function(e){return function(){return function(e){return n(this,void 0,void 0,function(){var t,n;return r(this,function(r){switch(r.label){case 0:return/\.vsix$/i.test(e)?(t=c.isAbsolute(e)?e:c.join(process.cwd(),e),[4,N.getManifest(t)]):[2,e];case 1:return n=r.sent(),[2,U(n)]}})})}(e).then(function(e){
return t.extensionManagementService.getInstalled(1).then(function(n){var r=n.filter(function(t){return A.areSameExtensions({id:A.getGalleryExtensionIdFromLocal(t)},{id:e})})[0];return r?(console.log(i.localize(13,null,e)),t.extensionManagementService.uninstall(r,!0).then(function(){return console.log(i.localize(14,null,e))})):Promise.reject(new Error(function(e){return i.localize(1,null,e)}(e)+"\n"+V))})})}}))},e=s([a(0,g.IEnvironmentService),a(1,m.IExtensionManagementService),a(2,m.IExtensionGalleryService)],e)}(),G="monacoworkbench";t.main=function(e){var t=new p.ServiceCollection,n=new v.EnvironmentService(e,process.execPath),r=L.createSpdLogService("cli",M.getLogLevel(n),n.logsPath);process.once("exit",function(){return r.dispose()}),r.info("main",e),t.set(g.IEnvironmentService,n),t.set(M.ILogService,r),t.set(T.IStateService,new d.SyncDescriptor(D.StateService));var i=new h.InstantiationService(t);return i.invokeFunction(function(t){var n=t.get(g.IEnvironmentService),s=t.get(T.IStateService)
;return Promise.all([n.appSettingsHome,n.extensionsPath].map(function(e){return k.mkdirp(e)})).then(function(){var t=n.appRoot,a=n.extensionsPath,c=n.extensionDevelopmentLocationURI,l=n.isBuilt,f=n.installSourcePath,h=new p.ServiceCollection;h.set(w.IConfigurationService,new d.SyncDescriptor(I.ConfigurationService)),h.set(P.IRequestService,new d.SyncDescriptor(_.RequestService)),h.set(m.IExtensionManagementService,new d.SyncDescriptor(y.ExtensionManagementService)),h.set(m.IExtensionGalleryService,new d.SyncDescriptor(b.ExtensionGalleryService));var g=[];if(l&&!c&&!n.args["disable-telemetry"]&&o.default.enableTelemetry){o.default.aiConfig&&o.default.aiConfig.asimovKey&&g.push(new O.AppInsightsAppender(G,null,o.default.aiConfig.asimovKey,r));var v={appender:S.combinedAppender.apply(void 0,g),commonProperties:C.resolveCommonProperties(o.default.commit,u.default.version,s.getItem("telemetry.machineId"),f),piiPaths:[t,a]};h.set(E.ITelemetryService,new d.SyncDescriptor(x.TelemetryService,[v]))
}else h.set(E.ITelemetryService,S.NullTelemetryService);return i.createChild(h).createInstance(q).run(e).then(function(){return S.combinedAppender.apply(void 0,g).dispose()})})})}})}).call(this);
//# sourceMappingURL=https://ticino.blob.core.windows.net/sourcemaps/08cba2fb66e1673b5f6537fce1de1555d169f0a4/core/vs/code/node/cliProcessMain.js.map
| { |
test_permissions_loading.py | # Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Test user permissions loading and caching."""
import mock
from appengine import base
from ggrc.models import all_models
from ggrc.cache import utils as cache_utils
from integration.ggrc import TestCase, generator
from integration.ggrc.api_helper import Api
from integration.ggrc.models import factories
# stub for module, which cannot be imported in global scope bacause of
# import error
ggrc_basic_permissions = None # pylint: invalid-name
def _lazy_load_module():
"""Load required module in runtime to prevent import error"""
global ggrc_basic_permissions # pylint: global-statement,invalid-name
import ggrc_basic_permissions # pylint: disable=redefined-outer-name
@base.with_memcache
class TestMemcacheBase(TestCase):
"""Base class for permissions tests"""
def setUp(self):
super(TestMemcacheBase, self).setUp()
_lazy_load_module()
class TestPermissionsLoading(TestMemcacheBase):
"""Test user permissions loading."""
def setUp(self):
super(TestPermissionsLoading, self).setUp()
self.api = Api()
self.generator = generator.ObjectGenerator()
self.control_id = factories.ControlFactory().id
_, user = self.generator.generate_person(user_role="Creator")
self.api.set_user(user)
def test_permissions_loading(self):
"""Test if permissions created only once for GET requests."""
with mock.patch(
"ggrc_basic_permissions.store_results_into_memcache",
side_effect=ggrc_basic_permissions.store_results_into_memcache
) as store_perm:
self.api.get(all_models.Control, self.control_id)
store_perm.assert_called_once()
store_perm.call_count = 0
# On second GET permissions should be loaded from memcache
# but not created from scratch.
self.api.get(all_models.Control, self.control_id)
store_perm.assert_not_called()
class TestPermissionsCacheFlushing(TestMemcacheBase):
"""Test user permissions loading."""
def setUp(self):
super(TestPermissionsCacheFlushing, self).setUp()
self.api = Api()
@staticmethod
def load_perms(user_id, new_perms):
"""Emulate procedure to load permissions
"""
with mock.patch(
'ggrc_basic_permissions._load_permissions_from_database',
return_value=new_perms
):
mock_user = mock.Mock()
mock_user.id = user_id
return ggrc_basic_permissions.load_permissions_for(mock_user)
def test_memcache_flushing(self):
"""Test if memcache is properly cleaned on object creation
Procedure to test functionality:
1) load and permissions for specific user and store them in memcahe
2) emulate new object creation, which cleans permissions in memcache
3) make request which tries to get cache for permissions from memcache
Also, it's assumed that 2 or more GGRC workers are running
"""
client = cache_utils.get_cache_manager().cache_object.memcache_client
client.flush_all()
# load perms and store them in memcache
self.load_perms(11, {"11": "a"})
# emulate situation when a new object is created
# this procedure cleans memcache in the end
cache_utils.clear_permission_cache()
# emulate work of worker #1 - get permissions for our user
# the first step - check permissions in memcache
ggrc_basic_permissions.query_memcache(client, "permissions:11")
# step 2 - load permissions from DB and save then into memcahe
# this step is omitted
# load permission on behalf of worker #2, before step 2 of worker #1
result = self.load_perms(11, {"11": "b"})
# ensure that new permissions were returned instead of old ones
self.assertEquals(result, {"11": "b"})
def test_permissions_flush_on_post(self):
"""Test that permissions in memcache are cleaned after POST request."""
user = self.create_user_with_role("Creator")
self.api.set_user(user)
self.api.client.get("/permissions")
perm_ids = self.memcache_client.get('permissions:list')
self.assertEqual(perm_ids, {'permissions:{}'.format(user.id)}) | response = self.api.post(
all_models.Objective,
{"objective": {"title": "Test Objective", "context": None}}
)
self.assert_status(response, 201)
perm_ids = self.memcache_client.get('permissions:list')
self.assertIsNone(perm_ids)
def test_permissions_flush_on_put(self):
"""Test that permissions in memcache are cleaned after PUT request."""
with factories.single_commit():
user = self.create_user_with_role("Creator")
objective = factories.ObjectiveFactory()
objective_id = objective.id
objective.add_person_with_role_name(user, "Admin")
self.api.set_user(user)
self.api.client.get("/permissions")
perm_ids = self.memcache_client.get('permissions:list')
self.assertEqual(perm_ids, {'permissions:{}'.format(user.id)})
objective = all_models.Objective.query.get(objective_id)
response = self.api.put(objective, {"title": "new title"})
self.assert200(response)
perm_ids = self.memcache_client.get('permissions:list')
self.assertIsNone(perm_ids)
def test_permissions_flush_on_delete(self):
"""Test that permissions in memcache are cleaned after DELETE request."""
with factories.single_commit():
user = self.create_user_with_role("Creator")
objective = factories.ObjectiveFactory()
objective.add_person_with_role_name(user, "Admin")
objective_id = objective.id
self.api.set_user(user)
self.api.client.get("/permissions")
perm_ids = self.memcache_client.get('permissions:list')
self.assertEqual(perm_ids, {'permissions:{}'.format(user.id)})
objective = all_models.Objective.query.get(objective_id)
response = self.api.delete(objective)
self.assert200(response)
perm_ids = self.memcache_client.get('permissions:list')
self.assertIsNone(perm_ids) | |
InternalHockeyAppCutoverStatusResponse.py | # coding: utf-8
"""
App Center Client
Microsoft Visual Studio App Center API # noqa: E501
OpenAPI spec version: preview
Contact: [email protected]
Project Repository: https://github.com/b3nab/appcenter-sdks
"""
import pprint
import re # noqa: F401
import six
class InternalHockeyAppCutoverStatusResponse(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
allowed enum values
"""
not_requested = "not_requested"
requested = "requested"
in_progress = "in_progress"
completed = "completed"
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'string',
'status': 'string'
}
attribute_map = {
'id': 'id',
'status': 'status'
}
def __init__(self, id=None, status=None): # noqa: E501
"""InternalHockeyAppCutoverStatusResponse - a model defined in Swagger""" # noqa: E501
self._id = None
self._status = None
self.discriminator = None
self.id = id
if status is not None:
self.status = status
@property
def id(self):
"""Gets the id of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
The ID of the app # noqa: E501
:return: The id of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
:rtype: string
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this InternalHockeyAppCutoverStatusResponse.
The ID of the app # noqa: E501
:param id: The id of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
:type: string
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501
self._id = id
@property
def status(self):
"""Gets the status of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
Does the HockeyApp app have crashes from within the last 90 days? # noqa: E501
:return: The status of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
:rtype: string
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this InternalHockeyAppCutoverStatusResponse.
Does the HockeyApp app have crashes from within the last 90 days? # noqa: E501 |
:param status: The status of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
:type: string
"""
allowed_values = [undefinedundefinedundefinedundefined] # noqa: E501
self._status = status
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, InternalHockeyAppCutoverStatusResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | |
mod.rs | mod common;
mod echo_service; |
||
virtual_network_resource.py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['VirtualNetworkResource']
class VirtualNetworkResource(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
allowed_subnets: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SubnetArgs']]]]] = None,
description: Optional[pulumi.Input[str]] = None,
external_provider_resource_id: Optional[pulumi.Input[str]] = None,
id: Optional[pulumi.Input[str]] = None,
lab_name: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
provisioning_state: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
subnet_overrides: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SubnetOverrideArgs']]]]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
type: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
A virtual network.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SubnetArgs']]]] allowed_subnets: The allowed subnets of the virtual network.
:param pulumi.Input[str] description: The description of the virtual network.
:param pulumi.Input[str] external_provider_resource_id: The Microsoft.Network resource identifier of the virtual network.
:param pulumi.Input[str] id: The identifier of the resource.
:param pulumi.Input[str] lab_name: The name of the lab.
:param pulumi.Input[str] location: The location of the resource.
:param pulumi.Input[str] name: The name of the resource.
:param pulumi.Input[str] provisioning_state: The provisioning status of the resource.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SubnetOverrideArgs']]]] subnet_overrides: The subnet overrides of the virtual network.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: The tags of the resource.
:param pulumi.Input[str] type: The type of the resource.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['allowed_subnets'] = allowed_subnets
__props__['description'] = description
__props__['external_provider_resource_id'] = external_provider_resource_id
__props__['id'] = id
if lab_name is None:
raise TypeError("Missing required property 'lab_name'")
__props__['lab_name'] = lab_name
__props__['location'] = location
if name is None:
raise TypeError("Missing required property 'name'")
__props__['name'] = name
__props__['provisioning_state'] = provisioning_state
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['subnet_overrides'] = subnet_overrides
__props__['tags'] = tags
__props__['type'] = type
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:devtestlab/latest:VirtualNetworkResource"), pulumi.Alias(type_="azure-nextgen:devtestlab/v20160515:VirtualNetworkResource"), pulumi.Alias(type_="azure-nextgen:devtestlab/v20180915:VirtualNetworkResource")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(VirtualNetworkResource, __self__).__init__(
'azure-nextgen:devtestlab/v20150521preview:VirtualNetworkResource',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'VirtualNetworkResource':
"""
Get an existing VirtualNetworkResource resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
return VirtualNetworkResource(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="allowedSubnets")
def allowed_subnets(self) -> pulumi.Output[Optional[Sequence['outputs.SubnetResponse']]]:
"""
The allowed subnets of the virtual network.
"""
return pulumi.get(self, "allowed_subnets")
@property
@pulumi.getter
def description(self) -> pulumi.Output[Optional[str]]:
"""
The description of the virtual network.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter(name="externalProviderResourceId")
def external_provider_resource_id(self) -> pulumi.Output[Optional[str]]:
"""
The Microsoft.Network resource identifier of the virtual network.
"""
return pulumi.get(self, "external_provider_resource_id")
@property
@pulumi.getter
def location(self) -> pulumi.Output[Optional[str]]:
"""
The location of the resource.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[Optional[str]]:
|
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[Optional[str]]:
"""
The provisioning status of the resource.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="subnetOverrides")
def subnet_overrides(self) -> pulumi.Output[Optional[Sequence['outputs.SubnetOverrideResponse']]]:
"""
The subnet overrides of the virtual network.
"""
return pulumi.get(self, "subnet_overrides")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
The tags of the resource.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> pulumi.Output[Optional[str]]:
"""
The type of the resource.
"""
return pulumi.get(self, "type")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| """
The name of the resource.
"""
return pulumi.get(self, "name") |
batch_spec_workspace_execution_worker_test.go | package background
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/graph-gophers/graphql-go/relay"
"github.com/keegancsmith/sqlf"
"github.com/sourcegraph/sourcegraph/enterprise/internal/batches/store"
ct "github.com/sourcegraph/sourcegraph/enterprise/internal/batches/testing"
btypes "github.com/sourcegraph/sourcegraph/enterprise/internal/batches/types"
"github.com/sourcegraph/sourcegraph/internal/database/dbtest"
"github.com/sourcegraph/sourcegraph/internal/observation"
"github.com/sourcegraph/sourcegraph/internal/workerutil"
dbworkerstore "github.com/sourcegraph/sourcegraph/internal/workerutil/dbworker/store"
batcheslib "github.com/sourcegraph/sourcegraph/lib/batches"
)
func TestBatchSpecWorkspaceExecutionWorkerStore_MarkComplete(t *testing.T) {
ctx := context.Background()
db := dbtest.NewDB(t, "")
user := ct.CreateTestUser(t, db, true)
repo, _ := ct.CreateTestRepo(t, ctx, db)
s := store.New(db, &observation.TestContext, nil)
workStore := dbworkerstore.NewWithMetrics(s.Handle(), batchSpecWorkspaceExecutionWorkerStoreOptions, &observation.TestContext)
// Setup all the associations
batchSpec := &btypes.BatchSpec{UserID: user.ID, NamespaceUserID: user.ID, RawSpec: "horse"}
if err := s.CreateBatchSpec(ctx, batchSpec); err != nil {
t.Fatal(err)
}
workspace := &btypes.BatchSpecWorkspace{BatchSpecID: batchSpec.ID, RepoID: repo.ID, Steps: []batcheslib.Step{}}
if err := s.CreateBatchSpecWorkspace(ctx, workspace); err != nil {
t.Fatal(err)
}
job := &btypes.BatchSpecWorkspaceExecutionJob{BatchSpecWorkspaceID: workspace.ID}
if err := s.CreateBatchSpecWorkspaceExecutionJob(ctx, job); err != nil {
t.Fatal(err)
}
job.State = btypes.BatchSpecWorkspaceExecutionJobStateProcessing
job.WorkerHostname = "worker-1"
if err := s.Exec(ctx, sqlf.Sprintf("UPDATE batch_spec_workspace_execution_jobs SET worker_hostname = %s, state = %s WHERE id = %s", job.WorkerHostname, job.State, job.ID)); err != nil {
t.Fatal(err)
}
// Create changeset_specs to simulate the job resulting in changeset_specs being created
var (
changesetSpecIDs []int64
changesetSpecGraphQLIDs []string
)
for i := 0; i < 3; i++ {
spec := &btypes.ChangesetSpec{RepoID: repo.ID, UserID: user.ID}
if err := s.CreateChangesetSpec(ctx, spec); err != nil {
t.Fatal(err)
}
changesetSpecIDs = append(changesetSpecIDs, spec.ID)
changesetSpecGraphQLIDs = append(changesetSpecGraphQLIDs, fmt.Sprintf("%q", relay.MarshalID("doesnotmatter", spec.RandID)))
}
// Add a log entry that contains the changeset spec IDs
jsonArray := `[` + strings.Join(changesetSpecGraphQLIDs, ",") + `]`
entry := workerutil.ExecutionLogEntry{
Key: "step.src.0",
Command: []string{"src", "batch", "preview", "-f", "spec.yml", "-text-only"},
StartTime: time.Now().Add(-5 * time.Second),
Out: `stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.95Z","status":"SUCCESS","metadata":{"ids":` + jsonArray + `}} `,
DurationMs: intptr(200),
}
_, err := workStore.AddExecutionLogEntry(ctx, int(job.ID), entry, dbworkerstore.ExecutionLogEntryOptions{})
if err != nil {
t.Fatal(err)
}
executionStore := &batchSpecWorkspaceExecutionWorkerStore{Store: workStore, observationContext: &observation.TestContext}
opts := dbworkerstore.MarkFinalOptions{WorkerHostname: job.WorkerHostname}
ok, err := executionStore.MarkComplete(context.Background(), int(job.ID), opts)
if !ok || err != nil {
t.Fatalf("MarkComplete failed. ok=%t, err=%s", ok, err)
}
// Now reload the involved entities and make sure they've been updated correctly
reloadedJob, err := s.GetBatchSpecWorkspaceExecutionJob(ctx, store.GetBatchSpecWorkspaceExecutionJobOpts{ID: job.ID})
if err != nil {
t.Fatalf("failed to reload job: %s", err)
}
if reloadedJob.State != btypes.BatchSpecWorkspaceExecutionJobStateCompleted {
t.Fatalf("wrong state: %s", reloadedJob.State)
}
reloadedWorkspace, err := s.GetBatchSpecWorkspace(ctx, store.GetBatchSpecWorkspaceOpts{ID: workspace.ID})
if err != nil {
t.Fatalf("failed to reload workspace: %s", err)
}
if diff := cmp.Diff(changesetSpecIDs, reloadedWorkspace.ChangesetSpecIDs); diff != "" {
t.Fatalf("reloaded workspace has wrong changeset spec IDs: %s", diff)
}
reloadedSpecs, _, err := s.ListChangesetSpecs(ctx, store.ListChangesetSpecsOpts{LimitOpts: store.LimitOpts{Limit: 0}, IDs: changesetSpecIDs})
if err != nil {
t.Fatalf("failed to reload changeset specs: %s", err)
}
for _, reloadedSpec := range reloadedSpecs {
if reloadedSpec.BatchSpecID != batchSpec.ID {
t.Fatalf("reloaded changeset spec does not have correct batch spec id: %d", reloadedSpec.BatchSpecID)
}
}
}
func TestExtractChangesetSpecIDs(t *testing.T) |
func intptr(i int) *int { return &i }
| {
tests := []struct {
name string
entries []workerutil.ExecutionLogEntry
wantRandIDs []string
wantErr error
}{
{
name: "success",
entries: []workerutil.ExecutionLogEntry{
{Key: "setup.firecracker.start"},
// Reduced log output because we don't care about _all_ lines
{
Key: "step.src.0",
Out: `
stdout: {"operation":"EXECUTING_TASKS","timestamp":"2021-09-09T13:20:32.942Z","status":"SUCCESS"}
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.942Z","status":"STARTED","metadata":{"total":1}}
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.95Z","status":"PROGRESS","metadata":{"done":1,"total":1}}
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.95Z","status":"SUCCESS","metadata":{"ids":["Q2hhbmdlc2V0U3BlYzoiNkxIYWN5dkI3WDYi"]}}
`,
},
},
// Run `echo "QmF0Y2hTcGVjOiJBZFBMTDU5SXJmWCI=" | base64 -d` to get this
wantRandIDs: []string{"6LHacyvB7X6"},
},
{
name: "no step.src.0 log entry",
entries: []workerutil.ExecutionLogEntry{},
wantErr: ErrNoChangesetSpecIDs,
},
{
name: "no upload step in the output",
entries: []workerutil.ExecutionLogEntry{
{
Key: "step.src.0",
Out: `stdout: {"operation":"PARSING_BATCH_SPEC","timestamp":"2021-07-06T09:38:51.481Z","status":"STARTED"}
stdout: {"operation":"PARSING_BATCH_SPEC","timestamp":"2021-07-06T09:38:51.481Z","status":"SUCCESS"}
`,
},
},
wantErr: ErrNoChangesetSpecIDs,
},
{
name: "empty array the output",
entries: []workerutil.ExecutionLogEntry{
{
Key: "step.src.0",
Out: `
stdout: {"operation":"EXECUTING_TASKS","timestamp":"2021-09-09T13:20:32.942Z","status":"SUCCESS"}
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.942Z","status":"STARTED","metadata":{"total":1}}
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.95Z","status":"PROGRESS","metadata":{"done":1,"total":1}}
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.95Z","status":"SUCCESS","metadata":{"ids":[]}}
`,
},
},
wantErr: ErrNoChangesetSpecIDs,
},
{
name: "additional text in log output",
entries: []workerutil.ExecutionLogEntry{
{
Key: "step.src.0",
Out: `stdout: {"operation":"EXECUTING_TASKS","timestamp":"2021-09-09T13:20:32.941Z","status":"STARTED","metadata":{"tasks":[]}}
stdout: {"operation":"EXECUTING_TASKS","timestamp":"2021-09-09T13:20:32.942Z","status":"SUCCESS"}
stderr: HORSE
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.942Z","status":"STARTED","metadata":{"total":1}}
stderr: HORSE
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.95Z","status":"PROGRESS","metadata":{"done":1,"total":1}}
stderr: HORSE
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.95Z","status":"SUCCESS","metadata":{"ids":["Q2hhbmdlc2V0U3BlYzoiNkxIYWN5dkI3WDYi"]}}
`,
},
},
wantRandIDs: []string{"6LHacyvB7X6"},
},
{
name: "invalid json",
entries: []workerutil.ExecutionLogEntry{
{
Key: "step.src.0",
Out: `stdout: {"operation":"PARSING_BATCH_SPEC","timestamp":"2021-07-06T09:38:51.481Z","status":"STARTED"}
stdout: {HOOOORSE}
stdout: {HORSE}
stdout: {HORSE}
`,
},
},
wantErr: ErrNoChangesetSpecIDs,
},
{
name: "non-json output inbetween valid json",
entries: []workerutil.ExecutionLogEntry{
{
Key: "step.src.0",
Out: `stdout: {"operation":"PARSING_BATCH_SPEC","timestamp":"2021-07-12T12:25:33.965Z","status":"STARTED"}
stdout: No changeset specs created
stdout: {"operation":"UPLOADING_CHANGESET_SPECS","timestamp":"2021-09-09T13:20:32.95Z","status":"SUCCESS","metadata":{"ids":["Q2hhbmdlc2V0U3BlYzoiNkxIYWN5dkI3WDYi"]}}`,
},
},
wantRandIDs: []string{"6LHacyvB7X6"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
have, err := extractChangesetSpecRandIDs(tt.entries)
if tt.wantErr != nil {
if err != tt.wantErr {
t.Fatalf("wrong error. want=%s, got=%s", tt.wantErr, err)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if diff := cmp.Diff(tt.wantRandIDs, have); diff != "" {
t.Fatalf("wrong IDs extracted: %s", diff)
}
})
}
} |
option_train_DistillationIQA_FR.py | # import template
import argparse
import os
"""
Configuration file
"""
def check_args(args, rank=0):
if rank == 0:
with open(args.setting_file, 'w') as opt_file:
opt_file.write('------------ Options -------------\n')
print('------------ Options -------------')
for k in args.__dict__:
v = args.__dict__[k]
opt_file.write('%s: %s\n' % (str(k), str(v)))
print('%s: %s' % (str(k), str(v)))
opt_file.write('-------------- End ----------------\n')
print('------------ End -------------')
return args
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Unsupported value encountered.')
def set_args():
parser = argparse.ArgumentParser()
parser.add_argument('--gpu_ids', type=str, default='0')
parser.add_argument('--test_dataset', type=str, default='live', help='Support datasets: pipal|livec|koniq-10k|bid|live|csiq|tid2013|kadid10k')
parser.add_argument('--train_dataset', type=str, default='kadid10k', help='Support datasets: pipal|livec|koniq-10k|bid|live|csiq|tid2013|kadid10k')
parser.add_argument('--train_patch_num', type=int, default=1, help='Number of sample patches from training image')
parser.add_argument('--test_patch_num', type=int, default=1, help='Number of sample patches from testing image')
parser.add_argument('--lr', dest='lr', type=float, default=2e-5, help='Learning rate')
parser.add_argument('--weight_decay', type=float, default=5e-4, help='Weight decay')
parser.add_argument('--batch_size', type=int, default=32, help='Batch size')
parser.add_argument('--epochs', type=int, default=100, help='Epochs for training')
parser.add_argument('--patch_size', type=int, default=224, help='Crop size for training & testing image patches')
parser.add_argument('--self_patch_num', type=int, default=10, help='number of training & testing image self patches')
parser.add_argument('--train_test_num', type=int, default=1, help='Train-test times')
parser.add_argument('--update_opt_epoch', type=int, default=300)
#Ref Img
parser.add_argument('--use_refHQ', type=str2bool, default=True)
parser.add_argument('--ref_folder_paths', type=str, default='./dataset/DIV2K_ref.tar.gz')
parser.add_argument('--distillation_layer', type=int, default=18, help='last xth layers of HQ-MLP for distillation')
parser.add_argument('--net_print', type=int, default=2000)
parser.add_argument('--setting_file', type=str, default='setting.txt')
parser.add_argument('--checkpoint_dir', type=str, default='./checkpoint_FRIQA_teacher/')
parser.add_argument('--use_fitting_prcc_srcc', type=str2bool, default=True)
parser.add_argument('--print_netC', type=str2bool, default=False)
parser.add_argument('--teacherNet_model_path', type=str, default=None, help='./model_zoo/FR_teacher_cross_dataset.pth')
args = parser.parse_args()
#Dataset
args.setting_file = os.path.join(args.checkpoint_dir, args.setting_file)
if not os.path.exists('./dataset/'):
os.mkdir('./dataset/')
folder_path = {
'live': './dataset/LIVE/',
'csiq': './dataset/CSIQ/',
'tid2013': './dataset/TID2013/',
'koniq-10k': './dataset/koniq-10k/',
}
ref_dataset_path = './dataset/DIV2K_ref/'
args.ref_train_dataset_path = ref_dataset_path + 'train_HR/'
args.ref_test_dataset_path = ref_dataset_path + 'val_HR/'
#checkpoint files
args.model_checkpoint_dir = args.checkpoint_dir + 'models/' |
if os.path.exists(args.checkpoint_dir) and os.path.isfile(args.checkpoint_dir):
raise IOError('Required dst path {} as a directory for checkpoint saving, got a file'.format(
args.checkpoint_dir))
elif not os.path.exists(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir)
print('%s created successfully!'%args.checkpoint_dir)
if os.path.exists(args.model_checkpoint_dir) and os.path.isfile(args.model_checkpoint_dir):
raise IOError('Required dst path {} as a directory for checkpoint model saving, got a file'.format(
args.model_checkpoint_dir))
elif not os.path.exists(args.model_checkpoint_dir):
os.makedirs(args.model_checkpoint_dir)
print('%s created successfully!'%args.model_checkpoint_dir)
if os.path.exists(args.result_checkpoint_dir) and os.path.isfile(args.result_checkpoint_dir):
raise IOError('Required dst path {} as a directory for checkpoint results saving, got a file'.format(
args.result_checkpoint_dir))
elif not os.path.exists(args.result_checkpoint_dir):
os.makedirs(args.result_checkpoint_dir)
print('%s created successfully!'%args.result_checkpoint_dir)
if os.path.exists(args.log_checkpoint_dir) and os.path.isfile(args.log_checkpoint_dir):
raise IOError('Required dst path {} as a directory for checkpoint log saving, got a file'.format(
args.log_checkpoint_dir))
elif not os.path.exists(args.log_checkpoint_dir):
os.makedirs(args.log_checkpoint_dir)
print('%s created successfully!'%args.log_checkpoint_dir)
return args
if __name__ == "__main__":
args = set_args() | args.result_checkpoint_dir = args.checkpoint_dir + 'results/'
args.log_checkpoint_dir = args.checkpoint_dir + 'log/' |
build-styles.js | const postcss = require('postcss')
const syntax = require('postcss-less')
const path = require('path')
const fs = require('fs')
const less = require('../../work_preject/一号掌柜商家(web)-project/build/less')
const shell = require('shelljs')
const distPath = path.resolve(__dirname, `../dist/styles/`)
shell.rm('-rf', distPath)
shell.mkdir('-p', distPath)
var pkg = require(path.join(__dirname, '../package.json'))
const p = path.resolve(__dirname, '../src/styles/')
fs.readdir(p, function (err, files) {
if (err) {
throw err
}
files.filter(function (file) {
return !fs.statSync(path.join(p, file)).isDirectory() && /less/.test(file) && !/index|variable|theme/.test(file)
}).forEach(function (file) {
parse(file)
})
})
const getPath = function (name) {
return path.resolve(__dirname, `../dist/styles/${name}`)
}
function parse (file) {
var code = fs.readFileSync(path.resolve(__dirname, `../src/styles/${file}`), 'utf-8')
less.render(code, { | compress: true,
paths: [path.resolve(__dirname, '../src/styles')]
},function (e, output) {
if (e) {
throw e
} else {
postcss([require('autoprefixer')(['iOS >= 7', 'Android >= 4.1'])])
.process(output.css, {
syntax: syntax
})
.then(function (result) {
const dist = getPath(file.replace('less', 'css'));
fs.writeFileSync(dist, result.css);
})
.catch(function(e){
console.log(e)
})
}
})
} | |
regress-crbug-631318-12.js | // Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax
function | (x) { return x >>> x; }
foo(1);
foo(2);
function bar(x) { foo(x); }
%OptimizeFunctionOnNextCall(bar);
assertThrows(() => bar(Symbol.toPrimitive));
| foo |
sqlstringmatcher.go | package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"github.com/onsi/gomega/types"
"github.com/weworksandbox/lingo/sql"
)
// SQLStringMatcher matches a `sql.Data` `String()` value
type SQLStringMatcher struct {
Expected interface{} | func (matcher *SQLStringMatcher) Match(actual interface{}) (success bool, err error) {
if isNil(actual) {
return false, fmt.Errorf("expected a sql.Data, got nil")
}
s, ok := actual.(sql.Data)
if !ok {
return false, fmt.Errorf("expected a sql.Data. Got:\n%s", format.Object(actual, 1))
}
var subMatcher types.GomegaMatcher
var hasSubMatcher bool
if matcher.Expected != nil {
subMatcher, hasSubMatcher = (matcher.Expected).(types.GomegaMatcher)
if hasSubMatcher {
return subMatcher.Match(s.String())
}
}
if exp, ok := toString(matcher.Expected); ok {
return s.String() == exp, nil
}
return false, fmt.Errorf(
"SQLStringMatcher must be passed a string or a string matcher. Got:\n%s",
format.Object(matcher.Expected, 1))
}
func (matcher *SQLStringMatcher) FailureMessage(actual interface{}) (message string) {
return format.Message(actual, "to match sql.Data string", matcher.Expected)
}
func (matcher *SQLStringMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return format.Message(actual, "not to match sql.Data string", matcher.Expected)
} | }
|
reference_processor.rs | use std::collections::HashSet;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Mutex;
use std::vec::Vec;
use crate::scheduler::ProcessEdgesWork;
use crate::util::ObjectReference;
use crate::util::VMWorkerThread;
use crate::vm::ReferenceGlue;
use crate::vm::VMBinding;
/// Holds all reference processors for each weak reference Semantics.
/// Currently this is based on Java's weak reference semantics (soft/weak/phantom).
/// We should make changes to make this general rather than Java specific.
pub struct ReferenceProcessors {
soft: ReferenceProcessor,
weak: ReferenceProcessor,
phantom: ReferenceProcessor,
}
impl ReferenceProcessors {
pub fn new() -> Self {
ReferenceProcessors {
soft: ReferenceProcessor::new(Semantics::SOFT),
weak: ReferenceProcessor::new(Semantics::WEAK),
phantom: ReferenceProcessor::new(Semantics::PHANTOM),
}
}
pub fn get(&self, semantics: Semantics) -> &ReferenceProcessor {
match semantics {
Semantics::SOFT => &self.soft,
Semantics::WEAK => &self.weak,
Semantics::PHANTOM => &self.phantom,
}
}
pub fn add_soft_candidate<VM: VMBinding>(&self, reff: ObjectReference) {
trace!("Add soft candidate: {}", reff);
self.soft.add_candidate::<VM>(reff);
}
pub fn add_weak_candidate<VM: VMBinding>(&self, reff: ObjectReference) {
trace!("Add weak candidate: {}", reff);
self.weak.add_candidate::<VM>(reff);
}
pub fn add_phantom_candidate<VM: VMBinding>(&self, reff: ObjectReference) {
trace!("Add phantom candidate: {}", reff);
self.phantom.add_candidate::<VM>(reff);
}
/// This will invoke enqueue for each reference processor, which will
/// call back to the VM to enqueue references whose referents are cleared
/// in this GC.
pub fn enqueue_refs<VM: VMBinding>(&self, tls: VMWorkerThread) {
self.soft.enqueue::<VM>(tls);
self.weak.enqueue::<VM>(tls);
self.phantom.enqueue::<VM>(tls);
}
/// A separate reference forwarding step. Normally when we scan refs, we deal with forwarding.
/// However, for some plans like mark compact, at the point we do ref scanning, we do not know
/// the forwarding addresses yet, thus we cannot do forwarding during scan refs. And for those
/// plans, this separate step is required.
pub fn forward_refs<E: ProcessEdgesWork>(&self, trace: &mut E, mmtk: &'static MMTK<E::VM>) {
debug_assert!(
mmtk.plan.constraints().needs_forward_after_liveness,
"A plan with needs_forward_after_liveness=false does not need a separate forward step"
); | self.phantom
.forward::<E>(trace, mmtk.plan.is_current_gc_nursery());
}
// Methods for scanning weak references. It needs to be called in a decreasing order of reference strengths, i.e. soft > weak > phantom
/// Scan soft references.
pub fn scan_soft_refs<E: ProcessEdgesWork>(&self, trace: &mut E, mmtk: &'static MMTK<E::VM>) {
// For soft refs, it is up to the VM to decide when to reclaim this.
// If this is not an emergency collection, we have no heap stress. We simply retain soft refs.
if !mmtk.plan.is_emergency_collection() {
// This step only retains the referents (keep the referents alive), it does not update its addresses.
// We will call soft.scan() again with retain=false to update its addresses based on liveness.
self.soft
.retain::<E>(trace, mmtk.plan.is_current_gc_nursery());
}
// This will update the references (and the referents).
self.soft
.scan::<E>(trace, mmtk.plan.is_current_gc_nursery());
}
/// Scan weak references.
pub fn scan_weak_refs<E: ProcessEdgesWork>(&self, trace: &mut E, mmtk: &'static MMTK<E::VM>) {
self.weak
.scan::<E>(trace, mmtk.plan.is_current_gc_nursery());
}
/// Scan phantom references.
pub fn scan_phantom_refs<E: ProcessEdgesWork>(
&self,
trace: &mut E,
mmtk: &'static MMTK<E::VM>,
) {
self.phantom
.scan::<E>(trace, mmtk.plan.is_current_gc_nursery());
}
}
impl Default for ReferenceProcessors {
fn default() -> Self {
Self::new()
}
}
// XXX: We differ from the original implementation
// by ignoring "stress," i.e. where the array
// of references is grown by 1 each time. We
// can't do this here b/c std::vec::Vec doesn't
// allow us to customize its behaviour like that.
// (Similarly, GROWTH_FACTOR is locked at 2.0, but
// luckily this is also the value used by Java MMTk.)
const INITIAL_SIZE: usize = 256;
/// We create a reference processor for each semantics. Generally we expect these
/// to happen for each processor:
/// 1. The VM adds reference candidates. They could either do it when a weak reference
/// is created, or when a weak reference is traced during GC.
/// 2. We scan references after the GC determins liveness.
/// 3. We forward references if the GC needs forwarding after liveness.
/// 4. We inform the binding of references whose referents are cleared during this GC by enqueue'ing.
pub struct ReferenceProcessor {
/// Most of the reference processor is protected by a mutex.
sync: Mutex<ReferenceProcessorSync>,
/// The semantics for the reference processor
semantics: Semantics,
/// Is it allowed to add candidate to this reference processor? The value is true for most of the time,
/// but it is set to false once we finish forwarding references, at which point we do not expect to encounter
/// any 'new' reference in the same GC. This makes sure that no new entry will be added to our reference table once
/// we finish forwarding, as we will not be able to process the entry in that GC.
// This avoids an issue in the following scenario in mark compact:
// 1. First trace: add a candidate WR
// 2. Weak reference scan: scan the reference table, as MC does not forward object in the first trace. This scan does not update any reference.
// 3. Second trace: call add_candidate again with WR, but WR gets ignored as we already have WR in our reference table.
// 4. Weak reference forward: call trace_object for WR, which pushes WR to the node buffer and update WR -> WR' in our reference table.
// 5. When we trace objects in the node buffer, we will attempt to add WR as a candidate. As we have updated WR to WR' in our reference
// table, we would accept WR as a candidate. But we will not trace WR again, and WR will be invalid after this GC.
// This flag is set to false after Step 4, so in Step 5, we will ignore adding WR.
allow_new_candidate: AtomicBool,
}
#[derive(Debug, PartialEq)]
pub enum Semantics {
SOFT,
WEAK,
PHANTOM,
}
struct ReferenceProcessorSync {
/// The table of reference objects for the current semantics. We add references to this table by
/// add_candidate(). After scanning this table, a reference in the table should either
/// stay in the table (if the referent is alive) or go to enqueued_reference (if the referent is dead and cleared).
/// Note that this table should not have duplicate entries, otherwise we will scan the duplicates multiple times, and
/// that may lead to incorrect results.
references: HashSet<ObjectReference>,
/// References whose referents are cleared during this GC. We add references to this table during
/// scanning, and we pop from this table during the enqueue work at the end of GC.
enqueued_references: Vec<ObjectReference>,
/// Index into the references table for the start of nursery objects
nursery_index: usize,
}
impl ReferenceProcessor {
pub fn new(semantics: Semantics) -> Self {
ReferenceProcessor {
sync: Mutex::new(ReferenceProcessorSync {
references: HashSet::with_capacity(INITIAL_SIZE),
enqueued_references: vec![],
nursery_index: 0,
}),
semantics,
allow_new_candidate: AtomicBool::new(true),
}
}
/// Add a candidate.
#[inline(always)]
pub fn add_candidate<VM: VMBinding>(&self, reff: ObjectReference) {
if !self.allow_new_candidate.load(Ordering::SeqCst) {
return;
}
let mut sync = self.sync.lock().unwrap();
sync.references.insert(reff);
}
fn disallow_new_candidate(&self) {
self.allow_new_candidate.store(false, Ordering::SeqCst);
}
fn allow_new_candidate(&self) {
self.allow_new_candidate.store(true, Ordering::SeqCst);
}
// These funcions simply call `trace_object()`, which does two things: 1. to make sure the object is kept alive
// and 2. to get the new object reference if the object is copied. The functions are intended to make the code
// easier to understand.
#[inline(always)]
fn get_forwarded_referent<E: ProcessEdgesWork>(
e: &mut E,
referent: ObjectReference,
) -> ObjectReference {
e.trace_object(referent)
}
#[inline(always)]
fn get_forwarded_reference<E: ProcessEdgesWork>(
e: &mut E,
object: ObjectReference,
) -> ObjectReference {
e.trace_object(object)
}
#[inline(always)]
fn keep_referent_alive<E: ProcessEdgesWork>(
e: &mut E,
referent: ObjectReference,
) -> ObjectReference {
e.trace_object(referent)
}
/// Inform the binding to enqueue the weak references whose referents were cleared in this GC.
pub fn enqueue<VM: VMBinding>(&self, tls: VMWorkerThread) {
let mut sync = self.sync.lock().unwrap();
// This is the end of a GC. We do some assertions here to make sure our reference tables are correct.
#[cfg(debug_assertions)]
{
// For references in the table, the reference needs to be valid, and if the referent is not null, it should be valid as well
sync.references.iter().for_each(|reff| {
debug_assert!(!reff.is_null());
debug_assert!(reff.is_in_any_space());
let referent = VM::VMReferenceGlue::get_referent(*reff);
if !referent.is_null() {
debug_assert!(
referent.is_in_any_space(),
"Referent {:?} (of reference {:?}) is not in any space",
referent,
reff
);
}
});
// For references that will be enqueue'd, the referent needs to be valid, and the referent needs to be null.
sync.enqueued_references.iter().for_each(|reff| {
debug_assert!(!reff.is_null());
debug_assert!(reff.is_in_any_space());
let referent = VM::VMReferenceGlue::get_referent(*reff);
debug_assert!(referent.is_null());
});
}
if !sync.enqueued_references.is_empty() {
trace!("enqueue: {:?}", sync.enqueued_references);
VM::VMReferenceGlue::enqueue_references(&sync.enqueued_references, tls);
sync.enqueued_references.clear();
}
self.allow_new_candidate();
}
/// Forward the reference tables in the reference processor. This is only needed if a plan does not forward
/// objects in their first transitive closure.
/// nursery is not used for this.
pub fn forward<E: ProcessEdgesWork>(&self, trace: &mut E, _nursery: bool) {
let mut sync = self.sync.lock().unwrap();
debug!("Starting ReferenceProcessor.forward({:?})", self.semantics);
// Forward a single reference
#[inline(always)]
fn forward_reference<E: ProcessEdgesWork>(
trace: &mut E,
reference: ObjectReference,
) -> ObjectReference {
let old_referent = <E::VM as VMBinding>::VMReferenceGlue::get_referent(reference);
let new_referent = ReferenceProcessor::get_forwarded_referent(trace, old_referent);
<E::VM as VMBinding>::VMReferenceGlue::set_referent(reference, new_referent);
let new_reference = ReferenceProcessor::get_forwarded_reference(trace, reference);
{
use crate::vm::ObjectModel;
trace!(
"Forwarding reference: {} (size: {})",
reference,
<E::VM as VMBinding>::VMObjectModel::get_current_size(reference)
);
trace!(
" referent: {} (forwarded to {})",
old_referent,
new_referent
);
trace!(" reference: forwarded to {}", new_reference);
}
debug_assert!(
!new_reference.is_null(),
"reference {:?}'s forwarding pointer is NULL",
reference
);
new_reference
}
sync.references = sync
.references
.iter()
.map(|reff| forward_reference::<E>(trace, *reff))
.collect();
sync.enqueued_references = sync
.enqueued_references
.iter()
.map(|reff| forward_reference::<E>(trace, *reff))
.collect();
debug!("Ending ReferenceProcessor.forward({:?})", self.semantics);
// We finish forwarding. No longer accept new candidates.
self.disallow_new_candidate();
}
/// Scan the reference table, and update each reference/referent.
// TODO: nursery is currently ignored. We used to use Vec for the reference table, and use an int
// to point to the reference that we last scanned. However, when we use HashSet for reference table,
// we can no longer do that.
fn scan<E: ProcessEdgesWork>(&self, trace: &mut E, _nursery: bool) {
let mut sync = self.sync.lock().unwrap();
debug!("Starting ReferenceProcessor.scan({:?})", self.semantics);
trace!(
"{:?} Reference table is {:?}",
self.semantics,
sync.references
);
debug_assert!(sync.enqueued_references.is_empty());
// Put enqueued reference in this vec
let mut enqueued_references = vec![];
// Determinine liveness for each reference and only keep the refs if `process_reference()` returns Some.
let new_set: HashSet<ObjectReference> = sync
.references
.iter()
.filter_map(|reff| self.process_reference(trace, *reff, &mut enqueued_references))
.collect();
debug!(
"{:?} reference table from {} to {} ({} enqueued)",
self.semantics,
sync.references.len(),
new_set.len(),
enqueued_references.len()
);
sync.references = new_set;
sync.enqueued_references = enqueued_references;
debug!("Ending ReferenceProcessor.scan({:?})", self.semantics);
}
/// Retain referent in the reference table. This method deals only with soft references.
/// It retains the referent if the reference is definitely reachable. This method does
/// not update reference or referent. So after this method, scan() should be used to update
/// the references/referents.
fn retain<E: ProcessEdgesWork>(&self, trace: &mut E, _nursery: bool) {
debug_assert!(self.semantics == Semantics::SOFT);
let sync = self.sync.lock().unwrap();
debug!("Starting ReferenceProcessor.retain({:?})", self.semantics);
trace!(
"{:?} Reference table is {:?}",
self.semantics,
sync.references
);
for reference in sync.references.iter() {
debug_assert!(!reference.is_null());
trace!("Processing reference: {:?}", reference);
if !reference.is_live() {
// Reference is currently unreachable but may get reachable by the
// following trace. We postpone the decision.
continue;
}
// Reference is definitely reachable. Retain the referent.
let referent = <E::VM as VMBinding>::VMReferenceGlue::get_referent(*reference);
if !referent.is_null() {
Self::keep_referent_alive(trace, referent);
}
trace!(" ~> {:?} (retained)", referent.to_address());
}
debug!("Ending ReferenceProcessor.retain({:?})", self.semantics);
}
/// Process a reference.
/// * If both the reference and the referent is alive, return the updated reference and update its referent properly.
/// * If the reference is alive, and the referent is not null but not alive, return None and the reference (with cleared referent) is enqueued.
/// * For other cases, return None.
///
/// If a None value is returned, the reference can be removed from the reference table. Otherwise, the updated reference should be kept
/// in the reference table.
fn process_reference<E: ProcessEdgesWork>(
&self,
trace: &mut E,
reference: ObjectReference,
enqueued_references: &mut Vec<ObjectReference>,
) -> Option<ObjectReference> {
debug_assert!(!reference.is_null());
trace!("Process reference: {}", reference);
// If the reference is dead, we're done with it. Let it (and
// possibly its referent) be garbage-collected.
if !reference.is_live() {
<E::VM as VMBinding>::VMReferenceGlue::clear_referent(reference);
trace!(" UNREACHABLE reference: {}", reference);
trace!(" (unreachable)");
return None;
}
// The reference object is live
let new_reference = Self::get_forwarded_reference(trace, reference);
let old_referent = <E::VM as VMBinding>::VMReferenceGlue::get_referent(reference);
trace!(" ~> {}", old_referent);
// If the application has cleared the referent the Java spec says
// this does not cause the Reference object to be enqueued. We
// simply allow the Reference object to fall out of our
// waiting list.
if old_referent.is_null() {
trace!(" (null referent) ");
return None;
}
trace!(" => {}", new_reference);
if old_referent.is_live() {
// Referent is still reachable in a way that is as strong as
// or stronger than the current reference level.
let new_referent = Self::get_forwarded_referent(trace, old_referent);
debug_assert!(new_referent.is_live());
trace!(" ~> {}", new_referent);
// The reference object stays on the waiting list, and the
// referent is untouched. The only thing we must do is
// ensure that the former addresses are updated with the
// new forwarding addresses in case the collector is a
// copying collector.
// Update the referent
<E::VM as VMBinding>::VMReferenceGlue::set_referent(new_reference, new_referent);
Some(new_reference)
} else {
// Referent is unreachable. Clear the referent and enqueue the reference object.
trace!(" UNREACHABLE referent: {}", old_referent);
<E::VM as VMBinding>::VMReferenceGlue::clear_referent(new_reference);
enqueued_references.push(new_reference);
None
}
}
}
use crate::scheduler::GCWork;
use crate::scheduler::GCWorker;
use crate::MMTK;
use std::marker::PhantomData;
#[derive(Default)]
pub struct SoftRefProcessing<E: ProcessEdgesWork>(PhantomData<E>);
impl<E: ProcessEdgesWork> GCWork<E::VM> for SoftRefProcessing<E> {
fn do_work(&mut self, worker: &mut GCWorker<E::VM>, mmtk: &'static MMTK<E::VM>) {
let mut w = E::new(vec![], false, mmtk);
w.set_worker(worker);
mmtk.reference_processors.scan_soft_refs(&mut w, mmtk);
w.flush();
}
}
impl<E: ProcessEdgesWork> SoftRefProcessing<E> {
pub fn new() -> Self {
Self(PhantomData)
}
}
#[derive(Default)]
pub struct WeakRefProcessing<E: ProcessEdgesWork>(PhantomData<E>);
impl<E: ProcessEdgesWork> GCWork<E::VM> for WeakRefProcessing<E> {
fn do_work(&mut self, worker: &mut GCWorker<E::VM>, mmtk: &'static MMTK<E::VM>) {
let mut w = E::new(vec![], false, mmtk);
w.set_worker(worker);
mmtk.reference_processors.scan_weak_refs(&mut w, mmtk);
w.flush();
}
}
impl<E: ProcessEdgesWork> WeakRefProcessing<E> {
pub fn new() -> Self {
Self(PhantomData)
}
}
#[derive(Default)]
pub struct PhantomRefProcessing<E: ProcessEdgesWork>(PhantomData<E>);
impl<E: ProcessEdgesWork> GCWork<E::VM> for PhantomRefProcessing<E> {
fn do_work(&mut self, worker: &mut GCWorker<E::VM>, mmtk: &'static MMTK<E::VM>) {
let mut w = E::new(vec![], false, mmtk);
w.set_worker(worker);
mmtk.reference_processors.scan_phantom_refs(&mut w, mmtk);
w.flush();
}
}
impl<E: ProcessEdgesWork> PhantomRefProcessing<E> {
pub fn new() -> Self {
Self(PhantomData)
}
}
#[derive(Default)]
pub struct RefForwarding<E: ProcessEdgesWork>(PhantomData<E>);
impl<E: ProcessEdgesWork> GCWork<E::VM> for RefForwarding<E> {
fn do_work(&mut self, worker: &mut GCWorker<E::VM>, mmtk: &'static MMTK<E::VM>) {
let mut w = E::new(vec![], false, mmtk);
w.set_worker(worker);
mmtk.reference_processors.forward_refs(&mut w, mmtk);
w.flush();
}
}
impl<E: ProcessEdgesWork> RefForwarding<E> {
pub fn new() -> Self {
Self(PhantomData)
}
}
#[derive(Default)]
pub struct RefEnqueue<VM: VMBinding>(PhantomData<VM>);
impl<VM: VMBinding> GCWork<VM> for RefEnqueue<VM> {
fn do_work(&mut self, worker: &mut GCWorker<VM>, mmtk: &'static MMTK<VM>) {
mmtk.reference_processors.enqueue_refs::<VM>(worker.tls);
}
}
impl<VM: VMBinding> RefEnqueue<VM> {
pub fn new() -> Self {
Self(PhantomData)
}
} | self.soft
.forward::<E>(trace, mmtk.plan.is_current_gc_nursery());
self.weak
.forward::<E>(trace, mmtk.plan.is_current_gc_nursery()); |
DataModel.py | import numpy as np
import pandas as pd
class DataModel:
"""
This class implements a data model - values at time points and provides methods for working with these data.
"""
def __init__(self, n=0, values=None, times=None):
"""
A constructor that takes values and a time point.
:param values: Array of values process
:param times: Array of a time points
"""
if (values is None) or (times is None):
self._times = np.zeros((n, ))
self._values = np.zeros((n, ))
else:
if len(values) != len(times):
print("Different size of values and times")
else:
self._times = np.array(times, dtype=float)
self._values = np.array(values, dtype=float)
def print(self, n=None):
if n is not None:
_n = n
elif self._times.shape:
_n = self._times.shape[0]
for i in range(_n):
print("Time: {}___Value: {}".format(self._times[i], self._values[i]))
@property
def mean(self):
|
def get_values(self):
return self._values
def get_times(self):
return self._times
def add_value(self, value, index):
# self._values.__add__(value)
self._values[index] = value
def add_time(self, time, index):
# self._times.__add__(time)
self._times[index] = time
def get_value(self, index):
return self._values[index]
def get_time(self, index):
return self._times[index] | """
:return: Mean of values
"""
return self._times.mean() |
event_loop.rs | #![allow(non_snake_case)]
mod runner;
use parking_lot::Mutex;
use std::{
cell::Cell,
collections::VecDeque,
marker::PhantomData,
mem, panic, ptr,
rc::Rc,
sync::{
mpsc::{self, Receiver, Sender},
Arc,
},
thread,
time::{Duration, Instant},
};
use winapi::shared::basetsd::{DWORD_PTR, UINT_PTR};
use winapi::{
shared::{
minwindef::{BOOL, DWORD, HIWORD, INT, LOWORD, LPARAM, LRESULT, UINT, WORD, WPARAM},
windef::{HWND, POINT, RECT},
windowsx, winerror,
},
um::{
commctrl, libloaderapi, ole2, processthreadsapi, winbase,
winnt::{HANDLE, LONG, LPCSTR, SHORT},
winuser,
},
};
use crate::{
dpi::{PhysicalPosition, PhysicalSize},
event::{DeviceEvent, Event, Force, KeyboardInput, Touch, TouchPhase, WindowEvent},
event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootELW},
monitor::MonitorHandle as RootMonitorHandle,
platform_impl::platform::{
dark_mode::try_theme,
dpi::{become_dpi_aware, dpi_to_scale_factor, enable_non_client_dpi_scaling},
drop_handler::FileDropHandler,
event::{self, handle_extended_keys, process_key_params, vkey_to_winit_vkey},
monitor::{self, MonitorHandle},
raw_input, util,
window_state::{CursorFlags, WindowFlags, WindowState},
wrap_device_id, WindowId, DEVICE_ID,
},
window::{Fullscreen, WindowId as RootWindowId},
};
use runner::{EventLoopRunner, EventLoopRunnerShared};
type GetPointerFrameInfoHistory = unsafe extern "system" fn(
pointerId: UINT,
entriesCount: *mut UINT,
pointerCount: *mut UINT,
pointerInfo: *mut winuser::POINTER_INFO,
) -> BOOL;
type SkipPointerFrameMessages = unsafe extern "system" fn(pointerId: UINT) -> BOOL;
type GetPointerDeviceRects = unsafe extern "system" fn(
device: HANDLE,
pointerDeviceRect: *mut RECT,
displayRect: *mut RECT,
) -> BOOL;
type GetPointerTouchInfo =
unsafe extern "system" fn(pointerId: UINT, touchInfo: *mut winuser::POINTER_TOUCH_INFO) -> BOOL;
type GetPointerPenInfo =
unsafe extern "system" fn(pointId: UINT, penInfo: *mut winuser::POINTER_PEN_INFO) -> BOOL;
lazy_static! {
static ref GET_POINTER_FRAME_INFO_HISTORY: Option<GetPointerFrameInfoHistory> =
get_function!("user32.dll", GetPointerFrameInfoHistory);
static ref SKIP_POINTER_FRAME_MESSAGES: Option<SkipPointerFrameMessages> =
get_function!("user32.dll", SkipPointerFrameMessages);
static ref GET_POINTER_DEVICE_RECTS: Option<GetPointerDeviceRects> =
get_function!("user32.dll", GetPointerDeviceRects);
static ref GET_POINTER_TOUCH_INFO: Option<GetPointerTouchInfo> =
get_function!("user32.dll", GetPointerTouchInfo);
static ref GET_POINTER_PEN_INFO: Option<GetPointerPenInfo> =
get_function!("user32.dll", GetPointerPenInfo);
}
pub(crate) struct SubclassInput<T: 'static> {
pub window_state: Arc<Mutex<WindowState>>,
pub event_loop_runner: EventLoopRunnerShared<T>,
pub file_drop_handler: Option<FileDropHandler>,
pub subclass_removed: Cell<bool>,
pub recurse_depth: Cell<u32>,
}
impl<T> SubclassInput<T> {
unsafe fn send_event(&self, event: Event<'_, T>) {
self.event_loop_runner.send_event(event);
}
}
struct ThreadMsgTargetSubclassInput<T: 'static> {
event_loop_runner: EventLoopRunnerShared<T>,
user_event_receiver: Receiver<T>,
}
impl<T> ThreadMsgTargetSubclassInput<T> {
unsafe fn send_event(&self, event: Event<'_, T>) {
self.event_loop_runner.send_event(event);
}
}
pub struct EventLoop<T: 'static> {
thread_msg_sender: Sender<T>,
window_target: RootELW<T>,
}
pub struct EventLoopWindowTarget<T: 'static> {
thread_id: DWORD,
thread_msg_target: HWND,
pub(crate) runner_shared: EventLoopRunnerShared<T>,
}
macro_rules! main_thread_check {
($fn_name:literal) => {{
let thread_id = unsafe { processthreadsapi::GetCurrentThreadId() };
if thread_id != main_thread_id() {
panic!(concat!(
"Initializing the event loop outside of the main thread is a significant \
cross-platform compatibility hazard. If you really, absolutely need to create an \
EventLoop on a different thread, please use the `EventLoopExtWindows::",
$fn_name,
"` function."
));
}
}};
}
impl<T: 'static> EventLoop<T> {
pub fn new() -> EventLoop<T> {
main_thread_check!("new_any_thread");
Self::new_any_thread()
}
pub fn new_any_thread() -> EventLoop<T> {
become_dpi_aware();
Self::new_dpi_unaware_any_thread()
}
pub fn new_dpi_unaware() -> EventLoop<T> {
main_thread_check!("new_dpi_unaware_any_thread");
Self::new_dpi_unaware_any_thread()
}
pub fn new_dpi_unaware_any_thread() -> EventLoop<T> {
let thread_id = unsafe { processthreadsapi::GetCurrentThreadId() };
let thread_msg_target = create_event_target_window();
let send_thread_msg_target = thread_msg_target as usize;
thread::spawn(move || wait_thread(thread_id, send_thread_msg_target as HWND));
let wait_thread_id = get_wait_thread_id();
let runner_shared = Rc::new(EventLoopRunner::new(thread_msg_target, wait_thread_id));
let thread_msg_sender =
subclass_event_target_window(thread_msg_target, runner_shared.clone());
raw_input::register_all_mice_and_keyboards_for_raw_input(thread_msg_target);
EventLoop {
thread_msg_sender,
window_target: RootELW {
p: EventLoopWindowTarget {
thread_id,
thread_msg_target,
runner_shared,
},
_marker: PhantomData,
},
}
}
pub fn window_target(&self) -> &RootELW<T> |
pub fn run<F>(mut self, event_handler: F) -> !
where
F: 'static + FnMut(Event<'_, T>, &RootELW<T>, &mut ControlFlow),
{
self.run_return(event_handler);
::std::process::exit(0);
}
pub fn run_return<F>(&mut self, mut event_handler: F)
where
F: FnMut(Event<'_, T>, &RootELW<T>, &mut ControlFlow),
{
let event_loop_windows_ref = &self.window_target;
unsafe {
self.window_target
.p
.runner_shared
.set_event_handler(move |event, control_flow| {
event_handler(event, event_loop_windows_ref, control_flow)
});
}
let runner = &self.window_target.p.runner_shared;
unsafe {
let mut msg = mem::zeroed();
runner.poll();
'main: loop {
if 0 == winuser::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) {
break 'main;
}
winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg);
if let Err(payload) = runner.take_panic_error() {
runner.reset_runner();
panic::resume_unwind(payload);
}
if runner.control_flow() == ControlFlow::Exit && !runner.handling_events() {
break 'main;
}
}
}
unsafe {
runner.loop_destroyed();
}
runner.reset_runner();
}
pub fn create_proxy(&self) -> EventLoopProxy<T> {
EventLoopProxy {
target_window: self.window_target.p.thread_msg_target,
event_send: self.thread_msg_sender.clone(),
}
}
}
impl<T> EventLoopWindowTarget<T> {
#[inline(always)]
pub(crate) fn create_thread_executor(&self) -> EventLoopThreadExecutor {
EventLoopThreadExecutor {
thread_id: self.thread_id,
target_window: self.thread_msg_target,
}
}
// TODO: Investigate opportunities for caching
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
monitor::available_monitors()
}
pub fn primary_monitor(&self) -> Option<RootMonitorHandle> {
let monitor = monitor::primary_monitor();
Some(RootMonitorHandle { inner: monitor })
}
}
fn main_thread_id() -> DWORD {
static mut MAIN_THREAD_ID: DWORD = 0;
#[used]
#[allow(non_upper_case_globals)]
#[link_section = ".CRT$XCU"]
static INIT_MAIN_THREAD_ID: unsafe fn() = {
unsafe fn initer() {
MAIN_THREAD_ID = processthreadsapi::GetCurrentThreadId();
}
initer
};
unsafe { MAIN_THREAD_ID }
}
fn get_wait_thread_id() -> DWORD {
unsafe {
let mut msg = mem::zeroed();
let result = winuser::GetMessageW(
&mut msg,
-1 as _,
*SEND_WAIT_THREAD_ID_MSG_ID,
*SEND_WAIT_THREAD_ID_MSG_ID,
);
assert_eq!(
msg.message, *SEND_WAIT_THREAD_ID_MSG_ID,
"this shouldn't be possible. please open an issue with Winit. error code: {}",
result
);
msg.lParam as DWORD
}
}
fn wait_thread(parent_thread_id: DWORD, msg_window_id: HWND) {
unsafe {
let mut msg: winuser::MSG;
let cur_thread_id = processthreadsapi::GetCurrentThreadId();
winuser::PostThreadMessageW(
parent_thread_id,
*SEND_WAIT_THREAD_ID_MSG_ID,
0,
cur_thread_id as LPARAM,
);
let mut wait_until_opt = None;
'main: loop {
// Zeroing out the message ensures that the `WaitUntilInstantBox` doesn't get
// double-freed if `MsgWaitForMultipleObjectsEx` returns early and there aren't
// additional messages to process.
msg = mem::zeroed();
if wait_until_opt.is_some() {
if 0 != winuser::PeekMessageW(&mut msg, ptr::null_mut(), 0, 0, winuser::PM_REMOVE) {
winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg);
}
} else {
if 0 == winuser::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) {
break 'main;
} else {
winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg);
}
}
if msg.message == *WAIT_UNTIL_MSG_ID {
wait_until_opt = Some(*WaitUntilInstantBox::from_raw(msg.lParam as *mut _));
} else if msg.message == *CANCEL_WAIT_UNTIL_MSG_ID {
wait_until_opt = None;
}
if let Some(wait_until) = wait_until_opt {
let now = Instant::now();
if now < wait_until {
// MsgWaitForMultipleObjects tends to overshoot just a little bit. We subtract
// 1 millisecond from the requested time and spinlock for the remainder to
// compensate for that.
let resume_reason = winuser::MsgWaitForMultipleObjectsEx(
0,
ptr::null(),
dur2timeout(wait_until - now).saturating_sub(1),
winuser::QS_ALLEVENTS,
winuser::MWMO_INPUTAVAILABLE,
);
if resume_reason == winerror::WAIT_TIMEOUT {
winuser::PostMessageW(msg_window_id, *PROCESS_NEW_EVENTS_MSG_ID, 0, 0);
wait_until_opt = None;
}
} else {
winuser::PostMessageW(msg_window_id, *PROCESS_NEW_EVENTS_MSG_ID, 0, 0);
wait_until_opt = None;
}
}
}
}
}
// Implementation taken from https://github.com/rust-lang/rust/blob/db5476571d9b27c862b95c1e64764b0ac8980e23/src/libstd/sys/windows/mod.rs
fn dur2timeout(dur: Duration) -> DWORD {
// Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the
// timeouts in windows APIs are typically u32 milliseconds. To translate, we
// have two pieces to take care of:
//
// * Nanosecond precision is rounded up
// * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE
// (never time out).
dur.as_secs()
.checked_mul(1000)
.and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000))
.and_then(|ms| {
ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 {
1
} else {
0
})
})
.map(|ms| {
if ms > DWORD::max_value() as u64 {
winbase::INFINITE
} else {
ms as DWORD
}
})
.unwrap_or(winbase::INFINITE)
}
impl<T> Drop for EventLoop<T> {
fn drop(&mut self) {
unsafe {
winuser::DestroyWindow(self.window_target.p.thread_msg_target);
}
}
}
pub(crate) struct EventLoopThreadExecutor {
thread_id: DWORD,
target_window: HWND,
}
unsafe impl Send for EventLoopThreadExecutor {}
unsafe impl Sync for EventLoopThreadExecutor {}
impl EventLoopThreadExecutor {
/// Check to see if we're in the parent event loop's thread.
pub(super) fn in_event_loop_thread(&self) -> bool {
let cur_thread_id = unsafe { processthreadsapi::GetCurrentThreadId() };
self.thread_id == cur_thread_id
}
/// Executes a function in the event loop thread. If we're already in the event loop thread,
/// we just call the function directly.
///
/// The `Inserted` can be used to inject a `WindowState` for the callback to use. The state is
/// removed automatically if the callback receives a `WM_CLOSE` message for the window.
///
/// Note that if you are using this to change some property of a window and updating
/// `WindowState` then you should call this within the lock of `WindowState`. Otherwise the
/// events may be sent to the other thread in different order to the one in which you set
/// `WindowState`, leaving them out of sync.
///
/// Note that we use a FnMut instead of a FnOnce because we're too lazy to create an equivalent
/// to the unstable FnBox.
pub(super) fn execute_in_thread<F>(&self, mut function: F)
where
F: FnMut() + Send + 'static,
{
unsafe {
if self.in_event_loop_thread() {
function();
} else {
// We double-box because the first box is a fat pointer.
let boxed = Box::new(function) as Box<dyn FnMut()>;
let boxed2: ThreadExecFn = Box::new(boxed);
let raw = Box::into_raw(boxed2);
let res = winuser::PostMessageW(
self.target_window,
*EXEC_MSG_ID,
raw as *mut () as usize as WPARAM,
0,
);
assert!(res != 0, "PostMessage failed ; is the messages queue full?");
}
}
}
}
type ThreadExecFn = Box<Box<dyn FnMut()>>;
pub struct EventLoopProxy<T: 'static> {
target_window: HWND,
event_send: Sender<T>,
}
unsafe impl<T: Send + 'static> Send for EventLoopProxy<T> {}
impl<T: 'static> Clone for EventLoopProxy<T> {
fn clone(&self) -> Self {
Self {
target_window: self.target_window,
event_send: self.event_send.clone(),
}
}
}
impl<T: 'static> EventLoopProxy<T> {
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
unsafe {
if winuser::PostMessageW(self.target_window, *USER_EVENT_MSG_ID, 0, 0) != 0 {
self.event_send.send(event).ok();
Ok(())
} else {
Err(EventLoopClosed(event))
}
}
}
}
type WaitUntilInstantBox = Box<Instant>;
lazy_static! {
// Message sent by the `EventLoopProxy` when we want to wake up the thread.
// WPARAM and LPARAM are unused.
static ref USER_EVENT_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::WakeupMsg\0".as_ptr() as LPCSTR)
}
};
// Message sent when we want to execute a closure in the thread.
// WPARAM contains a Box<Box<dyn FnMut()>> that must be retrieved with `Box::from_raw`,
// and LPARAM is unused.
static ref EXEC_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::ExecMsg\0".as_ptr() as *const i8)
}
};
static ref PROCESS_NEW_EVENTS_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::ProcessNewEvents\0".as_ptr() as *const i8)
}
};
/// lparam is the wait thread's message id.
static ref SEND_WAIT_THREAD_ID_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::SendWaitThreadId\0".as_ptr() as *const i8)
}
};
/// lparam points to a `Box<Instant>` signifying the time `PROCESS_NEW_EVENTS_MSG_ID` should
/// be sent.
static ref WAIT_UNTIL_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::WaitUntil\0".as_ptr() as *const i8)
}
};
static ref CANCEL_WAIT_UNTIL_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::CancelWaitUntil\0".as_ptr() as *const i8)
}
};
// Message sent by a `Window` when it wants to be destroyed by the main thread.
// WPARAM and LPARAM are unused.
pub static ref DESTROY_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::DestroyMsg\0".as_ptr() as LPCSTR)
}
};
// WPARAM is a bool specifying the `WindowFlags::MARKER_RETAIN_STATE_ON_SIZE` flag. See the
// documentation in the `window_state` module for more information.
pub static ref SET_RETAIN_STATE_ON_SIZE_MSG_ID: u32 = unsafe {
winuser::RegisterWindowMessageA("Winit::SetRetainMaximized\0".as_ptr() as LPCSTR)
};
static ref THREAD_EVENT_TARGET_WINDOW_CLASS: Vec<u16> = unsafe {
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
let class_name: Vec<_> = OsStr::new("Winit Thread Event Target")
.encode_wide()
.chain(Some(0).into_iter())
.collect();
let class = winuser::WNDCLASSEXW {
cbSize: mem::size_of::<winuser::WNDCLASSEXW>() as UINT,
style: 0,
lpfnWndProc: Some(winuser::DefWindowProcW),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: libloaderapi::GetModuleHandleW(ptr::null()),
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: ptr::null_mut(),
};
winuser::RegisterClassExW(&class);
class_name
};
}
fn create_event_target_window() -> HWND {
unsafe {
let window = winuser::CreateWindowExW(
winuser::WS_EX_NOACTIVATE | winuser::WS_EX_TRANSPARENT | winuser::WS_EX_LAYERED,
THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(),
ptr::null_mut(),
0,
0,
0,
0,
0,
ptr::null_mut(),
ptr::null_mut(),
libloaderapi::GetModuleHandleW(ptr::null()),
ptr::null_mut(),
);
winuser::SetWindowLongPtrW(
window,
winuser::GWL_STYLE,
// The window technically has to be visible to receive WM_PAINT messages (which are used
// for delivering events during resizes), but it isn't displayed to the user because of
// the LAYERED style.
(winuser::WS_VISIBLE | winuser::WS_POPUP) as _,
);
window
}
}
fn subclass_event_target_window<T>(
window: HWND,
event_loop_runner: EventLoopRunnerShared<T>,
) -> Sender<T> {
unsafe {
let (tx, rx) = mpsc::channel();
let subclass_input = ThreadMsgTargetSubclassInput {
event_loop_runner,
user_event_receiver: rx,
};
let input_ptr = Box::into_raw(Box::new(subclass_input));
let subclass_result = commctrl::SetWindowSubclass(
window,
Some(thread_event_target_callback::<T>),
THREAD_EVENT_TARGET_SUBCLASS_ID,
input_ptr as DWORD_PTR,
);
assert_eq!(subclass_result, 1);
tx
}
}
fn remove_event_target_window_subclass<T: 'static>(window: HWND) {
let removal_result = unsafe {
commctrl::RemoveWindowSubclass(
window,
Some(thread_event_target_callback::<T>),
THREAD_EVENT_TARGET_SUBCLASS_ID,
)
};
assert_eq!(removal_result, 1);
}
/// Capture mouse input, allowing `window` to receive mouse events when the cursor is outside of
/// the window.
unsafe fn capture_mouse(window: HWND, window_state: &mut WindowState) {
window_state.mouse.capture_count += 1;
winuser::SetCapture(window);
}
/// Release mouse input, stopping windows on this thread from receiving mouse input when the cursor
/// is outside the window.
unsafe fn release_mouse(mut window_state: parking_lot::MutexGuard<'_, WindowState>) {
window_state.mouse.capture_count = window_state.mouse.capture_count.saturating_sub(1);
if window_state.mouse.capture_count == 0 {
// ReleaseCapture() causes a WM_CAPTURECHANGED where we lock the window_state.
drop(window_state);
winuser::ReleaseCapture();
}
}
const WINDOW_SUBCLASS_ID: UINT_PTR = 0;
const THREAD_EVENT_TARGET_SUBCLASS_ID: UINT_PTR = 1;
pub(crate) fn subclass_window<T>(window: HWND, subclass_input: SubclassInput<T>) {
subclass_input.event_loop_runner.register_window(window);
let input_ptr = Box::into_raw(Box::new(subclass_input));
let subclass_result = unsafe {
commctrl::SetWindowSubclass(
window,
Some(public_window_callback::<T>),
WINDOW_SUBCLASS_ID,
input_ptr as DWORD_PTR,
)
};
assert_eq!(subclass_result, 1);
}
fn remove_window_subclass<T: 'static>(window: HWND) {
let removal_result = unsafe {
commctrl::RemoveWindowSubclass(
window,
Some(public_window_callback::<T>),
WINDOW_SUBCLASS_ID,
)
};
assert_eq!(removal_result, 1);
}
fn normalize_pointer_pressure(pressure: u32) -> Option<Force> {
match pressure {
1..=1024 => Some(Force::Normalized(pressure as f64 / 1024.0)),
_ => None,
}
}
/// Flush redraw events for Winit's windows.
///
/// Winit's API guarantees that all redraw events will be clustered together and dispatched all at
/// once, but the standard Windows message loop doesn't always exhibit that behavior. If multiple
/// windows have had redraws scheduled, but an input event is pushed to the message queue between
/// the `WM_PAINT` call for the first window and the `WM_PAINT` call for the second window, Windows
/// will dispatch the input event immediately instead of flushing all the redraw events. This
/// function explicitly pulls all of Winit's redraw events out of the event queue so that they
/// always all get processed in one fell swoop.
///
/// Returns `true` if this invocation flushed all the redraw events. If this function is re-entrant,
/// it won't flush the redraw events and will return `false`.
#[must_use]
unsafe fn flush_paint_messages<T: 'static>(
except: Option<HWND>,
runner: &EventLoopRunner<T>,
) -> bool {
if !runner.redrawing() {
runner.main_events_cleared();
let mut msg = mem::zeroed();
runner.owned_windows(|redraw_window| {
if Some(redraw_window) == except {
return;
}
if 0 == winuser::PeekMessageW(
&mut msg,
redraw_window,
winuser::WM_PAINT,
winuser::WM_PAINT,
winuser::PM_REMOVE | winuser::PM_QS_PAINT,
) {
return;
}
winuser::TranslateMessage(&mut msg);
winuser::DispatchMessageW(&mut msg);
});
true
} else {
false
}
}
unsafe fn process_control_flow<T: 'static>(runner: &EventLoopRunner<T>) {
match runner.control_flow() {
ControlFlow::Poll => {
winuser::PostMessageW(runner.thread_msg_target(), *PROCESS_NEW_EVENTS_MSG_ID, 0, 0);
}
ControlFlow::Wait => (),
ControlFlow::WaitUntil(until) => {
winuser::PostThreadMessageW(
runner.wait_thread_id(),
*WAIT_UNTIL_MSG_ID,
0,
Box::into_raw(WaitUntilInstantBox::new(until)) as LPARAM,
);
}
ControlFlow::Exit => (),
}
}
/// Emit a `ModifiersChanged` event whenever modifiers have changed.
fn update_modifiers<T>(window: HWND, subclass_input: &SubclassInput<T>) {
use crate::event::WindowEvent::ModifiersChanged;
let modifiers = event::get_key_mods();
let mut window_state = subclass_input.window_state.lock();
if window_state.modifiers_state != modifiers {
window_state.modifiers_state = modifiers;
// Drop lock
drop(window_state);
unsafe {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ModifiersChanged(modifiers),
});
}
}
}
/// Any window whose callback is configured to this function will have its events propagated
/// through the events loop of the thread the window was created in.
//
// This is the callback that is called by `DispatchMessage` in the events loop.
//
// Returning 0 tells the Win32 API that the message has been processed.
// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary
unsafe extern "system" fn public_window_callback<T: 'static>(
window: HWND,
msg: UINT,
wparam: WPARAM,
lparam: LPARAM,
uidsubclass: UINT_PTR,
subclass_input_ptr: DWORD_PTR,
) -> LRESULT {
let subclass_input_ptr = subclass_input_ptr as *mut SubclassInput<T>;
let (result, subclass_removed, recurse_depth) = {
let subclass_input = &*subclass_input_ptr;
subclass_input
.recurse_depth
.set(subclass_input.recurse_depth.get() + 1);
let result =
public_window_callback_inner(window, msg, wparam, lparam, uidsubclass, subclass_input);
let subclass_removed = subclass_input.subclass_removed.get();
let recurse_depth = subclass_input.recurse_depth.get() - 1;
subclass_input.recurse_depth.set(recurse_depth);
(result, subclass_removed, recurse_depth)
};
if subclass_removed && recurse_depth == 0 {
Box::from_raw(subclass_input_ptr);
}
result
}
unsafe fn public_window_callback_inner<T: 'static>(
window: HWND,
msg: UINT,
wparam: WPARAM,
lparam: LPARAM,
_: UINT_PTR,
subclass_input: &SubclassInput<T>,
) -> LRESULT {
winuser::RedrawWindow(
subclass_input.event_loop_runner.thread_msg_target(),
ptr::null(),
ptr::null_mut(),
winuser::RDW_INTERNALPAINT,
);
// I decided to bind the closure to `callback` and pass it to catch_unwind rather than passing
// the closure to catch_unwind directly so that the match body indendation wouldn't change and
// the git blame and history would be preserved.
let callback = || match msg {
winuser::WM_ENTERSIZEMOVE => {
subclass_input
.window_state
.lock()
.set_window_flags_in_place(|f| f.insert(WindowFlags::MARKER_IN_SIZE_MOVE));
0
}
winuser::WM_EXITSIZEMOVE => {
subclass_input
.window_state
.lock()
.set_window_flags_in_place(|f| f.remove(WindowFlags::MARKER_IN_SIZE_MOVE));
0
}
winuser::WM_NCCREATE => {
enable_non_client_dpi_scaling(window);
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_NCLBUTTONDOWN => {
if wparam == winuser::HTCAPTION as _ {
winuser::PostMessageW(window, winuser::WM_MOUSEMOVE, 0, lparam);
}
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_CLOSE => {
use crate::event::WindowEvent::CloseRequested;
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: CloseRequested,
});
0
}
winuser::WM_DESTROY => {
use crate::event::WindowEvent::Destroyed;
ole2::RevokeDragDrop(window);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: Destroyed,
});
subclass_input.event_loop_runner.remove_window(window);
0
}
winuser::WM_NCDESTROY => {
remove_window_subclass::<T>(window);
subclass_input.subclass_removed.set(true);
0
}
winuser::WM_PAINT => {
if subclass_input.event_loop_runner.should_buffer() {
// this branch can happen in response to `UpdateWindow`, if win32 decides to
// redraw the window outside the normal flow of the event loop.
winuser::RedrawWindow(
window,
ptr::null(),
ptr::null_mut(),
winuser::RDW_INTERNALPAINT,
);
} else {
let managing_redraw =
flush_paint_messages(Some(window), &subclass_input.event_loop_runner);
subclass_input.send_event(Event::RedrawRequested(RootWindowId(WindowId(window))));
if managing_redraw {
subclass_input.event_loop_runner.redraw_events_cleared();
process_control_flow(&subclass_input.event_loop_runner);
}
}
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_WINDOWPOSCHANGING => {
let mut window_state = subclass_input.window_state.lock();
if let Some(ref mut fullscreen) = window_state.fullscreen {
let window_pos = &mut *(lparam as *mut winuser::WINDOWPOS);
let new_rect = RECT {
left: window_pos.x,
top: window_pos.y,
right: window_pos.x + window_pos.cx,
bottom: window_pos.y + window_pos.cy,
};
let new_monitor =
winuser::MonitorFromRect(&new_rect, winuser::MONITOR_DEFAULTTONULL);
match fullscreen {
Fullscreen::Borderless(ref mut fullscreen_monitor) => {
if new_monitor != ptr::null_mut()
&& fullscreen_monitor
.as_ref()
.map(|monitor| new_monitor != monitor.inner.hmonitor())
.unwrap_or(true)
{
if let Ok(new_monitor_info) = monitor::get_monitor_info(new_monitor) {
let new_monitor_rect = new_monitor_info.rcMonitor;
window_pos.x = new_monitor_rect.left;
window_pos.y = new_monitor_rect.top;
window_pos.cx = new_monitor_rect.right - new_monitor_rect.left;
window_pos.cy = new_monitor_rect.bottom - new_monitor_rect.top;
}
*fullscreen_monitor = Some(crate::monitor::MonitorHandle {
inner: MonitorHandle::new(new_monitor),
});
}
}
Fullscreen::Exclusive(ref video_mode) => {
let old_monitor = video_mode.video_mode.monitor.hmonitor();
if let Ok(old_monitor_info) = monitor::get_monitor_info(old_monitor) {
let old_monitor_rect = old_monitor_info.rcMonitor;
window_pos.x = old_monitor_rect.left;
window_pos.y = old_monitor_rect.top;
window_pos.cx = old_monitor_rect.right - old_monitor_rect.left;
window_pos.cy = old_monitor_rect.bottom - old_monitor_rect.top;
}
}
}
}
0
}
// WM_MOVE supplies client area positions, so we send Moved here instead.
winuser::WM_WINDOWPOSCHANGED => {
use crate::event::WindowEvent::Moved;
let windowpos = lparam as *const winuser::WINDOWPOS;
if (*windowpos).flags & winuser::SWP_NOMOVE != winuser::SWP_NOMOVE {
let physical_position =
PhysicalPosition::new((*windowpos).x as i32, (*windowpos).y as i32);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: Moved(physical_position),
});
}
// This is necessary for us to still get sent WM_SIZE.
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_SIZE => {
use crate::event::WindowEvent::Resized;
let w = LOWORD(lparam as DWORD) as u32;
let h = HIWORD(lparam as DWORD) as u32;
let physical_size = PhysicalSize::new(w, h);
let event = Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: Resized(physical_size),
};
{
let mut w = subclass_input.window_state.lock();
// See WindowFlags::MARKER_RETAIN_STATE_ON_SIZE docs for info on why this `if` check exists.
if !w
.window_flags()
.contains(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE)
{
let maximized = wparam == winuser::SIZE_MAXIMIZED;
w.set_window_flags_in_place(|f| f.set(WindowFlags::MAXIMIZED, maximized));
}
}
subclass_input.send_event(event);
0
}
winuser::WM_CHAR | winuser::WM_SYSCHAR => {
use crate::event::WindowEvent::ReceivedCharacter;
use std::char;
let is_high_surrogate = 0xD800 <= wparam && wparam <= 0xDBFF;
let is_low_surrogate = 0xDC00 <= wparam && wparam <= 0xDFFF;
if is_high_surrogate {
subclass_input.window_state.lock().high_surrogate = Some(wparam as u16);
} else if is_low_surrogate {
let high_surrogate = subclass_input.window_state.lock().high_surrogate.take();
if let Some(high_surrogate) = high_surrogate {
let pair = [high_surrogate, wparam as u16];
if let Some(Ok(chr)) = char::decode_utf16(pair.iter().copied()).next() {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ReceivedCharacter(chr),
});
}
}
} else {
subclass_input.window_state.lock().high_surrogate = None;
if let Some(chr) = char::from_u32(wparam as u32) {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ReceivedCharacter(chr),
});
}
}
0
}
// this is necessary for us to maintain minimize/restore state
winuser::WM_SYSCOMMAND => {
if wparam == winuser::SC_RESTORE {
let mut w = subclass_input.window_state.lock();
w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, false));
}
if wparam == winuser::SC_MINIMIZE {
let mut w = subclass_input.window_state.lock();
w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, true));
}
// Send `WindowEvent::Minimized` here if we decide to implement one
if wparam == winuser::SC_SCREENSAVE {
let window_state = subclass_input.window_state.lock();
if window_state.fullscreen.is_some() {
return 0;
}
}
winuser::DefWindowProcW(window, msg, wparam, lparam)
}
winuser::WM_MOUSEMOVE => {
use crate::event::WindowEvent::{CursorEntered, CursorMoved};
let mouse_was_outside_window = {
let mut w = subclass_input.window_state.lock();
let was_outside_window = !w.mouse.cursor_flags().contains(CursorFlags::IN_WINDOW);
w.mouse
.set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, true))
.ok();
was_outside_window
};
if mouse_was_outside_window {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: CursorEntered {
device_id: DEVICE_ID,
},
});
// Calling TrackMouseEvent in order to receive mouse leave events.
winuser::TrackMouseEvent(&mut winuser::TRACKMOUSEEVENT {
cbSize: mem::size_of::<winuser::TRACKMOUSEEVENT>() as DWORD,
dwFlags: winuser::TME_LEAVE,
hwndTrack: window,
dwHoverTime: winuser::HOVER_DEFAULT,
});
}
let x = windowsx::GET_X_LPARAM(lparam) as f64;
let y = windowsx::GET_Y_LPARAM(lparam) as f64;
let position = PhysicalPosition::new(x, y);
let cursor_moved;
{
// handle spurious WM_MOUSEMOVE messages
// see https://devblogs.microsoft.com/oldnewthing/20031001-00/?p=42343
// and http://debugandconquer.blogspot.com/2015/08/the-cause-of-spurious-mouse-move.html
let mut w = subclass_input.window_state.lock();
cursor_moved = w.mouse.last_position != Some(position);
w.mouse.last_position = Some(position);
}
if cursor_moved {
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: CursorMoved {
device_id: DEVICE_ID,
position,
modifiers: event::get_key_mods(),
},
});
}
0
}
winuser::WM_MOUSELEAVE => {
use crate::event::WindowEvent::CursorLeft;
{
let mut w = subclass_input.window_state.lock();
w.mouse
.set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false))
.ok();
}
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: CursorLeft {
device_id: DEVICE_ID,
},
});
0
}
winuser::WM_MOUSEWHEEL => {
use crate::event::MouseScrollDelta::LineDelta;
let value = (wparam >> 16) as i16;
let value = value as i32;
let value = value as f32 / winuser::WHEEL_DELTA as f32;
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::MouseWheel {
device_id: DEVICE_ID,
delta: LineDelta(0.0, value),
phase: TouchPhase::Moved,
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_MOUSEHWHEEL => {
use crate::event::MouseScrollDelta::LineDelta;
let value = (wparam >> 16) as i16;
let value = value as i32;
let value = value as f32 / winuser::WHEEL_DELTA as f32;
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::MouseWheel {
device_id: DEVICE_ID,
delta: LineDelta(value, 0.0),
phase: TouchPhase::Moved,
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_KEYDOWN | winuser::WM_SYSKEYDOWN => {
use crate::event::{ElementState::Pressed, VirtualKeyCode};
if msg == winuser::WM_SYSKEYDOWN && wparam as i32 == winuser::VK_F4 {
commctrl::DefSubclassProc(window, msg, wparam, lparam)
} else {
if let Some((scancode, vkey)) = process_key_params(wparam, lparam) {
update_modifiers(window, subclass_input);
#[allow(deprecated)]
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::KeyboardInput {
device_id: DEVICE_ID,
input: KeyboardInput {
state: Pressed,
scancode,
virtual_keycode: vkey,
modifiers: event::get_key_mods(),
},
is_synthetic: false,
},
});
// Windows doesn't emit a delete character by default, but in order to make it
// consistent with the other platforms we'll emit a delete character here.
if vkey == Some(VirtualKeyCode::Delete) {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::ReceivedCharacter('\u{7F}'),
});
}
}
0
}
}
winuser::WM_KEYUP | winuser::WM_SYSKEYUP => {
use crate::event::ElementState::Released;
if let Some((scancode, vkey)) = process_key_params(wparam, lparam) {
update_modifiers(window, subclass_input);
#[allow(deprecated)]
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::KeyboardInput {
device_id: DEVICE_ID,
input: KeyboardInput {
state: Released,
scancode,
virtual_keycode: vkey,
modifiers: event::get_key_mods(),
},
is_synthetic: false,
},
});
}
0
}
winuser::WM_LBUTTONDOWN => {
use crate::event::{ElementState::Pressed, MouseButton::Left, WindowEvent::MouseInput};
capture_mouse(window, &mut *subclass_input.window_state.lock());
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: MouseInput {
device_id: DEVICE_ID,
state: Pressed,
button: Left,
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_LBUTTONUP => {
use crate::event::{
ElementState::Released, MouseButton::Left, WindowEvent::MouseInput,
};
release_mouse(subclass_input.window_state.lock());
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: MouseInput {
device_id: DEVICE_ID,
state: Released,
button: Left,
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_RBUTTONDOWN => {
use crate::event::{
ElementState::Pressed, MouseButton::Right, WindowEvent::MouseInput,
};
capture_mouse(window, &mut *subclass_input.window_state.lock());
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: MouseInput {
device_id: DEVICE_ID,
state: Pressed,
button: Right,
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_RBUTTONUP => {
use crate::event::{
ElementState::Released, MouseButton::Right, WindowEvent::MouseInput,
};
release_mouse(subclass_input.window_state.lock());
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: MouseInput {
device_id: DEVICE_ID,
state: Released,
button: Right,
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_MBUTTONDOWN => {
use crate::event::{
ElementState::Pressed, MouseButton::Middle, WindowEvent::MouseInput,
};
capture_mouse(window, &mut *subclass_input.window_state.lock());
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: MouseInput {
device_id: DEVICE_ID,
state: Pressed,
button: Middle,
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_MBUTTONUP => {
use crate::event::{
ElementState::Released, MouseButton::Middle, WindowEvent::MouseInput,
};
release_mouse(subclass_input.window_state.lock());
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: MouseInput {
device_id: DEVICE_ID,
state: Released,
button: Middle,
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_XBUTTONDOWN => {
use crate::event::{
ElementState::Pressed, MouseButton::Other, WindowEvent::MouseInput,
};
let xbutton = winuser::GET_XBUTTON_WPARAM(wparam);
capture_mouse(window, &mut *subclass_input.window_state.lock());
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: MouseInput {
device_id: DEVICE_ID,
state: Pressed,
button: Other(xbutton),
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_XBUTTONUP => {
use crate::event::{
ElementState::Released, MouseButton::Other, WindowEvent::MouseInput,
};
let xbutton = winuser::GET_XBUTTON_WPARAM(wparam);
release_mouse(subclass_input.window_state.lock());
update_modifiers(window, subclass_input);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: MouseInput {
device_id: DEVICE_ID,
state: Released,
button: Other(xbutton),
modifiers: event::get_key_mods(),
},
});
0
}
winuser::WM_CAPTURECHANGED => {
// lparam here is a handle to the window which is gaining mouse capture.
// If it is the same as our window, then we're essentially retaining the capture. This
// can happen if `SetCapture` is called on our window when it already has the mouse
// capture.
if lparam != window as isize {
subclass_input.window_state.lock().mouse.capture_count = 0;
}
0
}
winuser::WM_TOUCH => {
let pcount = LOWORD(wparam as DWORD) as usize;
let mut inputs = Vec::with_capacity(pcount);
inputs.set_len(pcount);
let htouch = lparam as winuser::HTOUCHINPUT;
if winuser::GetTouchInputInfo(
htouch,
pcount as UINT,
inputs.as_mut_ptr(),
mem::size_of::<winuser::TOUCHINPUT>() as INT,
) > 0
{
for input in &inputs {
let mut location = POINT {
x: input.x / 100,
y: input.y / 100,
};
if winuser::ScreenToClient(window, &mut location as *mut _) == 0 {
continue;
}
let x = location.x as f64 + (input.x % 100) as f64 / 100f64;
let y = location.y as f64 + (input.y % 100) as f64 / 100f64;
let location = PhysicalPosition::new(x, y);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::Touch(Touch {
phase: if input.dwFlags & winuser::TOUCHEVENTF_DOWN != 0 {
TouchPhase::Started
} else if input.dwFlags & winuser::TOUCHEVENTF_UP != 0 {
TouchPhase::Ended
} else if input.dwFlags & winuser::TOUCHEVENTF_MOVE != 0 {
TouchPhase::Moved
} else {
continue;
},
location,
force: None, // WM_TOUCH doesn't support pressure information
id: input.dwID as u64,
device_id: DEVICE_ID,
}),
});
}
}
winuser::CloseTouchInputHandle(htouch);
0
}
winuser::WM_POINTERDOWN | winuser::WM_POINTERUPDATE | winuser::WM_POINTERUP => {
if let (
Some(GetPointerFrameInfoHistory),
Some(SkipPointerFrameMessages),
Some(GetPointerDeviceRects),
) = (
*GET_POINTER_FRAME_INFO_HISTORY,
*SKIP_POINTER_FRAME_MESSAGES,
*GET_POINTER_DEVICE_RECTS,
) {
let pointer_id = LOWORD(wparam as DWORD) as UINT;
let mut entries_count = 0 as UINT;
let mut pointers_count = 0 as UINT;
if GetPointerFrameInfoHistory(
pointer_id,
&mut entries_count as *mut _,
&mut pointers_count as *mut _,
std::ptr::null_mut(),
) == 0
{
return 0;
}
let pointer_info_count = (entries_count * pointers_count) as usize;
let mut pointer_infos = Vec::with_capacity(pointer_info_count);
pointer_infos.set_len(pointer_info_count);
if GetPointerFrameInfoHistory(
pointer_id,
&mut entries_count as *mut _,
&mut pointers_count as *mut _,
pointer_infos.as_mut_ptr(),
) == 0
{
return 0;
}
// https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getpointerframeinfohistory
// The information retrieved appears in reverse chronological order, with the most recent entry in the first
// row of the returned array
for pointer_info in pointer_infos.iter().rev() {
let mut device_rect = mem::MaybeUninit::uninit();
let mut display_rect = mem::MaybeUninit::uninit();
if (GetPointerDeviceRects(
pointer_info.sourceDevice,
device_rect.as_mut_ptr(),
display_rect.as_mut_ptr(),
)) == 0
{
continue;
}
let device_rect = device_rect.assume_init();
let display_rect = display_rect.assume_init();
// For the most precise himetric to pixel conversion we calculate the ratio between the resolution
// of the display device (pixel) and the touch device (himetric).
let himetric_to_pixel_ratio_x = (display_rect.right - display_rect.left) as f64
/ (device_rect.right - device_rect.left) as f64;
let himetric_to_pixel_ratio_y = (display_rect.bottom - display_rect.top) as f64
/ (device_rect.bottom - device_rect.top) as f64;
// ptHimetricLocation's origin is 0,0 even on multi-monitor setups.
// On multi-monitor setups we need to translate the himetric location to the rect of the
// display device it's attached to.
let x = display_rect.left as f64
+ pointer_info.ptHimetricLocation.x as f64 * himetric_to_pixel_ratio_x;
let y = display_rect.top as f64
+ pointer_info.ptHimetricLocation.y as f64 * himetric_to_pixel_ratio_y;
let mut location = POINT {
x: x.floor() as i32,
y: y.floor() as i32,
};
if winuser::ScreenToClient(window, &mut location as *mut _) == 0 {
continue;
}
let force = match pointer_info.pointerType {
winuser::PT_TOUCH => {
let mut touch_info = mem::MaybeUninit::uninit();
GET_POINTER_TOUCH_INFO.and_then(|GetPointerTouchInfo| {
match GetPointerTouchInfo(
pointer_info.pointerId,
touch_info.as_mut_ptr(),
) {
0 => None,
_ => normalize_pointer_pressure(
touch_info.assume_init().pressure,
),
}
})
}
winuser::PT_PEN => {
let mut pen_info = mem::MaybeUninit::uninit();
GET_POINTER_PEN_INFO.and_then(|GetPointerPenInfo| {
match GetPointerPenInfo(
pointer_info.pointerId,
pen_info.as_mut_ptr(),
) {
0 => None,
_ => {
normalize_pointer_pressure(pen_info.assume_init().pressure)
}
}
})
}
_ => None,
};
let x = location.x as f64 + x.fract();
let y = location.y as f64 + y.fract();
let location = PhysicalPosition::new(x, y);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::Touch(Touch {
phase: if pointer_info.pointerFlags & winuser::POINTER_FLAG_DOWN != 0 {
TouchPhase::Started
} else if pointer_info.pointerFlags & winuser::POINTER_FLAG_UP != 0 {
TouchPhase::Ended
} else if pointer_info.pointerFlags & winuser::POINTER_FLAG_UPDATE != 0
{
TouchPhase::Moved
} else {
continue;
},
location,
force,
id: pointer_info.pointerId as u64,
device_id: DEVICE_ID,
}),
});
}
SkipPointerFrameMessages(pointer_id);
}
0
}
winuser::WM_SETFOCUS => {
use crate::event::{ElementState::Released, WindowEvent::Focused};
for windows_keycode in event::get_pressed_keys() {
let scancode =
winuser::MapVirtualKeyA(windows_keycode as _, winuser::MAPVK_VK_TO_VSC);
let virtual_keycode = event::vkey_to_winit_vkey(windows_keycode);
update_modifiers(window, subclass_input);
#[allow(deprecated)]
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::KeyboardInput {
device_id: DEVICE_ID,
input: KeyboardInput {
scancode,
virtual_keycode,
state: Released,
modifiers: event::get_key_mods(),
},
is_synthetic: true,
},
})
}
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: Focused(true),
});
0
}
winuser::WM_KILLFOCUS => {
use crate::event::{
ElementState::Released,
ModifiersState,
WindowEvent::{Focused, ModifiersChanged},
};
for windows_keycode in event::get_pressed_keys() {
let scancode =
winuser::MapVirtualKeyA(windows_keycode as _, winuser::MAPVK_VK_TO_VSC);
let virtual_keycode = event::vkey_to_winit_vkey(windows_keycode);
#[allow(deprecated)]
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: WindowEvent::KeyboardInput {
device_id: DEVICE_ID,
input: KeyboardInput {
scancode,
virtual_keycode,
state: Released,
modifiers: event::get_key_mods(),
},
is_synthetic: true,
},
})
}
subclass_input.window_state.lock().modifiers_state = ModifiersState::empty();
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ModifiersChanged(ModifiersState::empty()),
});
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: Focused(false),
});
0
}
winuser::WM_SETCURSOR => {
let set_cursor_to = {
let window_state = subclass_input.window_state.lock();
// The return value for the preceding `WM_NCHITTEST` message is conveniently
// provided through the low-order word of lParam. We use that here since
// `WM_MOUSEMOVE` seems to come after `WM_SETCURSOR` for a given cursor movement.
let in_client_area = LOWORD(lparam as DWORD) == winuser::HTCLIENT as WORD;
if in_client_area {
Some(window_state.mouse.cursor)
} else {
None
}
};
match set_cursor_to {
Some(cursor) => {
let cursor = winuser::LoadCursorW(ptr::null_mut(), cursor.to_windows_cursor());
winuser::SetCursor(cursor);
0
}
None => winuser::DefWindowProcW(window, msg, wparam, lparam),
}
}
winuser::WM_DROPFILES => {
// See `FileDropHandler` for implementation.
0
}
winuser::WM_GETMINMAXINFO => {
let mmi = lparam as *mut winuser::MINMAXINFO;
let window_state = subclass_input.window_state.lock();
if window_state.min_size.is_some() || window_state.max_size.is_some() {
if let Some(min_size) = window_state.min_size {
let min_size = min_size.to_physical(window_state.scale_factor);
let (width, height): (u32, u32) = util::adjust_size(window, min_size).into();
(*mmi).ptMinTrackSize = POINT {
x: width as i32,
y: height as i32,
};
}
if let Some(max_size) = window_state.max_size {
let max_size = max_size.to_physical(window_state.scale_factor);
let (width, height): (u32, u32) = util::adjust_size(window, max_size).into();
(*mmi).ptMaxTrackSize = POINT {
x: width as i32,
y: height as i32,
};
}
}
0
}
// Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change
// DPI, therefore all applications are closed while DPI is changing.
winuser::WM_DPICHANGED => {
use crate::event::WindowEvent::ScaleFactorChanged;
// This message actually provides two DPI values - x and y. However MSDN says that
// "you only need to use either the X-axis or the Y-axis value when scaling your
// application since they are the same".
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn312083(v=vs.85).aspx
let new_dpi_x = u32::from(LOWORD(wparam as DWORD));
let new_scale_factor = dpi_to_scale_factor(new_dpi_x);
let old_scale_factor: f64;
let allow_resize = {
let mut window_state = subclass_input.window_state.lock();
old_scale_factor = window_state.scale_factor;
window_state.scale_factor = new_scale_factor;
if new_scale_factor == old_scale_factor {
return 0;
}
window_state.fullscreen.is_none()
&& !window_state.window_flags().contains(WindowFlags::MAXIMIZED)
};
let style = winuser::GetWindowLongW(window, winuser::GWL_STYLE) as _;
let style_ex = winuser::GetWindowLongW(window, winuser::GWL_EXSTYLE) as _;
// New size as suggested by Windows.
let suggested_rect = *(lparam as *const RECT);
// The window rect provided is the window's outer size, not it's inner size. However,
// win32 doesn't provide an `UnadjustWindowRectEx` function to get the client rect from
// the outer rect, so we instead adjust the window rect to get the decoration margins
// and remove them from the outer size.
let margin_left: i32;
let margin_top: i32;
// let margin_right: i32;
// let margin_bottom: i32;
{
let adjusted_rect =
util::adjust_window_rect_with_styles(window, style, style_ex, suggested_rect)
.unwrap_or(suggested_rect);
margin_left = suggested_rect.left - adjusted_rect.left;
margin_top = suggested_rect.top - adjusted_rect.top;
// margin_right = adjusted_rect.right - suggested_rect.right;
// margin_bottom = adjusted_rect.bottom - suggested_rect.bottom;
}
let old_physical_inner_rect = {
let mut old_physical_inner_rect = mem::zeroed();
winuser::GetClientRect(window, &mut old_physical_inner_rect);
let mut origin = mem::zeroed();
winuser::ClientToScreen(window, &mut origin);
old_physical_inner_rect.left += origin.x;
old_physical_inner_rect.right += origin.x;
old_physical_inner_rect.top += origin.y;
old_physical_inner_rect.bottom += origin.y;
old_physical_inner_rect
};
let old_physical_inner_size = PhysicalSize::new(
(old_physical_inner_rect.right - old_physical_inner_rect.left) as u32,
(old_physical_inner_rect.bottom - old_physical_inner_rect.top) as u32,
);
// `allow_resize` prevents us from re-applying DPI adjustment to the restored size after
// exiting fullscreen (the restored size is already DPI adjusted).
let mut new_physical_inner_size = match allow_resize {
// We calculate our own size because the default suggested rect doesn't do a great job
// of preserving the window's logical size.
true => old_physical_inner_size
.to_logical::<f64>(old_scale_factor)
.to_physical::<u32>(new_scale_factor),
false => old_physical_inner_size,
};
let _ = subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ScaleFactorChanged {
scale_factor: new_scale_factor,
new_inner_size: &mut new_physical_inner_size,
},
});
let dragging_window: bool;
{
let window_state = subclass_input.window_state.lock();
dragging_window = window_state
.window_flags()
.contains(WindowFlags::MARKER_IN_SIZE_MOVE);
// Unset maximized if we're changing the window's size.
if new_physical_inner_size != old_physical_inner_size {
WindowState::set_window_flags(window_state, window, |f| {
f.set(WindowFlags::MAXIMIZED, false)
});
}
}
let new_outer_rect: RECT;
{
let suggested_ul = (
suggested_rect.left + margin_left,
suggested_rect.top + margin_top,
);
let mut conservative_rect = RECT {
left: suggested_ul.0,
top: suggested_ul.1,
right: suggested_ul.0 + new_physical_inner_size.width as LONG,
bottom: suggested_ul.1 + new_physical_inner_size.height as LONG,
};
conservative_rect = util::adjust_window_rect_with_styles(
window,
style,
style_ex,
conservative_rect,
)
.unwrap_or(conservative_rect);
// If we're dragging the window, offset the window so that the cursor's
// relative horizontal position in the title bar is preserved.
if dragging_window {
let bias = {
let cursor_pos = {
let mut pos = mem::zeroed();
winuser::GetCursorPos(&mut pos);
pos
};
let suggested_cursor_horizontal_ratio = (cursor_pos.x - suggested_rect.left)
as f64
/ (suggested_rect.right - suggested_rect.left) as f64;
(cursor_pos.x
- (suggested_cursor_horizontal_ratio
* (conservative_rect.right - conservative_rect.left) as f64)
as LONG)
- conservative_rect.left
};
conservative_rect.left += bias;
conservative_rect.right += bias;
}
// Check to see if the new window rect is on the monitor with the new DPI factor.
// If it isn't, offset the window so that it is.
let new_dpi_monitor = winuser::MonitorFromWindow(window, 0);
let conservative_rect_monitor = winuser::MonitorFromRect(&conservative_rect, 0);
new_outer_rect = if conservative_rect_monitor == new_dpi_monitor {
conservative_rect
} else {
let get_monitor_rect = |monitor| {
let mut monitor_info = winuser::MONITORINFO {
cbSize: mem::size_of::<winuser::MONITORINFO>() as _,
..mem::zeroed()
};
winuser::GetMonitorInfoW(monitor, &mut monitor_info);
monitor_info.rcMonitor
};
let wrong_monitor = conservative_rect_monitor;
let wrong_monitor_rect = get_monitor_rect(wrong_monitor);
let new_monitor_rect = get_monitor_rect(new_dpi_monitor);
// The direction to nudge the window in to get the window onto the monitor with
// the new DPI factor. We calculate this by seeing which monitor edges are
// shared and nudging away from the wrong monitor based on those.
let delta_nudge_to_dpi_monitor = (
if wrong_monitor_rect.left == new_monitor_rect.right {
-1
} else if wrong_monitor_rect.right == new_monitor_rect.left {
1
} else {
0
},
if wrong_monitor_rect.bottom == new_monitor_rect.top {
1
} else if wrong_monitor_rect.top == new_monitor_rect.bottom {
-1
} else {
0
},
);
let abort_after_iterations = new_monitor_rect.right - new_monitor_rect.left
+ new_monitor_rect.bottom
- new_monitor_rect.top;
for _ in 0..abort_after_iterations {
conservative_rect.left += delta_nudge_to_dpi_monitor.0;
conservative_rect.right += delta_nudge_to_dpi_monitor.0;
conservative_rect.top += delta_nudge_to_dpi_monitor.1;
conservative_rect.bottom += delta_nudge_to_dpi_monitor.1;
if winuser::MonitorFromRect(&conservative_rect, 0) == new_dpi_monitor {
break;
}
}
conservative_rect
};
}
winuser::SetWindowPos(
window,
ptr::null_mut(),
new_outer_rect.left,
new_outer_rect.top,
new_outer_rect.right - new_outer_rect.left,
new_outer_rect.bottom - new_outer_rect.top,
winuser::SWP_NOZORDER | winuser::SWP_NOACTIVATE,
);
0
}
winuser::WM_SETTINGCHANGE => {
use crate::event::WindowEvent::ThemeChanged;
let preferred_theme = subclass_input.window_state.lock().preferred_theme;
if preferred_theme == None {
let new_theme = try_theme(window, preferred_theme);
let mut window_state = subclass_input.window_state.lock();
if window_state.current_theme != new_theme {
window_state.current_theme = new_theme;
mem::drop(window_state);
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ThemeChanged(new_theme),
});
}
}
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
_ => {
if msg == *DESTROY_MSG_ID {
winuser::DestroyWindow(window);
0
} else if msg == *SET_RETAIN_STATE_ON_SIZE_MSG_ID {
let mut window_state = subclass_input.window_state.lock();
window_state.set_window_flags_in_place(|f| {
f.set(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE, wparam != 0)
});
0
} else {
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
}
};
subclass_input
.event_loop_runner
.catch_unwind(callback)
.unwrap_or(-1)
}
unsafe extern "system" fn thread_event_target_callback<T: 'static>(
window: HWND,
msg: UINT,
wparam: WPARAM,
lparam: LPARAM,
_: UINT_PTR,
subclass_input_ptr: DWORD_PTR,
) -> LRESULT {
let subclass_input = Box::from_raw(subclass_input_ptr as *mut ThreadMsgTargetSubclassInput<T>);
if msg != winuser::WM_PAINT {
winuser::RedrawWindow(
window,
ptr::null(),
ptr::null_mut(),
winuser::RDW_INTERNALPAINT,
);
}
let mut subclass_removed = false;
// I decided to bind the closure to `callback` and pass it to catch_unwind rather than passing
// the closure to catch_unwind directly so that the match body indendation wouldn't change and
// the git blame and history would be preserved.
let callback = || match msg {
winuser::WM_NCDESTROY => {
remove_event_target_window_subclass::<T>(window);
subclass_removed = true;
0
}
// Because WM_PAINT comes after all other messages, we use it during modal loops to detect
// when the event queue has been emptied. See `process_event` for more details.
winuser::WM_PAINT => {
winuser::ValidateRect(window, ptr::null());
// If the WM_PAINT handler in `public_window_callback` has already flushed the redraw
// events, `handling_events` will return false and we won't emit a second
// `RedrawEventsCleared` event.
if subclass_input.event_loop_runner.handling_events() {
if subclass_input.event_loop_runner.should_buffer() {
// This branch can be triggered when a nested win32 event loop is triggered
// inside of the `event_handler` callback.
winuser::RedrawWindow(
window,
ptr::null(),
ptr::null_mut(),
winuser::RDW_INTERNALPAINT,
);
} else {
// This WM_PAINT handler will never be re-entrant because `flush_paint_messages`
// doesn't call WM_PAINT for the thread event target (i.e. this window).
assert!(flush_paint_messages(
None,
&subclass_input.event_loop_runner
));
subclass_input.event_loop_runner.redraw_events_cleared();
process_control_flow(&subclass_input.event_loop_runner);
}
}
// Default WM_PAINT behaviour. This makes sure modals and popups are shown immediatly when opening them.
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
winuser::WM_INPUT_DEVICE_CHANGE => {
let event = match wparam as _ {
winuser::GIDC_ARRIVAL => DeviceEvent::Added,
winuser::GIDC_REMOVAL => DeviceEvent::Removed,
_ => unreachable!(),
};
subclass_input.send_event(Event::DeviceEvent {
device_id: wrap_device_id(lparam as _),
event,
});
0
}
winuser::WM_INPUT => {
use crate::event::{
DeviceEvent::{Button, Key, Motion, MouseMotion, MouseWheel},
ElementState::{Pressed, Released},
MouseScrollDelta::LineDelta,
};
if let Some(data) = raw_input::get_raw_input_data(lparam as _) {
let device_id = wrap_device_id(data.header.hDevice as _);
if data.header.dwType == winuser::RIM_TYPEMOUSE {
let mouse = data.data.mouse();
if util::has_flag(mouse.usFlags, winuser::MOUSE_MOVE_RELATIVE) {
let x = mouse.lLastX as f64;
let y = mouse.lLastY as f64;
if x != 0.0 {
subclass_input.send_event(Event::DeviceEvent {
device_id,
event: Motion { axis: 0, value: x },
});
}
if y != 0.0 {
subclass_input.send_event(Event::DeviceEvent {
device_id,
event: Motion { axis: 1, value: y },
});
}
if x != 0.0 || y != 0.0 {
subclass_input.send_event(Event::DeviceEvent {
device_id,
event: MouseMotion { delta: (x, y) },
});
}
}
if util::has_flag(mouse.usButtonFlags, winuser::RI_MOUSE_WHEEL) {
let delta =
mouse.usButtonData as SHORT as f32 / winuser::WHEEL_DELTA as f32;
subclass_input.send_event(Event::DeviceEvent {
device_id,
event: MouseWheel {
delta: LineDelta(0.0, delta),
},
});
}
let button_state = raw_input::get_raw_mouse_button_state(mouse.usButtonFlags);
// Left, middle, and right, respectively.
for (index, state) in button_state.iter().enumerate() {
if let Some(state) = *state {
// This gives us consistency with X11, since there doesn't
// seem to be anything else reasonable to do for a mouse
// button ID.
let button = (index + 1) as _;
subclass_input.send_event(Event::DeviceEvent {
device_id,
event: Button { button, state },
});
}
}
} else if data.header.dwType == winuser::RIM_TYPEKEYBOARD {
let keyboard = data.data.keyboard();
let pressed = keyboard.Message == winuser::WM_KEYDOWN
|| keyboard.Message == winuser::WM_SYSKEYDOWN;
let released = keyboard.Message == winuser::WM_KEYUP
|| keyboard.Message == winuser::WM_SYSKEYUP;
if pressed || released {
let state = if pressed { Pressed } else { Released };
let scancode = keyboard.MakeCode as _;
let extended = util::has_flag(keyboard.Flags, winuser::RI_KEY_E0 as _)
| util::has_flag(keyboard.Flags, winuser::RI_KEY_E1 as _);
if let Some((vkey, scancode)) =
handle_extended_keys(keyboard.VKey as _, scancode, extended)
{
let virtual_keycode = vkey_to_winit_vkey(vkey);
#[allow(deprecated)]
subclass_input.send_event(Event::DeviceEvent {
device_id,
event: Key(KeyboardInput {
scancode,
state,
virtual_keycode,
modifiers: event::get_key_mods(),
}),
});
}
}
}
}
commctrl::DefSubclassProc(window, msg, wparam, lparam)
}
_ if msg == *USER_EVENT_MSG_ID => {
if let Ok(event) = subclass_input.user_event_receiver.recv() {
subclass_input.send_event(Event::UserEvent(event));
}
0
}
_ if msg == *EXEC_MSG_ID => {
let mut function: ThreadExecFn = Box::from_raw(wparam as usize as *mut _);
function();
0
}
_ if msg == *PROCESS_NEW_EVENTS_MSG_ID => {
winuser::PostThreadMessageW(
subclass_input.event_loop_runner.wait_thread_id(),
*CANCEL_WAIT_UNTIL_MSG_ID,
0,
0,
);
// if the control_flow is WaitUntil, make sure the given moment has actually passed
// before emitting NewEvents
if let ControlFlow::WaitUntil(wait_until) =
subclass_input.event_loop_runner.control_flow()
{
let mut msg = mem::zeroed();
while Instant::now() < wait_until {
if 0 != winuser::PeekMessageW(&mut msg, ptr::null_mut(), 0, 0, 0) {
// This works around a "feature" in PeekMessageW. If the message PeekMessageW
// gets is a WM_PAINT message that had RDW_INTERNALPAINT set (i.e. doesn't
// have an update region), PeekMessageW will remove that window from the
// redraw queue even though we told it not to remove messages from the
// queue. We fix it by re-dispatching an internal paint message to that
// window.
if msg.message == winuser::WM_PAINT {
let mut rect = mem::zeroed();
if 0 == winuser::GetUpdateRect(msg.hwnd, &mut rect, 0) {
winuser::RedrawWindow(
msg.hwnd,
ptr::null(),
ptr::null_mut(),
winuser::RDW_INTERNALPAINT,
);
}
}
break;
}
}
}
subclass_input.event_loop_runner.poll();
0
}
_ => commctrl::DefSubclassProc(window, msg, wparam, lparam),
};
let result = subclass_input
.event_loop_runner
.catch_unwind(callback)
.unwrap_or(-1);
if subclass_removed {
mem::drop(subclass_input);
} else {
Box::into_raw(subclass_input);
}
result
}
| {
&self.window_target
} |
error.rs | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateDevicePoolError {
pub kind: CreateDevicePoolErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateDevicePoolErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateDevicePoolError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateDevicePoolErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateDevicePoolErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateDevicePoolErrorKind::NotFoundException(_inner) => _inner.fmt(f),
CreateDevicePoolErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
CreateDevicePoolErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateDevicePoolError {
fn code(&self) -> Option<&str> {
CreateDevicePoolError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateDevicePoolError {
pub fn new(kind: CreateDevicePoolErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateDevicePoolErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateDevicePoolErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, CreateDevicePoolErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateDevicePoolErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, CreateDevicePoolErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
CreateDevicePoolErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for CreateDevicePoolError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateDevicePoolErrorKind::ArgumentException(_inner) => Some(_inner),
CreateDevicePoolErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateDevicePoolErrorKind::NotFoundException(_inner) => Some(_inner),
CreateDevicePoolErrorKind::ServiceAccountException(_inner) => Some(_inner),
CreateDevicePoolErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateInstanceProfileError {
pub kind: CreateInstanceProfileErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateInstanceProfileErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateInstanceProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateInstanceProfileErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateInstanceProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateInstanceProfileErrorKind::NotFoundException(_inner) => _inner.fmt(f),
CreateInstanceProfileErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
CreateInstanceProfileErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateInstanceProfileError {
fn code(&self) -> Option<&str> {
CreateInstanceProfileError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateInstanceProfileError {
pub fn new(kind: CreateInstanceProfileErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateInstanceProfileErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateInstanceProfileErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
CreateInstanceProfileErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateInstanceProfileErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateInstanceProfileErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
CreateInstanceProfileErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for CreateInstanceProfileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateInstanceProfileErrorKind::ArgumentException(_inner) => Some(_inner),
CreateInstanceProfileErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateInstanceProfileErrorKind::NotFoundException(_inner) => Some(_inner),
CreateInstanceProfileErrorKind::ServiceAccountException(_inner) => Some(_inner),
CreateInstanceProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateNetworkProfileError {
pub kind: CreateNetworkProfileErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateNetworkProfileErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateNetworkProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateNetworkProfileErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateNetworkProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateNetworkProfileErrorKind::NotFoundException(_inner) => _inner.fmt(f),
CreateNetworkProfileErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
CreateNetworkProfileErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateNetworkProfileError {
fn code(&self) -> Option<&str> {
CreateNetworkProfileError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateNetworkProfileError {
pub fn new(kind: CreateNetworkProfileErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateNetworkProfileErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateNetworkProfileErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
CreateNetworkProfileErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateNetworkProfileErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateNetworkProfileErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
CreateNetworkProfileErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for CreateNetworkProfileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateNetworkProfileErrorKind::ArgumentException(_inner) => Some(_inner),
CreateNetworkProfileErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateNetworkProfileErrorKind::NotFoundException(_inner) => Some(_inner),
CreateNetworkProfileErrorKind::ServiceAccountException(_inner) => Some(_inner),
CreateNetworkProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateProjectError {
pub kind: CreateProjectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateProjectErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
TagOperationException(crate::error::TagOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateProjectErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateProjectErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateProjectErrorKind::NotFoundException(_inner) => _inner.fmt(f),
CreateProjectErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
CreateProjectErrorKind::TagOperationException(_inner) => _inner.fmt(f),
CreateProjectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateProjectError {
fn code(&self) -> Option<&str> {
CreateProjectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateProjectError {
pub fn new(kind: CreateProjectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateProjectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateProjectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, CreateProjectErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateProjectErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, CreateProjectErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
CreateProjectErrorKind::ServiceAccountException(_)
)
}
pub fn is_tag_operation_exception(&self) -> bool {
matches!(&self.kind, CreateProjectErrorKind::TagOperationException(_))
}
}
impl std::error::Error for CreateProjectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateProjectErrorKind::ArgumentException(_inner) => Some(_inner),
CreateProjectErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateProjectErrorKind::NotFoundException(_inner) => Some(_inner),
CreateProjectErrorKind::ServiceAccountException(_inner) => Some(_inner),
CreateProjectErrorKind::TagOperationException(_inner) => Some(_inner),
CreateProjectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateRemoteAccessSessionError {
pub kind: CreateRemoteAccessSessionErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateRemoteAccessSessionErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateRemoteAccessSessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateRemoteAccessSessionErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateRemoteAccessSessionErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateRemoteAccessSessionErrorKind::NotFoundException(_inner) => _inner.fmt(f),
CreateRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
CreateRemoteAccessSessionErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateRemoteAccessSessionError {
fn code(&self) -> Option<&str> {
CreateRemoteAccessSessionError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateRemoteAccessSessionError {
pub fn new(kind: CreateRemoteAccessSessionErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateRemoteAccessSessionErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateRemoteAccessSessionErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
CreateRemoteAccessSessionErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateRemoteAccessSessionErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
CreateRemoteAccessSessionErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
CreateRemoteAccessSessionErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for CreateRemoteAccessSessionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateRemoteAccessSessionErrorKind::ArgumentException(_inner) => Some(_inner),
CreateRemoteAccessSessionErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateRemoteAccessSessionErrorKind::NotFoundException(_inner) => Some(_inner),
CreateRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => Some(_inner),
CreateRemoteAccessSessionErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateTestGridProjectError {
pub kind: CreateTestGridProjectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateTestGridProjectErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
LimitExceededException(crate::error::LimitExceededException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateTestGridProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateTestGridProjectErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateTestGridProjectErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
CreateTestGridProjectErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateTestGridProjectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateTestGridProjectError {
fn code(&self) -> Option<&str> {
CreateTestGridProjectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateTestGridProjectError {
pub fn new(kind: CreateTestGridProjectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateTestGridProjectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateTestGridProjectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
CreateTestGridProjectErrorKind::ArgumentException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
CreateTestGridProjectErrorKind::InternalServiceException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateTestGridProjectErrorKind::LimitExceededException(_)
)
}
}
impl std::error::Error for CreateTestGridProjectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateTestGridProjectErrorKind::ArgumentException(_inner) => Some(_inner),
CreateTestGridProjectErrorKind::InternalServiceException(_inner) => Some(_inner),
CreateTestGridProjectErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateTestGridProjectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateTestGridUrlError {
pub kind: CreateTestGridUrlErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateTestGridUrlErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
NotFoundException(crate::error::NotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateTestGridUrlError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateTestGridUrlErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateTestGridUrlErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
CreateTestGridUrlErrorKind::NotFoundException(_inner) => _inner.fmt(f),
CreateTestGridUrlErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateTestGridUrlError {
fn code(&self) -> Option<&str> {
CreateTestGridUrlError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateTestGridUrlError {
pub fn new(kind: CreateTestGridUrlErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateTestGridUrlErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateTestGridUrlErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, CreateTestGridUrlErrorKind::ArgumentException(_))
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
CreateTestGridUrlErrorKind::InternalServiceException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, CreateTestGridUrlErrorKind::NotFoundException(_))
}
}
impl std::error::Error for CreateTestGridUrlError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateTestGridUrlErrorKind::ArgumentException(_inner) => Some(_inner),
CreateTestGridUrlErrorKind::InternalServiceException(_inner) => Some(_inner),
CreateTestGridUrlErrorKind::NotFoundException(_inner) => Some(_inner),
CreateTestGridUrlErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateUploadError {
pub kind: CreateUploadErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateUploadErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateUploadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateUploadErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateUploadErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateUploadErrorKind::NotFoundException(_inner) => _inner.fmt(f),
CreateUploadErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
CreateUploadErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateUploadError {
fn code(&self) -> Option<&str> {
CreateUploadError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateUploadError {
pub fn new(kind: CreateUploadErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateUploadErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateUploadErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, CreateUploadErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, CreateUploadErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, CreateUploadErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
CreateUploadErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for CreateUploadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateUploadErrorKind::ArgumentException(_inner) => Some(_inner),
CreateUploadErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateUploadErrorKind::NotFoundException(_inner) => Some(_inner),
CreateUploadErrorKind::ServiceAccountException(_inner) => Some(_inner),
CreateUploadErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateVPCEConfigurationError {
pub kind: CreateVPCEConfigurationErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateVPCEConfigurationErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for CreateVPCEConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateVPCEConfigurationErrorKind::ArgumentException(_inner) => _inner.fmt(f),
CreateVPCEConfigurationErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
CreateVPCEConfigurationErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
CreateVPCEConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for CreateVPCEConfigurationError {
fn code(&self) -> Option<&str> {
CreateVPCEConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl CreateVPCEConfigurationError {
pub fn new(kind: CreateVPCEConfigurationErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateVPCEConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateVPCEConfigurationErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
CreateVPCEConfigurationErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateVPCEConfigurationErrorKind::LimitExceededException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
CreateVPCEConfigurationErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for CreateVPCEConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateVPCEConfigurationErrorKind::ArgumentException(_inner) => Some(_inner),
CreateVPCEConfigurationErrorKind::LimitExceededException(_inner) => Some(_inner),
CreateVPCEConfigurationErrorKind::ServiceAccountException(_inner) => Some(_inner),
CreateVPCEConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteDevicePoolError {
pub kind: DeleteDevicePoolErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteDevicePoolErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteDevicePoolError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteDevicePoolErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteDevicePoolErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
DeleteDevicePoolErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteDevicePoolErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
DeleteDevicePoolErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteDevicePoolError {
fn code(&self) -> Option<&str> {
DeleteDevicePoolError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteDevicePoolError {
pub fn new(kind: DeleteDevicePoolErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteDevicePoolErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteDevicePoolErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, DeleteDevicePoolErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDevicePoolErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, DeleteDevicePoolErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDevicePoolErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for DeleteDevicePoolError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteDevicePoolErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteDevicePoolErrorKind::LimitExceededException(_inner) => Some(_inner),
DeleteDevicePoolErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteDevicePoolErrorKind::ServiceAccountException(_inner) => Some(_inner),
DeleteDevicePoolErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteInstanceProfileError {
pub kind: DeleteInstanceProfileErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteInstanceProfileErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteInstanceProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteInstanceProfileErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteInstanceProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
DeleteInstanceProfileErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteInstanceProfileErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
DeleteInstanceProfileErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteInstanceProfileError {
fn code(&self) -> Option<&str> {
DeleteInstanceProfileError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteInstanceProfileError {
pub fn new(kind: DeleteInstanceProfileErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteInstanceProfileErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteInstanceProfileErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInstanceProfileErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInstanceProfileErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInstanceProfileErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInstanceProfileErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for DeleteInstanceProfileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteInstanceProfileErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteInstanceProfileErrorKind::LimitExceededException(_inner) => Some(_inner),
DeleteInstanceProfileErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteInstanceProfileErrorKind::ServiceAccountException(_inner) => Some(_inner),
DeleteInstanceProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteNetworkProfileError {
pub kind: DeleteNetworkProfileErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteNetworkProfileErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteNetworkProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteNetworkProfileErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteNetworkProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
DeleteNetworkProfileErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteNetworkProfileErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
DeleteNetworkProfileErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteNetworkProfileError {
fn code(&self) -> Option<&str> {
DeleteNetworkProfileError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteNetworkProfileError {
pub fn new(kind: DeleteNetworkProfileErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteNetworkProfileErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteNetworkProfileErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
DeleteNetworkProfileErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteNetworkProfileErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteNetworkProfileErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
DeleteNetworkProfileErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for DeleteNetworkProfileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteNetworkProfileErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteNetworkProfileErrorKind::LimitExceededException(_inner) => Some(_inner),
DeleteNetworkProfileErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteNetworkProfileErrorKind::ServiceAccountException(_inner) => Some(_inner),
DeleteNetworkProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteProjectError {
pub kind: DeleteProjectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteProjectErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteProjectErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteProjectErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
DeleteProjectErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteProjectErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
DeleteProjectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteProjectError {
fn code(&self) -> Option<&str> {
DeleteProjectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteProjectError {
pub fn new(kind: DeleteProjectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteProjectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteProjectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, DeleteProjectErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteProjectErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, DeleteProjectErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
DeleteProjectErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for DeleteProjectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteProjectErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteProjectErrorKind::LimitExceededException(_inner) => Some(_inner),
DeleteProjectErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteProjectErrorKind::ServiceAccountException(_inner) => Some(_inner),
DeleteProjectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteRemoteAccessSessionError {
pub kind: DeleteRemoteAccessSessionErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteRemoteAccessSessionErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteRemoteAccessSessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteRemoteAccessSessionErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteRemoteAccessSessionErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
DeleteRemoteAccessSessionErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
DeleteRemoteAccessSessionErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteRemoteAccessSessionError {
fn code(&self) -> Option<&str> {
DeleteRemoteAccessSessionError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteRemoteAccessSessionError {
pub fn new(kind: DeleteRemoteAccessSessionErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteRemoteAccessSessionErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteRemoteAccessSessionErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
DeleteRemoteAccessSessionErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteRemoteAccessSessionErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteRemoteAccessSessionErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
DeleteRemoteAccessSessionErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for DeleteRemoteAccessSessionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteRemoteAccessSessionErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteRemoteAccessSessionErrorKind::LimitExceededException(_inner) => Some(_inner),
DeleteRemoteAccessSessionErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => Some(_inner),
DeleteRemoteAccessSessionErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteRunError {
pub kind: DeleteRunErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteRunErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteRunError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteRunErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteRunErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
DeleteRunErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteRunErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
DeleteRunErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteRunError {
fn code(&self) -> Option<&str> {
DeleteRunError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteRunError {
pub fn new(kind: DeleteRunErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteRunErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteRunErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, DeleteRunErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, DeleteRunErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, DeleteRunErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, DeleteRunErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for DeleteRunError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteRunErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteRunErrorKind::LimitExceededException(_inner) => Some(_inner),
DeleteRunErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteRunErrorKind::ServiceAccountException(_inner) => Some(_inner),
DeleteRunErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteTestGridProjectError {
pub kind: DeleteTestGridProjectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteTestGridProjectErrorKind {
ArgumentException(crate::error::ArgumentException),
CannotDeleteException(crate::error::CannotDeleteException),
InternalServiceException(crate::error::InternalServiceException),
NotFoundException(crate::error::NotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteTestGridProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteTestGridProjectErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteTestGridProjectErrorKind::CannotDeleteException(_inner) => _inner.fmt(f),
DeleteTestGridProjectErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
DeleteTestGridProjectErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteTestGridProjectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteTestGridProjectError {
fn code(&self) -> Option<&str> {
DeleteTestGridProjectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteTestGridProjectError {
pub fn new(kind: DeleteTestGridProjectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteTestGridProjectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteTestGridProjectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
DeleteTestGridProjectErrorKind::ArgumentException(_)
)
}
pub fn is_cannot_delete_exception(&self) -> bool {
matches!(
&self.kind,
DeleteTestGridProjectErrorKind::CannotDeleteException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
DeleteTestGridProjectErrorKind::InternalServiceException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteTestGridProjectErrorKind::NotFoundException(_)
)
}
}
impl std::error::Error for DeleteTestGridProjectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteTestGridProjectErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteTestGridProjectErrorKind::CannotDeleteException(_inner) => Some(_inner),
DeleteTestGridProjectErrorKind::InternalServiceException(_inner) => Some(_inner),
DeleteTestGridProjectErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteTestGridProjectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteUploadError {
pub kind: DeleteUploadErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteUploadErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteUploadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteUploadErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteUploadErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
DeleteUploadErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteUploadErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
DeleteUploadErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteUploadError {
fn code(&self) -> Option<&str> {
DeleteUploadError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteUploadError {
pub fn new(kind: DeleteUploadErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteUploadErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteUploadErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, DeleteUploadErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, DeleteUploadErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, DeleteUploadErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
DeleteUploadErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for DeleteUploadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteUploadErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteUploadErrorKind::LimitExceededException(_inner) => Some(_inner),
DeleteUploadErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteUploadErrorKind::ServiceAccountException(_inner) => Some(_inner),
DeleteUploadErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteVPCEConfigurationError {
pub kind: DeleteVPCEConfigurationErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteVPCEConfigurationErrorKind {
ArgumentException(crate::error::ArgumentException),
InvalidOperationException(crate::error::InvalidOperationException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DeleteVPCEConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteVPCEConfigurationErrorKind::ArgumentException(_inner) => _inner.fmt(f),
DeleteVPCEConfigurationErrorKind::InvalidOperationException(_inner) => _inner.fmt(f),
DeleteVPCEConfigurationErrorKind::NotFoundException(_inner) => _inner.fmt(f),
DeleteVPCEConfigurationErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
DeleteVPCEConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for DeleteVPCEConfigurationError {
fn code(&self) -> Option<&str> {
DeleteVPCEConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteVPCEConfigurationError {
pub fn new(kind: DeleteVPCEConfigurationErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteVPCEConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteVPCEConfigurationErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
DeleteVPCEConfigurationErrorKind::ArgumentException(_)
)
}
pub fn is_invalid_operation_exception(&self) -> bool {
matches!(
&self.kind,
DeleteVPCEConfigurationErrorKind::InvalidOperationException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DeleteVPCEConfigurationErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
DeleteVPCEConfigurationErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for DeleteVPCEConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteVPCEConfigurationErrorKind::ArgumentException(_inner) => Some(_inner),
DeleteVPCEConfigurationErrorKind::InvalidOperationException(_inner) => Some(_inner),
DeleteVPCEConfigurationErrorKind::NotFoundException(_inner) => Some(_inner),
DeleteVPCEConfigurationErrorKind::ServiceAccountException(_inner) => Some(_inner),
DeleteVPCEConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetAccountSettingsError {
pub kind: GetAccountSettingsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetAccountSettingsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetAccountSettingsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetAccountSettingsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetAccountSettingsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetAccountSettingsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetAccountSettingsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetAccountSettingsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetAccountSettingsError {
fn code(&self) -> Option<&str> {
GetAccountSettingsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetAccountSettingsError {
pub fn new(kind: GetAccountSettingsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetAccountSettingsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetAccountSettingsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
GetAccountSettingsErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetAccountSettingsErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetAccountSettingsErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetAccountSettingsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetAccountSettingsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetAccountSettingsErrorKind::ArgumentException(_inner) => Some(_inner),
GetAccountSettingsErrorKind::LimitExceededException(_inner) => Some(_inner),
GetAccountSettingsErrorKind::NotFoundException(_inner) => Some(_inner),
GetAccountSettingsErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetAccountSettingsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetDeviceError {
pub kind: GetDeviceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetDeviceErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetDeviceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetDeviceErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetDeviceErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetDeviceErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetDeviceErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetDeviceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetDeviceError {
fn code(&self) -> Option<&str> {
GetDeviceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetDeviceError {
pub fn new(kind: GetDeviceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetDeviceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetDeviceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetDeviceErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, GetDeviceErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetDeviceErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, GetDeviceErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for GetDeviceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetDeviceErrorKind::ArgumentException(_inner) => Some(_inner),
GetDeviceErrorKind::LimitExceededException(_inner) => Some(_inner),
GetDeviceErrorKind::NotFoundException(_inner) => Some(_inner),
GetDeviceErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetDeviceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetDeviceInstanceError {
pub kind: GetDeviceInstanceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetDeviceInstanceErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetDeviceInstanceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetDeviceInstanceErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetDeviceInstanceErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetDeviceInstanceErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetDeviceInstanceErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetDeviceInstanceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetDeviceInstanceError {
fn code(&self) -> Option<&str> {
GetDeviceInstanceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetDeviceInstanceError {
pub fn new(kind: GetDeviceInstanceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetDeviceInstanceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetDeviceInstanceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetDeviceInstanceErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetDeviceInstanceErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetDeviceInstanceErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetDeviceInstanceErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetDeviceInstanceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetDeviceInstanceErrorKind::ArgumentException(_inner) => Some(_inner),
GetDeviceInstanceErrorKind::LimitExceededException(_inner) => Some(_inner),
GetDeviceInstanceErrorKind::NotFoundException(_inner) => Some(_inner),
GetDeviceInstanceErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetDeviceInstanceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetDevicePoolError {
pub kind: GetDevicePoolErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetDevicePoolErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetDevicePoolError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetDevicePoolErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetDevicePoolErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetDevicePoolErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetDevicePoolErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetDevicePoolErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetDevicePoolError {
fn code(&self) -> Option<&str> {
GetDevicePoolError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetDevicePoolError {
pub fn new(kind: GetDevicePoolErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetDevicePoolErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetDevicePoolErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetDevicePoolErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetDevicePoolErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetDevicePoolErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetDevicePoolErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetDevicePoolError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetDevicePoolErrorKind::ArgumentException(_inner) => Some(_inner),
GetDevicePoolErrorKind::LimitExceededException(_inner) => Some(_inner),
GetDevicePoolErrorKind::NotFoundException(_inner) => Some(_inner),
GetDevicePoolErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetDevicePoolErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetDevicePoolCompatibilityError {
pub kind: GetDevicePoolCompatibilityErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetDevicePoolCompatibilityErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetDevicePoolCompatibilityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetDevicePoolCompatibilityErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetDevicePoolCompatibilityErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetDevicePoolCompatibilityErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetDevicePoolCompatibilityErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetDevicePoolCompatibilityErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetDevicePoolCompatibilityError {
fn code(&self) -> Option<&str> {
GetDevicePoolCompatibilityError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetDevicePoolCompatibilityError {
pub fn new(kind: GetDevicePoolCompatibilityErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetDevicePoolCompatibilityErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetDevicePoolCompatibilityErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
GetDevicePoolCompatibilityErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetDevicePoolCompatibilityErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetDevicePoolCompatibilityErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetDevicePoolCompatibilityErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetDevicePoolCompatibilityError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetDevicePoolCompatibilityErrorKind::ArgumentException(_inner) => Some(_inner),
GetDevicePoolCompatibilityErrorKind::LimitExceededException(_inner) => Some(_inner),
GetDevicePoolCompatibilityErrorKind::NotFoundException(_inner) => Some(_inner),
GetDevicePoolCompatibilityErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetDevicePoolCompatibilityErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetInstanceProfileError {
pub kind: GetInstanceProfileErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetInstanceProfileErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetInstanceProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetInstanceProfileErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetInstanceProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetInstanceProfileErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetInstanceProfileErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetInstanceProfileErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetInstanceProfileError {
fn code(&self) -> Option<&str> {
GetInstanceProfileError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetInstanceProfileError {
pub fn new(kind: GetInstanceProfileErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetInstanceProfileErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetInstanceProfileErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
GetInstanceProfileErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetInstanceProfileErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetInstanceProfileErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetInstanceProfileErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetInstanceProfileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetInstanceProfileErrorKind::ArgumentException(_inner) => Some(_inner),
GetInstanceProfileErrorKind::LimitExceededException(_inner) => Some(_inner),
GetInstanceProfileErrorKind::NotFoundException(_inner) => Some(_inner),
GetInstanceProfileErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetInstanceProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetJobError {
pub kind: GetJobErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetJobErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetJobError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetJobErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetJobErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetJobErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetJobErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetJobErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetJobError {
fn code(&self) -> Option<&str> {
GetJobError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetJobError {
pub fn new(kind: GetJobErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetJobErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetJobErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetJobErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, GetJobErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetJobErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, GetJobErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for GetJobError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetJobErrorKind::ArgumentException(_inner) => Some(_inner),
GetJobErrorKind::LimitExceededException(_inner) => Some(_inner),
GetJobErrorKind::NotFoundException(_inner) => Some(_inner),
GetJobErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetJobErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetNetworkProfileError {
pub kind: GetNetworkProfileErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetNetworkProfileErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetNetworkProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetNetworkProfileErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetNetworkProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetNetworkProfileErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetNetworkProfileErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetNetworkProfileErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetNetworkProfileError {
fn code(&self) -> Option<&str> {
GetNetworkProfileError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetNetworkProfileError {
pub fn new(kind: GetNetworkProfileErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetNetworkProfileErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetNetworkProfileErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetNetworkProfileErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetNetworkProfileErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetNetworkProfileErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetNetworkProfileErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetNetworkProfileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetNetworkProfileErrorKind::ArgumentException(_inner) => Some(_inner),
GetNetworkProfileErrorKind::LimitExceededException(_inner) => Some(_inner),
GetNetworkProfileErrorKind::NotFoundException(_inner) => Some(_inner),
GetNetworkProfileErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetNetworkProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetOfferingStatusError {
pub kind: GetOfferingStatusErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetOfferingStatusErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotEligibleException(crate::error::NotEligibleException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetOfferingStatusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetOfferingStatusErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetOfferingStatusErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetOfferingStatusErrorKind::NotEligibleException(_inner) => _inner.fmt(f),
GetOfferingStatusErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetOfferingStatusErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetOfferingStatusErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetOfferingStatusError {
fn code(&self) -> Option<&str> {
GetOfferingStatusError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetOfferingStatusError {
pub fn new(kind: GetOfferingStatusErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetOfferingStatusErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetOfferingStatusErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetOfferingStatusErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetOfferingStatusErrorKind::LimitExceededException(_)
)
}
pub fn is_not_eligible_exception(&self) -> bool {
matches!(
&self.kind,
GetOfferingStatusErrorKind::NotEligibleException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetOfferingStatusErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetOfferingStatusErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetOfferingStatusError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetOfferingStatusErrorKind::ArgumentException(_inner) => Some(_inner),
GetOfferingStatusErrorKind::LimitExceededException(_inner) => Some(_inner),
GetOfferingStatusErrorKind::NotEligibleException(_inner) => Some(_inner),
GetOfferingStatusErrorKind::NotFoundException(_inner) => Some(_inner),
GetOfferingStatusErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetOfferingStatusErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetProjectError {
pub kind: GetProjectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetProjectErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetProjectErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetProjectErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetProjectErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetProjectErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetProjectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetProjectError {
fn code(&self) -> Option<&str> {
GetProjectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetProjectError {
pub fn new(kind: GetProjectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetProjectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetProjectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetProjectErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, GetProjectErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetProjectErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, GetProjectErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for GetProjectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetProjectErrorKind::ArgumentException(_inner) => Some(_inner),
GetProjectErrorKind::LimitExceededException(_inner) => Some(_inner),
GetProjectErrorKind::NotFoundException(_inner) => Some(_inner),
GetProjectErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetProjectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetRemoteAccessSessionError {
pub kind: GetRemoteAccessSessionErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetRemoteAccessSessionErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetRemoteAccessSessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetRemoteAccessSessionErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetRemoteAccessSessionErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetRemoteAccessSessionErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetRemoteAccessSessionErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetRemoteAccessSessionError {
fn code(&self) -> Option<&str> {
GetRemoteAccessSessionError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetRemoteAccessSessionError {
pub fn new(kind: GetRemoteAccessSessionErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetRemoteAccessSessionErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetRemoteAccessSessionErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
GetRemoteAccessSessionErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetRemoteAccessSessionErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetRemoteAccessSessionErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetRemoteAccessSessionErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetRemoteAccessSessionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetRemoteAccessSessionErrorKind::ArgumentException(_inner) => Some(_inner),
GetRemoteAccessSessionErrorKind::LimitExceededException(_inner) => Some(_inner),
GetRemoteAccessSessionErrorKind::NotFoundException(_inner) => Some(_inner),
GetRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetRemoteAccessSessionErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetRunError {
pub kind: GetRunErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetRunErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetRunError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetRunErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetRunErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetRunErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetRunErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetRunErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetRunError {
fn code(&self) -> Option<&str> {
GetRunError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetRunError {
pub fn new(kind: GetRunErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetRunErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetRunErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetRunErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, GetRunErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetRunErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, GetRunErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for GetRunError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetRunErrorKind::ArgumentException(_inner) => Some(_inner),
GetRunErrorKind::LimitExceededException(_inner) => Some(_inner),
GetRunErrorKind::NotFoundException(_inner) => Some(_inner),
GetRunErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetRunErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetSuiteError {
pub kind: GetSuiteErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetSuiteErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetSuiteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetSuiteErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetSuiteErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetSuiteErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetSuiteErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetSuiteErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetSuiteError {
fn code(&self) -> Option<&str> {
GetSuiteError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetSuiteError {
pub fn new(kind: GetSuiteErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetSuiteErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetSuiteErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetSuiteErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, GetSuiteErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetSuiteErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, GetSuiteErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for GetSuiteError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetSuiteErrorKind::ArgumentException(_inner) => Some(_inner),
GetSuiteErrorKind::LimitExceededException(_inner) => Some(_inner),
GetSuiteErrorKind::NotFoundException(_inner) => Some(_inner),
GetSuiteErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetSuiteErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetTestError {
pub kind: GetTestErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetTestErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetTestError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetTestErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetTestErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetTestErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetTestErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetTestErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetTestError {
fn code(&self) -> Option<&str> {
GetTestError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetTestError {
pub fn new(kind: GetTestErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetTestErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetTestErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetTestErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, GetTestErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetTestErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, GetTestErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for GetTestError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetTestErrorKind::ArgumentException(_inner) => Some(_inner),
GetTestErrorKind::LimitExceededException(_inner) => Some(_inner),
GetTestErrorKind::NotFoundException(_inner) => Some(_inner),
GetTestErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetTestErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetTestGridProjectError {
pub kind: GetTestGridProjectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetTestGridProjectErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
NotFoundException(crate::error::NotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetTestGridProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetTestGridProjectErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetTestGridProjectErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
GetTestGridProjectErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetTestGridProjectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetTestGridProjectError {
fn code(&self) -> Option<&str> {
GetTestGridProjectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetTestGridProjectError {
pub fn new(kind: GetTestGridProjectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetTestGridProjectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetTestGridProjectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
GetTestGridProjectErrorKind::ArgumentException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
GetTestGridProjectErrorKind::InternalServiceException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetTestGridProjectErrorKind::NotFoundException(_)
)
}
}
impl std::error::Error for GetTestGridProjectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetTestGridProjectErrorKind::ArgumentException(_inner) => Some(_inner),
GetTestGridProjectErrorKind::InternalServiceException(_inner) => Some(_inner),
GetTestGridProjectErrorKind::NotFoundException(_inner) => Some(_inner),
GetTestGridProjectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetTestGridSessionError {
pub kind: GetTestGridSessionErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetTestGridSessionErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
NotFoundException(crate::error::NotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetTestGridSessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetTestGridSessionErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetTestGridSessionErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
GetTestGridSessionErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetTestGridSessionErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetTestGridSessionError {
fn code(&self) -> Option<&str> {
GetTestGridSessionError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetTestGridSessionError {
pub fn new(kind: GetTestGridSessionErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetTestGridSessionErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetTestGridSessionErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
GetTestGridSessionErrorKind::ArgumentException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
GetTestGridSessionErrorKind::InternalServiceException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetTestGridSessionErrorKind::NotFoundException(_)
)
}
}
impl std::error::Error for GetTestGridSessionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetTestGridSessionErrorKind::ArgumentException(_inner) => Some(_inner),
GetTestGridSessionErrorKind::InternalServiceException(_inner) => Some(_inner),
GetTestGridSessionErrorKind::NotFoundException(_inner) => Some(_inner),
GetTestGridSessionErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetUploadError {
pub kind: GetUploadErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetUploadErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetUploadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetUploadErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetUploadErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
GetUploadErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetUploadErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetUploadErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetUploadError {
fn code(&self) -> Option<&str> {
GetUploadError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetUploadError {
pub fn new(kind: GetUploadErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetUploadErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetUploadErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, GetUploadErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, GetUploadErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, GetUploadErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, GetUploadErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for GetUploadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetUploadErrorKind::ArgumentException(_inner) => Some(_inner),
GetUploadErrorKind::LimitExceededException(_inner) => Some(_inner),
GetUploadErrorKind::NotFoundException(_inner) => Some(_inner),
GetUploadErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetUploadErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetVPCEConfigurationError {
pub kind: GetVPCEConfigurationErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetVPCEConfigurationErrorKind {
ArgumentException(crate::error::ArgumentException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetVPCEConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetVPCEConfigurationErrorKind::ArgumentException(_inner) => _inner.fmt(f),
GetVPCEConfigurationErrorKind::NotFoundException(_inner) => _inner.fmt(f),
GetVPCEConfigurationErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
GetVPCEConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for GetVPCEConfigurationError {
fn code(&self) -> Option<&str> {
GetVPCEConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl GetVPCEConfigurationError {
pub fn new(kind: GetVPCEConfigurationErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetVPCEConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetVPCEConfigurationErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
GetVPCEConfigurationErrorKind::ArgumentException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetVPCEConfigurationErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
GetVPCEConfigurationErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for GetVPCEConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetVPCEConfigurationErrorKind::ArgumentException(_inner) => Some(_inner),
GetVPCEConfigurationErrorKind::NotFoundException(_inner) => Some(_inner),
GetVPCEConfigurationErrorKind::ServiceAccountException(_inner) => Some(_inner),
GetVPCEConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct InstallToRemoteAccessSessionError {
pub kind: InstallToRemoteAccessSessionErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum InstallToRemoteAccessSessionErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for InstallToRemoteAccessSessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
InstallToRemoteAccessSessionErrorKind::ArgumentException(_inner) => _inner.fmt(f),
InstallToRemoteAccessSessionErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
InstallToRemoteAccessSessionErrorKind::NotFoundException(_inner) => _inner.fmt(f),
InstallToRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
InstallToRemoteAccessSessionErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for InstallToRemoteAccessSessionError {
fn code(&self) -> Option<&str> {
InstallToRemoteAccessSessionError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl InstallToRemoteAccessSessionError {
pub fn new(kind: InstallToRemoteAccessSessionErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: InstallToRemoteAccessSessionErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: InstallToRemoteAccessSessionErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
InstallToRemoteAccessSessionErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
InstallToRemoteAccessSessionErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
InstallToRemoteAccessSessionErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
InstallToRemoteAccessSessionErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for InstallToRemoteAccessSessionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
InstallToRemoteAccessSessionErrorKind::ArgumentException(_inner) => Some(_inner),
InstallToRemoteAccessSessionErrorKind::LimitExceededException(_inner) => Some(_inner),
InstallToRemoteAccessSessionErrorKind::NotFoundException(_inner) => Some(_inner),
InstallToRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => Some(_inner),
InstallToRemoteAccessSessionErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListArtifactsError {
pub kind: ListArtifactsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListArtifactsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListArtifactsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListArtifactsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListArtifactsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListArtifactsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListArtifactsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListArtifactsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListArtifactsError {
fn code(&self) -> Option<&str> {
ListArtifactsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListArtifactsError {
pub fn new(kind: ListArtifactsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListArtifactsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListArtifactsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListArtifactsErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListArtifactsErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListArtifactsErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListArtifactsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListArtifactsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListArtifactsErrorKind::ArgumentException(_inner) => Some(_inner),
ListArtifactsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListArtifactsErrorKind::NotFoundException(_inner) => Some(_inner),
ListArtifactsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListArtifactsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListDeviceInstancesError {
pub kind: ListDeviceInstancesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListDeviceInstancesErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListDeviceInstancesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListDeviceInstancesErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListDeviceInstancesErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListDeviceInstancesErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListDeviceInstancesErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListDeviceInstancesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListDeviceInstancesError {
fn code(&self) -> Option<&str> {
ListDeviceInstancesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListDeviceInstancesError {
pub fn new(kind: ListDeviceInstancesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListDeviceInstancesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListDeviceInstancesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListDeviceInstancesErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListDeviceInstancesErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListDeviceInstancesErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListDeviceInstancesErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListDeviceInstancesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListDeviceInstancesErrorKind::ArgumentException(_inner) => Some(_inner),
ListDeviceInstancesErrorKind::LimitExceededException(_inner) => Some(_inner),
ListDeviceInstancesErrorKind::NotFoundException(_inner) => Some(_inner),
ListDeviceInstancesErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListDeviceInstancesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListDevicePoolsError {
pub kind: ListDevicePoolsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListDevicePoolsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListDevicePoolsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListDevicePoolsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListDevicePoolsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListDevicePoolsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListDevicePoolsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListDevicePoolsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListDevicePoolsError {
fn code(&self) -> Option<&str> {
ListDevicePoolsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListDevicePoolsError {
pub fn new(kind: ListDevicePoolsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListDevicePoolsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListDevicePoolsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListDevicePoolsErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListDevicePoolsErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListDevicePoolsErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListDevicePoolsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListDevicePoolsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListDevicePoolsErrorKind::ArgumentException(_inner) => Some(_inner),
ListDevicePoolsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListDevicePoolsErrorKind::NotFoundException(_inner) => Some(_inner),
ListDevicePoolsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListDevicePoolsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListDevicesError {
pub kind: ListDevicesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListDevicesErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListDevicesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListDevicesErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListDevicesErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListDevicesErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListDevicesErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListDevicesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListDevicesError {
fn code(&self) -> Option<&str> {
ListDevicesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListDevicesError {
pub fn new(kind: ListDevicesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListDevicesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListDevicesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListDevicesErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ListDevicesErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListDevicesErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, ListDevicesErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for ListDevicesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListDevicesErrorKind::ArgumentException(_inner) => Some(_inner),
ListDevicesErrorKind::LimitExceededException(_inner) => Some(_inner),
ListDevicesErrorKind::NotFoundException(_inner) => Some(_inner),
ListDevicesErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListDevicesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListInstanceProfilesError {
pub kind: ListInstanceProfilesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListInstanceProfilesErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListInstanceProfilesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListInstanceProfilesErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListInstanceProfilesErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListInstanceProfilesErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListInstanceProfilesErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListInstanceProfilesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListInstanceProfilesError {
fn code(&self) -> Option<&str> {
ListInstanceProfilesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListInstanceProfilesError {
pub fn new(kind: ListInstanceProfilesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListInstanceProfilesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListInstanceProfilesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListInstanceProfilesErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListInstanceProfilesErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListInstanceProfilesErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListInstanceProfilesErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListInstanceProfilesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListInstanceProfilesErrorKind::ArgumentException(_inner) => Some(_inner),
ListInstanceProfilesErrorKind::LimitExceededException(_inner) => Some(_inner),
ListInstanceProfilesErrorKind::NotFoundException(_inner) => Some(_inner),
ListInstanceProfilesErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListInstanceProfilesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListJobsError {
pub kind: ListJobsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListJobsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListJobsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListJobsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListJobsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListJobsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListJobsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListJobsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListJobsError {
fn code(&self) -> Option<&str> {
ListJobsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListJobsError {
pub fn new(kind: ListJobsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListJobsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListJobsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListJobsErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ListJobsErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListJobsErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, ListJobsErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for ListJobsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListJobsErrorKind::ArgumentException(_inner) => Some(_inner),
ListJobsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListJobsErrorKind::NotFoundException(_inner) => Some(_inner),
ListJobsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListJobsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListNetworkProfilesError {
pub kind: ListNetworkProfilesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListNetworkProfilesErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListNetworkProfilesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListNetworkProfilesErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListNetworkProfilesErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListNetworkProfilesErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListNetworkProfilesErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListNetworkProfilesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListNetworkProfilesError {
fn code(&self) -> Option<&str> {
ListNetworkProfilesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListNetworkProfilesError {
pub fn new(kind: ListNetworkProfilesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListNetworkProfilesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListNetworkProfilesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListNetworkProfilesErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListNetworkProfilesErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListNetworkProfilesErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListNetworkProfilesErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListNetworkProfilesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListNetworkProfilesErrorKind::ArgumentException(_inner) => Some(_inner),
ListNetworkProfilesErrorKind::LimitExceededException(_inner) => Some(_inner),
ListNetworkProfilesErrorKind::NotFoundException(_inner) => Some(_inner),
ListNetworkProfilesErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListNetworkProfilesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListOfferingPromotionsError {
pub kind: ListOfferingPromotionsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListOfferingPromotionsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotEligibleException(crate::error::NotEligibleException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListOfferingPromotionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListOfferingPromotionsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListOfferingPromotionsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListOfferingPromotionsErrorKind::NotEligibleException(_inner) => _inner.fmt(f),
ListOfferingPromotionsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListOfferingPromotionsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListOfferingPromotionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListOfferingPromotionsError {
fn code(&self) -> Option<&str> {
ListOfferingPromotionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListOfferingPromotionsError {
pub fn new(kind: ListOfferingPromotionsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListOfferingPromotionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListOfferingPromotionsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingPromotionsErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingPromotionsErrorKind::LimitExceededException(_)
)
}
pub fn is_not_eligible_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingPromotionsErrorKind::NotEligibleException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingPromotionsErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingPromotionsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListOfferingPromotionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListOfferingPromotionsErrorKind::ArgumentException(_inner) => Some(_inner),
ListOfferingPromotionsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListOfferingPromotionsErrorKind::NotEligibleException(_inner) => Some(_inner),
ListOfferingPromotionsErrorKind::NotFoundException(_inner) => Some(_inner),
ListOfferingPromotionsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListOfferingPromotionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListOfferingsError {
pub kind: ListOfferingsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListOfferingsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotEligibleException(crate::error::NotEligibleException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListOfferingsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListOfferingsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListOfferingsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListOfferingsErrorKind::NotEligibleException(_inner) => _inner.fmt(f),
ListOfferingsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListOfferingsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListOfferingsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListOfferingsError {
fn code(&self) -> Option<&str> {
ListOfferingsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListOfferingsError {
pub fn new(kind: ListOfferingsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListOfferingsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListOfferingsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListOfferingsErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingsErrorKind::LimitExceededException(_)
)
}
pub fn is_not_eligible_exception(&self) -> bool {
matches!(&self.kind, ListOfferingsErrorKind::NotEligibleException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListOfferingsErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListOfferingsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListOfferingsErrorKind::ArgumentException(_inner) => Some(_inner),
ListOfferingsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListOfferingsErrorKind::NotEligibleException(_inner) => Some(_inner),
ListOfferingsErrorKind::NotFoundException(_inner) => Some(_inner),
ListOfferingsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListOfferingsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListOfferingTransactionsError {
pub kind: ListOfferingTransactionsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListOfferingTransactionsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotEligibleException(crate::error::NotEligibleException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListOfferingTransactionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListOfferingTransactionsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListOfferingTransactionsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListOfferingTransactionsErrorKind::NotEligibleException(_inner) => _inner.fmt(f),
ListOfferingTransactionsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListOfferingTransactionsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListOfferingTransactionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListOfferingTransactionsError {
fn code(&self) -> Option<&str> {
ListOfferingTransactionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListOfferingTransactionsError {
pub fn new(kind: ListOfferingTransactionsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListOfferingTransactionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListOfferingTransactionsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingTransactionsErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingTransactionsErrorKind::LimitExceededException(_)
)
}
pub fn is_not_eligible_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingTransactionsErrorKind::NotEligibleException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingTransactionsErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListOfferingTransactionsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListOfferingTransactionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListOfferingTransactionsErrorKind::ArgumentException(_inner) => Some(_inner),
ListOfferingTransactionsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListOfferingTransactionsErrorKind::NotEligibleException(_inner) => Some(_inner),
ListOfferingTransactionsErrorKind::NotFoundException(_inner) => Some(_inner),
ListOfferingTransactionsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListOfferingTransactionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListProjectsError {
pub kind: ListProjectsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListProjectsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListProjectsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListProjectsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListProjectsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListProjectsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListProjectsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListProjectsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListProjectsError {
fn code(&self) -> Option<&str> {
ListProjectsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListProjectsError {
pub fn new(kind: ListProjectsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListProjectsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListProjectsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListProjectsErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ListProjectsErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListProjectsErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListProjectsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListProjectsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListProjectsErrorKind::ArgumentException(_inner) => Some(_inner),
ListProjectsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListProjectsErrorKind::NotFoundException(_inner) => Some(_inner),
ListProjectsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListProjectsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListRemoteAccessSessionsError {
pub kind: ListRemoteAccessSessionsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListRemoteAccessSessionsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListRemoteAccessSessionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListRemoteAccessSessionsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListRemoteAccessSessionsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListRemoteAccessSessionsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListRemoteAccessSessionsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListRemoteAccessSessionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListRemoteAccessSessionsError {
fn code(&self) -> Option<&str> {
ListRemoteAccessSessionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListRemoteAccessSessionsError {
pub fn new(kind: ListRemoteAccessSessionsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListRemoteAccessSessionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListRemoteAccessSessionsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListRemoteAccessSessionsErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListRemoteAccessSessionsErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListRemoteAccessSessionsErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListRemoteAccessSessionsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListRemoteAccessSessionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListRemoteAccessSessionsErrorKind::ArgumentException(_inner) => Some(_inner),
ListRemoteAccessSessionsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListRemoteAccessSessionsErrorKind::NotFoundException(_inner) => Some(_inner),
ListRemoteAccessSessionsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListRemoteAccessSessionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListRunsError {
pub kind: ListRunsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListRunsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListRunsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListRunsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListRunsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListRunsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListRunsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListRunsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListRunsError {
fn code(&self) -> Option<&str> {
ListRunsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListRunsError {
pub fn new(kind: ListRunsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListRunsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListRunsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListRunsErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ListRunsErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListRunsErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, ListRunsErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for ListRunsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListRunsErrorKind::ArgumentException(_inner) => Some(_inner),
ListRunsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListRunsErrorKind::NotFoundException(_inner) => Some(_inner),
ListRunsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListRunsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListSamplesError {
pub kind: ListSamplesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListSamplesErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListSamplesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListSamplesErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListSamplesErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListSamplesErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListSamplesErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListSamplesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListSamplesError {
fn code(&self) -> Option<&str> {
ListSamplesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListSamplesError {
pub fn new(kind: ListSamplesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListSamplesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListSamplesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListSamplesErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ListSamplesErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListSamplesErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, ListSamplesErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for ListSamplesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListSamplesErrorKind::ArgumentException(_inner) => Some(_inner),
ListSamplesErrorKind::LimitExceededException(_inner) => Some(_inner),
ListSamplesErrorKind::NotFoundException(_inner) => Some(_inner),
ListSamplesErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListSamplesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListSuitesError {
pub kind: ListSuitesErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListSuitesErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListSuitesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListSuitesErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListSuitesErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListSuitesErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListSuitesErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListSuitesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListSuitesError {
fn code(&self) -> Option<&str> {
ListSuitesError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListSuitesError {
pub fn new(kind: ListSuitesErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListSuitesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListSuitesErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListSuitesErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ListSuitesErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListSuitesErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, ListSuitesErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for ListSuitesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListSuitesErrorKind::ArgumentException(_inner) => Some(_inner),
ListSuitesErrorKind::LimitExceededException(_inner) => Some(_inner),
ListSuitesErrorKind::NotFoundException(_inner) => Some(_inner),
ListSuitesErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListSuitesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListTagsForResourceError {
pub kind: ListTagsForResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListTagsForResourceErrorKind {
ArgumentException(crate::error::ArgumentException),
NotFoundException(crate::error::NotFoundException),
TagOperationException(crate::error::TagOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListTagsForResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListTagsForResourceErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListTagsForResourceErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListTagsForResourceErrorKind::TagOperationException(_inner) => _inner.fmt(f),
ListTagsForResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListTagsForResourceError {
fn code(&self) -> Option<&str> {
ListTagsForResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListTagsForResourceError {
pub fn new(kind: ListTagsForResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListTagsForResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListTagsForResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListTagsForResourceErrorKind::ArgumentException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListTagsForResourceErrorKind::NotFoundException(_)
)
}
pub fn is_tag_operation_exception(&self) -> bool {
matches!(
&self.kind,
ListTagsForResourceErrorKind::TagOperationException(_)
)
}
}
impl std::error::Error for ListTagsForResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTagsForResourceErrorKind::ArgumentException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::NotFoundException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::TagOperationException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListTestGridProjectsError {
pub kind: ListTestGridProjectsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListTestGridProjectsErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListTestGridProjectsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListTestGridProjectsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListTestGridProjectsErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
ListTestGridProjectsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListTestGridProjectsError {
fn code(&self) -> Option<&str> {
ListTestGridProjectsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListTestGridProjectsError {
pub fn new(kind: ListTestGridProjectsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListTestGridProjectsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListTestGridProjectsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridProjectsErrorKind::ArgumentException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridProjectsErrorKind::InternalServiceException(_)
)
}
}
impl std::error::Error for ListTestGridProjectsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTestGridProjectsErrorKind::ArgumentException(_inner) => Some(_inner),
ListTestGridProjectsErrorKind::InternalServiceException(_inner) => Some(_inner),
ListTestGridProjectsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListTestGridSessionActionsError {
pub kind: ListTestGridSessionActionsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListTestGridSessionActionsErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
NotFoundException(crate::error::NotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListTestGridSessionActionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListTestGridSessionActionsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListTestGridSessionActionsErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
ListTestGridSessionActionsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListTestGridSessionActionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListTestGridSessionActionsError {
fn code(&self) -> Option<&str> {
ListTestGridSessionActionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListTestGridSessionActionsError {
pub fn new(kind: ListTestGridSessionActionsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListTestGridSessionActionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListTestGridSessionActionsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionActionsErrorKind::ArgumentException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionActionsErrorKind::InternalServiceException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionActionsErrorKind::NotFoundException(_)
)
}
}
impl std::error::Error for ListTestGridSessionActionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTestGridSessionActionsErrorKind::ArgumentException(_inner) => Some(_inner),
ListTestGridSessionActionsErrorKind::InternalServiceException(_inner) => Some(_inner),
ListTestGridSessionActionsErrorKind::NotFoundException(_inner) => Some(_inner),
ListTestGridSessionActionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListTestGridSessionArtifactsError {
pub kind: ListTestGridSessionArtifactsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListTestGridSessionArtifactsErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
NotFoundException(crate::error::NotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListTestGridSessionArtifactsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListTestGridSessionArtifactsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListTestGridSessionArtifactsErrorKind::InternalServiceException(_inner) => {
_inner.fmt(f)
}
ListTestGridSessionArtifactsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListTestGridSessionArtifactsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListTestGridSessionArtifactsError {
fn code(&self) -> Option<&str> {
ListTestGridSessionArtifactsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListTestGridSessionArtifactsError {
pub fn new(kind: ListTestGridSessionArtifactsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListTestGridSessionArtifactsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListTestGridSessionArtifactsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionArtifactsErrorKind::ArgumentException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionArtifactsErrorKind::InternalServiceException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionArtifactsErrorKind::NotFoundException(_)
)
}
}
impl std::error::Error for ListTestGridSessionArtifactsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTestGridSessionArtifactsErrorKind::ArgumentException(_inner) => Some(_inner),
ListTestGridSessionArtifactsErrorKind::InternalServiceException(_inner) => Some(_inner),
ListTestGridSessionArtifactsErrorKind::NotFoundException(_inner) => Some(_inner),
ListTestGridSessionArtifactsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListTestGridSessionsError {
pub kind: ListTestGridSessionsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListTestGridSessionsErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
NotFoundException(crate::error::NotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListTestGridSessionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListTestGridSessionsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListTestGridSessionsErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
ListTestGridSessionsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListTestGridSessionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListTestGridSessionsError {
fn code(&self) -> Option<&str> {
ListTestGridSessionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListTestGridSessionsError {
pub fn new(kind: ListTestGridSessionsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListTestGridSessionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListTestGridSessionsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionsErrorKind::ArgumentException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionsErrorKind::InternalServiceException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListTestGridSessionsErrorKind::NotFoundException(_)
)
}
}
impl std::error::Error for ListTestGridSessionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTestGridSessionsErrorKind::ArgumentException(_inner) => Some(_inner),
ListTestGridSessionsErrorKind::InternalServiceException(_inner) => Some(_inner),
ListTestGridSessionsErrorKind::NotFoundException(_inner) => Some(_inner),
ListTestGridSessionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListTestsError {
pub kind: ListTestsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListTestsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListTestsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListTestsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListTestsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListTestsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListTestsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListTestsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListTestsError {
fn code(&self) -> Option<&str> {
ListTestsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListTestsError {
pub fn new(kind: ListTestsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListTestsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListTestsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListTestsErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ListTestsErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListTestsErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, ListTestsErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for ListTestsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTestsErrorKind::ArgumentException(_inner) => Some(_inner),
ListTestsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListTestsErrorKind::NotFoundException(_inner) => Some(_inner),
ListTestsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListTestsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListUniqueProblemsError {
pub kind: ListUniqueProblemsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListUniqueProblemsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListUniqueProblemsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListUniqueProblemsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListUniqueProblemsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListUniqueProblemsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListUniqueProblemsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListUniqueProblemsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListUniqueProblemsError {
fn code(&self) -> Option<&str> {
ListUniqueProblemsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListUniqueProblemsError {
pub fn new(kind: ListUniqueProblemsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListUniqueProblemsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListUniqueProblemsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListUniqueProblemsErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListUniqueProblemsErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListUniqueProblemsErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListUniqueProblemsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListUniqueProblemsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListUniqueProblemsErrorKind::ArgumentException(_inner) => Some(_inner),
ListUniqueProblemsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListUniqueProblemsErrorKind::NotFoundException(_inner) => Some(_inner),
ListUniqueProblemsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListUniqueProblemsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListUploadsError {
pub kind: ListUploadsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListUploadsErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListUploadsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListUploadsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListUploadsErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ListUploadsErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ListUploadsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListUploadsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListUploadsError {
fn code(&self) -> Option<&str> {
ListUploadsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListUploadsError {
pub fn new(kind: ListUploadsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListUploadsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListUploadsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ListUploadsErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ListUploadsErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ListUploadsErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, ListUploadsErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for ListUploadsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListUploadsErrorKind::ArgumentException(_inner) => Some(_inner),
ListUploadsErrorKind::LimitExceededException(_inner) => Some(_inner),
ListUploadsErrorKind::NotFoundException(_inner) => Some(_inner),
ListUploadsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListUploadsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListVPCEConfigurationsError {
pub kind: ListVPCEConfigurationsErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListVPCEConfigurationsErrorKind {
ArgumentException(crate::error::ArgumentException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListVPCEConfigurationsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListVPCEConfigurationsErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ListVPCEConfigurationsErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ListVPCEConfigurationsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ListVPCEConfigurationsError {
fn code(&self) -> Option<&str> {
ListVPCEConfigurationsError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ListVPCEConfigurationsError {
pub fn new(kind: ListVPCEConfigurationsErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListVPCEConfigurationsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListVPCEConfigurationsErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
ListVPCEConfigurationsErrorKind::ArgumentException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
ListVPCEConfigurationsErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for ListVPCEConfigurationsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListVPCEConfigurationsErrorKind::ArgumentException(_inner) => Some(_inner),
ListVPCEConfigurationsErrorKind::ServiceAccountException(_inner) => Some(_inner),
ListVPCEConfigurationsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct PurchaseOfferingError {
pub kind: PurchaseOfferingErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum PurchaseOfferingErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotEligibleException(crate::error::NotEligibleException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for PurchaseOfferingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
PurchaseOfferingErrorKind::ArgumentException(_inner) => _inner.fmt(f),
PurchaseOfferingErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
PurchaseOfferingErrorKind::NotEligibleException(_inner) => _inner.fmt(f),
PurchaseOfferingErrorKind::NotFoundException(_inner) => _inner.fmt(f),
PurchaseOfferingErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
PurchaseOfferingErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for PurchaseOfferingError {
fn code(&self) -> Option<&str> {
PurchaseOfferingError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl PurchaseOfferingError {
pub fn new(kind: PurchaseOfferingErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: PurchaseOfferingErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: PurchaseOfferingErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, PurchaseOfferingErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
PurchaseOfferingErrorKind::LimitExceededException(_)
)
}
pub fn is_not_eligible_exception(&self) -> bool {
matches!(
&self.kind,
PurchaseOfferingErrorKind::NotEligibleException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, PurchaseOfferingErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
PurchaseOfferingErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for PurchaseOfferingError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
PurchaseOfferingErrorKind::ArgumentException(_inner) => Some(_inner),
PurchaseOfferingErrorKind::LimitExceededException(_inner) => Some(_inner),
PurchaseOfferingErrorKind::NotEligibleException(_inner) => Some(_inner),
PurchaseOfferingErrorKind::NotFoundException(_inner) => Some(_inner),
PurchaseOfferingErrorKind::ServiceAccountException(_inner) => Some(_inner),
PurchaseOfferingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct RenewOfferingError {
pub kind: RenewOfferingErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum RenewOfferingErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotEligibleException(crate::error::NotEligibleException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for RenewOfferingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
RenewOfferingErrorKind::ArgumentException(_inner) => _inner.fmt(f),
RenewOfferingErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
RenewOfferingErrorKind::NotEligibleException(_inner) => _inner.fmt(f),
RenewOfferingErrorKind::NotFoundException(_inner) => _inner.fmt(f),
RenewOfferingErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
RenewOfferingErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for RenewOfferingError {
fn code(&self) -> Option<&str> {
RenewOfferingError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl RenewOfferingError {
pub fn new(kind: RenewOfferingErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: RenewOfferingErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: RenewOfferingErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> |
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, RenewOfferingErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
RenewOfferingErrorKind::LimitExceededException(_)
)
}
pub fn is_not_eligible_exception(&self) -> bool {
matches!(&self.kind, RenewOfferingErrorKind::NotEligibleException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, RenewOfferingErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
RenewOfferingErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for RenewOfferingError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
RenewOfferingErrorKind::ArgumentException(_inner) => Some(_inner),
RenewOfferingErrorKind::LimitExceededException(_inner) => Some(_inner),
RenewOfferingErrorKind::NotEligibleException(_inner) => Some(_inner),
RenewOfferingErrorKind::NotFoundException(_inner) => Some(_inner),
RenewOfferingErrorKind::ServiceAccountException(_inner) => Some(_inner),
RenewOfferingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ScheduleRunError {
pub kind: ScheduleRunErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ScheduleRunErrorKind {
ArgumentException(crate::error::ArgumentException),
IdempotencyException(crate::error::IdempotencyException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ScheduleRunError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ScheduleRunErrorKind::ArgumentException(_inner) => _inner.fmt(f),
ScheduleRunErrorKind::IdempotencyException(_inner) => _inner.fmt(f),
ScheduleRunErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
ScheduleRunErrorKind::NotFoundException(_inner) => _inner.fmt(f),
ScheduleRunErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
ScheduleRunErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for ScheduleRunError {
fn code(&self) -> Option<&str> {
ScheduleRunError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl ScheduleRunError {
pub fn new(kind: ScheduleRunErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ScheduleRunErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ScheduleRunErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, ScheduleRunErrorKind::ArgumentException(_))
}
pub fn is_idempotency_exception(&self) -> bool {
matches!(&self.kind, ScheduleRunErrorKind::IdempotencyException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, ScheduleRunErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, ScheduleRunErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, ScheduleRunErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for ScheduleRunError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ScheduleRunErrorKind::ArgumentException(_inner) => Some(_inner),
ScheduleRunErrorKind::IdempotencyException(_inner) => Some(_inner),
ScheduleRunErrorKind::LimitExceededException(_inner) => Some(_inner),
ScheduleRunErrorKind::NotFoundException(_inner) => Some(_inner),
ScheduleRunErrorKind::ServiceAccountException(_inner) => Some(_inner),
ScheduleRunErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct StopJobError {
pub kind: StopJobErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum StopJobErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for StopJobError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
StopJobErrorKind::ArgumentException(_inner) => _inner.fmt(f),
StopJobErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
StopJobErrorKind::NotFoundException(_inner) => _inner.fmt(f),
StopJobErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
StopJobErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for StopJobError {
fn code(&self) -> Option<&str> {
StopJobError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl StopJobError {
pub fn new(kind: StopJobErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: StopJobErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: StopJobErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, StopJobErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, StopJobErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, StopJobErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, StopJobErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for StopJobError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
StopJobErrorKind::ArgumentException(_inner) => Some(_inner),
StopJobErrorKind::LimitExceededException(_inner) => Some(_inner),
StopJobErrorKind::NotFoundException(_inner) => Some(_inner),
StopJobErrorKind::ServiceAccountException(_inner) => Some(_inner),
StopJobErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct StopRemoteAccessSessionError {
pub kind: StopRemoteAccessSessionErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum StopRemoteAccessSessionErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for StopRemoteAccessSessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
StopRemoteAccessSessionErrorKind::ArgumentException(_inner) => _inner.fmt(f),
StopRemoteAccessSessionErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
StopRemoteAccessSessionErrorKind::NotFoundException(_inner) => _inner.fmt(f),
StopRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
StopRemoteAccessSessionErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for StopRemoteAccessSessionError {
fn code(&self) -> Option<&str> {
StopRemoteAccessSessionError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl StopRemoteAccessSessionError {
pub fn new(kind: StopRemoteAccessSessionErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: StopRemoteAccessSessionErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: StopRemoteAccessSessionErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
StopRemoteAccessSessionErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
StopRemoteAccessSessionErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
StopRemoteAccessSessionErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
StopRemoteAccessSessionErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for StopRemoteAccessSessionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
StopRemoteAccessSessionErrorKind::ArgumentException(_inner) => Some(_inner),
StopRemoteAccessSessionErrorKind::LimitExceededException(_inner) => Some(_inner),
StopRemoteAccessSessionErrorKind::NotFoundException(_inner) => Some(_inner),
StopRemoteAccessSessionErrorKind::ServiceAccountException(_inner) => Some(_inner),
StopRemoteAccessSessionErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct StopRunError {
pub kind: StopRunErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum StopRunErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for StopRunError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
StopRunErrorKind::ArgumentException(_inner) => _inner.fmt(f),
StopRunErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
StopRunErrorKind::NotFoundException(_inner) => _inner.fmt(f),
StopRunErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
StopRunErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for StopRunError {
fn code(&self) -> Option<&str> {
StopRunError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl StopRunError {
pub fn new(kind: StopRunErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: StopRunErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: StopRunErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, StopRunErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, StopRunErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, StopRunErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(&self.kind, StopRunErrorKind::ServiceAccountException(_))
}
}
impl std::error::Error for StopRunError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
StopRunErrorKind::ArgumentException(_inner) => Some(_inner),
StopRunErrorKind::LimitExceededException(_inner) => Some(_inner),
StopRunErrorKind::NotFoundException(_inner) => Some(_inner),
StopRunErrorKind::ServiceAccountException(_inner) => Some(_inner),
StopRunErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct TagResourceError {
pub kind: TagResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum TagResourceErrorKind {
ArgumentException(crate::error::ArgumentException),
NotFoundException(crate::error::NotFoundException),
TagOperationException(crate::error::TagOperationException),
TagPolicyException(crate::error::TagPolicyException),
TooManyTagsException(crate::error::TooManyTagsException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for TagResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
TagResourceErrorKind::ArgumentException(_inner) => _inner.fmt(f),
TagResourceErrorKind::NotFoundException(_inner) => _inner.fmt(f),
TagResourceErrorKind::TagOperationException(_inner) => _inner.fmt(f),
TagResourceErrorKind::TagPolicyException(_inner) => _inner.fmt(f),
TagResourceErrorKind::TooManyTagsException(_inner) => _inner.fmt(f),
TagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for TagResourceError {
fn code(&self) -> Option<&str> {
TagResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl TagResourceError {
pub fn new(kind: TagResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: TagResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: TagResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, TagResourceErrorKind::ArgumentException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, TagResourceErrorKind::NotFoundException(_))
}
pub fn is_tag_operation_exception(&self) -> bool {
matches!(&self.kind, TagResourceErrorKind::TagOperationException(_))
}
pub fn is_tag_policy_exception(&self) -> bool {
matches!(&self.kind, TagResourceErrorKind::TagPolicyException(_))
}
pub fn is_too_many_tags_exception(&self) -> bool {
matches!(&self.kind, TagResourceErrorKind::TooManyTagsException(_))
}
}
impl std::error::Error for TagResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
TagResourceErrorKind::ArgumentException(_inner) => Some(_inner),
TagResourceErrorKind::NotFoundException(_inner) => Some(_inner),
TagResourceErrorKind::TagOperationException(_inner) => Some(_inner),
TagResourceErrorKind::TagPolicyException(_inner) => Some(_inner),
TagResourceErrorKind::TooManyTagsException(_inner) => Some(_inner),
TagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UntagResourceError {
pub kind: UntagResourceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UntagResourceErrorKind {
ArgumentException(crate::error::ArgumentException),
NotFoundException(crate::error::NotFoundException),
TagOperationException(crate::error::TagOperationException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UntagResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UntagResourceErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::TagOperationException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UntagResourceError {
fn code(&self) -> Option<&str> {
UntagResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UntagResourceError {
pub fn new(kind: UntagResourceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UntagResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UntagResourceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, UntagResourceErrorKind::ArgumentException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, UntagResourceErrorKind::NotFoundException(_))
}
pub fn is_tag_operation_exception(&self) -> bool {
matches!(&self.kind, UntagResourceErrorKind::TagOperationException(_))
}
}
impl std::error::Error for UntagResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UntagResourceErrorKind::ArgumentException(_inner) => Some(_inner),
UntagResourceErrorKind::NotFoundException(_inner) => Some(_inner),
UntagResourceErrorKind::TagOperationException(_inner) => Some(_inner),
UntagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateDeviceInstanceError {
pub kind: UpdateDeviceInstanceErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateDeviceInstanceErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateDeviceInstanceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateDeviceInstanceErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UpdateDeviceInstanceErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
UpdateDeviceInstanceErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UpdateDeviceInstanceErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
UpdateDeviceInstanceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateDeviceInstanceError {
fn code(&self) -> Option<&str> {
UpdateDeviceInstanceError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateDeviceInstanceError {
pub fn new(kind: UpdateDeviceInstanceErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateDeviceInstanceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateDeviceInstanceErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDeviceInstanceErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDeviceInstanceErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDeviceInstanceErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDeviceInstanceErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for UpdateDeviceInstanceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateDeviceInstanceErrorKind::ArgumentException(_inner) => Some(_inner),
UpdateDeviceInstanceErrorKind::LimitExceededException(_inner) => Some(_inner),
UpdateDeviceInstanceErrorKind::NotFoundException(_inner) => Some(_inner),
UpdateDeviceInstanceErrorKind::ServiceAccountException(_inner) => Some(_inner),
UpdateDeviceInstanceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateDevicePoolError {
pub kind: UpdateDevicePoolErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateDevicePoolErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateDevicePoolError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateDevicePoolErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UpdateDevicePoolErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
UpdateDevicePoolErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UpdateDevicePoolErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
UpdateDevicePoolErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateDevicePoolError {
fn code(&self) -> Option<&str> {
UpdateDevicePoolError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateDevicePoolError {
pub fn new(kind: UpdateDevicePoolErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateDevicePoolErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateDevicePoolErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, UpdateDevicePoolErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDevicePoolErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, UpdateDevicePoolErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDevicePoolErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for UpdateDevicePoolError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateDevicePoolErrorKind::ArgumentException(_inner) => Some(_inner),
UpdateDevicePoolErrorKind::LimitExceededException(_inner) => Some(_inner),
UpdateDevicePoolErrorKind::NotFoundException(_inner) => Some(_inner),
UpdateDevicePoolErrorKind::ServiceAccountException(_inner) => Some(_inner),
UpdateDevicePoolErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateInstanceProfileError {
pub kind: UpdateInstanceProfileErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateInstanceProfileErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateInstanceProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateInstanceProfileErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UpdateInstanceProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
UpdateInstanceProfileErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UpdateInstanceProfileErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
UpdateInstanceProfileErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateInstanceProfileError {
fn code(&self) -> Option<&str> {
UpdateInstanceProfileError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateInstanceProfileError {
pub fn new(kind: UpdateInstanceProfileErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateInstanceProfileErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateInstanceProfileErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInstanceProfileErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInstanceProfileErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInstanceProfileErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInstanceProfileErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for UpdateInstanceProfileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateInstanceProfileErrorKind::ArgumentException(_inner) => Some(_inner),
UpdateInstanceProfileErrorKind::LimitExceededException(_inner) => Some(_inner),
UpdateInstanceProfileErrorKind::NotFoundException(_inner) => Some(_inner),
UpdateInstanceProfileErrorKind::ServiceAccountException(_inner) => Some(_inner),
UpdateInstanceProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateNetworkProfileError {
pub kind: UpdateNetworkProfileErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateNetworkProfileErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateNetworkProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateNetworkProfileErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UpdateNetworkProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
UpdateNetworkProfileErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UpdateNetworkProfileErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
UpdateNetworkProfileErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateNetworkProfileError {
fn code(&self) -> Option<&str> {
UpdateNetworkProfileError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateNetworkProfileError {
pub fn new(kind: UpdateNetworkProfileErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateNetworkProfileErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateNetworkProfileErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
UpdateNetworkProfileErrorKind::ArgumentException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateNetworkProfileErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateNetworkProfileErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
UpdateNetworkProfileErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for UpdateNetworkProfileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateNetworkProfileErrorKind::ArgumentException(_inner) => Some(_inner),
UpdateNetworkProfileErrorKind::LimitExceededException(_inner) => Some(_inner),
UpdateNetworkProfileErrorKind::NotFoundException(_inner) => Some(_inner),
UpdateNetworkProfileErrorKind::ServiceAccountException(_inner) => Some(_inner),
UpdateNetworkProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateProjectError {
pub kind: UpdateProjectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateProjectErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateProjectErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UpdateProjectErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
UpdateProjectErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UpdateProjectErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
UpdateProjectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateProjectError {
fn code(&self) -> Option<&str> {
UpdateProjectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateProjectError {
pub fn new(kind: UpdateProjectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateProjectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateProjectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, UpdateProjectErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateProjectErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, UpdateProjectErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
UpdateProjectErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for UpdateProjectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateProjectErrorKind::ArgumentException(_inner) => Some(_inner),
UpdateProjectErrorKind::LimitExceededException(_inner) => Some(_inner),
UpdateProjectErrorKind::NotFoundException(_inner) => Some(_inner),
UpdateProjectErrorKind::ServiceAccountException(_inner) => Some(_inner),
UpdateProjectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateTestGridProjectError {
pub kind: UpdateTestGridProjectErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateTestGridProjectErrorKind {
ArgumentException(crate::error::ArgumentException),
InternalServiceException(crate::error::InternalServiceException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateTestGridProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateTestGridProjectErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UpdateTestGridProjectErrorKind::InternalServiceException(_inner) => _inner.fmt(f),
UpdateTestGridProjectErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
UpdateTestGridProjectErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UpdateTestGridProjectErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateTestGridProjectError {
fn code(&self) -> Option<&str> {
UpdateTestGridProjectError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateTestGridProjectError {
pub fn new(kind: UpdateTestGridProjectErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateTestGridProjectErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateTestGridProjectErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
UpdateTestGridProjectErrorKind::ArgumentException(_)
)
}
pub fn is_internal_service_exception(&self) -> bool {
matches!(
&self.kind,
UpdateTestGridProjectErrorKind::InternalServiceException(_)
)
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateTestGridProjectErrorKind::LimitExceededException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateTestGridProjectErrorKind::NotFoundException(_)
)
}
}
impl std::error::Error for UpdateTestGridProjectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateTestGridProjectErrorKind::ArgumentException(_inner) => Some(_inner),
UpdateTestGridProjectErrorKind::InternalServiceException(_inner) => Some(_inner),
UpdateTestGridProjectErrorKind::LimitExceededException(_inner) => Some(_inner),
UpdateTestGridProjectErrorKind::NotFoundException(_inner) => Some(_inner),
UpdateTestGridProjectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateUploadError {
pub kind: UpdateUploadErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateUploadErrorKind {
ArgumentException(crate::error::ArgumentException),
LimitExceededException(crate::error::LimitExceededException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateUploadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateUploadErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UpdateUploadErrorKind::LimitExceededException(_inner) => _inner.fmt(f),
UpdateUploadErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UpdateUploadErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
UpdateUploadErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateUploadError {
fn code(&self) -> Option<&str> {
UpdateUploadError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateUploadError {
pub fn new(kind: UpdateUploadErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateUploadErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateUploadErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(&self.kind, UpdateUploadErrorKind::ArgumentException(_))
}
pub fn is_limit_exceeded_exception(&self) -> bool {
matches!(&self.kind, UpdateUploadErrorKind::LimitExceededException(_))
}
pub fn is_not_found_exception(&self) -> bool {
matches!(&self.kind, UpdateUploadErrorKind::NotFoundException(_))
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
UpdateUploadErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for UpdateUploadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateUploadErrorKind::ArgumentException(_inner) => Some(_inner),
UpdateUploadErrorKind::LimitExceededException(_inner) => Some(_inner),
UpdateUploadErrorKind::NotFoundException(_inner) => Some(_inner),
UpdateUploadErrorKind::ServiceAccountException(_inner) => Some(_inner),
UpdateUploadErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateVPCEConfigurationError {
pub kind: UpdateVPCEConfigurationErrorKind,
pub(crate) meta: smithy_types::Error,
}
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateVPCEConfigurationErrorKind {
ArgumentException(crate::error::ArgumentException),
InvalidOperationException(crate::error::InvalidOperationException),
NotFoundException(crate::error::NotFoundException),
ServiceAccountException(crate::error::ServiceAccountException),
/// An unexpected error, eg. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateVPCEConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateVPCEConfigurationErrorKind::ArgumentException(_inner) => _inner.fmt(f),
UpdateVPCEConfigurationErrorKind::InvalidOperationException(_inner) => _inner.fmt(f),
UpdateVPCEConfigurationErrorKind::NotFoundException(_inner) => _inner.fmt(f),
UpdateVPCEConfigurationErrorKind::ServiceAccountException(_inner) => _inner.fmt(f),
UpdateVPCEConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl smithy_types::retry::ProvideErrorKind for UpdateVPCEConfigurationError {
fn code(&self) -> Option<&str> {
UpdateVPCEConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateVPCEConfigurationError {
pub fn new(kind: UpdateVPCEConfigurationErrorKind, meta: smithy_types::Error) -> Self {
Self { kind, meta }
}
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateVPCEConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
pub fn generic(err: smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateVPCEConfigurationErrorKind::Unhandled(err.into()),
}
}
// Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display
// as implemented by std::Error to generate a message in that case.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
pub fn meta(&self) -> &smithy_types::Error {
&self.meta
}
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
pub fn is_argument_exception(&self) -> bool {
matches!(
&self.kind,
UpdateVPCEConfigurationErrorKind::ArgumentException(_)
)
}
pub fn is_invalid_operation_exception(&self) -> bool {
matches!(
&self.kind,
UpdateVPCEConfigurationErrorKind::InvalidOperationException(_)
)
}
pub fn is_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateVPCEConfigurationErrorKind::NotFoundException(_)
)
}
pub fn is_service_account_exception(&self) -> bool {
matches!(
&self.kind,
UpdateVPCEConfigurationErrorKind::ServiceAccountException(_)
)
}
}
impl std::error::Error for UpdateVPCEConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateVPCEConfigurationErrorKind::ArgumentException(_inner) => Some(_inner),
UpdateVPCEConfigurationErrorKind::InvalidOperationException(_inner) => Some(_inner),
UpdateVPCEConfigurationErrorKind::NotFoundException(_inner) => Some(_inner),
UpdateVPCEConfigurationErrorKind::ServiceAccountException(_inner) => Some(_inner),
UpdateVPCEConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// <p>There was a problem with the service account.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServiceAccountException {
/// <p>Any additional information about the exception.</p>
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ServiceAccountException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServiceAccountException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ServiceAccountException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ServiceAccountException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ServiceAccountException")?;
if let Some(inner_1) = &self.message {
write!(f, ": {}", inner_1)?;
}
Ok(())
}
}
impl std::error::Error for ServiceAccountException {}
/// See [`ServiceAccountException`](crate::error::ServiceAccountException)
pub mod service_account_exception {
/// A builder for [`ServiceAccountException`](crate::error::ServiceAccountException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Any additional information about the exception.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`ServiceAccountException`](crate::error::ServiceAccountException)
pub fn build(self) -> crate::error::ServiceAccountException {
crate::error::ServiceAccountException {
message: self.message,
}
}
}
}
impl ServiceAccountException {
/// Creates a new builder-style object to manufacture [`ServiceAccountException`](crate::error::ServiceAccountException)
pub fn builder() -> crate::error::service_account_exception::Builder {
crate::error::service_account_exception::Builder::default()
}
}
/// <p>The specified entity was not found.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct NotFoundException {
/// <p>Any additional information about the exception.</p>
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for NotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("NotFoundException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl NotFoundException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for NotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "NotFoundException")?;
if let Some(inner_2) = &self.message {
write!(f, ": {}", inner_2)?;
}
Ok(())
}
}
impl std::error::Error for NotFoundException {}
/// See [`NotFoundException`](crate::error::NotFoundException)
pub mod not_found_exception {
/// A builder for [`NotFoundException`](crate::error::NotFoundException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Any additional information about the exception.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`NotFoundException`](crate::error::NotFoundException)
pub fn build(self) -> crate::error::NotFoundException {
crate::error::NotFoundException {
message: self.message,
}
}
}
}
impl NotFoundException {
/// Creates a new builder-style object to manufacture [`NotFoundException`](crate::error::NotFoundException)
pub fn builder() -> crate::error::not_found_exception::Builder {
crate::error::not_found_exception::Builder::default()
}
}
/// <p>There was an error with the update request, or you do not have sufficient permissions
/// to update this VPC endpoint configuration.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidOperationException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InvalidOperationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidOperationException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidOperationException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidOperationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidOperationException")?;
if let Some(inner_3) = &self.message {
write!(f, ": {}", inner_3)?;
}
Ok(())
}
}
impl std::error::Error for InvalidOperationException {}
/// See [`InvalidOperationException`](crate::error::InvalidOperationException)
pub mod invalid_operation_exception {
/// A builder for [`InvalidOperationException`](crate::error::InvalidOperationException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`InvalidOperationException`](crate::error::InvalidOperationException)
pub fn build(self) -> crate::error::InvalidOperationException {
crate::error::InvalidOperationException {
message: self.message,
}
}
}
}
impl InvalidOperationException {
/// Creates a new builder-style object to manufacture [`InvalidOperationException`](crate::error::InvalidOperationException)
pub fn builder() -> crate::error::invalid_operation_exception::Builder {
crate::error::invalid_operation_exception::Builder::default()
}
}
/// <p>An invalid argument was specified.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ArgumentException {
/// <p>Any additional information about the exception.</p>
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ArgumentException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ArgumentException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ArgumentException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ArgumentException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ArgumentException")?;
if let Some(inner_4) = &self.message {
write!(f, ": {}", inner_4)?;
}
Ok(())
}
}
impl std::error::Error for ArgumentException {}
/// See [`ArgumentException`](crate::error::ArgumentException)
pub mod argument_exception {
/// A builder for [`ArgumentException`](crate::error::ArgumentException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Any additional information about the exception.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`ArgumentException`](crate::error::ArgumentException)
pub fn build(self) -> crate::error::ArgumentException {
crate::error::ArgumentException {
message: self.message,
}
}
}
}
impl ArgumentException {
/// Creates a new builder-style object to manufacture [`ArgumentException`](crate::error::ArgumentException)
pub fn builder() -> crate::error::argument_exception::Builder {
crate::error::argument_exception::Builder::default()
}
}
/// <p>A limit was exceeded.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct LimitExceededException {
/// <p>Any additional information about the exception.</p>
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for LimitExceededException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("LimitExceededException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl LimitExceededException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for LimitExceededException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "LimitExceededException")?;
if let Some(inner_5) = &self.message {
write!(f, ": {}", inner_5)?;
}
Ok(())
}
}
impl std::error::Error for LimitExceededException {}
/// See [`LimitExceededException`](crate::error::LimitExceededException)
pub mod limit_exceeded_exception {
/// A builder for [`LimitExceededException`](crate::error::LimitExceededException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Any additional information about the exception.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`LimitExceededException`](crate::error::LimitExceededException)
pub fn build(self) -> crate::error::LimitExceededException {
crate::error::LimitExceededException {
message: self.message,
}
}
}
}
impl LimitExceededException {
/// Creates a new builder-style object to manufacture [`LimitExceededException`](crate::error::LimitExceededException)
pub fn builder() -> crate::error::limit_exceeded_exception::Builder {
crate::error::limit_exceeded_exception::Builder::default()
}
}
/// <p>An internal exception was raised in the service. Contact <a href="mailto:[email protected]">[email protected]</a> if you see this
/// error. </p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InternalServiceException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InternalServiceException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InternalServiceException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InternalServiceException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InternalServiceException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InternalServiceException")?;
if let Some(inner_6) = &self.message {
write!(f, ": {}", inner_6)?;
}
Ok(())
}
}
impl std::error::Error for InternalServiceException {}
/// See [`InternalServiceException`](crate::error::InternalServiceException)
pub mod internal_service_exception {
/// A builder for [`InternalServiceException`](crate::error::InternalServiceException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`InternalServiceException`](crate::error::InternalServiceException)
pub fn build(self) -> crate::error::InternalServiceException {
crate::error::InternalServiceException {
message: self.message,
}
}
}
}
impl InternalServiceException {
/// Creates a new builder-style object to manufacture [`InternalServiceException`](crate::error::InternalServiceException)
pub fn builder() -> crate::error::internal_service_exception::Builder {
crate::error::internal_service_exception::Builder::default()
}
}
/// <p>The operation was not successful. Try again.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct TagOperationException {
pub message: std::option::Option<std::string::String>,
pub resource_name: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for TagOperationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("TagOperationException");
formatter.field("message", &self.message);
formatter.field("resource_name", &self.resource_name);
formatter.finish()
}
}
impl TagOperationException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for TagOperationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TagOperationException")?;
if let Some(inner_7) = &self.message {
write!(f, ": {}", inner_7)?;
}
Ok(())
}
}
impl std::error::Error for TagOperationException {}
/// See [`TagOperationException`](crate::error::TagOperationException)
pub mod tag_operation_exception {
/// A builder for [`TagOperationException`](crate::error::TagOperationException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
pub(crate) resource_name: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
pub fn resource_name(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_name = Some(input.into());
self
}
pub fn set_resource_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.resource_name = input;
self
}
/// Consumes the builder and constructs a [`TagOperationException`](crate::error::TagOperationException)
pub fn build(self) -> crate::error::TagOperationException {
crate::error::TagOperationException {
message: self.message,
resource_name: self.resource_name,
}
}
}
}
impl TagOperationException {
/// Creates a new builder-style object to manufacture [`TagOperationException`](crate::error::TagOperationException)
pub fn builder() -> crate::error::tag_operation_exception::Builder {
crate::error::tag_operation_exception::Builder::default()
}
}
/// <p>The list of tags on the repository is over the limit. The maximum number of tags that
/// can be applied to a repository is 50. </p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct TooManyTagsException {
pub message: std::option::Option<std::string::String>,
pub resource_name: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for TooManyTagsException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("TooManyTagsException");
formatter.field("message", &self.message);
formatter.field("resource_name", &self.resource_name);
formatter.finish()
}
}
impl TooManyTagsException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for TooManyTagsException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TooManyTagsException")?;
if let Some(inner_8) = &self.message {
write!(f, ": {}", inner_8)?;
}
Ok(())
}
}
impl std::error::Error for TooManyTagsException {}
/// See [`TooManyTagsException`](crate::error::TooManyTagsException)
pub mod too_many_tags_exception {
/// A builder for [`TooManyTagsException`](crate::error::TooManyTagsException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
pub(crate) resource_name: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
pub fn resource_name(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_name = Some(input.into());
self
}
pub fn set_resource_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.resource_name = input;
self
}
/// Consumes the builder and constructs a [`TooManyTagsException`](crate::error::TooManyTagsException)
pub fn build(self) -> crate::error::TooManyTagsException {
crate::error::TooManyTagsException {
message: self.message,
resource_name: self.resource_name,
}
}
}
}
impl TooManyTagsException {
/// Creates a new builder-style object to manufacture [`TooManyTagsException`](crate::error::TooManyTagsException)
pub fn builder() -> crate::error::too_many_tags_exception::Builder {
crate::error::too_many_tags_exception::Builder::default()
}
}
/// <p>The request doesn't comply with the AWS Identity and Access Management (IAM) tag
/// policy. Correct your request and then retry it.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct TagPolicyException {
pub message: std::option::Option<std::string::String>,
pub resource_name: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for TagPolicyException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("TagPolicyException");
formatter.field("message", &self.message);
formatter.field("resource_name", &self.resource_name);
formatter.finish()
}
}
impl TagPolicyException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for TagPolicyException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TagPolicyException")?;
if let Some(inner_9) = &self.message {
write!(f, ": {}", inner_9)?;
}
Ok(())
}
}
impl std::error::Error for TagPolicyException {}
/// See [`TagPolicyException`](crate::error::TagPolicyException)
pub mod tag_policy_exception {
/// A builder for [`TagPolicyException`](crate::error::TagPolicyException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
pub(crate) resource_name: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
pub fn resource_name(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_name = Some(input.into());
self
}
pub fn set_resource_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.resource_name = input;
self
}
/// Consumes the builder and constructs a [`TagPolicyException`](crate::error::TagPolicyException)
pub fn build(self) -> crate::error::TagPolicyException {
crate::error::TagPolicyException {
message: self.message,
resource_name: self.resource_name,
}
}
}
}
impl TagPolicyException {
/// Creates a new builder-style object to manufacture [`TagPolicyException`](crate::error::TagPolicyException)
pub fn builder() -> crate::error::tag_policy_exception::Builder {
crate::error::tag_policy_exception::Builder::default()
}
}
/// <p>An entity with the same name already exists.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct IdempotencyException {
/// <p>Any additional information about the exception.</p>
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for IdempotencyException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("IdempotencyException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl IdempotencyException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for IdempotencyException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "IdempotencyException")?;
if let Some(inner_10) = &self.message {
write!(f, ": {}", inner_10)?;
}
Ok(())
}
}
impl std::error::Error for IdempotencyException {}
/// See [`IdempotencyException`](crate::error::IdempotencyException)
pub mod idempotency_exception {
/// A builder for [`IdempotencyException`](crate::error::IdempotencyException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Any additional information about the exception.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`IdempotencyException`](crate::error::IdempotencyException)
pub fn build(self) -> crate::error::IdempotencyException {
crate::error::IdempotencyException {
message: self.message,
}
}
}
}
impl IdempotencyException {
/// Creates a new builder-style object to manufacture [`IdempotencyException`](crate::error::IdempotencyException)
pub fn builder() -> crate::error::idempotency_exception::Builder {
crate::error::idempotency_exception::Builder::default()
}
}
/// <p>Exception gets thrown when a user is not eligible to perform the specified
/// transaction.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct NotEligibleException {
/// <p>The HTTP response code of a Not Eligible exception.</p>
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for NotEligibleException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("NotEligibleException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl NotEligibleException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for NotEligibleException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "NotEligibleException")?;
if let Some(inner_11) = &self.message {
write!(f, ": {}", inner_11)?;
}
Ok(())
}
}
impl std::error::Error for NotEligibleException {}
/// See [`NotEligibleException`](crate::error::NotEligibleException)
pub mod not_eligible_exception {
/// A builder for [`NotEligibleException`](crate::error::NotEligibleException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The HTTP response code of a Not Eligible exception.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`NotEligibleException`](crate::error::NotEligibleException)
pub fn build(self) -> crate::error::NotEligibleException {
crate::error::NotEligibleException {
message: self.message,
}
}
}
}
impl NotEligibleException {
/// Creates a new builder-style object to manufacture [`NotEligibleException`](crate::error::NotEligibleException)
pub fn builder() -> crate::error::not_eligible_exception::Builder {
crate::error::not_eligible_exception::Builder::default()
}
}
/// <p>The requested object could not be deleted.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CannotDeleteException {
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for CannotDeleteException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CannotDeleteException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl CannotDeleteException {
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for CannotDeleteException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "CannotDeleteException")?;
if let Some(inner_12) = &self.message {
write!(f, ": {}", inner_12)?;
}
Ok(())
}
}
impl std::error::Error for CannotDeleteException {}
/// See [`CannotDeleteException`](crate::error::CannotDeleteException)
pub mod cannot_delete_exception {
/// A builder for [`CannotDeleteException`](crate::error::CannotDeleteException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`CannotDeleteException`](crate::error::CannotDeleteException)
pub fn build(self) -> crate::error::CannotDeleteException {
crate::error::CannotDeleteException {
message: self.message,
}
}
}
}
impl CannotDeleteException {
/// Creates a new builder-style object to manufacture [`CannotDeleteException`](crate::error::CannotDeleteException)
pub fn builder() -> crate::error::cannot_delete_exception::Builder {
crate::error::cannot_delete_exception::Builder::default()
}
}
| {
self.meta.request_id()
} |
index.js | import { parseNumber } from '../../helpers/index.js';
function parse(trailValue) {
return parseNumber(trailValue, 'Trail value must be a non-zero number.', {
allowZero: false,
});
}
| PARSER: parse,
};
export { TRAIL_VALUE }; | const TRAIL_VALUE = {
FLAGS: '--trail-value <value>',
DESCRIPTION:
'Distance the price must change direction and move in order to trigger trailing stop orders.', |
SingleBed.js | "use strict"; |
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var React = _interopRequireWildcard(require("react"));
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _default = (0, _createSvgIcon["default"])( /*#__PURE__*/React.createElement("path", {
d: "M20 12c0-1.1-.9-2-2-2V7c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v3c-1.1 0-2 .9-2 2v5h1.33L6 19h1l.67-2h8.67l.66 2h1l.67-2H20v-5zm-4-2h-3V7h3v3zM8 7h3v3H8V7zm-2 5h12v3H6v-3z"
}), 'SingleBed');
exports["default"] = _default; |
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); |
allocator.go | package allocation
import (
"fmt"
"sync"
"github.com/go-logr/logr"
"github.com/prometheus/common/model"
)
/*
Load balancer will serve on an HTTP server exposing /jobs/<job_id>/targets <- these are configured using least connection
Load balancer will need information about the collectors in order to set the URLs
Keep a Map of what each collector currently holds and update it based on new scrape target updates
*/
type TargetItem struct {
JobName string
Link LinkJSON
TargetURL string
Label model.LabelSet
Collector *collector
}
// Create a struct that holds collector - and jobs for that collector
// This struct will be parsed into endpoint with collector and jobs info
type collector struct {
Name string
NumTargets int
}
// Allocator makes decisions to distribute work among
// a number of OpenTelemetry collectors based on the number of targets.
// Users need to call SetTargets when they have new targets in their
// clusters and call Reshard to process the new targets and reshard.
type Allocator struct {
m sync.Mutex
targetsWaiting map[string]TargetItem // temp buffer to keep targets that are waiting to be processed
collectors map[string]*collector // all current collectors
TargetItems map[string]*TargetItem
log logr.Logger
}
// findNextCollector finds the next collector with less number of targets.
func (allocator *Allocator) findNextCollector() *collector {
var col *collector
for _, v := range allocator.collectors {
// If the initial collector is empty, set the initial collector to the first element of map
if col == nil {
col = v
} else {
if v.NumTargets < col.NumTargets {
col = v
}
}
}
return col
}
// SetTargets accepts the a list of targets that will be used to make
// load balancing decisions. This method should be called when where are
// new targets discovered or existing targets are shutdown.
func (allocator *Allocator) SetWaitingTargets(targets []TargetItem) {
// Dump old data
allocator.m.Lock()
defer allocator.m.Unlock()
allocator.targetsWaiting = make(map[string]TargetItem, len(targets))
// Set new data
for _, i := range targets {
allocator.targetsWaiting[i.JobName+i.TargetURL] = i
}
}
// SetCollectors sets the set of collectors with key=collectorName, value=Collector object.
// SetCollectors is called when Collectors are added or removed
func (allocator *Allocator) SetCollectors(collectors []string) {
log := allocator.log.WithValues("opentelemetry-targetallocator")
allocator.m.Lock()
defer allocator.m.Unlock()
if len(collectors) == 0 {
log.Info("No collector instances present")
return
}
for k := range allocator.collectors {
delete(allocator.collectors, k)
}
for _, i := range collectors {
allocator.collectors[i] = &collector{Name: i, NumTargets: 0}
}
}
// Reallocate needs to be called to process the new target updates.
// Until Reallocate is called, old targets will be served.
func (allocator *Allocator) AllocateTargets() {
allocator.m.Lock()
defer allocator.m.Unlock()
allocator.removeOutdatedTargets()
allocator.processWaitingTargets()
}
// ReallocateCollectors reallocates the targets among the new collector instances
func (allocator *Allocator) ReallocateCollectors() {
allocator.m.Lock()
defer allocator.m.Unlock()
allocator.TargetItems = make(map[string]*TargetItem)
allocator.processWaitingTargets()
}
// removeOutdatedTargets removes targets that are no longer available.
func (allocator *Allocator) removeOutdatedTargets() {
for k := range allocator.TargetItems {
if _, ok := allocator.targetsWaiting[k]; !ok {
allocator.collectors[allocator.TargetItems[k].Collector.Name].NumTargets--
delete(allocator.TargetItems, k)
}
}
}
// processWaitingTargets processes the newly set targets.
func (allocator *Allocator) processWaitingTargets() {
for k, v := range allocator.targetsWaiting {
if _, ok := allocator.TargetItems[k]; !ok {
col := allocator.findNextCollector()
allocator.TargetItems[k] = &v
targetItem := TargetItem{
JobName: v.JobName,
Link: LinkJSON{fmt.Sprintf("/jobs/%s/targets", v.JobName)},
TargetURL: v.TargetURL,
Label: v.Label,
Collector: col,
}
col.NumTargets++
allocator.TargetItems[v.JobName+v.TargetURL] = &targetItem
}
}
}
func NewAllocator(log logr.Logger) *Allocator | {
return &Allocator{
log: log,
targetsWaiting: make(map[string]TargetItem),
collectors: make(map[string]*collector),
TargetItems: make(map[string]*TargetItem),
}
} |
|
follow.dto.ts | import { ApiProperty } from '@nestjs/swagger'; | @IsString()
@ApiProperty({ type: String })
ownerId: string;
@IsString()
@ApiProperty({ type: String })
followOwnerId: string;
}
export class RemoveFollow {
@IsString()
@ApiProperty({ type: String })
ownerId: string;
@IsString()
@ApiProperty({ type: String })
followOwnerId: string;
} | import { IsString } from 'class-validator';
export class CreateFollow { |
train-nn.py | from __future__ import absolute_import, division, print_function
import sys
import pathlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
EPOCHS = 1000
# The patience parameter is the amount of epochs to check for improvement
EARLY_STOP = keras.callbacks.EarlyStopping(monitor='val_loss', patience=30)
class PrintDot(keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs):
if epoch % 100 == 0: print('')
print('.', end='')
def plot_history(history):
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
plt.figure()
plt.xlabel('Epoch')
plt.ylabel('Mean Abs Error [cost]')
plt.plot(hist['epoch'], hist['mean_absolute_error'],
label='Train Error')
plt.plot(hist['epoch'], hist['val_mean_absolute_error'],
label = 'Val Error')
plt.ylim([0,5])
plt.legend()
plt.figure()
plt.xlabel('Epoch')
plt.ylabel('Mean Square Error [$cost^2$]')
plt.plot(hist['epoch'], hist['mean_squared_error'],
label='Train Error')
plt.plot(hist['epoch'], hist['val_mean_squared_error'],
label = 'Val Error')
plt.ylim([0,20])
plt.legend()
plt.show()
# we hard-code the values instead of using stats so that integration with
# predictor using the model is easier
scaling = pd.DataFrame(data={
'min': [-10000, -10000, -10000, -2300, -2300, -2300, -6.0, -6.0, -6.0, -3.2, -3.2, -3.2],
'max': [ 10000, 10000, 10000, 2300, 2300, 2300, 6.0, 6.0, 6.0, 3.2, 3.2, 3.2],
}, index=[ 'x', 'y', 'z', 'vx', 'vy', 'vz', 'avx', 'avy', 'avz', 'roll', 'pitch', 'yaw'])
# scale to range [0, 1]
# TODO try polar coordinates. for velocity: https://math.stackexchange.com/questions/2444965/relationship-between-cartesian-velocity-and-polar-velocity
def scale(x):
return (x - scaling['min']) / (scaling['max'] - scaling['min'])
def build_model():
model = keras.Sequential([
layers.Dense(128, activation=tf.nn.relu, input_shape=[len(train_dataset.keys())]),
layers.Dense(128, activation=tf.nn.relu),
# these extra layers seem to hurt more than they help!
#layers.Dropout(0.01),
#layers.Dense(64, activation=tf.nn.relu),
# this doesn't work as well as a single 64-wide layer
#layers.Dense(12, activation=tf.nn.relu, input_shape=[len(train_dataset.keys())]),
#layers.Dense(12, activation=tf.nn.relu),
#layers.Dense(12, activation=tf.nn.relu),
#layers.Dense(12, activation=tf.nn.relu),
#layers.Dense(12, activation=tf.nn.relu),
layers.Dense(1)
])
#optimizer = tf.keras.optimizers.RMSprop(0.001)
optimizer = tf.train.AdamOptimizer(0.001)
model.compile(loss='mean_squared_error',
optimizer=optimizer,
metrics=['mean_absolute_error', 'mean_squared_error'])
return model
# should be the time.csv from generate-data's time binary
dataset_path = sys.argv[1]
column_names = ['cost', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'avx', 'avy', 'avz', 'roll', 'pitch', 'yaw']
raw_dataset = pd.read_csv(dataset_path, names=column_names,
na_values = "", #comment='\t',
sep=",", skipinitialspace=True)
# visualize the data!
pos_plot = sns.pairplot(raw_dataset[["cost", "x", "y", "z"]], diag_kind="kde")
pos_plot.savefig("./pos.fig.png")
vel_plot = sns.pairplot(raw_dataset[["cost", "vx", "vy", "vz"]], diag_kind="kde")
vel_plot.savefig("./vel.fig.png")
avel_plot = sns.pairplot(raw_dataset[["cost", "avx", "avy", "avz"]], diag_kind="kde")
avel_plot.savefig("./avel.fig.png")
rot_plot = sns.pairplot(raw_dataset[["cost", "roll", "pitch", "yaw"]], diag_kind="kde")
rot_plot.savefig("./rot.fig.png")
pos_rot_plot = sns.pairplot(raw_dataset[["cost", "x", "y", "yaw"]], diag_kind="kde")
pos_rot_plot.savefig("./pos_rot.fig.png")
dataset = raw_dataset.copy()
dataset.tail()
# we don't have missing data
# dataset.isna().sum()
# dataset = dataset.dropna()
# split into training vs test datasets
train_dataset = dataset.sample(frac=0.95,random_state=0)
test_dataset = dataset.drop(train_dataset.index)
# using stats from full dataset
stats = raw_dataset.describe()
stats.pop("cost")
stats = stats.transpose() | test_labels = test_dataset.pop('cost')
scaled_train_dataset = scale(train_dataset)
scaled_test_dataset = scale(test_dataset)
# build and train moddel
model = build_model()
model.summary()
history = model.fit(scaled_train_dataset, train_labels, epochs=EPOCHS,
validation_split = 0.2, verbose=0, callbacks=[EARLY_STOP, PrintDot()])
plot_history(history)
# check against test set
loss, mae, mse = model.evaluate(scaled_test_dataset, test_labels, verbose=0)
print("Testing set Mean Abs Error: {:5.2f} cost".format(mae))
# plot all test predictions
test_predictions = model.predict(scaled_test_dataset).flatten()
plt.scatter(test_labels, test_predictions)
plt.xlabel('True Values [cost]')
plt.ylabel('Predictions [cost]')
plt.axis('equal')
plt.axis('square')
plt.xlim([0,plt.xlim()[1]])
plt.ylim([0,plt.ylim()[1]])
plt.plot([-100, 100], [-100, 100])
plt.show()
# error distribution
error = test_predictions - test_labels
plt.hist(error, bins = 25)
plt.xlabel("Prediction Error [cost]")
plt.ylabel("Count")
plt.show()
model.save('./simple_throttle_cost_model.h5')
saved_model_path = tf.contrib.saved_model.save_keras_model(model, "./simple_throttle_cost_saved_model") | stats
train_labels = train_dataset.pop('cost') |
protocol.py | # -*- test-case-name: vumi.transports.smpp.tests.test_protocol -*-
from functools import wraps
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet.task import LoopingCall
from twisted.internet.defer import (
inlineCallbacks, returnValue, maybeDeferred, DeferredQueue, succeed)
from smpp.pdu import unpack_pdu
from smpp.pdu_builder import (
BindTransceiver, BindReceiver, BindTransmitter,
UnbindResp, Unbind,
DeliverSMResp,
EnquireLink, EnquireLinkResp,
SubmitSM, QuerySM)
from vumi.transports.smpp.pdu_utils import (
pdu_ok, seq_no, command_status, command_id, message_id, chop_pdu_stream)
def require_bind(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.is_bound():
raise EsmeProtocolError('%s called in unbound state.' % (func,))
return func(self, *args, **kwargs)
return wrapper
class EsmeProtocolError(Exception):
pass
class EsmeProtocol(Protocol):
noisy = True
unbind_timeout = 2
OPEN_STATE = 'OPEN'
CLOSED_STATE = 'CLOSED'
BOUND_STATE_TRX = 'BOUND_TRX'
BOUND_STATE_TX = 'BOUND_TX'
BOUND_STATE_RX = 'BOUND_RX'
BOUND_STATES = set([
BOUND_STATE_RX,
BOUND_STATE_TX,
BOUND_STATE_TRX,
])
_BIND_PDU = {
'TX': BindTransmitter,
'RX': BindReceiver,
'TRX': BindTransceiver,
}
def __init__(self, service, bind_type):
"""
An SMPP 3.4 client suitable for use by a Vumi Transport.
:param SmppService service:
The SMPP service that is using this protocol to communicate with an
SMSC.
"""
self.service = service
self.log = service.log
self.bind_pdu = self._BIND_PDU[bind_type]
self.clock = service.clock
self.config = self.service.get_config()
self.buffer = b''
self.state = self.CLOSED_STATE
self.deliver_sm_processor = self.service.deliver_sm_processor
self.dr_processor = self.service.dr_processor
self.sequence_generator = self.service.sequence_generator
self.enquire_link_call = LoopingCall(self.enquire_link)
self.drop_link_call = None
self.idle_timeout = self.config.smpp_enquire_link_interval * 2
self.disconnect_call = None
self.unbind_resp_queue = DeferredQueue()
def emit(self, msg):
if self.noisy:
self.log.debug(msg)
@inlineCallbacks
def connectionMade(self):
self.state = self.OPEN_STATE
self.log.msg('Connection made, current state: %s' % (self.state,))
self.bind(
system_id=self.config.system_id,
password=self.config.password,
system_type=self.config.system_type,
interface_version=self.config.interface_version,
address_range=self.config.address_range)
yield self.service.on_smpp_binding()
@inlineCallbacks
def | (self,
system_id,
password,
system_type,
interface_version='34',
addr_ton='',
addr_npi='',
address_range=''):
"""
Send the `bind_transmitter`, `bind_transceiver` or `bind_receiver`
PDU to the SMSC in order to establish the connection.
:param str system_id:
Identifies the ESME system requesting to bind.
:param str password:
The password may be used by the SMSC to authenticate the ESME
requesting to bind. If this is longer than 8 characters, it will be
truncated and a warning will be logged.
:param str system_type:
Identifies the type of ESME system requesting to bind
with the SMSC.
:param str interface_version:
Indicates the version of the SMPP protocol supported by the
ESME.
:param str addr_ton:
Indicates Type of Number of the ESME address.
:param str addr_npi:
Numbering Plan Indicator for ESME address.
:param str address_range:
The ESME address.
"""
# Overly long passwords should be truncated.
if len(password) > 8:
password = password[:8]
self.log.warning("Password longer than 8 characters, truncating.")
sequence_number = yield self.sequence_generator.next()
pdu = self.bind_pdu(
sequence_number, system_id=system_id, password=password,
system_type=system_type, interface_version=interface_version,
addr_ton=addr_ton, addr_npi=addr_npi, address_range=address_range)
self.send_pdu(pdu)
self.drop_link_call = self.clock.callLater(
self.config.smpp_bind_timeout, self.drop_link)
@inlineCallbacks
def drop_link(self):
"""
Called if the SMPP connection is not bound within
``smpp_bind_timeout`` amount of seconds
"""
if self.is_bound():
return
yield self.service.on_smpp_bind_timeout()
yield self.disconnect(
'Dropping link due to binding delay. Current state: %s' % (
self.state))
def disconnect(self, log_msg=None):
"""
Forcibly close the connection, logging ``log_msg`` if provided.
:param str log_msg:
The entry to write to the log file.
"""
if log_msg is not None:
self.log.info(log_msg)
if not self.connected:
return succeed(self.transport.loseConnection())
d = self.unbind()
d.addCallback(lambda _: self.unbind_resp_queue.get())
d.addBoth(lambda *a: self.transport.loseConnection())
# Give the SMSC a few seconds to respond with an unbind_resp
self.clock.callLater(self.unbind_timeout, d.cancel)
return d
def connectionLost(self, reason):
"""
:param Exception reason:
The reason for the connection closed, generally a
``ConnectionDone``
"""
self.state = self.CLOSED_STATE
if self.enquire_link_call.running:
self.enquire_link_call.stop()
if self.drop_link_call is not None and self.drop_link_call.active():
self.drop_link_call.cancel()
if self.disconnect_call is not None and self.disconnect_call.active():
self.disconnect_call.cancel()
return self.service.on_connection_lost(reason)
def is_bound(self):
"""
Returns ``True`` if the connection is in one of the known
values of ``self.BOUND_STATES``
"""
return self.state in self.BOUND_STATES
@require_bind
@inlineCallbacks
def enquire_link(self):
"""
Ping the SMSC to see if they're still around.
"""
sequence_number = yield self.sequence_generator.next()
self.send_pdu(EnquireLink(sequence_number))
returnValue(sequence_number)
def send_pdu(self, pdu):
"""
Send a PDU to the SMSC
:param smpp.pdu_builder.PDU pdu:
The PDU object to send.
"""
self.emit('OUTGOING >> %r' % (pdu.get_obj(),))
return self.transport.write(pdu.get_bin())
def dataReceived(self, data):
self.buffer += data
data = self.handle_buffer()
while data is not None:
self.on_pdu(unpack_pdu(data))
data = self.handle_buffer()
def handle_buffer(self):
pdu_found = chop_pdu_stream(self.buffer)
if pdu_found is None:
return
data, self.buffer = pdu_found
return data
def on_pdu(self, pdu):
"""
Handle a PDU that was received & decoded.
:param dict pdu:
The dict result one gets when calling ``smpp.pdu.unpack_pdu()``
on the received PDU
"""
self.emit('INCOMING << %r' % (pdu,))
handler = getattr(self, 'handle_%s' % (command_id(pdu),),
self.on_unsupported_command_id)
return maybeDeferred(handler, pdu)
def on_unsupported_command_id(self, pdu):
"""
Called when an SMPP PDU is received for which no handler function has
been defined.
:param dict pdu:
The dict result one gets when calling ``smpp.pdu.unpack_pdu()``
on the received PDU
"""
self.log.warning(
'Received unsupported SMPP command_id: %r' % (command_id(pdu),))
def handle_bind_transceiver_resp(self, pdu):
if not pdu_ok(pdu):
self.log.warning('Unable to bind: %r' % (command_status(pdu),))
self.transport.loseConnection()
return
self.state = self.BOUND_STATE_TRX
return self.on_smpp_bind(seq_no(pdu))
def handle_bind_transmitter_resp(self, pdu):
if not pdu_ok(pdu):
self.log.warning('Unable to bind: %r' % (command_status(pdu),))
self.transport.loseConnection()
return
self.state = self.BOUND_STATE_TX
return self.on_smpp_bind(seq_no(pdu))
def handle_bind_receiver_resp(self, pdu):
if not pdu_ok(pdu):
self.log.warning('Unable to bind: %r' % (command_status(pdu),))
self.transport.loseConnection()
return
self.state = self.BOUND_STATE_RX
return self.on_smpp_bind(seq_no(pdu))
def on_smpp_bind(self, sequence_number):
"""Called when the bind has been setup"""
self.drop_link_call.cancel()
self.disconnect_call = self.clock.callLater(
self.idle_timeout, self.disconnect,
'Disconnecting, no response from SMSC for longer '
'than %s seconds' % (self.idle_timeout,))
self.enquire_link_call.clock = self.clock
self.enquire_link_call.start(self.config.smpp_enquire_link_interval)
return self.service.on_smpp_bind()
def handle_unbind(self, pdu):
return self.send_pdu(UnbindResp(seq_no(pdu)))
def handle_submit_sm_resp(self, pdu):
return self.on_submit_sm_resp(
seq_no(pdu), message_id(pdu), command_status(pdu))
def on_submit_sm_resp(self, sequence_number, smpp_message_id,
command_status):
"""
Called when a ``submit_sm_resp`` command was received.
:param int sequence_number:
The sequence_number of the command, should correlate with the
sequence_number of the ``submit_sm`` command that this is a
response to.
:param str smpp_message_id:
The message id that the SMSC is using for this message.
This will be referred to in the delivery reports (if any).
:param str command_status:
The SMPP command_status for this command. Will determine if
the ``submit_sm`` command was successful or not. Refer to the
SMPP specification for full list of options.
"""
message_stash = self.service.message_stash
d = message_stash.get_sequence_number_message_id(sequence_number)
# only set the remote message id if the submission was successful, we
# use remote message ids for delivery reports, so we won't need remote
# message ids for failed submissions
if command_status == 'ESME_ROK':
d.addCallback(
message_stash.set_remote_message_id, smpp_message_id)
d.addCallback(
self._handle_submit_sm_resp_callback, smpp_message_id,
command_status, sequence_number)
return d
def _handle_submit_sm_resp_callback(self, message_id, smpp_message_id,
command_status, sequence_number):
if message_id is None:
# We have no message_id, so log a warning instead of calling the
# callback.
self.log.warning(
"Failed to retrieve message id for deliver_sm_resp."
" ack/nack from %s discarded." % self.service.transport_name)
else:
return self.service.handle_submit_sm_resp(
message_id, smpp_message_id, command_status, sequence_number)
@inlineCallbacks
def handle_deliver_sm(self, pdu):
# These operate before the PDUs ``short_message`` or
# ``message_payload`` fields have been string decoded.
# NOTE: order is important!
pdu_handler_chain = [
self.dr_processor.handle_delivery_report_pdu,
self.deliver_sm_processor.handle_multipart_pdu,
self.deliver_sm_processor.handle_ussd_pdu,
]
for handler in pdu_handler_chain:
handled = yield handler(pdu)
if handled:
self.send_pdu(DeliverSMResp(seq_no(pdu),
command_status='ESME_ROK'))
return
# At this point we either have a DR in the message payload
# or have a normal SMS that needs to be decoded and handled.
content_parts = self.deliver_sm_processor.decode_pdus([pdu])
if not all([isinstance(part, unicode) for part in content_parts]):
command_status = self.config.deliver_sm_decoding_error
self.log.msg(
'Not all parts of the PDU were able to be decoded. '
'Responding with %s.' % (command_status,),
parts=content_parts)
self.send_pdu(DeliverSMResp(seq_no(pdu),
command_status=command_status))
return
content = u''.join(content_parts)
was_cdr = yield self.dr_processor.handle_delivery_report_content(
content)
if was_cdr:
self.send_pdu(DeliverSMResp(seq_no(pdu),
command_status='ESME_ROK'))
return
handled = yield self.deliver_sm_processor.handle_short_message_pdu(pdu)
if handled:
self.send_pdu(DeliverSMResp(seq_no(pdu),
command_status="ESME_ROK"))
return
command_status = self.config.deliver_sm_decoding_error
self.log.warning(
'Unable to process message. '
'Responding with %s.' % (command_status,),
content=content, pdu=pdu.get_obj())
self.send_pdu(DeliverSMResp(seq_no(pdu),
command_status=command_status))
def handle_enquire_link(self, pdu):
return self.send_pdu(EnquireLinkResp(seq_no(pdu)))
def handle_enquire_link_resp(self, pdu):
self.disconnect_call.reset(self.idle_timeout)
@require_bind
@inlineCallbacks
def submit_sm(self,
vumi_message_id,
destination_addr,
source_addr='',
esm_class=0,
protocol_id=0,
priority_flag=0,
schedule_delivery_time='',
validity_period='',
replace_if_present=0,
data_coding=0,
sm_default_msg_id=0,
sm_length=0,
short_message='',
optional_parameters=None,
**configured_parameters
):
"""
Put a `submit_sm` command on the wire.
:param str source_addr:
Address of SME which originated this message.
If unknown leave blank.
:param str destination_addr:
Destination address of this short message.
For mobile terminated messages, this is the directory number
of the recipient MS.
:param str service_type:
The service_type parameter can be used to indicate the SMS
Application service associated with the message.
If unknown leave blank.
:param int source_addr_ton:
Type of Number for source address.
:param int source_addr_npi:
Numbering Plan Indicator for source address.
:param int dest_addr_ton:
Type of Number for destination.
:param int dest_addr_npi:
Numbering Plan Indicator for destination.
:param int esm_class:
Indicates Message Mode & Message Type.
:param int protocol_id:
Protocol Identifier. Network specific field.
:param int priority_flag:
Designates the priority level of the message.
:param str schedule_delivery_time:
The short message is to be scheduled by the SMSC for delivery.
Leave blank for immediate delivery.
:param str validity_period:
The validity period of this message.
Leave blank for SMSC default.
:param int registered_delivery:
Indicator to signify if an SMSC delivery receipt or an SME
acknowledgement is required.
:param int replace_if_present:
Flag indicating if submitted message should replace an
existing message.
:param int data_coding:
Defines the encoding scheme of the short message user data.
:param int sm_default_msg_id:
Indicates the short message to send from a list of pre- defined
('canned') short messages stored on the SMSC.
Leave blank if not using an SMSC canned message.
:param int sm_length:
Length in octets of the short_message user data.
This is automatically calculated and set during PDU encoding,
no need to specify.
:param int short_message:
Up to 254 octets of short message user data.
The exact physical limit for short_message size may vary
according to the underlying network.
Applications which need to send messages longer than 254
octets should use the message_payload parameter. In this
case the sm_length field should be set to zero.
:param dict optional_parameters:
keys and values to be embedded in the PDU as tag-length-values.
Refer to the SMPP specification and your SMSCs instructions
on what valid and suitable keys and values are.
:returns: list of 1 sequence number (int) for consistency with other
submit_sm calls.
:rtype: list
"""
configured_param_values = {
'service_type': self.config.service_type,
'source_addr_ton': self.config.source_addr_ton,
'source_addr_npi': self.config.source_addr_npi,
'dest_addr_ton': self.config.dest_addr_ton,
'dest_addr_npi': self.config.dest_addr_npi,
'registered_delivery': self.config.registered_delivery,
}
configured_param_values.update(configured_parameters)
sequence_number = yield self.sequence_generator.next()
pdu = SubmitSM(
sequence_number=sequence_number,
source_addr=source_addr,
destination_addr=destination_addr,
esm_class=esm_class,
protocol_id=protocol_id,
priority_flag=priority_flag,
schedule_delivery_time=schedule_delivery_time,
validity_period=validity_period,
replace_if_present=replace_if_present,
data_coding=data_coding,
sm_default_msg_id=sm_default_msg_id,
sm_length=sm_length,
short_message=short_message,
**configured_param_values)
if optional_parameters:
for key, value in optional_parameters.items():
pdu.add_optional_parameter(key, value)
yield self.send_submit_sm(vumi_message_id, pdu)
returnValue([sequence_number])
@inlineCallbacks
def send_submit_sm(self, vumi_message_id, pdu):
yield self.service.message_stash.cache_pdu(vumi_message_id, pdu)
yield self.service.message_stash.set_sequence_number_message_id(
seq_no(pdu.obj), vumi_message_id)
self.send_pdu(pdu)
@require_bind
@inlineCallbacks
def query_sm(self,
message_id,
source_addr_ton=0,
source_addr_npi=0,
source_addr=''
):
"""
Query the SMSC for the status of an earlier sent message.
:param str message_id:
Message ID of the message whose state is to be queried.
This must be the SMSC assigned Message ID allocated to the
original short message when submitted to the SMSC by the
submit_sm, data_sm or submit_multi command, and returned
in the response PDU by the SMSC.
:param int source_addr_ton:
Type of Number of message originator. This is used for
verification purposes, and must match that supplied in the
original request PDU (e.g. submit_sm).
:param int source_addr_npi:
Numbering Plan Identity of message originator. This is used
for verification purposes, and must match that supplied in
the original request PDU (e.g. submit_sm).
:param str source_addr:
Address of message originator.
This is used for verification purposes, and must match that
supplied in the original request PDU (e.g. submit_sm).
"""
sequence_number = yield self.sequence_generator.next()
pdu = QuerySM(
sequence_number=sequence_number,
message_id=message_id,
source_addr=source_addr,
source_addr_npi=source_addr_npi,
source_addr_ton=source_addr_ton)
self.send_pdu(pdu)
returnValue([sequence_number])
@inlineCallbacks
def unbind(self):
sequence_number = yield self.sequence_generator.next()
self.send_pdu(Unbind(sequence_number))
yield self.service.on_smpp_unbinding()
returnValue([sequence_number])
def handle_unbind_resp(self, pdu):
self.unbind_resp_queue.put(pdu)
class EsmeProtocolFactory(ClientFactory):
protocol = EsmeProtocol
def __init__(self, service, bind_type):
self.service = service
self.bind_type = bind_type
def buildProtocol(self, addr):
proto = self.protocol(self.service, self.bind_type)
proto.factory = self
return proto
| bind |
timestamp.rs | use serde;
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Timestamp(u64);
impl From<f64> for Timestamp {
fn from(t: f64) -> Self {
let micro_seconds = t * 1_000_000.0;
Timestamp(micro_seconds as u64)
}
}
impl Into<f64> for Timestamp {
fn into(self) -> f64 {
let seconds = (self.0 as f64) / 1_000_000.0;
seconds
}
}
impl Into<f64> for &Timestamp {
fn | (self) -> f64 {
let seconds = (self.0 as f64) / 1_000_000.0;
seconds
}
}
impl<'de> ::serde::Deserialize<'de> for Timestamp {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
use serde::de::Error as SerdeError;
let value = ::serde_json::Value::deserialize(deserializer)?;
if let Some(s) = value.as_str() {
s.parse::<f64>()
.map_err(|e| D::Error::custom(e))
.map(Into::into)
} else if let Some(f) = value.as_f64() {
Ok(f.into())
} else if let Some(u) = value.as_u64() {
Ok((u as f64).into())
} else {
Err(D::Error::custom(format!(
"expected a timestamp but got: {}",
value.to_string()
)))
}
}
}
impl Timestamp {
pub fn to_param_value(&self) -> String {
let t: f64 = self.into();
serde_json::to_string(&t).unwrap()
}
}
| into |
mod.rs | mod atoms;
mod full;
mod mapped;
mod parts;
use super::models::{KeyAuthorization, KeysFile, KeysFileLine};
use std::str::FromStr;
impl FromStr for KeyAuthorization {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
full::key_authorization(s)
.map(|(_, res)| res)
.map_err(|e| match e {
nom::Err::Incomplete(_) => unreachable!(),
nom::Err::Error(err) | nom::Err::Failure(err) => err.0.to_string(),
})
}
}
impl FromStr for KeysFile {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let in_lines = s.lines().enumerate().collect::<Vec<_>>();
let mut lines: Vec<KeysFileLine> = Vec::with_capacity(in_lines.len());
for (line_no, line) in in_lines {
let comment_indicator = line.chars().skip_while(char::is_ascii_whitespace).next();
// line was all whitespace, or first non-whitespace was comment char | KeysFileLine::Comment(line.to_owned())
} else {
match line.parse() {
Ok(authorization) => KeysFileLine::Key(authorization),
Err(e) => return Err(format!("failed to parse line {}: {}", line_no, e)),
}
},
);
}
Ok(Self { lines })
}
} | lines.push(
if comment_indicator == None || comment_indicator == Some('#') { |
nav-panel.tsx | import * as React from "react"
import styled from "styled-components"
import { Link } from "gatsby-plugin-intl"
const Wrap = styled.nav`
display: flex;
flex-direction: column;
background-color: #f2f2f2;
border-left: 1px solid #d5d5d5;
width: 350px;
min-height: 100vh;
`
const WrapInner = styled.div`
position: fixed;
top: 50px;
`
const Elements = styled.ul`
list-style: none;
margin: 0;
padding: 10px 0;
`
const Element = styled.li`
margin: 0;
padding: 5px 10px;
font-size: 16px;
cursor: pointer;
&:hover {
color: #6a6a6a;
}
.link {
border-left: 4px solid transparent;
color: black;
text-decoration: none;
padding-left: 12px;
display: block;
height: 100%;
:hover {
color: #838383;
}
}
.link-active {
border-left: 4px solid #61DAFB;
font-weight: bold;
}
`
export type TElement = {
id: number | string;
label: React.ReactNode;
link: string;
}
interface IProps {
elements: Array<TElement>
}
const NavPanel = React.memo(({ elements }: IProps) => { | <Wrap>
<WrapInner>
<Elements>
{elements.map(({ id, label, link }) => (
<Element key={id}>
<Link to={link} className="link" activeClassName="link-active">
{label}
</Link>
</Element>
))}
</Elements>
</WrapInner>
</Wrap>
)
})
export default NavPanel |
return ( |
sensu-client.go | package main
import (
"log"
"github.com/upfluence/sensu-go/sensu/transport/rabbitmq"
"github.com/upfluence/sensu-client-go/sensu"
)
func main() | {
cfg, err := sensu.NewConfigFromFlagSet(sensu.ExtractFlags())
if err != nil {
log.Fatal(err.Error())
}
t, err := rabbitmq.NewRabbitMQTransport(cfg.RabbitMQURI())
if err != nil {
log.Fatal(err.Error())
}
client := sensu.NewClient(t, cfg)
client.Start()
} |
|
78922.rs | fn | () {
std::<0>
}
| main |
kucoin.py | # -*- coding:utf-8 -*-
"""
Kucoin Trade module.
https://docs.kucoin.com
Author: HuangTao
Date: 2019/08/01
Email: [email protected]
"""
import json
import copy
import hmac
import base64
import hashlib
from urllib.parse import urljoin
from quant.error import Error
from quant.utils import tools
from quant.utils import logger
from quant.const import KUCOIN
from quant.order import Order
from quant.asset import Asset, AssetSubscribe
from quant.tasks import SingleTask, LoopRunTask
from quant.utils.http_client import AsyncHttpRequests
from quant.utils.decorator import async_method_locker
from quant.order import ORDER_TYPE_LIMIT, ORDER_TYPE_MARKET
from quant.order import ORDER_ACTION_BUY, ORDER_ACTION_SELL
from quant.order import ORDER_STATUS_SUBMITTED, ORDER_STATUS_PARTIAL_FILLED, ORDER_STATUS_FILLED, \
ORDER_STATUS_CANCELED, ORDER_STATUS_FAILED, ORDER_STATUS_NONE
__all__ = ("KucoinRestAPI", "KucoinTrade", )
class KucoinRestAPI:
""" Kucoin REST API client.
Attributes:
host: HTTP request host.
access_key: Account"s ACCESS KEY.
secret_key: Account"s SECRET KEY.
passphrase: API KEY passphrase.
"""
def __init__(self, host, access_key, secret_key, passphrase):
"""initialize REST API client."""
self._host = host
self._access_key = access_key
self._secret_key = secret_key
self._passphrase = passphrase
async def get_sub_users(self):
"""Get the user info of all sub-users via this interface.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/sub/user"
success, error = await self.request("GET", uri, auth=True)
return success, error
async def get_accounts(self, account_type=None, currency=None):
"""Get a list of accounts.
Args:
account_type: Account type, main or trade.
currency: Currency name, e.g. BTC, ETH ...
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/accounts"
params = {}
if account_type:
params["type"] = account_type
if currency:
params["currency"] = currency
success, error = await self.request("GET", uri, params=params, auth=True)
return success, error
async def get_account(self, account_id):
"""Information for a single account.
Args:
account_id: Account id.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/accounts/{}".format(account_id)
success, error = await self.request("GET", uri, auth=True)
return success, error
async def create_account(self, account_type, currency):
"""Create a account.
Args:
account_type: Account type, main or trade.
currency: Currency name, e.g. BTC, ETH ...
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/accounts"
body = {
"type": account_type,
"currency": currency
}
success, error = await self.request("POST", uri, body=body, auth=True)
return success, error
async def create_order(self, client_id, side, symbol, order_type, price, size):
""" Add standard order.
Args:
client_id: Unique order id selected by you to identify your order.
side: Trade side, buy or sell.
symbol: A valid trading symbol code. e.g. ETH-BTC.
order_type: Order type, limit or market (default is limit).
price: Price per base currency.
size: Amount of base currency to buy or sell.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/orders"
body = {
"clientOid": client_id,
"side": side,
"symbol": symbol,
"type": order_type,
"price": price,
"size": size
}
success, error = await self.request("POST", uri, body=body, auth=True)
return success, error
async def revoke_order(self, order_id):
""" Cancel a previously placed order.
Args:
order_id: Order ID, unique identifier of an order.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/orders/{}".format(order_id)
success, error = await self.request("DELETE", uri, auth=True)
return success, error
async def revoke_orders_all(self, symbol=None):
""" Attempt to cancel all open orders. The response is a list of ids of the canceled orders.
Args:
symbol: A valid trading symbol code. e.g. ETH-BTC.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/orders"
params = {}
if symbol:
params["symbol"] = symbol
success, error = await self.request("DELETE", uri, params=params, auth=True)
return success, error
async def get_order_list(self, status="active", symbol=None, order_type=None, start=None, end=None):
""" Get order information list.
Args:
status: Only list orders with a specific status, `active` or `done`, default is `active`.
symbol: A valid trading symbol code. e.g. ETH-BTC.
order_type: Order type, limit, market, limit_stop or market_stop.
start: Start time. Unix timestamp calculated in milliseconds will return only items which were created
after the start time.
end: End time. Unix timestamp calculated in milliseconds will return only items which were created
before the end time.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/orders"
params = {"status": status}
if symbol:
params["symbol"] = symbol
if order_type:
params["type"] = order_type
if start:
params["startAt"] = start
if end:
params["endAt"] = end
success, error = await self.request("GET", uri, params=params, auth=True)
return success, error
async def get_order_detail(self, order_id):
""" Get a single order by order ID.
Args:
order_id: Order ID, unique identifier of an order.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
uri = "/api/v1/orders/{}".format(order_id)
success, error = await self.request("GET", uri, auth=True)
return success, error
async def get_websocket_token(self, private=False):
""" Get a Websocket token from server.
Args:
private: If a private token, default is False.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
if private:
uri = "/api/v1/bullet-private"
success, error = await self.request("POST", uri, auth=True)
else:
uri = "/api/v1/bullet-public"
success, error = await self.request("POST", uri)
return success, error
async def get_orderbook(self, symbol, count=20):
""" Get orderbook information.
Args:
symbol: A valid trading symbol code. e.g. ETH-BTC.
count: Orderbook length, only support 20 or 100.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
if count == 20:
uri = "/api/v1/market/orderbook/level2_20?symbol={}".format(symbol)
else:
uri = "/api/v2/market/orderbook/level2_100?symbol={}".format(symbol)
success, error = await self.request("GET", uri)
return success, error
async def request(self, method, uri, params=None, body=None, headers=None, auth=False):
""" Do HTTP request.
Args:
method: HTTP request method. GET, POST, DELETE, PUT.
uri: HTTP request uri.
params: HTTP query params.
body: HTTP request body.
headers: HTTP request headers.
auth: If this request requires authentication.
Returns:
success: Success results, otherwise it"s None.
error: Error information, otherwise it"s None.
"""
if params:
query = "&".join(["{}={}".format(k, params[k]) for k in sorted(params.keys())])
uri += "?" + query
url = urljoin(self._host, uri)
if auth:
if not headers:
headers = {}
timestamp = str(tools.get_cur_timestamp_ms())
signature = self._generate_signature(timestamp, method, uri, body)
headers["KC-API-KEY"] = self._access_key
headers["KC-API-SIGN"] = signature
headers["KC-API-TIMESTAMP"] = timestamp
headers["KC-API-PASSPHRASE"] = self._passphrase
_, success, error = await AsyncHttpRequests.fetch(method, url, data=body, headers=headers, timeout=10)
if error:
return None, error
if success["code"] != "200000":
return None, success
return success["data"], error
def _generate_signature(self, nonce, method, path, data):
"""Generate the call signature."""
data = json.dumps(data) if data else ""
sig_str = "{}{}{}{}".format(nonce, method, path, data)
m = hmac.new(self._secret_key.encode("utf-8"), sig_str.encode("utf-8"), hashlib.sha256)
return base64.b64encode(m.digest()).decode("utf-8")
class KucoinTrade:
""" Kucoin Trade module. You can initialize trade object with some attributes in kwargs.
Attributes:
account: Account name for this trade exchange.
strategy: What's name would you want to created for you strategy.
symbol: Symbol name for your trade.
host: HTTP request host. (default is "https://openapi-v2.kucoin.com")
access_key: Account's ACCESS KEY.
secret_key: Account's SECRET KEY.
passphrase: API KEY passphrase.
asset_update_callback: You can use this param to specific a async callback function when you initializing Trade
object. `asset_update_callback` is like `async def on_asset_update_callback(asset: Asset): pass` and this
callback function will be executed asynchronous when received AssetEvent.
order_update_callback: You can use this param to specific a async callback function when you initializing Trade
object. `order_update_callback` is like `async def on_order_update_callback(order: Order): pass` and this
callback function will be executed asynchronous when some order state updated.
init_success_callback: You can use this param to specific a async callback function when you initializing Trade
object. `init_success_callback` is like `async def on_init_success_callback(success: bool, error: Error, **kwargs): pass`
and this callback function will be executed asynchronous after Trade module object initialized successfully.
check_order_interval: The interval time(seconds) for loop run task to check order status. (default is 2 seconds)
"""
def __init__(self, **kwargs):
"""Initialize."""
e = None
if not kwargs.get("account"):
e = Error("param account miss")
if not kwargs.get("strategy"):
e = Error("param strategy miss")
if not kwargs.get("symbol"):
e = Error("param symbol miss")
if not kwargs.get("host"):
kwargs["host"] = "https://openapi-v2.kucoin.com"
if not kwargs.get("access_key"):
e = Error("param access_key miss")
if not kwargs.get("secret_key"):
e = Error("param secret_key miss")
if not kwargs.get("passphrase"):
e = Error("param passphrase miss")
if e:
logger.error(e, caller=self)
if kwargs.get("init_success_callback"):
SingleTask.run(kwargs["init_success_callback"], False, e)
return
self._account = kwargs["account"]
self._strategy = kwargs["strategy"]
self._platform = KUCOIN
self._symbol = kwargs["symbol"]
self._host = kwargs["host"]
self._access_key = kwargs["access_key"]
self._secret_key = kwargs["secret_key"]
self._passphrase = kwargs["passphrase"]
self._asset_update_callback = kwargs.get("asset_update_callback")
self._order_update_callback = kwargs.get("order_update_callback")
self._init_success_callback = kwargs.get("init_success_callback")
self._check_order_interval = kwargs.get("check_order_interval", 2)
self._raw_symbol = self._symbol.replace("/", "-") # Raw symbol name.
self._assets = {} # Asset information. e.g. {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... }
self._orders = {} # Order details. e.g. {order_no: order-object, ... }
# Initialize our REST API client.
self._rest_api = KucoinRestAPI(self._host, self._access_key, self._secret_key, self._passphrase)
# Create a loop run task to check order status.
LoopRunTask.register(self._check_order_update, self._check_order_interval)
# Subscribe asset event.
if self._asset_update_callback:
AssetSubscribe(self._platform, self._account, self.on_event_asset_update)
SingleTask.run(self._initialize)
@property
def assets(self):
return copy.copy(self._assets)
@property
def orders(self):
return copy.copy(self._orders)
@property
def rest_api(self):
|
async def _initialize(self):
""" Initialize. fetch all open order information."""
result, error = await self._rest_api.get_order_list(symbol=self._raw_symbol)
if error:
e = Error("get open order nos failed: {}".format(error))
logger.error(e, caller=self)
if self._init_success_callback:
SingleTask.run(self._init_success_callback, False, e)
return
for item in result["items"]:
if item["symbol"] != self._raw_symbol:
continue
await self._update_order(item)
if self._init_success_callback:
SingleTask.run(self._init_success_callback, True, None)
async def create_order(self, action, price, quantity, order_type=ORDER_TYPE_LIMIT, **kwargs):
""" Create an order.
Args:
action: Trade direction, BUY or SELL.
price: Price of order.
quantity: The buying or selling quantity.
order_type: order type, MARKET or LIMIT.
Returns:
order_no: Order ID if created successfully, otherwise it's None.
error: Error information, otherwise it's None.
"""
if action == ORDER_ACTION_BUY:
action_type = "buy"
elif action == ORDER_ACTION_SELL:
action_type = "sell"
else:
return None, "action error"
if order_type == ORDER_TYPE_MARKET:
order_type_2 = "market"
elif order_type == ORDER_TYPE_LIMIT:
order_type_2 = "limit"
else:
return None, "order_type error"
client_id = tools.get_uuid1()
price = tools.float_to_str(price)
quantity = tools.float_to_str(quantity)
success, error = await self._rest_api.create_order(client_id, action_type, self._raw_symbol, order_type_2,
price, quantity)
if error:
return None, error
order_no = success["orderId"]
infos = {
"account": self._account,
"platform": self._platform,
"strategy": self._strategy,
"order_no": order_no,
"symbol": self._symbol,
"action": action,
"price": price,
"quantity": quantity,
"order_type": order_type
}
order = Order(**infos)
self._orders[order_no] = order
if self._order_update_callback:
SingleTask.run(self._order_update_callback, copy.copy(order))
return order_no, None
async def revoke_order(self, *order_nos):
""" Revoke (an) order(s).
Args:
order_nos: Order id list, you can set this param to 0 or multiple items. If you set 0 param, you can cancel
all orders for this symbol(initialized in Trade object). If you set 1 param, you can cancel an order.
If you set multiple param, you can cancel multiple orders. Do not set param length more than 100.
Returns:
Success or error, see bellow.
"""
# If len(order_nos) == 0, you will cancel all orders for this symbol(initialized in Trade object).
if len(order_nos) == 0:
_, error = await self._rest_api.revoke_orders_all(self._raw_symbol)
if error:
return False, error
return True, None
# If len(order_nos) == 1, you will cancel an order.
if len(order_nos) == 1:
success, error = await self._rest_api.revoke_order(order_nos[0])
if error:
return order_nos[0], error
else:
return order_nos[0], None
# If len(order_nos) > 1, you will cancel multiple orders.
if len(order_nos) > 1:
s, e, = [], []
for order_no in order_nos:
success, error = await self._rest_api.revoke_order(order_no)
if error:
e.append(error)
else:
s.append(order_no)
return s, e
async def get_open_order_nos(self):
""" Get open order id list.
Args:
None.
Returns:
order_nos: Open order id list, otherwise it's None.
error: Error information, otherwise it's None.
"""
result, error = await self._rest_api.get_order_list(symbol=self._raw_symbol)
if error:
return False, error
order_nos = []
for item in result["items"]:
if item["symbol"] != self._raw_symbol:
continue
order_nos.append(item["id"])
return order_nos, None
async def _check_order_update(self, *args, **kwargs):
""" Loop run task for check order status.
"""
order_nos = list(self._orders.keys())
if not order_nos:
return
for order_no in order_nos:
success, error = await self._rest_api.get_order_detail(order_no)
if error:
return
await self._update_order(success)
@async_method_locker("KucoinTrade.order.locker")
async def _update_order(self, order_info):
""" Update order object.
Args:
order_info: Order information.
"""
if not order_info:
return
order_no = order_info["id"]
size = float(order_info["size"])
deal_size = float(order_info["dealSize"])
order = self._orders.get(order_no)
if not order:
info = {
"platform": self._platform,
"account": self._account,
"strategy": self._strategy,
"order_no": order_no,
"action": ORDER_ACTION_BUY if order_info["side"] == "buy" else ORDER_ACTION_SELL,
"symbol": self._symbol,
"price": order_info["price"],
"quantity": order_info["size"],
"remain": order_info["size"],
"avg_price": order_info["price"]
}
order = Order(**info)
self._orders[order_no] = order
if order_info["isActive"]:
if size == deal_size:
status = ORDER_STATUS_SUBMITTED
else:
status = ORDER_STATUS_PARTIAL_FILLED
else:
if size == deal_size:
status = ORDER_STATUS_FILLED
else:
status = ORDER_STATUS_CANCELED
if status != order.status:
order.status = status
order.remain = size - deal_size
order.ctime = order_info["createdAt"]
order.utime = tools.get_cur_timestamp_ms()
SingleTask.run(self._order_update_callback, copy.copy(order))
# Delete order that already completed.
if order.status in [ORDER_STATUS_FAILED, ORDER_STATUS_CANCELED, ORDER_STATUS_FILLED]:
self._orders.pop(order_no)
async def on_event_asset_update(self, asset: Asset):
""" Asset update callback.
Args:
asset: Asset object.
"""
self._assets = asset
SingleTask.run(self._asset_update_callback, asset)
| return self._rest_api |
psp.py | from typing import List
from functools import partial
import torch
from .core import DecoderSpec
from ..blocks.core import _get_block
from ..blocks.psp import PSPBlock
from ..abn import ABN
class PSPDecoder(DecoderSpec):
def __init__(
self,
in_channels: List[int],
in_strides: List[int],
downsample_factor: int = 8,
use_batchnorm: bool = True,
out_channels: int = 512
):
super().__init__(in_channels, in_strides)
self.block_offset = self._get_block_offset(downsample_factor)
psp_out_channels: int = self._get(in_channels)
self.psp = PSPBlock(
psp_out_channels,
pool_sizes=(1, 2, 3, 6),
use_batchnorm=use_batchnorm,
)
self.conv = _get_block(
psp_out_channels * 2,
out_channels,
kernel_size=1,
padding=0,
abn_block=partial(ABN, use_batchnorm=use_batchnorm),
complexity=0,
)
self._out_channels = out_channels
self.downsample_factor = downsample_factor
@property
def out_channels(self) -> List[int]:
return [self._out_channels]
@property
def | (self) -> List[int]:
return [self.downsample_factor]
def _get_block_offset(self, downsample_factor: int):
offset = self.in_strides.index(downsample_factor)
return offset
def _get(self, xs: List):
return xs[self.block_offset]
def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
features = self._get(x)
x = self.psp(features)
x = self.conv(x)
return [x]
| out_strides |
data_cache.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Scratchpad for on chain values during the execution.
use crate::create_access_path;
use libra_logger::prelude::*;
use libra_state_view::StateView;
use libra_types::{
access_path::AccessPath,
on_chain_config::ConfigStorage,
vm_status::StatusCode,
write_set::{WriteOp, WriteSet},
};
use move_core_types::{
account_address::AccountAddress,
language_storage::{ModuleId, TypeTag},
};
use move_vm_runtime::data_cache::RemoteCache;
use std::collections::btree_map::BTreeMap;
use vm::errors::*;
/// A local cache for a given a `StateView`. The cache is private to the Libra layer
/// but can be used as a one shot cache for systems that need a simple `RemoteCache`
/// implementation (e.g. tests or benchmarks).
///
/// The cache is responsible to track all changes to the `StateView` that are the result
/// of transaction execution. Those side effects are published at the end of a transaction
/// execution via `StateViewCache::push_write_set`.
///
/// `StateViewCache` is responsible to give an up to date view over the data store,
/// so that changes executed but not yet committed are visible to subsequent transactions.
///
/// If a system wishes to execute a block of transaction on a given view, a cache that keeps
/// track of incremental changes is vital to the consistency of the data store and the system.
pub struct StateViewCache<'a> {
data_view: &'a dyn StateView,
data_map: BTreeMap<AccessPath, Option<Vec<u8>>>,
}
impl<'a> StateViewCache<'a> {
/// Create a `StateViewCache` give a `StateView`. Hold updates to the data store and
/// forward data request to the `StateView` if not in the local cache.
pub fn new(data_view: &'a dyn StateView) -> Self {
StateViewCache {
data_view,
data_map: BTreeMap::new(),
}
}
// Publishes a `WriteSet` computed at the end of a transaction.
// The effect is to build a layer in front of the `StateView` which keeps
// track of the data as if the changes were applied immediately.
pub(crate) fn push_write_set(&mut self, write_set: &WriteSet) {
for (ref ap, ref write_op) in write_set.iter() {
match write_op {
WriteOp::Value(blob) => {
self.data_map.insert(ap.clone(), Some(blob.clone()));
}
WriteOp::Deletion => {
self.data_map.remove(ap);
self.data_map.insert(ap.clone(), None);
}
}
}
}
}
impl<'block> StateView for StateViewCache<'block> {
// Get some data either through the cache or the `StateView` on a cache miss.
fn get(&self, access_path: &AccessPath) -> anyhow::Result<Option<Vec<u8>>> {
match self.data_map.get(access_path) {
Some(opt_data) => Ok(opt_data.clone()),
None => match self.data_view.get(&access_path) {
Ok(remote_data) => Ok(remote_data),
// TODO: should we forward some error info?
Err(e) => {
crit!("[VM] Error getting data from storage for {:?}", access_path);
Err(e)
}
},
}
}
fn | (&self, _access_paths: &[AccessPath]) -> anyhow::Result<Vec<Option<Vec<u8>>>> {
unimplemented!()
}
fn is_genesis(&self) -> bool {
self.data_view.is_genesis()
}
}
impl<'block> RemoteCache for StateViewCache<'block> {
fn get_module(&self, module_id: &ModuleId) -> VMResult<Option<Vec<u8>>> {
RemoteStorage::new(self).get_module(module_id)
}
fn get_resource(
&self,
address: &AccountAddress,
tag: &TypeTag,
) -> PartialVMResult<Option<Vec<u8>>> {
RemoteStorage::new(self).get_resource(address, tag)
}
}
impl<'block> ConfigStorage for StateViewCache<'block> {
fn fetch_config(&self, access_path: AccessPath) -> Option<Vec<u8>> {
self.get(&access_path).ok()?
}
}
// Adapter to convert a `StateView` into a `RemoteCache`.
pub struct RemoteStorage<'a, S>(&'a S);
impl<'a, S: StateView> RemoteStorage<'a, S> {
pub fn new(state_store: &'a S) -> Self {
Self(state_store)
}
pub fn get(&self, access_path: &AccessPath) -> PartialVMResult<Option<Vec<u8>>> {
self.0
.get(access_path)
.map_err(|_| PartialVMError::new(StatusCode::STORAGE_ERROR))
}
}
impl<'a, S: StateView> RemoteCache for RemoteStorage<'a, S> {
fn get_module(&self, module_id: &ModuleId) -> VMResult<Option<Vec<u8>>> {
// REVIEW: cache this?
let ap = AccessPath::from(module_id);
self.get(&ap).map_err(|e| e.finish(Location::Undefined))
}
fn get_resource(
&self,
address: &AccountAddress,
tag: &TypeTag,
) -> PartialVMResult<Option<Vec<u8>>> {
let struct_tag = match tag {
TypeTag::Struct(struct_tag) => struct_tag.clone(),
_ => return Err(PartialVMError::new(StatusCode::VALUE_DESERIALIZATION_ERROR)),
};
let ap = create_access_path(*address, struct_tag);
self.get(&ap)
}
}
impl<'a, S: StateView> ConfigStorage for RemoteStorage<'a, S> {
fn fetch_config(&self, access_path: AccessPath) -> Option<Vec<u8>> {
self.get(&access_path).ok()?
}
}
| multi_get |
terminator.py | class Terminator:
def __init__(self):
self.dead = False
self.training = False
self.image = None
self.steering = 0
self.throttle = 0
def poll():
|
def update():
while True:
self.poll()
def run_threaded(self, image, steering, throttle, training):
def run(self, image, steering, throttle, training):
return self.run_threaded()
def is_dead(self, img):
"""
Counts the black pixels from the ground and compares the amount to a threshold value.
If there are not enough black pixels the car is assumed to be off the track.
"""
crop_height = 20
crop_width = 20
threshold = 70
pixels_percentage = 0.10
pixels_required = (img.shape[1] - 2 * crop_width) * crop_height * pixels_percentage
crop = img[-crop_height:, crop_width:-crop_width]
r = crop[:,:,0] < threshold
g = crop[:,:,1] < threshold
b = crop[:,:,2] < threshold
pixels = (r & g & b).sum()
print("Pixels: {}, Required: {}".format(pixels, pixels_required))
return pixels < pixels_required | self.dead = self.is_dead(self.image)
self.steering *= self.dead
self.throttle *= self.dead |
progress.rs | use webcore::value::Reference;
use webcore::try_from::TryInto;
use webapi::event::{IEvent, Event, ConcreteEvent};
/// The `IProgressEvent` interface represents progress-related
/// events.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent)
// https://xhr.spec.whatwg.org/#progressevent
pub trait IProgressEvent: IEvent {
/// Indicates whether the progress is measureable.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent/lengthComputable)
// https://xhr.spec.whatwg.org/#ref-for-dom-progressevent-lengthcomputable
#[inline]
fn length_computable( &self ) -> bool |
/// Returns the amount of work already performed by the underlying process.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent/loaded)
// https://xhr.spec.whatwg.org/#ref-for-dom-progressevent-loaded
#[inline]
fn loaded( &self ) -> u64 {
js!(
return @{self.as_ref()}.loaded;
).try_into().unwrap()
}
/// Returns the total amount of work that the underlying process will perform.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent/total)
// https://xhr.spec.whatwg.org/#ref-for-dom-progressevent-total
#[inline]
fn total( &self ) -> u64 {
js!(
return @{self.as_ref()}.total;
).try_into().unwrap()
}
}
/// A reference to a JavaScript object which implements the [IProgressEvent](trait.IProgressEvent.html)
/// interface.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent)
// https://xhr.spec.whatwg.org/#progressevent
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "ProgressEvent")]
#[reference(subclass_of(Event))]
pub struct ProgressRelatedEvent( Reference );
impl IEvent for ProgressRelatedEvent {}
impl IProgressEvent for ProgressRelatedEvent {}
/// The `ProgressEvent` is fired to indicate that an operation is in progress.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/progress)
// https://xhr.spec.whatwg.org/#event-xhr-progress
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "ProgressEvent", constraint="type=progress")]
#[reference(subclass_of(Event, ProgressRelatedEvent))]
pub struct ProgressEvent( Reference );
impl IEvent for ProgressEvent {}
impl IProgressEvent for ProgressEvent {}
impl ConcreteEvent for ProgressEvent {
const EVENT_TYPE: &'static str = "progress";
}
/// The `ProgressLoadEvent` is fired when progress has successful finished.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/load_(ProgressEvent))
// https://xhr.spec.whatwg.org/#event-xhr-load
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "ProgressEvent", constraint="type=load")]
#[reference(subclass_of(Event, ProgressRelatedEvent))]
pub struct ProgressLoadEvent( Reference );
impl IEvent for ProgressLoadEvent {}
impl IProgressEvent for ProgressLoadEvent {}
impl ConcreteEvent for ProgressLoadEvent {
const EVENT_TYPE: &'static str = "load";
}
/// The `LoadStartEvent` is fired when progress has begun.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/loadstart)
// https://xhr.spec.whatwg.org/#event-xhr-loadstart
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "ProgressEvent", constraint="type=loadstart")]
#[reference(subclass_of(Event, ProgressRelatedEvent))]
pub struct LoadStartEvent( Reference );
impl IEvent for LoadStartEvent {}
impl IProgressEvent for LoadStartEvent {}
impl ConcreteEvent for LoadStartEvent {
const EVENT_TYPE: &'static str = "loadstart";
}
/// The `LoadEndEvent` is fired when progress has stopped,
/// e.g. after `ProgressErrorEvent`, `ProgressAbortEvent`
/// or `ProgressLoadEvent` have been dispatched.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/loadend)
// https://xhr.spec.whatwg.org/#event-xhr-loadend
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "ProgressEvent", constraint="type=loadend")]
#[reference(subclass_of(Event, ProgressRelatedEvent))]
pub struct LoadEndEvent( Reference );
impl IEvent for LoadEndEvent {}
impl IProgressEvent for LoadEndEvent {}
impl ConcreteEvent for LoadEndEvent {
const EVENT_TYPE: &'static str = "loadend";
}
/// The `ProgressAbortEvent` is fired when the progress has been aborted.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/abort_(ProgressEvent))
// https://xhr.spec.whatwg.org/#event-xhr-abort
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "ProgressEvent", constraint="type=abort")]
#[reference(subclass_of(Event, ProgressRelatedEvent))]
pub struct ProgressAbortEvent( Reference );
impl IEvent for ProgressAbortEvent {}
impl IProgressEvent for ProgressAbortEvent {}
impl ConcreteEvent for ProgressAbortEvent {
const EVENT_TYPE: &'static str = "abort";
}
/// The `ProgressErrorEvent` is fired when the progress has failed.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/error_(ProgressEvent))
// https://xhr.spec.whatwg.org/#event-xhr-error
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "ProgressEvent", constraint="type=error")]
#[reference(subclass_of(Event, ProgressRelatedEvent))]
pub struct ProgressErrorEvent( Reference );
impl IEvent for ProgressErrorEvent {}
impl IProgressEvent for ProgressErrorEvent {}
impl ConcreteEvent for ProgressErrorEvent {
const EVENT_TYPE: &'static str = "error";
}
#[cfg(all(test, feature = "web_test"))]
mod tests {
use super::*;
#[test]
fn test_progress_event() {
let event: ProgressEvent = js!(
return new ProgressEvent(
@{ProgressEvent::EVENT_TYPE},
{
lengthComputable: true,
loaded: 10,
total: 100,
}
);
).try_into().unwrap();
assert_eq!( event.event_type(), ProgressEvent::EVENT_TYPE );
assert!( event.length_computable() );
assert_eq!( event.loaded(), 10 );
assert_eq!( event.total(), 100 );
}
#[test]
fn test_load_start_event() {
let event: LoadStartEvent = js!(
return new ProgressEvent( @{LoadStartEvent::EVENT_TYPE} );
).try_into().unwrap();
assert_eq!( event.event_type(), LoadStartEvent::EVENT_TYPE );
}
#[test]
fn test_load_end_event() {
let event: LoadEndEvent = js!(
return new ProgressEvent( @{LoadEndEvent::EVENT_TYPE} );
).try_into().unwrap();
assert_eq!( event.event_type(), LoadEndEvent::EVENT_TYPE );
}
}
| {
js!(
return @{self.as_ref()}.lengthComputable;
).try_into().unwrap()
} |
hashing.py | # Copyright 2018-2021 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Hashing for st.memo and st.singleton."""
import collections
import functools
import hashlib
import inspect
import io
import os
import pickle
import sys
import tempfile
import threading
import unittest.mock
import weakref
from typing import Any, Pattern, Optional, Dict, List
from streamlit import type_util
from streamlit import util
from streamlit.logger import get_logger
from streamlit.uploaded_file_manager import UploadedFile
from .cache_errors import (
CacheType,
UnhashableTypeError,
)
_LOGGER = get_logger(__name__)
# If a dataframe has more than this many rows, we consider it large and hash a sample.
_PANDAS_ROWS_LARGE = 100000
_PANDAS_SAMPLE_SIZE = 10000
# Similar to dataframes, we also sample large numpy arrays.
_NP_SIZE_LARGE = 1000000
_NP_SAMPLE_SIZE = 100000
# Arbitrary item to denote where we found a cycle in a hashed object.
# This allows us to hash self-referencing lists, dictionaries, etc.
_CYCLE_PLACEHOLDER = b"streamlit-57R34ML17-hesamagicalponyflyingthroughthesky-CYCLE"
def update_hash(val: Any, hasher, cache_type: CacheType) -> None:
"""Updates a hashlib hasher with the hash of val.
This is the main entrypoint to hashing.py.
"""
ch = _CacheFuncHasher(cache_type)
ch.update(hasher, val)
class _HashStack:
"""Stack of what has been hashed, for debug and circular reference detection.
This internally keeps 1 stack per thread.
Internally, this stores the ID of pushed objects rather than the objects
themselves because otherwise the "in" operator inside __contains__ would
fail for objects that don't return a boolean for "==" operator. For
example, arr == 10 where arr is a NumPy array returns another NumPy array.
This causes the "in" to crash since it expects a boolean.
"""
def __init__(self):
self._stack: collections.OrderedDict[int, List[Any]] = collections.OrderedDict()
def __repr__(self) -> str:
return util.repr_(self)
def push(self, val: Any):
self._stack[id(val)] = val
def pop(self):
self._stack.popitem()
def __contains__(self, val: Any):
return id(val) in self._stack
class _HashStacks:
"""Stacks of what has been hashed, with at most 1 stack per thread."""
def __init__(self):
self._stacks: weakref.WeakKeyDictionary[
threading.Thread, _HashStack
] = weakref.WeakKeyDictionary()
def __repr__(self) -> str:
return util.repr_(self)
@property
def current(self) -> _HashStack:
current_thread = threading.current_thread()
stack = self._stacks.get(current_thread, None)
if stack is None:
stack = _HashStack()
self._stacks[current_thread] = stack
return stack
hash_stacks = _HashStacks()
def _int_to_bytes(i: int) -> bytes:
num_bytes = (i.bit_length() + 8) // 8
return i.to_bytes(num_bytes, "little", signed=True)
def _key(obj: Optional[Any]) -> Any:
"""Return key for memoization."""
if obj is None:
return None
def is_simple(obj):
return (
isinstance(obj, bytes)
or isinstance(obj, bytearray)
or isinstance(obj, str)
or isinstance(obj, float)
or isinstance(obj, int)
or isinstance(obj, bool)
or obj is None
)
if is_simple(obj):
return obj
if isinstance(obj, tuple):
if all(map(is_simple, obj)):
return obj
if isinstance(obj, list):
if all(map(is_simple, obj)):
return ("__l", tuple(obj))
if (
type_util.is_type(obj, "pandas.core.frame.DataFrame")
or type_util.is_type(obj, "numpy.ndarray")
or inspect.isbuiltin(obj)
or inspect.isroutine(obj)
or inspect.iscode(obj)
):
return id(obj)
return NoResult
class _CacheFuncHasher:
"""A hasher that can hash objects with cycles."""
def __init__(self, cache_type: CacheType):
self._hashes: Dict[Any, bytes] = {}
# The number of the bytes in the hash.
self.size = 0
self.cache_type = cache_type
def __repr__(self) -> str:
return util.repr_(self)
def to_bytes(self, obj: Any) -> bytes:
"""Add memoization to _to_bytes and protect against cycles in data structures."""
tname = type(obj).__qualname__.encode()
key = (tname, _key(obj))
# Memoize if possible.
if key[1] is not NoResult:
if key in self._hashes:
return self._hashes[key]
# Break recursive cycles.
if obj in hash_stacks.current:
return _CYCLE_PLACEHOLDER
hash_stacks.current.push(obj)
try:
# Hash the input
b = b"%s:%s" % (tname, self._to_bytes(obj))
# Hmmm... It's possible that the size calculation is wrong. When we
# call to_bytes inside _to_bytes things get double-counted.
self.size += sys.getsizeof(b)
if key[1] is not NoResult:
self._hashes[key] = b
finally:
# In case an UnhashableTypeError (or other) error is thrown, clean up the
# stack so we don't get false positives in future hashing calls
hash_stacks.current.pop()
return b
def update(self, hasher, obj: Any) -> None:
"""Update the provided hasher with the hash of an object."""
b = self.to_bytes(obj)
hasher.update(b)
def _to_bytes(self, obj: Any) -> bytes:
"""Hash objects to bytes, including code with dependencies.
Python's built in `hash` does not produce consistent results across
runs.
"""
if isinstance(obj, unittest.mock.Mock):
# Mock objects can appear to be infinitely
# deep, so we don't try to hash them at all.
return self.to_bytes(id(obj))
elif isinstance(obj, bytes) or isinstance(obj, bytearray):
return obj
elif isinstance(obj, str):
return obj.encode()
elif isinstance(obj, float):
return self.to_bytes(hash(obj))
elif isinstance(obj, int):
return _int_to_bytes(obj)
elif isinstance(obj, (list, tuple)):
h = hashlib.new("md5")
for item in obj:
self.update(h, item)
return h.digest()
elif isinstance(obj, dict):
h = hashlib.new("md5")
for item in obj.items():
self.update(h, item)
return h.digest()
elif obj is None:
return b"0"
elif obj is True:
return b"1"
elif obj is False:
return b"0"
elif type_util.is_type(obj, "pandas.core.frame.DataFrame") or type_util.is_type(
obj, "pandas.core.series.Series"
):
import pandas as pd
if len(obj) >= _PANDAS_ROWS_LARGE:
obj = obj.sample(n=_PANDAS_SAMPLE_SIZE, random_state=0)
try:
return b"%s" % pd.util.hash_pandas_object(obj).sum()
except TypeError:
# Use pickle if pandas cannot hash the object for example if
# it contains unhashable objects.
return b"%s" % pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
elif type_util.is_type(obj, "numpy.ndarray"):
h = hashlib.new("md5")
self.update(h, obj.shape)
if obj.size >= _NP_SIZE_LARGE:
|
self.update(h, obj.tobytes())
return h.digest()
elif inspect.isbuiltin(obj):
return bytes(obj.__name__.encode())
elif type_util.is_type(obj, "builtins.mappingproxy") or type_util.is_type(
obj, "builtins.dict_items"
):
return self.to_bytes(dict(obj))
elif type_util.is_type(obj, "builtins.getset_descriptor"):
return bytes(obj.__qualname__.encode())
elif isinstance(obj, UploadedFile):
# UploadedFile is a BytesIO (thus IOBase) but has a name.
# It does not have a timestamp so this must come before
# temproary files
h = hashlib.new("md5")
self.update(h, obj.name)
self.update(h, obj.tell())
self.update(h, obj.getvalue())
return h.digest()
elif hasattr(obj, "name") and (
isinstance(obj, io.IOBase)
# Handle temporary files used during testing
or isinstance(obj, tempfile._TemporaryFileWrapper)
):
# Hash files as name + last modification date + offset.
# NB: we're using hasattr("name") to differentiate between
# on-disk and in-memory StringIO/BytesIO file representations.
# That means that this condition must come *before* the next
# condition, which just checks for StringIO/BytesIO.
h = hashlib.new("md5")
obj_name = getattr(obj, "name", "wonthappen") # Just to appease MyPy.
self.update(h, obj_name)
self.update(h, os.path.getmtime(obj_name))
self.update(h, obj.tell())
return h.digest()
elif isinstance(obj, Pattern):
return self.to_bytes([obj.pattern, obj.flags])
elif isinstance(obj, io.StringIO) or isinstance(obj, io.BytesIO):
# Hash in-memory StringIO/BytesIO by their full contents
# and seek position.
h = hashlib.new("md5")
self.update(h, obj.tell())
self.update(h, obj.getvalue())
return h.digest()
elif type_util.is_type(obj, "numpy.ufunc"):
# For numpy.remainder, this returns remainder.
return bytes(obj.__name__.encode())
elif inspect.ismodule(obj):
# TODO: Figure out how to best show this kind of warning to the
# user. In the meantime, show nothing. This scenario is too common,
# so the current warning is quite annoying...
# st.warning(('Streamlit does not support hashing modules. '
# 'We did not hash `%s`.') % obj.__name__)
# TODO: Hash more than just the name for internal modules.
return self.to_bytes(obj.__name__)
elif inspect.isclass(obj):
# TODO: Figure out how to best show this kind of warning to the
# user. In the meantime, show nothing. This scenario is too common,
# (e.g. in every "except" statement) so the current warning is
# quite annoying...
# st.warning(('Streamlit does not support hashing classes. '
# 'We did not hash `%s`.') % obj.__name__)
# TODO: Hash more than just the name of classes.
return self.to_bytes(obj.__name__)
elif isinstance(obj, functools.partial):
# The return value of functools.partial is not a plain function:
# it's a callable object that remembers the original function plus
# the values you pickled into it. So here we need to special-case it.
h = hashlib.new("md5")
self.update(h, obj.args)
self.update(h, obj.func)
self.update(h, obj.keywords)
return h.digest()
else:
# As a last resort, hash the output of the object's __reduce__ method
h = hashlib.new("md5")
try:
reduce_data = obj.__reduce__()
except BaseException as e:
raise UnhashableTypeError() from e
for item in reduce_data:
self.update(h, item)
return h.digest()
class NoResult:
"""Placeholder class for return values when None is meaningful."""
pass
| import numpy as np
state = np.random.RandomState(0)
obj = state.choice(obj.flat, size=_NP_SAMPLE_SIZE) |
controllers.go | package twitter
import (
"fmt"
"net/http"
"strings"
)
// ControllerV2 exposes methods for interfacing with the Twitter API v2 web service layer
type ControllerV2 interface {
GetTweetByID(tweetID string, queryParams map[string]string) (GetTweetByIDResponse, error)
GetTweets(tweetIDs []string, queryParams map[string]string) (GetTweetsResponse, error)
GetUserByUsername(username string, queryParams map[string]string) (GetUserByUsernameResponse, error)
SearchTweetsRecent(queryParams map[string]string) (SearchTweetsResponse, error)
}
// operator implements the Twitter API v2 client contract via HTTP client
type operatorV2 struct {
cfgV2 ControllerConfigV2
http *http.Client
}
// ControllerConfigV2 the Twitter API v2 client's available HTTP connection, security and third-party options
type ControllerConfigV2 struct {
APIKey string `json:"api_key" yaml:"api_key"`
APISecretKey string `json:"api_secret_key" yaml:"api_secret_key"`
BaseURL string `json:"base_url" yaml:"base_url"`
BearerToken string `json:"bearer_token" yaml:"bearer_token"`
// TODO: Additional config options i.e. HTTP client options, Monitoring enabled, ...
}
// NewControllerV2 construct a new Twitter API v2 client operator
func NewControllerV2(cfg ControllerConfigV2) (ControllerV2, error) {
if err := sanitizeAndValidateConfigV2(&cfg); err != nil {
return nil, fmt.Errorf("failed to sanitize and validate API client v2 configuration; %w", err)
}
return &operatorV2{
cfgV2: cfg,
http: http.DefaultClient, // TODO: create an HTTP client with custom config options
}, nil
}
// check for empty, whitespace-only or zero configuration values and apply default settings when relevant
func sanitizeAndValidateConfigV2(cfg *ControllerConfigV2) error { | }
cfg.APISecretKey = strings.TrimSpace(cfg.APISecretKey)
if cfg.APISecretKey == "" {
return fmt.Errorf("cannot construct twitter API client v2 with an empty or whitespace-only API secret key")
}
cfg.BaseURL = strings.TrimSpace(cfg.BaseURL)
if cfg.BaseURL == "" {
cfg.BaseURL = defaultBaseURL
}
cfg.BearerToken = strings.TrimSpace(cfg.BearerToken)
if cfg.BearerToken == "" {
return fmt.Errorf("cannot construct twitter API client v2 with an empty or whitespace-only oauth 2.0 bearer token")
}
return nil
} | cfg.APIKey = strings.TrimSpace(cfg.APIKey)
if cfg.APIKey == "" {
return fmt.Errorf("cannot construct twitter API client v2 with an empty or whitespace-only API key") |
objsequence.rs | use crate::function::OptionalArg;
use crate::obj::objnone::PyNone;
use std::cell::RefCell;
use std::marker::Sized;
use std::ops::{Deref, DerefMut, Range};
use crate::pyobject::{IdProtocol, PyObject, PyObjectRef, PyResult, TryFromObject, TypeProtocol};
use crate::vm::VirtualMachine;
use num_bigint::{BigInt, ToBigInt};
use num_traits::{One, Signed, ToPrimitive, Zero};
use super::objbool;
use super::objint::{PyInt, PyIntRef};
use super::objlist::PyList;
use super::objslice::{PySlice, PySliceRef};
use super::objtuple::PyTuple;
pub trait PySliceableSequence {
type Sliced;
fn do_slice(&self, range: Range<usize>) -> Self::Sliced;
fn do_slice_reverse(&self, range: Range<usize>) -> Self::Sliced;
fn do_stepped_slice(&self, range: Range<usize>, step: usize) -> Self::Sliced;
fn do_stepped_slice_reverse(&self, range: Range<usize>, step: usize) -> Self::Sliced;
fn empty() -> Self::Sliced;
fn len(&self) -> usize;
fn is_empty(&self) -> bool;
fn get_pos(&self, p: i32) -> Option<usize> {
if p < 0 {
if -p as usize > self.len() {
None
} else {
Some(self.len() - ((-p) as usize))
}
} else if p as usize >= self.len() {
None
} else {
Some(p as usize)
}
}
fn get_slice_pos(&self, slice_pos: &BigInt) -> usize {
if let Some(pos) = slice_pos.to_i32() {
if let Some(index) = self.get_pos(pos) {
// within bounds
return index;
}
}
if slice_pos.is_negative() {
0
} else {
self.len()
}
}
fn get_slice_range(&self, start: &Option<BigInt>, stop: &Option<BigInt>) -> Range<usize> {
let start = start.as_ref().map(|x| self.get_slice_pos(x)).unwrap_or(0);
let stop = stop
.as_ref()
.map(|x| self.get_slice_pos(x))
.unwrap_or_else(|| self.len());
start..stop
}
fn get_slice_items(
&self,
vm: &VirtualMachine,
slice: &PyObjectRef,
) -> Result<Self::Sliced, PyObjectRef>
where
Self: Sized,
{
match slice.clone().downcast::<PySlice>() {
Ok(slice) => {
let start = slice.start_index(vm)?;
let stop = slice.stop_index(vm)?;
let step = slice.step_index(vm)?.unwrap_or_else(BigInt::one);
if step.is_zero() {
Err(vm.new_value_error("slice step cannot be zero".to_string()))
} else if step.is_positive() {
let range = self.get_slice_range(&start, &stop);
if range.start < range.end {
#[allow(clippy::range_plus_one)]
match step.to_i32() {
Some(1) => Ok(self.do_slice(range)),
Some(num) => Ok(self.do_stepped_slice(range, num as usize)),
None => Ok(self.do_slice(range.start..range.start + 1)),
}
} else {
Ok(Self::empty())
}
} else {
// calculate the range for the reverse slice, first the bounds needs to be made
// exclusive around stop, the lower number
let start = start.as_ref().map(|x| {
if *x == (-1).to_bigint().unwrap() {
self.len() + BigInt::one() //.to_bigint().unwrap()
} else {
x + 1
}
});
let stop = stop.as_ref().map(|x| {
if *x == (-1).to_bigint().unwrap() {
self.len().to_bigint().unwrap()
} else {
x + 1
}
});
let range = self.get_slice_range(&stop, &start);
if range.start < range.end {
match (-step).to_i32() {
Some(1) => Ok(self.do_slice_reverse(range)),
Some(num) => Ok(self.do_stepped_slice_reverse(range, num as usize)),
None => Ok(self.do_slice(range.end - 1..range.end)),
}
} else {
Ok(Self::empty())
}
}
}
payload => panic!("get_slice_items called with non-slice: {:?}", payload),
}
}
}
impl<T: Clone> PySliceableSequence for Vec<T> {
type Sliced = Vec<T>;
fn do_slice(&self, range: Range<usize>) -> Self::Sliced {
self[range].to_vec()
}
fn do_slice_reverse(&self, range: Range<usize>) -> Self::Sliced {
let mut slice = self[range].to_vec();
slice.reverse();
slice
}
fn do_stepped_slice(&self, range: Range<usize>, step: usize) -> Self::Sliced {
self[range].iter().step_by(step).cloned().collect()
}
fn do_stepped_slice_reverse(&self, range: Range<usize>, step: usize) -> Self::Sliced |
fn empty() -> Self::Sliced {
Vec::new()
}
fn len(&self) -> usize {
self.len()
}
fn is_empty(&self) -> bool {
self.is_empty()
}
}
pub enum SequenceIndex {
Int(i32),
Slice(PySliceRef),
}
impl TryFromObject for SequenceIndex {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
match_class!(match obj {
i @ PyInt => Ok(SequenceIndex::Int(i32::try_from_object(
vm,
i.into_object()
)?)),
s @ PySlice => Ok(SequenceIndex::Slice(s)),
obj => Err(vm.new_type_error(format!(
"sequence indices be integers or slices, not {}",
obj.class(),
))),
})
}
}
/// Get the index into a sequence like type. Get it from a python integer
/// object, accounting for negative index, and out of bounds issues.
pub fn get_sequence_index(vm: &VirtualMachine, index: &PyIntRef, length: usize) -> PyResult<usize> {
if let Some(value) = index.as_bigint().to_i64() {
if value < 0 {
let from_end: usize = -value as usize;
if from_end > length {
Err(vm.new_index_error("Index out of bounds!".to_string()))
} else {
let index = length - from_end;
Ok(index)
}
} else {
let index = value as usize;
if index >= length {
Err(vm.new_index_error("Index out of bounds!".to_string()))
} else {
Ok(index)
}
}
} else {
Err(vm.new_index_error("cannot fit 'int' into an index-sized integer".to_string()))
}
}
pub fn get_item(
vm: &VirtualMachine,
sequence: &PyObjectRef,
elements: &[PyObjectRef],
subscript: PyObjectRef,
) -> PyResult {
if let Some(i) = subscript.payload::<PyInt>() {
return match i.as_bigint().to_i32() {
Some(value) => {
if let Some(pos_index) = elements.to_vec().get_pos(value) {
let obj = elements[pos_index].clone();
Ok(obj)
} else {
Err(vm.new_index_error("Index out of bounds!".to_string()))
}
}
None => {
Err(vm.new_index_error("cannot fit 'int' into an index-sized integer".to_string()))
}
};
}
if subscript.payload::<PySlice>().is_some() {
if sequence.payload::<PyList>().is_some() {
Ok(PyObject::new(
PyList::from(elements.to_vec().get_slice_items(vm, &subscript)?),
sequence.class(),
None,
))
} else if sequence.payload::<PyTuple>().is_some() {
Ok(PyObject::new(
PyTuple::from(elements.to_vec().get_slice_items(vm, &subscript)?),
sequence.class(),
None,
))
} else {
panic!("sequence get_item called for non-sequence")
}
} else {
Err(vm.new_type_error(format!(
"indexing type {:?} with index {:?} is not supported (yet?)",
sequence, subscript
)))
}
}
type DynPyIter<'a> = Box<dyn ExactSizeIterator<Item = &'a PyObjectRef> + 'a>;
#[allow(clippy::len_without_is_empty)]
pub trait SimpleSeq {
fn len(&self) -> usize;
fn iter(&self) -> DynPyIter;
}
impl SimpleSeq for &[PyObjectRef] {
fn len(&self) -> usize {
(&**self).len()
}
fn iter(&self) -> DynPyIter {
Box::new((&**self).iter())
}
}
impl SimpleSeq for std::collections::VecDeque<PyObjectRef> {
fn len(&self) -> usize {
self.len()
}
fn iter(&self) -> DynPyIter {
Box::new(self.iter())
}
}
// impl<'a, I>
pub fn seq_equal(
vm: &VirtualMachine,
zelf: &dyn SimpleSeq,
other: &dyn SimpleSeq,
) -> Result<bool, PyObjectRef> {
if zelf.len() == other.len() {
for (a, b) in Iterator::zip(zelf.iter(), other.iter()) {
if !a.is(b) {
let eq = vm._eq(a.clone(), b.clone())?;
let value = objbool::boolval(vm, eq)?;
if !value {
return Ok(false);
}
}
}
Ok(true)
} else {
Ok(false)
}
}
pub fn seq_lt(
vm: &VirtualMachine,
zelf: &dyn SimpleSeq,
other: &dyn SimpleSeq,
) -> Result<bool, PyObjectRef> {
for (a, b) in Iterator::zip(zelf.iter(), other.iter()) {
if vm.bool_lt(a.clone(), b.clone())? {
return Ok(true);
} else if !vm.bool_eq(a.clone(), b.clone())? {
return Ok(false);
}
}
if zelf.len() == other.len() {
Ok(false)
} else {
Ok(zelf.len() < other.len())
}
}
pub fn seq_gt(
vm: &VirtualMachine,
zelf: &dyn SimpleSeq,
other: &dyn SimpleSeq,
) -> Result<bool, PyObjectRef> {
for (a, b) in Iterator::zip(zelf.iter(), other.iter()) {
if vm.bool_gt(a.clone(), b.clone())? {
return Ok(true);
} else if !vm.bool_eq(a.clone(), b.clone())? {
return Ok(false);
}
}
if zelf.len() == other.len() {
Ok(false)
} else {
Ok(zelf.len() > other.len())
}
}
pub fn seq_ge(
vm: &VirtualMachine,
zelf: &dyn SimpleSeq,
other: &dyn SimpleSeq,
) -> Result<bool, PyObjectRef> {
for (a, b) in Iterator::zip(zelf.iter(), other.iter()) {
if vm.bool_gt(a.clone(), b.clone())? {
return Ok(true);
} else if !vm.bool_eq(a.clone(), b.clone())? {
return Ok(false);
}
}
if zelf.len() == other.len() {
Ok(true)
} else {
Ok(zelf.len() > other.len())
}
}
pub fn seq_le(
vm: &VirtualMachine,
zelf: &dyn SimpleSeq,
other: &dyn SimpleSeq,
) -> Result<bool, PyObjectRef> {
for (a, b) in Iterator::zip(zelf.iter(), other.iter()) {
if vm.bool_lt(a.clone(), b.clone())? {
return Ok(true);
} else if !vm.bool_eq(a.clone(), b.clone())? {
return Ok(false);
}
}
if zelf.len() == other.len() {
Ok(true)
} else {
Ok(zelf.len() < other.len())
}
}
pub struct SeqMul<'a> {
seq: &'a dyn SimpleSeq,
repetitions: usize,
iter: Option<DynPyIter<'a>>,
}
impl<'a> Iterator for SeqMul<'a> {
type Item = &'a PyObjectRef;
fn next(&mut self) -> Option<Self::Item> {
if self.seq.len() == 0 {
return None;
}
match self.iter.as_mut().and_then(Iterator::next) {
Some(item) => Some(item),
None => {
if self.repetitions == 0 {
None
} else {
self.repetitions -= 1;
self.iter = Some(self.seq.iter());
self.next()
}
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = self.iter.as_ref().map_or(0, ExactSizeIterator::len)
+ (self.repetitions * self.seq.len());
(size, Some(size))
}
}
impl ExactSizeIterator for SeqMul<'_> {}
pub fn seq_mul(seq: &dyn SimpleSeq, repetitions: isize) -> SeqMul {
SeqMul {
seq,
repetitions: repetitions.max(0) as usize,
iter: None,
}
}
pub fn get_elements_cell<'a>(obj: &'a PyObjectRef) -> &'a RefCell<Vec<PyObjectRef>> {
if let Some(list) = obj.payload::<PyList>() {
return &list.elements;
}
panic!("Cannot extract elements from non-sequence");
}
pub fn get_elements_list<'a>(obj: &'a PyObjectRef) -> impl Deref<Target = Vec<PyObjectRef>> + 'a {
if let Some(list) = obj.payload::<PyList>() {
return list.elements.borrow();
}
panic!("Cannot extract elements from non-sequence");
}
pub fn get_elements_tuple<'a>(obj: &'a PyObjectRef) -> impl Deref<Target = Vec<PyObjectRef>> + 'a {
if let Some(tuple) = obj.payload::<PyTuple>() {
return &tuple.elements;
}
panic!("Cannot extract elements from non-sequence");
}
pub fn get_mut_elements<'a>(obj: &'a PyObjectRef) -> impl DerefMut<Target = Vec<PyObjectRef>> + 'a {
if let Some(list) = obj.payload::<PyList>() {
return list.elements.borrow_mut();
}
panic!("Cannot extract elements from non-sequence");
}
//Check if given arg could be used with PySliceableSequence.get_slice_range()
pub fn is_valid_slice_arg(
arg: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> Result<Option<BigInt>, PyObjectRef> {
if let OptionalArg::Present(value) = arg {
match_class!(match value {
i @ PyInt => Ok(Some(i.as_bigint().clone())),
_obj @ PyNone => Ok(None),
_ => Err(vm.new_type_error(
"slice indices must be integers or None or have an __index__ method".to_string()
)), // TODO: check for an __index__ method
})
} else {
Ok(None)
}
}
| {
self[range].iter().rev().step_by(step).cloned().collect()
} |
bases.py | import copy
from collections import OrderedDict
from enum import Enum
from typing import Any, Dict, Optional, Tuple, Type, Union
from vyper import ast as vy_ast
from vyper.context.types.abstract import AbstractDataType
from vyper.exceptions import (
CompilerPanic,
ImmutableViolation,
InvalidLiteral,
InvalidOperation,
NamespaceCollision,
StructureException,
UnexpectedNodeType,
UnexpectedValue,
UnknownAttribute,
)
class DataLocation(Enum):
UNSET = 0
MEMORY = 1
STORAGE = 2
CALLDATA = 3
class BasePrimitive:
"""
Base class for primitive type classes.
Primitives are objects that are invoked when applying a type to a variable.
They must contain a `from_annotation` (and optionally `from_literal`) method
that returns their equivalent `BaseTypeDefinition` object.
Attributes
----------
_id : str
The name of the type.
_type : BaseTypeDefinition
The related `BaseTypeDefinition` class generated from this primitive
_as_array: bool, optional
If `True`, this type can be used as the base member for an array.
_valid_literal : Tuple
A tuple of Vyper ast classes that may be assigned this type.
"""
_id: str
_type: Type["BaseTypeDefinition"]
_valid_literal: Tuple
@classmethod
def from_annotation(
cls,
node: Union[vy_ast.Name, vy_ast.Call],
location: DataLocation = DataLocation.UNSET,
is_immutable: bool = False,
is_public: bool = False,
) -> "BaseTypeDefinition":
"""
Generate a `BaseTypeDefinition` instance of this type from `AnnAssign.annotation`
Arguments
---------
node : VyperNode
Vyper ast node from the `annotation` member of an `AnnAssign` node.
Returns
-------
BaseTypeDefinition
BaseTypeDefinition related to the primitive that the method was called on.
"""
if not isinstance(node, vy_ast.Name):
raise StructureException("Invalid type assignment", node)
if node.id != cls._id:
raise UnexpectedValue("Node id does not match type name")
return cls._type(location, is_immutable, is_public)
@classmethod
def from_literal(cls, node: vy_ast.Constant) -> "BaseTypeDefinition":
"""
Generate a `BaseTypeDefinition` instance of this type from a literal constant.
This method is called on every primitive class in order to determine
potential types for a `Constant` AST node.
Types that may be assigned from literals should include a `_valid_literal`
attribute, containing a list of AST node classes that may be valid for
this type. If the `_valid_literal` attribute is not included, the type
cannot be assigned to a literal.
Arguments
---------
node : VyperNode
`Constant` Vyper ast node, or a list or tuple of constants.
Returns
-------
BaseTypeDefinition
BaseTypeDefinition related to the primitive that the method was called on.
"""
if not isinstance(node, vy_ast.Constant):
raise UnexpectedNodeType(f"Attempted to validate a '{node.ast_type}' node.")
if not isinstance(node, cls._valid_literal):
raise InvalidLiteral(f"Invalid literal type for {cls.__name__}", node)
return cls._type()
@classmethod
def compare_type(
cls, other: Union["BaseTypeDefinition", "BasePrimitive", AbstractDataType]
) -> bool:
"""
Compare this type object against another type object.
Failed comparisons must return `False`, not raise an exception.
This method is not intended to be called directly. Type comparisons
are handled by methods in `vyper.context.validation.utils`
Arguments
---------
other : BaseTypeDefinition
Another type object to be compared against this one.
Returns
-------
bool
Indicates if the types are equivalent.
"""
return isinstance(other, cls._type)
@classmethod
def fetch_call_return(self, node: vy_ast.Call) -> "BaseTypeDefinition":
"""
Validate a call to this type and return the result.
This method must raise if the type is not callable, or the call arguments
are not valid.
Arguments
---------
node : Call
Vyper ast node of call action to validate.
Returns
-------
BaseTypeDefinition, optional
Type generated as a result of the call.
"""
raise StructureException("Type is not callable", node)
@classmethod
def get_index_type(self, node: vy_ast.Index) -> None:
# always raises - do not implement in inherited classes
raise StructureException("Types cannot be indexed", node)
@classmethod
def get_member(cls, key: str, node: vy_ast.Attribute) -> None:
# always raises - do not implement in inherited classes
raise StructureException("Types do not have members", node)
@classmethod
def validate_modification(cls, node: Union[vy_ast.Assign, vy_ast.AugAssign]) -> None:
# always raises - do not implement in inherited classes
raise InvalidOperation("Cannot assign to a type", node)
class BaseTypeDefinition:
"""
Base class for type definition classes.
Type definitions are objects that represent the type of a specific object
within a contract. They are usually derived from a `BasePrimitive` counterpart.
Class Attributes
-----------------
_id : str
The name of the type.
_is_callable : bool, optional
If `True`, attempts to assign this value without calling it will raise
a more expressive error message recommending that the user performs a
function call.
Object Attributes
-----------------
is_immutable : bool, optional
If `True`, the value of this object cannot be modified after assignment.
"""
def __init__(
self,
location: DataLocation = DataLocation.UNSET,
is_immutable: bool = False,
is_public: bool = False,
) -> None:
self.location = location
self.is_immutable = is_immutable
self.is_public = is_public
def from_annotation(self, node: vy_ast.VyperNode, **kwargs: Any) -> None:
# always raises, user should have used a primitive
raise StructureException("Value is not a type", node)
def compare_type(
self, other: Union["BaseTypeDefinition", BasePrimitive, AbstractDataType]
) -> bool:
"""
Compare this type object against another type object.
Failed comparisons must return `False`, not raise an exception.
This method is not intended to be called directly. Type comparisons
are handled by methods in `vyper.context.validation.utils`
Arguments
---------
other : BaseTypeDefinition
Another type object to be compared against this one.
Returns
-------
bool
Indicates if the types are equivalent.
"""
return isinstance(other, type(self))
def validate_numeric_op(
self, node: Union[vy_ast.UnaryOp, vy_ast.BinOp, vy_ast.AugAssign]
) -> None:
"""
Validate a numeric operation for this type.
Arguments
---------
node : UnaryOp | BinOp | AugAssign
Vyper ast node of the numeric operation to be validated.
Returns
-------
None. A failed validation must raise an exception.
"""
raise InvalidOperation(f"Cannot perform {node.op.description} on {self}", node)
def validate_boolean_op(self, node: vy_ast.BoolOp) -> None:
"""
Validate a boolean operation for this type.
Arguments
---------
node : BoolOp
Vyper ast node of the boolean operation to be validated.
Returns
-------
None. A failed validation must raise an exception.
"""
raise InvalidOperation(f"Invalid type for operand: {self}", node)
def validate_comparator(self, node: vy_ast.Compare) -> None:
"""
Validate a comparator for this type.
Arguments
---------
node : Compare
Vyper ast node of the comparator to be validated.
Returns
-------
None. A failed validation must raise an exception.
"""
if not isinstance(node.op, (vy_ast.Eq, vy_ast.NotEq)):
raise InvalidOperation(
f"Cannot perform {node.op.description} comparison on {self}", node
)
def validate_implements(self, node: vy_ast.AnnAssign) -> None:
"""
Validate an implements statement.
This method is unique to user-defined interfaces. It should not be
included in other types.
Arguments
---------
node : AnnAssign
Vyper ast node of the implements statement being validated.
Returns
-------
None. A failed validation must raise an exception.
"""
raise StructureException("Value is not an interface", node)
def fetch_call_return(self, node: vy_ast.Call) -> Union["BaseTypeDefinition", None]:
"""
Validate a call to this value and return the result.
This method must raise if the value is not callable, or the call arguments
are not valid.
Arguments
---------
node : Call
Vyper ast node of call action to validate.
Returns
-------
BaseTypeDefinition, optional
Type generated as a result of the call.
"""
raise StructureException("Value is not callable", node)
def get_index_type(self, node: vy_ast.Index) -> "BaseTypeDefinition":
"""
Validate an index reference and return the given type at the index.
Arguments
---------
node : Index
Vyper ast node from the `slice` member of a Subscript node.
Returns
-------
BaseTypeDefinition
Type object for value at the given index.
"""
raise StructureException(f"Type '{self}' does not support indexing", node)
def get_member(self, key: str, node: vy_ast.Attribute) -> "BaseTypeDefinition":
"""
Validate an attribute reference and return the given type for the member.
Arguments
---------
key : str
Name of the member being accessed.
node: Attribute
Vyper ast Attribute node representing the member being accessed.
Returns
-------
BaseTypeDefinition
A type object for the value of the given member. Raises if the member
does not exist for the given type.
"""
raise StructureException(f"Type '{self}' does not support members", node)
def validate_modification(self, node: Union[vy_ast.Assign, vy_ast.AugAssign]) -> None:
"""
Validate an attempt to modify this value.
Raises if the value is a constant or involves an invalid operation.
Arguments
---------
node : Assign | AugAssign
Vyper ast node of the modifying action.
"""
if self.location == DataLocation.CALLDATA:
raise ImmutableViolation("Cannot write to calldata", node)
if self.is_immutable:
raise ImmutableViolation("Immutable value cannot be written to", node)
if isinstance(node, vy_ast.AugAssign):
self.validate_numeric_op(node)
def get_signature(self) -> Tuple[Tuple, Optional["BaseTypeDefinition"]]:
raise CompilerPanic("Method must be implemented by the inherited class")
def compare_signature(self, other: "BaseTypeDefinition") -> bool:
"""
Compare the signature of this type with another type.
Used when determining if an interface has been implemented. This method
should not be directly implemented by any inherited classes.
"""
if not self.is_public:
return False
arguments, return_type = self.get_signature()
other_arguments, other_return_type = other.get_signature()
if len(arguments) != len(other_arguments):
return False
for a, b in zip(arguments, other_arguments):
if not a.compare_type(b):
return False
if return_type and not return_type.compare_type(other_return_type): # type: ignore
return False
return True
class ValueTypeDefinition(BaseTypeDefinition):
"""
Base class for types representing a single value.
Class attributes
----------------
_valid_literal: VyperNode | Tuple
A vyper ast class or tuple of ast classes that can represent valid literals
for the given type. Including this attribute will allow literal values to be
assigned this type.
"""
def __repr__(self):
return self._id
def get_signature(self):
return (), self
class MemberTypeDefinition(ValueTypeDefinition):
"""
Base class for types that have accessible members.
Class attributes
----------------
_type_members : Dict[str, BaseType]
Dictionary of members common to all values of this type.
Object attributes
-----------------
members : OrderedDict[str, BaseType]
Dictionary of members for the given type.
"""
_type_members: Dict
def __init__(
self,
location: DataLocation = DataLocation.UNSET,
is_immutable: bool = False,
is_public: bool = False,
) -> None:
super().__init__(location, is_immutable, is_public)
self.members: OrderedDict = OrderedDict()
def add_member(self, name: str, type_: BaseTypeDefinition) -> None:
if name in self.members:
raise NamespaceCollision(f"Member {name} already exists in {self}")
if name in getattr(self, "_type_members", []):
raise NamespaceCollision(f"Member {name} already exists in {self}")
self.members[name] = type_
def get_member(self, key: str, node: vy_ast.VyperNode) -> BaseTypeDefinition:
if key in self.members:
return self.members[key]
elif key in getattr(self, "_type_members", []):
type_ = copy.deepcopy(self._type_members[key])
type_.location = self.location
type_.is_immutable = self.is_immutable
return type_
raise UnknownAttribute(f"{self} has no member '{key}'", node)
def __repr__(self):
return f"{self._id}"
class IndexableTypeDefinition(BaseTypeDefinition):
"""
Base class for indexable types such as arrays and mappings.
Attributes
----------
key_type: BaseType
Type representing the index value for this object.
value_type : BaseType
Type representing the value(s) contained in this object.
_id : str
Name of the type.
"""
def __init__(
self,
value_type: BaseTypeDefinition,
key_type: BaseTypeDefinition,
_id: str,
location: DataLocation = DataLocation.UNSET,
is_immutable: bool = False,
is_public: bool = False,
) -> None:
super().__init__(location, is_immutable, is_public)
self.value_type = value_type
self.key_type = key_type
self._id = _id
def | (self) -> Tuple[Tuple, Optional[BaseTypeDefinition]]:
new_args, return_type = self.value_type.get_signature()
return (self.key_type,) + new_args, return_type
| get_signature |
chain_spec.rs | use aura_primitives::sr25519::AuthorityId as AuraId;
use grandpa_primitives::AuthorityId as GrandpaId;
use primitives::{sr25519, Pair, Public};
use sr_primitives::traits::{IdentifyAccount, Verify};
use substrate_service;
use utxo_runtime::{
AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, IndicesConfig, Signature,
SudoConfig, SystemConfig, UtxoConfig, WASM_BINARY,
};
use primitives::H256;
use utxo_runtime::utxo;
// Note this is the URL for the telemetry server
//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = substrate_service::ChainSpec<GenesisConfig>;
/// The chain specification option. This is expected to come in from the CLI and
/// is little more than one of a number of alternatives which can easily be converted
/// from a string (`--chain=...`) into a `ChainSpec`.
#[derive(Clone, Debug)]
pub enum Alternative {
/// Whatever the current runtime is, with just Alice as an auth.
Development,
/// Whatever the current runtime is, with simple Alice/Bob auths.
LocalTestnet,
}
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed")
.public()
}
type AccountPublic = <Signature as Verify>::Signer;
/// Helper function to generate an account ID from seed
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
/// Helper function to generate an authority key for Aura
pub fn get_authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {
(get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))
}
impl Alternative {
/// Get an actual chain config from one of the alternatives.
pub(crate) fn load(self) -> Result<ChainSpec, String> {
Ok(match self {
Alternative::Development => ChainSpec::from_genesis(
"Development",
"dev",
|| {
testnet_genesis(
vec![get_authority_keys_from_seed("Alice")],
get_account_id_from_seed::<sr25519::Public>("Alice"),
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
],
true,
)
},
vec![],
None,
None,
None,
None,
),
Alternative::LocalTestnet => ChainSpec::from_genesis(
"Local Testnet",
"local_testnet",
|| {
testnet_genesis(
vec![ | get_account_id_from_seed::<sr25519::Public>("Alice"),
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
],
true,
)
},
vec![],
None,
None,
None,
None,
),
})
}
pub(crate) fn from(s: &str) -> Option<Self> {
match s {
"dev" => Some(Alternative::Development),
"" | "local" => Some(Alternative::LocalTestnet),
_ => None,
}
}
}
const NICOLE: [u8; 32] = [
68, 169, 150, 190, 177, 238, 247, 189, 202, 185, 118, 171, 109, 44, 162, 97, 4, 131, 65, 100,
236, 242, 143, 179, 117, 96, 5, 118, 252, 198, 235, 15,
];
fn testnet_genesis(
initial_authorities: Vec<(AuraId, GrandpaId)>,
root_key: AccountId,
endowed_accounts: Vec<AccountId>,
_enable_println: bool,
) -> GenesisConfig {
GenesisConfig {
system: Some(SystemConfig {
code: WASM_BINARY.to_vec(),
changes_trie_config: Default::default(),
}),
aura: Some(AuraConfig {
authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),
}),
indices: Some(IndicesConfig {
ids: endowed_accounts.clone(),
}),
balances: Some(BalancesConfig {
balances: endowed_accounts
.iter()
.cloned()
.map(|k| (k, 1 << 60))
.collect(),
vesting: vec![],
}),
sudo: Some(SudoConfig { key: root_key }),
utxo: Some(UtxoConfig {
initial_utxo: vec![utxo::TransactionOutput {
value: utxo::Value::max_value(),
pubkey: H256::from_slice(&NICOLE),
salt: 0,
}],
}),
grandpa: Some(GrandpaConfig {
authorities: initial_authorities
.iter()
.map(|x| (x.1.clone(), 1))
.collect(),
}),
}
} | get_authority_keys_from_seed("Alice"),
get_authority_keys_from_seed("Bob"),
], |
ant.py | import numpy as np
from gym.envs.mujoco import AntEnv as AntEnv_
class AntEnv(AntEnv_):
@property
def action_scaling(self):
if (not hasattr(self, 'action_space')) or (self.action_space is None):
return 1.0
if self._action_scaling is None:
lb, ub = self.action_space.low, self.action_space.high
self._action_scaling = 0.5 * (ub - lb)
return self._action_scaling
def _get_obs(self):
return np.concatenate([
self.sim.data.qpos.flat,
self.sim.data.qvel.flat,
np.clip(self.sim.data.cfrc_ext, -1, 1).flat,
self.sim.data.get_body_xmat("torso").flat,
self.get_body_com("torso").flat,
]).astype(np.float32).flatten()
def viewer_setup(self):
camera_id = self.model.camera_name2id('track')
self.viewer.cam.type = 2
self.viewer.cam.fixedcamid = camera_id
self.viewer.cam.distance = self.model.stat.extent * 0.35
# Hide the overlay
self.viewer._hide_overlay = True
def render(self, mode='human'):
if mode == 'rgb_array':
self._get_viewer().render()
# window size used for old mujoco-py:
width, height = 500, 500
data = self._get_viewer().read_pixels(width, height, depth=False)
return data
elif mode == 'human':
self._get_viewer().render()
class AntVelEnv(AntEnv):
"""Ant environment with target velocity, as described in [1]. The
code is adapted from
https://github.com/cbfinn/maml_rl/blob/9c8e2ebd741cb0c7b8bf2d040c4caeeb8e06cc95/rllab/envs/mujoco/ant_env_rand.py
The ant follows the dynamics from MuJoCo [2], and receives at each
time step a reward composed of a control cost, a contact cost, a survival
reward, and a penalty equal to the difference between its current velocity
and the target velocity. The tasks are generated by sampling the target
velocities from the uniform distribution on [0, 3].
[1] Chelsea Finn, Pieter Abbeel, Sergey Levine, "Model-Agnostic
Meta-Learning for Fast Adaptation of Deep Networks", 2017
(https://arxiv.org/abs/1703.03400)
[2] Emanuel Todorov, Tom Erez, Yuval Tassa, "MuJoCo: A physics engine for
model-based control", 2012
(https://homes.cs.washington.edu/~todorov/papers/TodorovIROS12.pdf)
"""
def __init__(self, task={}):
self._task = task
self._goal_vel = task.get('velocity', 0.0)
self._action_scaling = None
super(AntVelEnv, self).__init__()
def | (self, action):
xposbefore = self.get_body_com("torso")[0]
self.do_simulation(action, self.frame_skip)
xposafter = self.get_body_com("torso")[0]
forward_vel = (xposafter - xposbefore) / self.dt
forward_reward = -1.0 * np.abs(forward_vel - self._goal_vel) + 1.0
survive_reward = 0.05
ctrl_cost = 0.5 * 1e-2 * np.sum(np.square(action / self.action_scaling))
contact_cost = 0.5 * 1e-3 * np.sum(
np.square(np.clip(self.sim.data.cfrc_ext, -1, 1)))
observation = self._get_obs()
reward = forward_reward - ctrl_cost - contact_cost + survive_reward
state = self.state_vector()
notdone = np.isfinite(state).all() \
and state[2] >= 0.2 and state[2] <= 1.0
done = not notdone
infos = dict(reward_forward=forward_reward, reward_ctrl=-ctrl_cost,
reward_contact=-contact_cost, reward_survive=survive_reward,
task=self._task)
return (observation, reward, done, infos)
def sample_tasks(self, num_tasks):
velocities = self.np_random.uniform(0.0, 3.0, size=(num_tasks,))
tasks = [{'velocity': velocity} for velocity in velocities]
return tasks
def reset_task(self, task):
self._task = task
self._goal_vel = task['velocity']
class AntDirEnv(AntEnv):
"""Ant environment with target direction, as described in [1]. The
code is adapted from
https://github.com/cbfinn/maml_rl/blob/9c8e2ebd741cb0c7b8bf2d040c4caeeb8e06cc95/rllab/envs/mujoco/ant_env_rand_direc.py
The ant follows the dynamics from MuJoCo [2], and receives at each
time step a reward composed of a control cost, a contact cost, a survival
reward, and a reward equal to its velocity in the target direction. The
tasks are generated by sampling the target directions from a Bernoulli
distribution on {-1, 1} with parameter 0.5 (-1: backward, +1: forward).
[1] Chelsea Finn, Pieter Abbeel, Sergey Levine, "Model-Agnostic
Meta-Learning for Fast Adaptation of Deep Networks", 2017
(https://arxiv.org/abs/1703.03400)
[2] Emanuel Todorov, Tom Erez, Yuval Tassa, "MuJoCo: A physics engine for
model-based control", 2012
(https://homes.cs.washington.edu/~todorov/papers/TodorovIROS12.pdf)
"""
def __init__(self, task={}):
self._task = task
self._goal_dir = task.get('direction', 1)
self._action_scaling = None
super(AntDirEnv, self).__init__()
def step(self, action):
xposbefore = self.get_body_com("torso")[0]
self.do_simulation(action, self.frame_skip)
xposafter = self.get_body_com("torso")[0]
forward_vel = (xposafter - xposbefore) / self.dt
forward_reward = self._goal_dir * forward_vel
survive_reward = 0.05
ctrl_cost = 0.5 * 1e-2 * np.sum(np.square(action / self.action_scaling))
contact_cost = 0.5 * 1e-3 * np.sum(
np.square(np.clip(self.sim.data.cfrc_ext, -1, 1)))
observation = self._get_obs()
reward = forward_reward - ctrl_cost - contact_cost + survive_reward
state = self.state_vector()
notdone = np.isfinite(state).all() \
and state[2] >= 0.2 and state[2] <= 1.0
done = not notdone
infos = dict(reward_forward=forward_reward, reward_ctrl=-ctrl_cost,
reward_contact=-contact_cost, reward_survive=survive_reward,
task=self._task)
return (observation, reward, done, infos)
def sample_tasks(self, num_tasks):
directions = 2 * self.np_random.binomial(1, p=0.5, size=(num_tasks,)) - 1
tasks = [{'direction': direction} for direction in directions]
return tasks
def reset_task(self, task):
self._task = task
self._goal_dir = task['direction']
class AntPosEnv(AntEnv):
"""Ant environment with target position. The code is adapted from
https://github.com/cbfinn/maml_rl/blob/9c8e2ebd741cb0c7b8bf2d040c4caeeb8e06cc95/rllab/envs/mujoco/ant_env_rand_goal.py
The ant follows the dynamics from MuJoCo [1], and receives at each
time step a reward composed of a control cost, a contact cost, a survival
reward, and a penalty equal to its L1 distance to the target position. The
tasks are generated by sampling the target positions from the uniform
distribution on [-3, 3]^2.
[1] Emanuel Todorov, Tom Erez, Yuval Tassa, "MuJoCo: A physics engine for
model-based control", 2012
(https://homes.cs.washington.edu/~todorov/papers/TodorovIROS12.pdf)
"""
def __init__(self, task={}):
self._task = task
self._goal_pos = task.get('position', np.zeros((2,), dtype=np.float32))
self._action_scaling = None
super(AntPosEnv, self).__init__()
def step(self, action):
self.do_simulation(action, self.frame_skip)
xyposafter = self.get_body_com("torso")[:2]
goal_reward = -np.sum(np.abs(xyposafter - self._goal_pos)) + 4.0
survive_reward = 0.05
ctrl_cost = 0.5 * 1e-2 * np.sum(np.square(action / self.action_scaling))
contact_cost = 0.5 * 1e-3 * np.sum(
np.square(np.clip(self.sim.data.cfrc_ext, -1, 1)))
observation = self._get_obs()
reward = goal_reward - ctrl_cost - contact_cost + survive_reward
state = self.state_vector()
notdone = np.isfinite(state).all() \
and state[2] >= 0.2 and state[2] <= 1.0
done = not notdone
infos = dict(reward_goal=goal_reward, reward_ctrl=-ctrl_cost,
reward_contact=-contact_cost, reward_survive=survive_reward,
task=self._task)
return (observation, reward, done, infos)
def sample_tasks(self, num_tasks):
positions = self.np_random.uniform(-3.0, 3.0, size=(num_tasks, 2))
tasks = [{'position': position} for position in positions]
return tasks
def reset_task(self, task):
self._task = task
self._goal_pos = task['position']
| step |
vstack.rs | #[allow(unused)]
views: T,
}
// macro_rules! vstack {
// () => {
//
// }
// }
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4)
}
} | //! TODO: document this
pub struct VStack<T> { |
|
logging_db.rs | //! Provides wrappers over `RustIrDatabase` which record used definitions and write
//! `.chalk` files containing those definitions.
use std::{
borrow::Borrow,
fmt::{self, Debug, Display},
io::Write,
marker::PhantomData,
sync::Arc,
sync::Mutex,
};
use crate::rust_ir::*;
use crate::{
display::{self, WriterState},
RustIrDatabase,
};
use chalk_ir::{interner::Interner, *};
use indexmap::IndexSet;
mod id_collector;
/// Wraps another `RustIrDatabase` (`DB`) and records which definitions are
/// used.
///
/// A full .chalk file containing all used definitions can be recovered through
/// `LoggingRustIrDatabase`'s `Display` implementation.
///
/// Uses a separate type, `P`, for the database stored inside to account for
/// `Arc` or wrapping other storage mediums.
#[derive(Debug)]
pub struct LoggingRustIrDatabase<I, DB, P = DB>
where
DB: RustIrDatabase<I>,
P: Borrow<DB>,
I: Interner,
{
ws: WriterState<I, DB, P>,
def_ids: Mutex<IndexSet<RecordedItemId<I>>>,
_phantom: PhantomData<DB>,
}
impl<I, DB, P> LoggingRustIrDatabase<I, DB, P>
where
DB: RustIrDatabase<I>,
P: Borrow<DB>,
I: Interner,
{
pub fn new(db: P) -> Self {
LoggingRustIrDatabase {
ws: WriterState::new(db),
def_ids: Default::default(),
_phantom: PhantomData,
}
}
}
impl<I, DB, P> Display for LoggingRustIrDatabase<I, DB, P>
where
DB: RustIrDatabase<I>,
P: Borrow<DB>,
I: Interner,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let def_ids = self.def_ids.lock().unwrap();
let stub_ids = id_collector::collect_unrecorded_ids(self.ws.db(), &def_ids);
display::write_stub_items(f, &self.ws, stub_ids)?;
display::write_items(f, &self.ws, def_ids.iter().copied())
}
}
impl<I, DB, P> LoggingRustIrDatabase<I, DB, P>
where
DB: RustIrDatabase<I>,
P: Borrow<DB>,
I: Interner,
{
fn record(&self, id: impl Into<RecordedItemId<I>>) {
self.def_ids.lock().unwrap().insert(id.into());
}
fn record_all<T, U>(&self, ids: T)
where
T: IntoIterator<Item = U>,
U: Into<RecordedItemId<I>>,
{
self.def_ids
.lock()
.unwrap()
.extend(ids.into_iter().map(Into::into));
}
}
impl<I, DB, P> UnificationDatabase<I> for LoggingRustIrDatabase<I, DB, P>
where
DB: RustIrDatabase<I>,
P: Borrow<DB> + Debug,
I: Interner,
{
fn fn_def_variance(&self, fn_def_id: chalk_ir::FnDefId<I>) -> Variances<I> {
self.ws
.db()
.unification_database()
.fn_def_variance(fn_def_id)
}
fn adt_variance(&self, adt_id: chalk_ir::AdtId<I>) -> Variances<I> {
self.ws.db().unification_database().adt_variance(adt_id)
}
}
impl<I, DB, P> RustIrDatabase<I> for LoggingRustIrDatabase<I, DB, P>
where
DB: RustIrDatabase<I>,
P: Borrow<DB> + Debug,
I: Interner,
{
fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<I>> {
self.ws.db().custom_clauses()
}
fn associated_ty_data(
&self,
ty: chalk_ir::AssocTypeId<I>,
) -> Arc<crate::rust_ir::AssociatedTyDatum<I>> {
let ty_datum = self.ws.db().associated_ty_data(ty);
self.record(ty_datum.trait_id);
ty_datum
}
fn trait_datum(&self, trait_id: TraitId<I>) -> Arc<TraitDatum<I>> {
self.record(trait_id);
self.ws.db().trait_datum(trait_id)
}
fn adt_datum(&self, adt_id: AdtId<I>) -> Arc<AdtDatum<I>> {
self.record(adt_id);
self.ws.db().adt_datum(adt_id)
}
| fn generator_datum(&self, generator_id: GeneratorId<I>) -> Arc<GeneratorDatum<I>> {
self.record(generator_id);
self.ws.db().borrow().generator_datum(generator_id)
}
fn generator_witness_datum(
&self,
generator_id: GeneratorId<I>,
) -> Arc<GeneratorWitnessDatum<I>> {
self.record(generator_id);
self.ws.db().borrow().generator_witness_datum(generator_id)
}
fn adt_repr(&self, id: AdtId<I>) -> Arc<AdtRepr<I>> {
self.record(id);
self.ws.db().adt_repr(id)
}
fn impl_datum(&self, impl_id: ImplId<I>) -> Arc<ImplDatum<I>> {
self.record(impl_id);
self.ws.db().impl_datum(impl_id)
}
fn hidden_opaque_type(&self, id: OpaqueTyId<I>) -> Ty<I> {
self.record(id);
self.ws.db().hidden_opaque_type(id)
}
fn associated_ty_value(
&self,
id: crate::rust_ir::AssociatedTyValueId<I>,
) -> Arc<crate::rust_ir::AssociatedTyValue<I>> {
let value = self.ws.db().associated_ty_value(id);
self.record(value.impl_id);
value
}
fn opaque_ty_data(&self, id: OpaqueTyId<I>) -> Arc<OpaqueTyDatum<I>> {
self.record(id);
self.ws.db().opaque_ty_data(id)
}
fn impls_for_trait(
&self,
trait_id: TraitId<I>,
parameters: &[chalk_ir::GenericArg<I>],
binders: &CanonicalVarKinds<I>,
) -> Vec<ImplId<I>> {
self.record(trait_id);
let impl_ids = self.ws.db().impls_for_trait(trait_id, parameters, binders);
self.record_all(impl_ids.iter().copied());
impl_ids
}
fn local_impls_to_coherence_check(&self, trait_id: TraitId<I>) -> Vec<ImplId<I>> {
self.record(trait_id);
self.ws.db().local_impls_to_coherence_check(trait_id)
}
fn impl_provided_for(&self, auto_trait_id: TraitId<I>, ty: &TyKind<I>) -> bool {
self.record(auto_trait_id);
if let TyKind::Adt(adt_id, _) = ty {
self.record(*adt_id);
}
self.ws.db().impl_provided_for(auto_trait_id, ty)
}
fn well_known_trait_id(
&self,
well_known_trait: crate::rust_ir::WellKnownTrait,
) -> Option<TraitId<I>> {
let trait_id = self.ws.db().well_known_trait_id(well_known_trait);
if let Some(id) = trait_id {
self.record(id);
}
trait_id
}
fn program_clauses_for_env(
&self,
environment: &chalk_ir::Environment<I>,
) -> chalk_ir::ProgramClauses<I> {
self.ws.db().program_clauses_for_env(environment)
}
fn interner(&self) -> I {
self.ws.db().interner()
}
fn trait_name(&self, trait_id: TraitId<I>) -> String {
self.ws.db().trait_name(trait_id)
}
fn adt_name(&self, adt_id: AdtId<I>) -> String {
self.ws.db().adt_name(adt_id)
}
fn assoc_type_name(&self, assoc_ty_id: AssocTypeId<I>) -> String {
self.ws.db().assoc_type_name(assoc_ty_id)
}
fn opaque_type_name(&self, opaque_ty_id: OpaqueTyId<I>) -> String {
self.ws.db().opaque_type_name(opaque_ty_id)
}
fn is_object_safe(&self, trait_id: TraitId<I>) -> bool {
self.record(trait_id);
self.ws.db().is_object_safe(trait_id)
}
fn fn_def_datum(&self, fn_def_id: chalk_ir::FnDefId<I>) -> Arc<FnDefDatum<I>> {
self.record(fn_def_id);
self.ws.db().fn_def_datum(fn_def_id)
}
fn fn_def_name(&self, fn_def_id: FnDefId<I>) -> String {
self.ws.db().fn_def_name(fn_def_id)
}
fn closure_kind(&self, closure_id: ClosureId<I>, substs: &Substitution<I>) -> ClosureKind {
// TODO: record closure IDs
self.ws.db().closure_kind(closure_id, substs)
}
fn closure_inputs_and_output(
&self,
closure_id: ClosureId<I>,
substs: &Substitution<I>,
) -> Binders<FnDefInputsAndOutputDatum<I>> {
// TODO: record closure IDs
self.ws.db().closure_inputs_and_output(closure_id, substs)
}
fn closure_upvars(&self, closure_id: ClosureId<I>, substs: &Substitution<I>) -> Binders<Ty<I>> {
// TODO: record closure IDs
self.ws.db().closure_upvars(closure_id, substs)
}
fn closure_fn_substitution(
&self,
closure_id: ClosureId<I>,
substs: &Substitution<I>,
) -> Substitution<I> {
// TODO: record closure IDs
self.ws.db().closure_fn_substitution(closure_id, substs)
}
fn discriminant_type(&self, ty: Ty<I>) -> Ty<I> {
self.ws.db().discriminant_type(ty)
}
fn unification_database(&self) -> &dyn UnificationDatabase<I> {
self
}
}
/// Wraps a [`RustIrDatabase`], and, when dropped, writes out all used
/// definition to the given file.
///
/// Uses [`LoggingRustIrDatabase`] internally.
///
/// Uses a separate type, `P`, for the database stored inside to account for
/// `Arc` or wrapping other storage mediums.
pub struct WriteOnDropRustIrDatabase<I, W, DB, P = DB>
where
I: Interner,
W: Write,
DB: RustIrDatabase<I>,
P: Borrow<DB>,
{
db: LoggingRustIrDatabase<I, DB, P>,
write: W,
}
impl<I, W, DB, P> fmt::Debug for WriteOnDropRustIrDatabase<I, W, DB, P>
where
I: Interner,
W: Write,
DB: RustIrDatabase<I>,
P: Borrow<DB> + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WriteOnDropRustIrDatabase")
.field("db", &self.db)
.field("write", &"<opaque>")
.finish()
}
}
impl<I, W, DB, P> WriteOnDropRustIrDatabase<I, W, DB, P>
where
I: Interner,
W: Write,
DB: RustIrDatabase<I>,
P: Borrow<DB>,
{
pub fn new(db: P, write: W) -> Self {
WriteOnDropRustIrDatabase {
db: LoggingRustIrDatabase::new(db),
write,
}
}
pub fn from_logging_db(db: LoggingRustIrDatabase<I, DB, P>, write: W) -> Self {
WriteOnDropRustIrDatabase { db, write }
}
}
impl<I, W, DB, P> Drop for WriteOnDropRustIrDatabase<I, W, DB, P>
where
I: Interner,
W: Write,
DB: RustIrDatabase<I>,
P: Borrow<DB>,
{
fn drop(&mut self) {
write!(self.write, "{}", self.db)
.and_then(|_| self.write.flush())
.expect("expected to be able to write rust ir database");
}
}
impl<I, W, DB, P> UnificationDatabase<I> for WriteOnDropRustIrDatabase<I, W, DB, P>
where
I: Interner,
W: Write,
DB: RustIrDatabase<I>,
P: Borrow<DB> + Debug,
{
fn fn_def_variance(&self, fn_def_id: chalk_ir::FnDefId<I>) -> Variances<I> {
self.db
.borrow()
.unification_database()
.fn_def_variance(fn_def_id)
}
fn adt_variance(&self, adt_id: chalk_ir::AdtId<I>) -> Variances<I> {
self.db.borrow().unification_database().adt_variance(adt_id)
}
}
impl<I, W, DB, P> RustIrDatabase<I> for WriteOnDropRustIrDatabase<I, W, DB, P>
where
I: Interner,
W: Write,
DB: RustIrDatabase<I>,
P: Borrow<DB> + Debug,
{
fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<I>> {
self.db.custom_clauses()
}
fn associated_ty_data(
&self,
ty: chalk_ir::AssocTypeId<I>,
) -> Arc<crate::rust_ir::AssociatedTyDatum<I>> {
self.db.associated_ty_data(ty)
}
fn trait_datum(&self, trait_id: TraitId<I>) -> Arc<TraitDatum<I>> {
self.db.trait_datum(trait_id)
}
fn adt_datum(&self, adt_id: AdtId<I>) -> Arc<AdtDatum<I>> {
self.db.adt_datum(adt_id)
}
fn generator_datum(&self, generator_id: GeneratorId<I>) -> Arc<GeneratorDatum<I>> {
self.db.borrow().generator_datum(generator_id)
}
/// Returns the generator witness datum for the generator with the given id.
fn generator_witness_datum(
&self,
generator_id: GeneratorId<I>,
) -> Arc<GeneratorWitnessDatum<I>> {
self.db.borrow().generator_witness_datum(generator_id)
}
fn adt_repr(&self, id: AdtId<I>) -> Arc<AdtRepr<I>> {
self.db.adt_repr(id)
}
fn impl_datum(&self, impl_id: ImplId<I>) -> Arc<ImplDatum<I>> {
self.db.impl_datum(impl_id)
}
fn associated_ty_value(
&self,
id: crate::rust_ir::AssociatedTyValueId<I>,
) -> Arc<crate::rust_ir::AssociatedTyValue<I>> {
self.db.associated_ty_value(id)
}
fn opaque_ty_data(&self, id: OpaqueTyId<I>) -> Arc<OpaqueTyDatum<I>> {
self.db.opaque_ty_data(id)
}
fn hidden_opaque_type(&self, id: OpaqueTyId<I>) -> Ty<I> {
self.db.hidden_opaque_type(id)
}
fn impls_for_trait(
&self,
trait_id: TraitId<I>,
parameters: &[chalk_ir::GenericArg<I>],
binders: &CanonicalVarKinds<I>,
) -> Vec<ImplId<I>> {
self.db.impls_for_trait(trait_id, parameters, binders)
}
fn local_impls_to_coherence_check(&self, trait_id: TraitId<I>) -> Vec<ImplId<I>> {
self.db.local_impls_to_coherence_check(trait_id)
}
fn impl_provided_for(&self, auto_trait_id: TraitId<I>, ty: &TyKind<I>) -> bool {
self.db.impl_provided_for(auto_trait_id, ty)
}
fn well_known_trait_id(
&self,
well_known_trait: crate::rust_ir::WellKnownTrait,
) -> Option<TraitId<I>> {
self.db.well_known_trait_id(well_known_trait)
}
fn program_clauses_for_env(
&self,
environment: &chalk_ir::Environment<I>,
) -> chalk_ir::ProgramClauses<I> {
self.db.program_clauses_for_env(environment)
}
fn interner(&self) -> I {
self.db.interner()
}
fn is_object_safe(&self, trait_id: TraitId<I>) -> bool {
self.db.is_object_safe(trait_id)
}
fn unification_database(&self) -> &dyn UnificationDatabase<I> {
self
}
fn trait_name(&self, trait_id: TraitId<I>) -> String {
self.db.trait_name(trait_id)
}
fn adt_name(&self, adt_id: AdtId<I>) -> String {
self.db.adt_name(adt_id)
}
fn assoc_type_name(&self, assoc_ty_id: AssocTypeId<I>) -> String {
self.db.assoc_type_name(assoc_ty_id)
}
fn opaque_type_name(&self, opaque_ty_id: OpaqueTyId<I>) -> String {
self.db.opaque_type_name(opaque_ty_id)
}
fn fn_def_datum(&self, fn_def_id: chalk_ir::FnDefId<I>) -> Arc<FnDefDatum<I>> {
self.db.fn_def_datum(fn_def_id)
}
fn fn_def_name(&self, fn_def_id: FnDefId<I>) -> String {
self.db.fn_def_name(fn_def_id)
}
fn closure_kind(&self, closure_id: ClosureId<I>, substs: &Substitution<I>) -> ClosureKind {
// TODO: record closure IDs
self.db.closure_kind(closure_id, substs)
}
fn closure_inputs_and_output(
&self,
closure_id: ClosureId<I>,
substs: &Substitution<I>,
) -> Binders<FnDefInputsAndOutputDatum<I>> {
self.db.closure_inputs_and_output(closure_id, substs)
}
fn closure_upvars(&self, closure_id: ClosureId<I>, substs: &Substitution<I>) -> Binders<Ty<I>> {
self.db.closure_upvars(closure_id, substs)
}
fn closure_fn_substitution(
&self,
closure_id: ClosureId<I>,
substs: &Substitution<I>,
) -> Substitution<I> {
self.db.closure_fn_substitution(closure_id, substs)
}
fn discriminant_type(&self, ty: Ty<I>) -> Ty<I> {
self.db.discriminant_type(ty)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum RecordedItemId<I: Interner> {
Adt(AdtId<I>),
Trait(TraitId<I>),
Impl(ImplId<I>),
OpaqueTy(OpaqueTyId<I>),
FnDef(FnDefId<I>),
Generator(GeneratorId<I>),
}
impl<I: Interner> From<AdtId<I>> for RecordedItemId<I> {
fn from(v: AdtId<I>) -> Self {
RecordedItemId::Adt(v)
}
}
impl<I: Interner> From<TraitId<I>> for RecordedItemId<I> {
fn from(v: TraitId<I>) -> Self {
RecordedItemId::Trait(v)
}
}
impl<I: Interner> From<ImplId<I>> for RecordedItemId<I> {
fn from(v: ImplId<I>) -> Self {
RecordedItemId::Impl(v)
}
}
impl<I: Interner> From<OpaqueTyId<I>> for RecordedItemId<I> {
fn from(v: OpaqueTyId<I>) -> Self {
RecordedItemId::OpaqueTy(v)
}
}
impl<I: Interner> From<FnDefId<I>> for RecordedItemId<I> {
fn from(v: FnDefId<I>) -> Self {
RecordedItemId::FnDef(v)
}
}
impl<I: Interner> From<GeneratorId<I>> for RecordedItemId<I> {
fn from(v: GeneratorId<I>) -> Self {
RecordedItemId::Generator(v)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.