file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
passwd.py
# Copyright (c) 2018 Aaron LI <[email protected]> # MIT License """ Custom Ansible template filters to crypt/hash passwords. """ import os import base64 import crypt import hashlib def cryptpass(p): """ Crypt the given plaintext password with salted SHA512 scheme, which is supported by Linux/BSDs. """ hashtype = "$6$" saltlen = 16 salt = os.urandom(saltlen) salt = base64.b64encode(salt)[:saltlen].decode("utf-8") return crypt.crypt(p, hashtype+salt) def dovecot_makepass(p): """ Generate the salted hashed password for Dovecot using the SHA512-CRYPT scheme. Implement the "doveadm pw -s SHA512-CRYPT" command. Dovecot password format: {<scheme>}$<type>$<salt>$<hash> """ scheme = "SHA512-CRYPT" cp = cryptpass(p) return "{%s}%s" % (scheme, cp) def znc_makepass(p, method="sha256", saltlen=20): """ Generate the salted hashed password for ZNC configuration. Implement the "znc --makepass" command. ZNC password format: <method>#<hash>#<salt> """ salt = os.urandom(saltlen) salt = base64.b64encode(salt)[:saltlen].decode("utf-8") s = p + salt h = getattr(hashlib, method)(s.encode("utf-8")) return "%s#%s#%s" % (method, h.hexdigest(), salt)
class FilterModule(object): def filters(self): return { "cryptpass": cryptpass, "dovecot_makepass": dovecot_makepass, "znc_makepass": znc_makepass, }
mod.rs
use crate::cpu::bit_ops::*; use crate::cpu::control_ops::*; use crate::cpu::eight_bit_arithm_logic_ops::*; use crate::cpu::eight_bit_load_ops::*; use crate::cpu::instructions::*; use crate::cpu::jump_ops::*; use crate::cpu::registers::*; use crate::cpu::rotate_ops::*; use crate::cpu::sixteen_bit_arithm_logic_ops::*; use crate::cpu::sixteen_bit_load_ops::*; use crate::memory::Memory; mod bit_ops; mod control_ops; mod eight_bit_arithm_logic_ops; mod eight_bit_load_ops; mod jump_ops; mod rotate_ops; mod sixteen_bit_arithm_logic_ops; mod sixteen_bit_load_ops; mod instructions; mod registers; pub struct CPU<'memory> { registers: Registers, memory: &'memory mut Memory, interrupts_enabled: bool, } impl<'memory> CPU<'memory> { pub fn new(memory: &'memory mut Memory) -> Self { CPU { registers: Registers::new(), memory, interrupts_enabled: true, } } /// ROMs start running at PC = 0x100 after the bootloader. /// This method creates a new CPU setting the registers and memory with the /// values when PC = 0x100 I observed when debugging test ROMs using the /// BGB emulator. pub fn new_at_0x100(memory: &'memory mut Memory) -> Self { let mut registers = Registers::new(); registers.write_pc(0x100); registers.write_sp(0xFFFE); registers.write_16b(&Register16bits::AF, 0x1180); registers.write_16b(&Register16bits::BC, 0x0000); registers.write_16b(&Register16bits::DE, 0xFF56); registers.write_16b(&Register16bits::HL, 0x000D); registers.write_flags(true, false, false, false); memory.write_byte(0xFF0F, 0xE1); CPU { registers, memory, interrupts_enabled: false, } } pub fn run_next_instruction(&mut self) { if self.attend_pending_interrupt() { return; } let mut instruction_byte = self.fetch_byte(); let prefixed = instruction_byte == instructions::PREFIX_INSTR_CODE; let instruction = if prefixed { instruction_byte = self.fetch_byte(); Instruction::decode_prefixed(instruction_byte) } else { Instruction::decode(instruction_byte) }; self.execute(instruction); } pub fn execute(&mut self, instruction: Instruction) { match instruction { // 8-bit arithmetic and logic Instruction::ADD(register) => add(self, register), Instruction::ADDHL => add_hl(self), Instruction::ADDD8 => add_d8(self), Instruction::INC(register) => inc(self, register), Instruction::INCHL => inc_hl(self), Instruction::ADC(register) => adc(self, register), Instruction::ADCHL => adc_hl(self), Instruction::ADCD8 => adc_d8(self), Instruction::SUB(register) => sub(self, register), Instruction::SUBHL => sub_hl(self), Instruction::SUBD8 => sub_d8(self), Instruction::AND(register) => and(self, register), Instruction::ANDHL => and_hl(self), Instruction::ANDD8 => and_d8(self), Instruction::OR(register) => or(self, register), Instruction::ORHL => or_hl(self), Instruction::ORD8 => or_d8(self), Instruction::XOR(register) => xor(self, register), Instruction::XORHL => xor_hl(self), Instruction::XORD8 => xor_d8(self), Instruction::CP(register) => cp(self, register), Instruction::CPHL => cp_hl(self), Instruction::CPD8 => cp_d8(self), Instruction::DEC(register) => dec(self, register), Instruction::DECHL => dec_hl(self), Instruction::SBC(register) => sbc(self, register), Instruction::SBCHL => sbc_hl(self), Instruction::SBCD8 => sbc_d8(self), Instruction::CPL => cpl(self), Instruction::DAA => daa(self), // 16-bit arithmetic and logic Instruction::ADD16(register) => add16(self, register), Instruction::DEC16(register) => dec16(self, register), Instruction::DECSP => dec_sp(self), Instruction::INC16(register) => inc16(self, register), Instruction::INCSP => inc_sp(self),
Instruction::RES(bit, register) => res(self, bit, register), Instruction::RESHL(bit) => res_hl(self, bit), Instruction::SET(bit, register) => set(self, bit, register), Instruction::SETHL(bit) => set_hl(self, bit), // Rotates and shifts Instruction::RL(register) => rl(self, register), Instruction::RLA => rla(self), Instruction::RLHL => rl_hl(self), Instruction::RLC(register) => rlc(self, register), Instruction::RLCA => rlca(self), Instruction::RLCHL => rlc_hl(self), Instruction::RR(register) => rr(self, register), Instruction::RRA => rra(self), Instruction::RRHL => rr_hl(self), Instruction::RRC(register) => rrc(self, register), Instruction::RRCA => rrca(self), Instruction::RRCHL => rrc_hl(self), Instruction::SLA(register) => sla(self, register), Instruction::SLAHL => sla_hl(self), Instruction::SRA(register) => sra(self, register), Instruction::SRAHL => sra_hl(self), Instruction::SRL(register) => srl(self, register), Instruction::SRLHL => srl_hl(self), Instruction::SWAP(register) => swap(self, register), Instruction::SWAPHL => swap_hl(self), // 8-bit load Instruction::LDR8R8(r1, r2) => ld_r8_r8(self, r1, r2), Instruction::LDR8D8(register) => ld_r8_d8(self, register), Instruction::LDHLD8 => ld_hl_d8(self), Instruction::LDR8ADDR(r1, r2) => ld_r8_addr(self, r1, r2), Instruction::LDADDRR8(r1, r2) => ld_addr_r8(self, r1, r2), Instruction::LDAHLI => ld_a_hli(self), Instruction::LDAHLD => ld_a_hld(self), Instruction::LDHLIA => ld_hli_a(self), Instruction::LDHLDA => ld_hld_a(self), Instruction::LDHLR8(register) => ld_hl_r8(self, register), Instruction::LDR8HL(register) => ld_r8_hl(self, register), Instruction::LDR16R8(r16, r8) => ld_r16_r8(self, r16, r8), Instruction::LDR8R16(r8, r16) => ld_r8_r16(self, r8, r16), Instruction::LDA8A => ld_a8_a(self), Instruction::LDAA8 => ld_a_a8(self), Instruction::LDA16A => ld_a16_a(self), Instruction::LDAA16 => ld_a_a16(self), // 16-bit load Instruction::LDR16D16(register) => ld_r16_d16(self, register), Instruction::LDSPD16 => ld_sp_d16(self), Instruction::LDA16SP => ld_a16_sp(self), Instruction::ADDHLSP => add_hl_sp(self), Instruction::LDSPHL => ld_sp_hl(self), Instruction::ADDSPr8 => add_sp_r8(self), Instruction::LDHLSPr8 => ld_hl_sp_r8(self), Instruction::PUSH(register) => push(self, register), Instruction::POP(register) => pop(self, register), // Control Instruction::CCF => ccf(self), Instruction::NOP => nop(), Instruction::SCF => scf(self), Instruction::HALT => halt(), Instruction::STOP => stop(), Instruction::DI => di(self), Instruction::EI => ei(self), Instruction::PREFIX => (), // Jumps Instruction::JP(condition) => jp(self, condition), Instruction::JPHL => jp_hl(self), Instruction::JR(condition) => jr(self, condition), Instruction::RST(offset) => rst(self, offset), Instruction::RET(condition) => ret(self, condition), Instruction::RETI => reti(self), Instruction::CALL(condition) => call(self, condition), Instruction::UNUSED => panic!("Tried to run unknown op code"), } } fn half_carry_in_add_16(x: u16, y: u16) -> bool { (x & 0xFFF) + (y & 0xFFF) > 0xFFF } fn fetch_byte(&mut self) -> u8 { let byte = self.memory.read_byte(self.registers.pc()); self.registers.increase_pc(1); byte } fn fetch_word(&mut self) -> u16 { let low = u16::from(self.fetch_byte()); let hi = u16::from(self.fetch_byte()); (hi << 8) | low } fn read_d8(&mut self) -> u8 { self.fetch_byte() } fn read_d16(&mut self) -> u16 { self.fetch_word() } fn read_a16(&mut self) -> u16 { self.fetch_word() } fn push_to_stack(&mut self, value: u16) { self.registers.decrease_sp(2); self.memory.write_word(self.registers.sp(), value); } fn pop_from_stack(&mut self) -> u16 { let value = self.memory.read_word(self.registers.sp()); self.registers.increase_sp(2); value } // Uses the value stored in a 16 bit register as an address and returns the // byte stored in that memory address. fn value_in_addr(&self, register: &Register16bits) -> u8 { let register_val = self.registers.read_16b(register); self.memory.read_byte(register_val) } fn attend_pending_interrupt(&mut self) -> bool { if self.interrupts_enabled { let isr_addr = self.memory.interrupts.isr_of_first_pending(); match isr_addr { Some(addr) => { self.interrupts_enabled = false; self.push_to_stack(self.registers.pc()); self.registers.write_pc(addr); return true; } None => return false, } } false } }
// Bit operations Instruction::BIT(bit_n, register) => bit(self, bit_n, register), Instruction::BITHL(bit) => bit_hl(self, bit),
myFileClass.py
import sys import sqlite3 import hashlib import time import logging import os.path logger = logging.getLogger(__name__) logpath = os.path.dirname(__file__) logpath = os.path.join(logpath, 'logs/') fileHandler = logging.FileHandler(logpath + __name__ + '.log') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fileHandler.setFormatter(formatter) fileHandler.setLevel(logging.INFO) logger.addHandler(fileHandler) def create(fname='hashes.sqlite'): conn = sqlite3.connect(fname) c = conn.cursor() # Create table c.execute( 'CREATE TABLE hashes(filename text, md5 text, sha1 text, hashtime real)' ) conn.commit() # We can also close the connection if we are done with it. # Just be sure any changes have been committed or they will be lost. conn.close() # based on # http://stackoverflow.com/questions/16085292/subclassing-file-objects-to-extend-open-and-close-operations-in-python-3 class _file_obj(object): """Check if `f` is a file name and open the file in `mode`. A context manager.""" hashdb = None def
(self, f, mode): if f is None: self.file = { 'r': sys.stdin, 'a': sys.stdout, 'w': sys.stdout }[mode[0]] self.none = True elif isinstance(f, str): self.file = open(f, mode) else: self.file = f self.close_file = (self.file is not f) self.md5 = hashlib.md5() self.sha1 = hashlib.sha1() # self.hashdb = None def __enter__(self): return self def __exit__(self, *args, **kwargs): if (not self.close_file) or hasattr(self, 'none'): return # do nothing # clean up exit = getattr(self.file, '__exit__', None) if exit is not None: return exit(*args, **kwargs) else: exit = getattr(self.file, 'close', None) if exit is not None: exit() def write(self, rawdata): byteswritten = self.file.tell() res = self.file.write(rawdata) # if res is not None: # It is None in python2 # logger.error('Problem with writing to file, res: %r' % res) byteswritten = self.file.tell() - byteswritten self.md5.update(rawdata) self.sha1.update(rawdata) # if self.hashdb is not None: # print('md5: %s, sha1: %s'%(self.md5.hexdigest(), # self.sha1.hexdigest())) # self.updatehashdb() return byteswritten def close(self): if self.hashdb is not None: logger.info('md5: %s, sha1: %s' % (self.md5.hexdigest(), self.sha1.hexdigest())) self.updatehashdb() return self.file.close() def updatehashdb(self): conn = sqlite3.connect(self.hashdb) c = conn.cursor() c.execute("INSERT INTO hashes VALUES (?,?,?,?)", (self.file.name, self.md5.hexdigest(), self.sha1.hexdigest(), time.time())) conn.commit() conn.close() def __getattr__(self, attr): return getattr(self.file, attr) def __iter__(self): return iter(self.file)
__init__
async_ops.rs
//! TicKV can be used asynchronously. This module provides documentation and //! tests for using it with an async `FlashController` interface. //! //! To do this first there are special error values to return from the //! `FlashController` functions. These are the `ReadNotReady`, `WriteNotReady` //! and `EraseNotReady` types. //! //! ```rust //! // EXAMPLE ONLY: The `DefaultHasher` is subject to change //! // and hence is not a good fit. //! use std::collections::hash_map::DefaultHasher; //! use core::hash::{Hash, Hasher}; //! use std::cell::{Cell, RefCell}; //! use tickv::{AsyncTicKV, MAIN_KEY}; //! use tickv::error_codes::ErrorCode; //! use tickv::flash_controller::FlashController; //! //! fn get_hashed_key(unhashed_key: &[u8]) -> u64 { //! let mut hash_function = DefaultHasher::new(); //! unhashed_key.hash(&mut hash_function); //! hash_function.finish() //! } //! //! struct FlashCtrl { //! buf: RefCell<[[u8; 1024]; 64]>, //! async_read_region: Cell<usize>, //! async_erase_region: Cell<usize>, //! } //! //! impl FlashCtrl { //! fn new() -> Self { //! Self { //! buf: RefCell::new([[0xFF; 1024]; 64]), //! async_read_region: Cell::new(10), //! async_erase_region: Cell::new(10), //! } //! } //! } //! //! impl FlashController<1024> for FlashCtrl { //! fn read_region( //! &self, //! region_number: usize, //! offset: usize, //! buf: &mut [u8; 1024], //! ) -> Result<(), ErrorCode> { //! // We aren't ready yet, launch the async operation //! self.async_read_region.set(region_number); //! return Err(ErrorCode::ReadNotReady(region_number)); //! //! Ok(()) //! } //! //! fn write(&self, address: usize, buf: &[u8]) -> Result<(), ErrorCode> { //! // Save the write operation to a queue, we don't need to re-call //! for (i, d) in buf.iter().enumerate() { //! self.buf.borrow_mut()[address / 1024][(address % 1024) + i] = *d; //! } //! Ok(()) //! } //! //! fn erase_region(&self, region_number: usize) -> Result<(), ErrorCode> { //! if self.async_erase_region.get() != region_number { //! // We aren't ready yet, launch the async operation //! self.async_erase_region.set(region_number); //! return Err(ErrorCode::EraseNotReady(region_number)); //! } //! //! Ok(()) //! } //! } //! //! // Create the TicKV instance and loop until everything is done //! // NOTE in an real implementation you will want to wait on //! // callbacks/interrupts and make this async. //! //! let mut read_buf: [u8; 1024] = [0; 1024]; //! let mut hash_function = DefaultHasher::new(); //! MAIN_KEY.hash(&mut hash_function); //! let tickv = AsyncTicKV::<FlashCtrl, 1024>::new(FlashCtrl::new(), //! &mut read_buf, 0x1000); //! //! let mut ret = tickv.initialise(hash_function.finish()); //! while ret.is_err() { //! // There is no actual delay here, in a real implementation wait on some event //! ret = tickv.continue_operation().0; //! //! match ret { //! Err(ErrorCode::ReadNotReady(reg)) => { //! tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); //! } //! Ok(_) => break, //! Err(ErrorCode::WriteNotReady(reg)) => break, //! Err(ErrorCode::EraseNotReady(reg)) => {} //! _ => unreachable!(), //! } //! } //! //! // Then when calling the TicKV function check for the error. For example //! // when appending a key: //! //! // Add a key //! static mut VALUE: [u8; 32] = [0x23; 32]; //! let ret = unsafe { tickv.append_key(get_hashed_key(b"ONE"), &mut VALUE) }; //! //! match ret { //! Err((_buf, ErrorCode::ReadNotReady(reg))) => { //! // There is no actual delay in the test, just continue now //! tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); //! tickv //! .continue_operation().0 //! .unwrap(); //! } //! Ok(_) => {} //! _ => unreachable!(), //! } //! //! ``` //! //! This will call into the `FlashController` again where the //! `FlashController` implementation must return the data that is requested. //! If the data isn't ready (multiple reads might occur) then the `NotReady` //! error types can still be used. //! use crate::error_codes::ErrorCode; use crate::flash_controller::FlashController; use crate::success_codes::SuccessCode; use crate::tickv::{State, TicKV}; use core::cell::Cell; /// The return type from the continue operation type ContinueReturn = ( // Result Result<SuccessCode, ErrorCode>, // Buf Buffer Option<&'static mut [u8]>, ); /// The struct storing all of the TicKV information for the async implementation. pub struct AsyncTicKV<'a, C: FlashController<S>, const S: usize> { /// The main TicKV struct pub tickv: TicKV<'a, C, S>, key: Cell<Option<u64>>, value: Cell<Option<&'static mut [u8]>>, buf: Cell<Option<&'static mut [u8]>>, } impl<'a, C: FlashController<S>, const S: usize> AsyncTicKV<'a, C, S> { /// Create a new struct /// /// `C`: An implementation of the `FlashController` trait /// /// `controller`: An new struct implementing `FlashController` /// `flash_size`: The total size of the flash used for TicKV pub fn new(controller: C, read_buffer: &'a mut [u8; S], flash_size: usize) -> Self { Self { tickv: TicKV::<C, S>::new(controller, read_buffer, flash_size), key: Cell::new(None), value: Cell::new(None), buf: Cell::new(None), } } /// This function setups the flash region to be used as a key-value store. /// If the region is already initialised this won't make any changes. /// /// `hashed_main_key`: The u64 hash of the const string `MAIN_KEY`. /// /// If the specified region has not already been setup for TicKV /// the entire region will be erased. /// /// On success a `SuccessCode` will be returned. /// On error a `ErrorCode` will be returned. pub fn initialise(&self, hashed_main_key: u64) -> Result<SuccessCode, ErrorCode> { self.key.replace(Some(hashed_main_key)); self.tickv.initialise(hashed_main_key) } /// Appends the key/value pair to flash storage. /// /// `hash`: A hashed key. This key will be used in future to retrieve /// or remove the `value`. /// `value`: A buffer containing the data to be stored to flash. /// /// On success nothing will be returned. /// On error a `ErrorCode` will be returned. pub fn append_key( &self, hash: u64, value: &'static mut [u8], ) -> Result<SuccessCode, (Option<&'static mut [u8]>, ErrorCode)> { match self.tickv.append_key(hash, value) { Ok(code) => Ok(code), Err(e) => match e { ErrorCode::ReadNotReady(_) | ErrorCode::EraseNotReady(_) | ErrorCode::WriteNotReady(_) => { self.key.replace(Some(hash)); self.value.replace(Some(value)); Err((None, e)) } _ => Err((Some(value), e)), }, } } /// Retrieves the value from flash storage. /// /// `hash`: A hashed key. /// `buf`: A buffer to store the value to. /// /// On success a `SuccessCode` will be returned. /// On error a `ErrorCode` will be returned. /// /// If a power loss occurs before success is returned the data is /// assumed to be lost. pub fn get_key( &self, hash: u64, buf: &'static mut [u8], ) -> Result<SuccessCode, (Option<&'static mut [u8]>, ErrorCode)> { match self.tickv.get_key(hash, buf) { Ok(code) => Ok(code), Err(e) => match e { ErrorCode::ReadNotReady(_) | ErrorCode::EraseNotReady(_) | ErrorCode::WriteNotReady(_) => { self.key.replace(Some(hash)); self.buf.replace(Some(buf)); Err((None, e)) } _ => Err((Some(buf), e)), }, } } /// Invalidates the key in flash storage /// /// `hash`: A hashed key. /// `key`: A unhashed key. This will be hashed internally. /// /// On success a `SuccessCode` will be returned. /// On error a `ErrorCode` will be returned. /// /// If a power loss occurs before success is returned the data is /// assumed to be lost. pub fn invalidate_key(&self, hash: u64) -> Result<SuccessCode, ErrorCode> { match self.tickv.invalidate_key(hash) { Ok(code) => Ok(code), Err(e) => { self.key.replace(Some(hash)); Err(e) } } } /// Perform a garbage collection on TicKV /// /// On success the number of bytes freed will be returned. /// On error a `ErrorCode` will be returned. pub fn garbage_collect(&self) -> Result<usize, ErrorCode> { self.tickv.garbage_collect() } /// Copy data from `read_buffer` argument to the internal read_buffer. /// This should be used to copy the data that the implementation wanted /// to read when calling `read_region` after the async operation has /// completed. pub fn set_read_buffer(&self, read_buffer: &[u8]) { let buf = self.tickv.read_buffer.take().unwrap(); buf.copy_from_slice(read_buffer); self.tickv.read_buffer.replace(Some(buf)); } /// Get the `value` buffer that was passed in by previous /// commands. pub fn
(&self) -> Option<&'static mut [u8]> { self.value.take() } /// Get the `buf` buffer that was passed in by previous /// commands. pub fn get_stored_buffer(&self) -> Option<&'static mut [u8]> { self.buf.take() } /// Continue the last operation after the async operation has completed. /// This should be called from a read/erase complete callback. /// NOTE: If called from a read callback, `set_read_buffer` should be /// called first to update the data. /// /// `hash_function`: Hash function with no previous state. This is /// usually a newly created hash. /// /// Returns a tuple of 4 values /// Result: /// On success a `SuccessCode` will be returned. /// On error a `ErrorCode` will be returned. /// Buf Buffer: /// An option of the buf buffer used /// The buffers will only be returned on a non async error or on success. pub fn continue_operation(&self) -> ContinueReturn { let ret = match self.tickv.state.get() { State::Init(_) => self.tickv.initialise(self.key.get().unwrap()), State::AppendKey(_) => { let value = self.value.take().unwrap(); let ret = self.tickv.append_key(self.key.get().unwrap(), value); self.value.replace(Some(value)); ret } State::GetKey(_) => { let buf = self.buf.take().unwrap(); let ret = self.tickv.get_key(self.key.get().unwrap(), buf); self.buf.replace(Some(buf)); ret } State::InvalidateKey(_) => self.tickv.invalidate_key(self.key.get().unwrap()), State::GarbageCollect(_) => match self.tickv.garbage_collect() { Ok(_) => Ok(SuccessCode::Complete), Err(e) => Err(e), }, _ => unreachable!(), }; match ret { Ok(_) => { self.tickv.state.set(State::None); (ret, self.buf.take()) } Err(e) => match e { ErrorCode::ReadNotReady(_) | ErrorCode::EraseNotReady(_) => (ret, None), ErrorCode::WriteNotReady(_) => { self.tickv.state.set(State::None); (ret, None) } _ => { self.tickv.state.set(State::None); (ret, self.buf.take()) } }, } } } #[cfg(test)] mod tests { #![allow(unsafe_code)] /// Tests using a flash controller that can store data mod store_flast_ctrl { use crate::async_ops::AsyncTicKV; use crate::error_codes::ErrorCode; use crate::flash_controller::FlashController; use crate::tickv::{HASH_OFFSET, LEN_OFFSET, MAIN_KEY, VERSION, VERSION_OFFSET}; use core::hash::{Hash, Hasher}; use std::cell::Cell; use std::cell::RefCell; use std::collections::hash_map::DefaultHasher; fn check_region_main(buf: &[u8]) { // Check the version assert_eq!(buf[VERSION_OFFSET], VERSION); // Check the length assert_eq!(buf[LEN_OFFSET], 0x80); assert_eq!(buf[LEN_OFFSET + 1], 15); // Check the hash assert_eq!(buf[HASH_OFFSET + 0], 0x7b); assert_eq!(buf[HASH_OFFSET + 1], 0xc9); assert_eq!(buf[HASH_OFFSET + 2], 0xf7); assert_eq!(buf[HASH_OFFSET + 3], 0xff); assert_eq!(buf[HASH_OFFSET + 4], 0x4f); assert_eq!(buf[HASH_OFFSET + 5], 0x76); assert_eq!(buf[HASH_OFFSET + 6], 0xf2); assert_eq!(buf[HASH_OFFSET + 7], 0x44); // Check the check hash assert_eq!(buf[HASH_OFFSET + 8], 0xbb); assert_eq!(buf[HASH_OFFSET + 9], 0x32); assert_eq!(buf[HASH_OFFSET + 10], 0x74); assert_eq!(buf[HASH_OFFSET + 11], 0x1d); } fn check_region_one(buf: &[u8]) { // Check the version assert_eq!(buf[VERSION_OFFSET], VERSION); // Check the length assert_eq!(buf[LEN_OFFSET], 0x80); assert_eq!(buf[LEN_OFFSET + 1], 47); // Check the hash assert_eq!(buf[HASH_OFFSET + 0], 0x81); assert_eq!(buf[HASH_OFFSET + 1], 0x13); assert_eq!(buf[HASH_OFFSET + 2], 0x7e); assert_eq!(buf[HASH_OFFSET + 3], 0x95); assert_eq!(buf[HASH_OFFSET + 4], 0x9e); assert_eq!(buf[HASH_OFFSET + 5], 0x93); assert_eq!(buf[HASH_OFFSET + 6], 0xaa); assert_eq!(buf[HASH_OFFSET + 7], 0x3d); // Check the value assert_eq!(buf[HASH_OFFSET + 8], 0x23); assert_eq!(buf[28], 0x23); assert_eq!(buf[42], 0x23); // Check the check hash assert_eq!(buf[43], 0xfd); assert_eq!(buf[44], 0x24); assert_eq!(buf[45], 0xf0); assert_eq!(buf[46], 0x07); } fn check_region_two(buf: &[u8]) { // Check the version assert_eq!(buf[VERSION_OFFSET], VERSION); // Check the length assert_eq!(buf[LEN_OFFSET], 0x80); assert_eq!(buf[LEN_OFFSET + 1], 47); // Check the hash assert_eq!(buf[HASH_OFFSET + 0], 0x9d); assert_eq!(buf[HASH_OFFSET + 1], 0xd3); assert_eq!(buf[HASH_OFFSET + 2], 0x71); assert_eq!(buf[HASH_OFFSET + 3], 0x45); assert_eq!(buf[HASH_OFFSET + 4], 0x05); assert_eq!(buf[HASH_OFFSET + 5], 0xc2); assert_eq!(buf[HASH_OFFSET + 6], 0xf8); assert_eq!(buf[HASH_OFFSET + 7], 0x66); // Check the value assert_eq!(buf[HASH_OFFSET + 8], 0x23); assert_eq!(buf[28], 0x23); assert_eq!(buf[42], 0x23); // Check the check hash assert_eq!(buf[43], 0x1b); assert_eq!(buf[44], 0x53); assert_eq!(buf[45], 0xf9); assert_eq!(buf[46], 0x54); } fn get_hashed_key(unhashed_key: &[u8]) -> u64 { let mut hash_function = DefaultHasher::new(); unhashed_key.hash(&mut hash_function); hash_function.finish() } // An example FlashCtrl implementation struct FlashCtrl { buf: RefCell<[[u8; 1024]; 64]>, run: Cell<u8>, async_read_region: Cell<usize>, async_erase_region: Cell<usize>, } impl FlashCtrl { fn new() -> Self { Self { buf: RefCell::new([[0xFF; 1024]; 64]), run: Cell::new(0), async_read_region: Cell::new(100), async_erase_region: Cell::new(100), } } } impl FlashController<1024> for FlashCtrl { fn read_region( &self, region_number: usize, offset: usize, buf: &mut [u8; 1024], ) -> Result<(), ErrorCode> { println!("Read from region: {}", region_number); if self.async_read_region.get() != region_number { // Pretend that we aren't ready self.async_read_region.set(region_number); println!(" Not ready"); return Err(ErrorCode::ReadNotReady(region_number)); } for (i, b) in buf.iter_mut().enumerate() { *b = self.buf.borrow()[region_number][offset + i] } // println!(" buf: {:#x?}", self.buf.borrow()[region_number]); Ok(()) } fn write(&self, address: usize, buf: &[u8]) -> Result<(), ErrorCode> { println!( "Write to address: {:#x}, region: {}", address, address / 1024 ); for (i, d) in buf.iter().enumerate() { self.buf.borrow_mut()[address / 1024][(address % 1024) + i] = *d; } // Check to see if we are adding a key if buf.len() > 1 { if self.run.get() == 0 { println!("Writing main key: {:#x?}", buf); check_region_main(buf); } else if self.run.get() == 1 { println!("Writing key ONE: {:#x?}", buf); check_region_one(buf); } else if self.run.get() == 2 { println!("Writing key TWO: {:#x?}", buf); check_region_two(buf); } } self.run.set(self.run.get() + 1); Ok(()) } fn erase_region(&self, region_number: usize) -> Result<(), ErrorCode> { println!("Erase region: {}", region_number); if self.async_erase_region.get() != region_number { // Pretend that we aren't ready self.async_erase_region.set(region_number); return Err(ErrorCode::EraseNotReady(region_number)); } let mut local_buf = self.buf.borrow_mut()[region_number]; for d in local_buf.iter_mut() { *d = 0xFF; } Ok(()) } } #[test] fn test_simple_append() { let mut read_buf: [u8; 1024] = [0; 1024]; let mut hash_function = DefaultHasher::new(); MAIN_KEY.hash(&mut hash_function); let tickv = AsyncTicKV::<FlashCtrl, 1024>::new(FlashCtrl::new(), &mut read_buf, 0x1000); let mut ret = tickv.initialise(hash_function.finish()); while ret.is_err() { // There is no actual delay in the test, just continue now let (r, _buf) = tickv.continue_operation(); ret = r; } static mut VALUE: [u8; 32] = [0x23; 32]; let ret = unsafe { tickv.append_key(get_hashed_key(b"ONE"), &mut VALUE) }; match ret { Err((_buf, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!(), } let ret = unsafe { tickv.append_key(get_hashed_key(b"TWO"), &mut VALUE) }; match ret { Err((_buf, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!(), } } #[test] fn test_double_append() { let mut read_buf: [u8; 1024] = [0; 1024]; let mut hash_function = DefaultHasher::new(); MAIN_KEY.hash(&mut hash_function); let tickv = AsyncTicKV::<FlashCtrl, 1024>::new(FlashCtrl::new(), &mut read_buf, 0x10000); let mut ret = tickv.initialise(hash_function.finish()); while ret.is_err() { // There is no actual delay in the test, just continue now let (r, _buf) = tickv.continue_operation(); ret = r; } static mut VALUE: [u8; 32] = [0x23; 32]; static mut BUF: [u8; 32] = [0; 32]; println!("Add key ONE"); let ret = unsafe { tickv.append_key(get_hashed_key(b"ONE"), &mut VALUE) }; match ret { Err((_buf, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!(), } println!("Get key ONE"); unsafe { tickv.get_key(get_hashed_key(b"ONE"), &mut BUF).unwrap(); } println!("Get non-existant key TWO"); let ret = unsafe { tickv.get_key(get_hashed_key(b"TWO"), &mut BUF) }; match ret { Err((_, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); assert_eq!(tickv.continue_operation().0, Err(ErrorCode::KeyNotFound)); } Err((_, ErrorCode::KeyNotFound)) => {} _ => unreachable!(), } println!("Add key ONE again"); let ret = unsafe { tickv.append_key(get_hashed_key(b"ONE"), &mut VALUE) }; match ret { Err((_buf, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); assert_eq!( tickv.continue_operation().0, Err(ErrorCode::KeyAlreadyExists) ); } Err((_buf, ErrorCode::KeyAlreadyExists)) => {} _ => unreachable!(), } println!("Add key TWO"); let ret = unsafe { tickv.append_key(get_hashed_key(b"TWO"), &mut VALUE) }; match ret { Err((_buf, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!(), } println!("Get key ONE"); let ret = unsafe { tickv.get_key(get_hashed_key(b"ONE"), &mut BUF) }; match ret { Err((_, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!(), } println!("Get key TWO"); let ret = unsafe { tickv.get_key(get_hashed_key(b"TWO"), &mut BUF) }; match ret { Err((_, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!(), } println!("Get non-existant key THREE"); let ret = unsafe { tickv.get_key(get_hashed_key(b"THREE"), &mut BUF) }; match ret { Err((_, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); assert_eq!(tickv.continue_operation().0, Err(ErrorCode::KeyNotFound)); } _ => unreachable!(), } unsafe { match tickv.get_key(get_hashed_key(b"THREE"), &mut BUF) { Err((_, ErrorCode::KeyNotFound)) => {} _ => { panic!("Expected ErrorCode::KeyNotFound"); } } } } #[test] fn test_append_and_delete() { let mut read_buf: [u8; 1024] = [0; 1024]; let mut hash_function = DefaultHasher::new(); MAIN_KEY.hash(&mut hash_function); let tickv = AsyncTicKV::<FlashCtrl, 1024>::new(FlashCtrl::new(), &mut read_buf, 0x10000); let mut ret = tickv.initialise(hash_function.finish()); while ret.is_err() { // There is no actual delay in the test, just continue now let (r, _buf) = tickv.continue_operation(); ret = r; } static mut VALUE: [u8; 32] = [0x23; 32]; static mut BUF: [u8; 32] = [0; 32]; println!("Add key ONE"); let ret = unsafe { tickv.append_key(get_hashed_key(b"ONE"), &mut VALUE) }; match ret { Err((_buf, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!(), } println!("Get key ONE"); unsafe { tickv.get_key(get_hashed_key(b"ONE"), &mut BUF).unwrap(); } println!("Delete Key ONE"); tickv.invalidate_key(get_hashed_key(b"ONE")).unwrap(); println!("Get non-existant key ONE"); unsafe { match tickv.get_key(get_hashed_key(b"ONE"), &mut BUF) { Err((_, ErrorCode::KeyNotFound)) => {} _ => { panic!("Expected ErrorCode::KeyNotFound"); } } } println!("Try to delete Key ONE Again"); assert_eq!( tickv.invalidate_key(get_hashed_key(b"ONE")), Err(ErrorCode::KeyNotFound) ); } #[test] fn test_garbage_collect() { let mut read_buf: [u8; 1024] = [0; 1024]; let mut hash_function = DefaultHasher::new(); MAIN_KEY.hash(&mut hash_function); let tickv = AsyncTicKV::<FlashCtrl, 1024>::new(FlashCtrl::new(), &mut read_buf, 0x10000); let mut ret = tickv.initialise(hash_function.finish()); while ret.is_err() { // There is no actual delay in the test, just continue now let (r, _buf) = tickv.continue_operation(); ret = r; } static mut VALUE: [u8; 32] = [0x23; 32]; static mut BUF: [u8; 32] = [0; 32]; println!("Garbage collect empty flash"); let mut ret = tickv.garbage_collect(); while ret.is_err() { // There is no actual delay in the test, just continue now ret = match tickv.continue_operation().0 { Ok(_) => Ok(0), Err(e) => Err(e), }; } println!("Add key ONE"); let ret = unsafe { tickv.append_key(get_hashed_key(b"ONE"), &mut VALUE) }; match ret { Err((_buf, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!(), } println!("Garbage collect flash with valid key"); let mut ret = tickv.garbage_collect(); while ret.is_err() { match ret { Err(ErrorCode::ReadNotReady(reg)) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); ret = match tickv.continue_operation().0 { Ok(_) => Ok(0), Err(e) => Err(e), }; } Ok(num) => { assert_eq!(num, 0); } _ => unreachable!(), } } println!("Delete Key ONE"); let ret = tickv.invalidate_key(get_hashed_key(b"ONE")); match ret { Err(ErrorCode::ReadNotReady(reg)) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); tickv.continue_operation().0.unwrap(); } Ok(_) => {} _ => unreachable!("ret: {:?}", ret), } println!("Garbage collect flash with deleted key"); let mut ret = tickv.garbage_collect(); while ret.is_err() { match ret { Err(ErrorCode::ReadNotReady(reg)) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); ret = match tickv.continue_operation().0 { Ok(_) => Ok(0), Err(e) => Err(e), }; } Err(ErrorCode::EraseNotReady(_reg)) => { // There is no actual delay in the test, just continue now ret = match tickv.continue_operation().0 { Ok(_) => Ok(0), Err(e) => Err(e), }; } Ok(num) => { assert_eq!(num, 1024); } _ => unreachable!("ret: {:?}", ret), } } println!("Get non-existant key ONE"); let ret = unsafe { tickv.get_key(get_hashed_key(b"ONE"), &mut BUF) }; match ret { Err((_, ErrorCode::ReadNotReady(reg))) => { // There is no actual delay in the test, just continue now tickv.set_read_buffer(&tickv.tickv.controller.buf.borrow()[reg]); assert_eq!(tickv.continue_operation().0, Err(ErrorCode::KeyNotFound)); } Err((_, ErrorCode::KeyNotFound)) => {} _ => unreachable!("ret: {:?}", ret), } println!("Add Key ONE"); unsafe { tickv .append_key(get_hashed_key(b"ONE"), &mut VALUE) .unwrap(); } } } }
get_stored_value_buffer
forms105.py
from reportlab.platypus import Paragraph, Spacer, Table, TableStyle, PageBreak from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import mm from copy import deepcopy from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY from directions.models import Napravleniya from appconf.manager import SettingManager import os.path from laboratory.settings import FONTS_FOLDER from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from .flowable import FrameDataUniversal from directions.models import Issledovaniya from ..prepare_data import fields_result_only_title_fields import simplejson as json import datetime from dateutil.relativedelta import relativedelta from hospitals.models import Hospitals pdfmetrics.registerFont(TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont(TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 9 style.alignment = TA_JUSTIFY style.leading = 3 * mm styleCentre = deepcopy(style) styleCentre.alignment = TA_CENTER styleBold = deepcopy(style) styleBold.fontName = "PTAstraSerifBold" styleCentreBold = deepcopy(styleBold) styleCentreBold.alignment = TA_CENTER hospital_name = SettingManager.get("org_title") hospital_address = SettingManager.get("org_address") hospital_kod_ogrn = SettingManager.get("org_ogrn") styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.fontSize = 9 styleT.leading = 3 * mm styleOrg = deepcopy(styleT) styleOrg.fontSize = 8 styleColontitul = deepcopy(styleT) styleColontitul.fontSize = 7 styleColontitul.leading = 2 * mm styleColontitulBold = deepcopy(styleColontitul) styleColontitulBold.fontName = "PTAstraSerifBold" styleTBold = deepcopy(styleT) styleTBold.fontName = "PTAstraSerifBold" styleOrgBold = deepcopy(styleOrg) styleOrgBold.fontName = "PTAstraSerifBold" styleOrgBold.leading = 2 * mm op_bold_tag = '<font face="PTAstraSerifBold">' cl_bold_tag = '</font>' space_symbol = '&nbsp;' def form_01(direction: Napravleniya, iss: Issledovaniya, fwb, doc, leftnone, user=None): # Мед. св-во о смерти 106/у data_individual = direction.client.get_data_individual() data = {} title_fields = [ "Серия", "Префикс номера", "Номер", "Дата выдачи", "Вид медицинского свидетельства о смерти", "Серия предшествующего", "Номер предшествующего", "Дата выдачи предшествующего", "Дата рождения", "Дата смерти", "Время смерти", "Место постоянного жительства (регистрации)", "Вид места жительства", "Место смерти", "Вид места смерти", "Типы мест наступления смерти", "Новорожденый", "Доношенность новорожденного", "Место рождения", "Масса тела ребёнка при рождении", "По счету был ребенок", "Дата рождения матери", "Возраст матери", "ФИО матери", "Семейное положение", "Образование", "Социальная группа", "Полис ОМС", "СНИЛС", "Тип ДУЛ", "ДУЛ", "Род причины смерти", "Смерть от внешних причин", "Дата смерти от внешних причин", "Время смерти от внешних причин", "Дата события", "Время события", "Место и обстоятельства", "Тип медицинского работника", "Основания для определения причины смерти", "а) Болезнь или состояние, непосредственно приведшее к смерти", "б) патологическое состояние, которое привело к возникновению вышеуказанной причины:", "в) первоначальная причина смерти:", "г) внешняя причина при травмах и отравлениях:", "II. Прочие важные состояния, способствовавшие смерти, но не связанные с болезнью или патологическим состоянием, приведшим к ней", "ДТП", "Связь смерти с ДТП", "Беременность", "Связь смерти с беременностью", "ФИО (получатель)", "Документ (получатель)", "Серия (получатель)", "Номер (получатель)", "Кем и когда выдан (получатель)", "СНИЛС (получатель)", "Заполнил", "Проверил", "Главный врач", "Должность", "Время известно", ] result = fields_result_only_title_fields(iss, title_fields, False) for i in result: data[i["title"]] = i["value"] data['fio'] = data_individual["fio"] data['sex'] = data_individual["sex"] ends = datetime.datetime.strptime(data["Дата рождения"], '%d.%m.%Y') start = datetime.datetime.strptime(data["Дата смерти"], '%d.%m.%Y') diff = relativedelta(start, ends) if diff.years == 0: data['число месяцев жизни'] = diff.months data['число дней жизни'] = diff.days else: data['число месяцев жизни'] = "" data['число дней жизни'] = "" if not data.get("Место рождения", None): data[ "Место рождения"] = '{"details": {"region": "", "region_type": "", "area": "", "area_type": "", "city": "", "city_type": "", "settlement": "", "settlement_type": "", ' \ '"street": "", "street_type": "", "house": "", "house_type": "", "flat": "", "flat_type": "", "postal_code": "", "custom": false}}' if not data.get("Место смерти", None): data[ "Место смерти"] = '{"details": {"region": "", "region_type": "", "area": "", "area_type": "", "city": "", "city_type": "", "settlement": "", "settlement_type": "", ' \ '"street": "", "street_type": "", "house": "", "house_type": "", "flat": "", "flat_type": "", "postal_code": "", "custom": false}}' if not data.get("Доношенность новорожденного", None): data["Доношенность новорожденного"] = '{"code": "", "title": ""}' if not data.get("Связь смерти с ДТП", None): data["Связь смерти с ДТП"] = '{"code": "", "title": ""}' if not data.get("Связь смерти с беременностью", None): data["Связь смерти с беременностью"] = '{"code": "", "title": ""}' if not data.get("Тип медицинского работника", None): data["Тип медицинского работника"] = '{"code": "", "title": ""}' if not data.get("Основания для определения причины смерти", None): data["Основания для определения причины смерти"] = '{"code": "", "title": ""}' if not data.get("Род причины смерти", None): data["Род причины смерти"] = '{"code": "", "title": ""}' if not data.get("Масса тела ребёнка при рождении", None): data["Масса тела ребёнка при рождении"] = "" if not data.get("По счету был ребенок", None): data["По счету был ребенок"] = "" if not data.get("Дата рождения матери", None): data["Дата рождения матери"] = "" if not data.get("Возраст матери", None): data["Возраст матери"] = "" if not data.get("ФИО (получатель)", None): data["ФИО (получатель)"] = "" if not data.get("Документ (получатель)", None): data["Документ (получатель)"] = "" if not data.get("Серия (получатель)", None): data["Серия (получатель)"] = "" if not data.get("Номер (получатель)", None): data["Номер (получатель)"] = "" if not data.get("Кем и когда выдан (получатель)", None): data["Кем и когда выдан (получатель)"] = "" if not data.get("СНИЛС (получатель)", None): data["СНИЛС (получатель)"] = "" if not data.get("Заполнил", None): data["Заполнил"] = iss.doc_confirmation.get_full_fio() if iss.doc_confirmation else "" if not data.get("Должность", None): data["Должность"] = iss.doc_position if iss.doc_confirmation else "" if not data.get("Проверил", None): data["Проверил"] = "" if not data.get("Главный врач", None): data["Главный врач"] = "" if not data.get("ФИО матери"): data["ФИО матери"] = '{"columns":{"titles":["Фамилия","Имя","Отчество"], "rows":[["иванова","Марья","Олеговна"]]}' mother_data = json.loads(data["ФИО матери"]) data["mother_fio"] = f"{mother_data['rows'][0][0]} {mother_data['rows'][0][1]} {mother_data['rows'][0][2]}" data["Фамилия матери"] = "" data["Имя матери"] = "" data["Отчество матери"] = "" if data["Новорожденый"] in ["от 168 час. до 1 года", "от 168 час. до 1 месяца"]: data["Фамилия матери"] = mother_data['rows'][0][0] data["Имя матери"] = mother_data['rows'][0][1] data["Отчество матери"] = mother_data['rows'][0][2] hospital_obj: Hospitals = user.doctorprofile.get_hospital() data['org'] = {"full_title": hospital_obj.title, "org_address": hospital_obj.address, "org_license": hospital_obj.license_data, "org_okpo": hospital_obj.okpo} data["а"] = json.loads(data["а) Болезнь или состояние, непосредственно приведшее к смерти"]) data["б"] = json.loads(data["б) патологическое состояние, которое привело к возникновению вышеуказанной причины:"]) data["в"] = json.loads(data["в) первоначальная причина смерти:"]) data["г"] = json.loads(data["г) внешняя причина при травмах и отравлениях:"]) data["ii"] = json.loads(data["II. Прочие важные состояния, способствовавшие смерти, но не связанные с болезнью или патологическим состоянием, приведшим к ней"]) template = add_template(iss, direction, data, 5 * mm) fwb.extend(template) template = add_line_split(iss, direction, 4 * mm) fwb.extend(template) template = death_data(iss, direction, data, 0 * mm) fwb.extend(template) fwb.append(PageBreak()) template = second_page_add_template(iss, direction, data, 0 * mm) fwb.extend(template) template = add_line_split(iss, direction, -1 * mm) fwb.extend(template) template = death_data2(iss, direction, data, -5 * mm) fwb.extend(template) return fwb def add_template(iss: Issledovaniya, direction, fields, offset=0): # Мед. св-во о смерти 106/у text = [] text = title_data("КОРЕШОК МЕДИЦИНСКОГО СВИДЕТЕЛЬСТВА О СМЕРТИ", "К УЧЕТНОЙ ФОРМЕ № 106/У", text, fields.get("Серия", ""), fields.get("Номер", ""), fields.get("Дата выдачи", ""), fields.get("Вид медицинского свидетельства о смерти", ""), fields) text.append(Spacer(1, 1.7 * mm)) text = fio_tbl(text, "1. Фамилия, имя, отчество (при наличии) умершего(ей):", fields.get('fio','')) # Пол text.append(Spacer(1, 0.3 * mm)) text = sex_tbl(text, fields.get('sex','')) # Дата рождения text = born_tbl(text, fields.get('Дата рождения', '')) text.append(Spacer(1, 0.3 * mm)) # Дата смерти text = death_tbl(text, "4. Дата смерти:", fields.get('Дата смерти', '-'), fields.get('Время смерти', '-')) text = address_tbl(text, "5. Регистрация по месту жительства (пребывания) умершего(ей):", fields.get("Место постоянного жительства (регистрации)", "")) # Смерть наступила text = where_death_start_tbl(text, fields.get("Типы мест наступления смерти"), "6") text.append(Spacer(1, 0.2 * mm)) text.append(Paragraph('Для детей, умерших в возрасте до 1 года:', styleBold)) text.append(Spacer(1, 0.5 * mm)) opinion = gen_opinion(['7. Дата рождения', 'число', fields['Дата рождения'].split('.')[0], ', месяц', fields['Дата рождения'].split('.')[1], ', год', fields['Дата рождения'].split('.')[2], ', число месяцев', fields["число месяцев жизни"], ', число дней', fields["число дней жизни"], 'жизни']) col_width = (29 * mm, 17 * mm, 8 * mm, 15 * mm, 8 * mm, 10 * mm, 12 * mm, 24 * mm, 8 * mm, 20 * mm, 8 * mm, 15 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), 0 * mm), ('LINEBELOW', (2, 0), (2, 0), 0.75, colors.black), ('LINEBELOW', (4, 0), (4, 0), 0.75, colors.black), ('LINEBELOW', (6, 0), (6, 0), 0.75, colors.black), ('LINEBELOW', (8, 0), (8, 0), 0.75, colors.black), ('LINEBELOW', (10, 0), (10, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) text = address_tbl(text, "8. Место рождения", fields["Место рождения"]) text = fio_tbl(text, "9. Фамилия, имя, отчество (при наличии) матери:", fields["mother_fio"]) obj = [] obj.append(FrameDataUniversal(0 * mm, offset, 190 * mm, 95 * mm, text=text)) return obj def add_line_split(iss: Issledovaniya, direction, offset=0): # Лини отреза text = [] text = line_split(text) obj = [(FrameDataUniversal(0 * mm, offset, 190 * mm, 5 * mm, text=text))] return obj def death_data(iss: Issledovaniya, direction, fields, offset=0): # Лини отреза text = [] text = title_med_organization(text, fields['org']) text = title_data("МЕДИЦИНСКОЕ СВИДЕТЕЛЬСТВО О СМЕРТИ", "", text, fields["Серия"], fields.get("Номер", ""), fields["Дата выдачи"], fields["Вид медицинского свидетельства о смерти"], fields) text.append(Spacer(1, 1.7 * mm)) text = fio_tbl(text, "1. Фамилия, имя, отчество (при наличии) умершего(ей):", fields["fio"]) # Пол text.append(Spacer(1, 0.3 * mm)) text = sex_tbl(text, fields['sex']) # Дата рождения text = born_tbl(text, fields['Дата рождения']) # print(fields["Тип ДУЛ"]) dul = json.loads(fields["ДУЛ"]) text = patient_passport(text, {"type": fields["Тип ДУЛ"], "serial": dul['rows'][0][0], "number": dul['rows'][0][1]}) text = who_issue_passport(text, {"who_issue": dul['rows'][0][2], "date_issue": dul['rows'][0][3]}) text = patient_snils(text, fields["СНИЛС"] or "") text = patient_polis(text, fields["Полис ОМС"] or "") text = death_tbl(text, "7. Дата смерти:", fields.get('Дата смерти', '-'), fields.get('Время смерти', '-')) text = address_tbl(text, "8. Регистрация по месту жительства (пребывания) умершего(ей):", fields["Место постоянного жительства (регистрации)"]) text = type_city(text, "9. Местность:", fields["Вид места жительства"]) text = address_tbl(text, "10. Место смерти:", fields["Место смерти"]) text = type_city(text, "11. Местность: ", fields["Вид места смерти"]) text = where_death_start_tbl(text, fields["Типы мест наступления смерти"], "12") text = child_death_befor_month(text, fields["Доношенность новорожденного"]) text = child_death_befor_year(text, {"weight": fields["Масса тела ребёнка при рождении"], "child_count": fields["По счету был ребенок"], "mother_born": fields["Дата рождения матери"], "mother_age": fields["Возраст матери"], "mother_family": fields["Фамилия матери"], "mother_name": fields["Имя матери"], "mother_patronimyc": fields["Отчество матери"]}) text = family_status(text, fields["Семейное положение"]) text = education(text, fields["Образование"]) text = work_position(text, fields["Социальная группа"]) text = bottom_colontitul(text, "* В случае смерти детей, возраст которых указан в пунктах 13 - 14, пункты 15 - 17 заполняются в отношении их матерей.") obj = [] obj.append(FrameDataUniversal(0 * mm, offset, 190 * mm, 178 * mm, text=text)) return obj def second_page_add_template(iss: Issledovaniya, direction, fields, offset=0): text = [] text = back_size(text) text = why_death(text, fields, '10', '11', '12', '13') text = fio_tbl(text, "14. Фамилия, имя, отчество (при наличии) получателя", fields["ФИО (получатель)"]) text.append(Paragraph("Документ, удостоверяющий личность получателя (серия, номер, кем выдан)", styleT)) text = destination_person_passport(text, f'{fields["Документ (получатель)"]} {fields["Серия (получатель)"]} {fields["Номер (получатель)"]} {fields["Кем и когда выдан (получатель)"]}') text = destination_person_snils(text, f'{fields["СНИЛС (получатель)"]}') text.append(Spacer(1, 2 * mm)) text.append(Paragraph(f"«___» ___________ 20 ___ г.{space_symbol * 30} Подпись получателя _________________________", styleT)) obj = [] obj.append(FrameDataUniversal(0 * mm, offset, 190 * mm, 95 * mm, text=text)) return obj def death_data2(iss: Issledovaniya, direction, fields, offset=0): text = [] text = death_happaned(text, fields["Род причины смерти"]) date, month, year, hour, min = "____", "____", "_________", "____", "____" date_event_data = fields.get("Дата события", None) time_event_data = fields.get("Время события", None) if date_event_data: date_event_data = date_event_data.split(".") date = f"<u>{space_symbol * 3}{date_event_data[0]}{space_symbol * 3}</u>" month = f"<u>{space_symbol * 3}{date_event_data[1]}{space_symbol * 3}</u>" year = f"<u>{space_symbol * 3}{date_event_data[2]}{space_symbol * 3}</u>" if time_event_data: time_event_data = time_event_data.split(":") hour = f"<u>{space_symbol * 3}{time_event_data[0]}{space_symbol * 3}</u>" min = f"<u>{space_symbol * 3}{time_event_data[1]}{space_symbol * 3}</u>" text.append(Paragraph( f"19. В случае смерти от несчастного случая, убийства, самоубийства, от военных и террористических действий, при неустановленном роде смерти - указать дату травмы (отравления): " f"число {date} месяц {month} год {year} час. {hour} мин. {min} , а также место и обстоятельства, при которых произошла травма (отравление)", styleT)) unfortunate_and_other_info = "________________________________________________________________________________________________________________________" place_and_reasons = fields.get("Место и обстоятельства", None) if place_and_reasons: unfortunate_and_other_info = f"<u>{space_symbol * 2}{place_and_reasons} {space_symbol * 2}</u>" text.append(Paragraph(f"{unfortunate_and_other_info}", styleT)) text = who_set_death(text, fields["Тип медицинского работника"]) text = doctor_fio(text, fields, iss) text.append(Spacer(1, 1 * mm)) text = why_death(text, fields, "22", "23", "24", "25") text.append(Spacer(1, 2 * mm)) text.append( Paragraph("<u>Руководитель (иное уполномоченное лицо **) медицинской организации</u>, индивидуальный предприниматель, осуществляющий медицинскую деятельность (подчеркнуть)", styleT)) text.append(Spacer(1, 2 * mm)) text = hospital_manager_stamp(text, fields["Главный врач"]) text.append(Spacer(1, 2 * mm)) text.append(Paragraph("26 Свидетельство проверено ответственным за правильность заполнения медицинских свидетельств.", styleT)) text = check_person_data(text, fields["Проверил"]) text = bottom_colontitul(text, '** В случае, установленном частью 10 статьи 9 Федерального закона от 5 июня 2012 г. № 50-ФЗ "О регулировании деятельности российских граждан и ' 'российских юридических лиц в Антарктике" (Собрание законодательства Российской Федерации, 2012, № 24, ст. 3067). ') obj = [] obj.append(FrameDataUniversal(0 * mm, offset, 190 * mm, 168 * mm, text=text)) return obj # общие функции def title_data(title_name, title_form, text, serial, number, date_issue, type_document, data_fields): text.append(Paragraph(f"{title_name}", styleCentreBold)) text.append(Spacer(1, 0.1 * mm)) text.append(Paragraph(f"{title_form}", styleCentreBold)) text.append(Spacer(1, 0.2 * mm)) prefix = data_fields.get("Префикс номера", "") text.append(Paragraph(f"СЕРИЯ {serial} № {prefix}{number}", styleCentreBold)) text.append(Spacer(1, 0.1 * mm)) text.append(Paragraph(f"Дата выдачи {date_issue}", styleCentreBold)) final, preparatory, instead_preparatory, instead_final = "окончательного", "предварительного", "взамен предварительного", "взамен окончательного" if title_name == "МЕДИЦИНСКОЕ СВИДЕТЕЛЬСТВО О СМЕРТИ": final, preparatory = "окончательное", "предварительное" type_death_document = json.loads(type_document) if type_death_document["code"] == '4': instead_final = f"<u>{op_bold_tag}{instead_final}{cl_bold_tag}</u>" elif type_death_document["code"] == '3': instead_preparatory = f"<u>{op_bold_tag}{instead_preparatory}{cl_bold_tag}</u>" elif type_death_document["code"] == '1': final = f"{op_bold_tag}<u>{final}</u>{cl_bold_tag}" elif type_death_document["code"] == '2': preparatory = f"<u>{op_bold_tag}{preparatory}{cl_bold_tag}</u>" text.append(Paragraph(f"({final}, {preparatory}, {instead_preparatory}, {instead_final}) (подчеркнуть)", styleCentre)) if data_fields.get("Серия предшествующего", None): text.append(Paragraph("ранее выданное свидетельство", styleCentre)) text.append(Paragraph(f"серия {data_fields['Серия предшествующего']} No {data_fields['Номер предшествующего']} от {data_fields['Дата выдачи предшествующего']} г.", styleCentre)) return text def gen_opinion(data): opinion = [[Paragraph(f"{k}", styleT) for k in data]] return opinion def gen_opinion_diag(data): opinion = [[Paragraph(f"{k}", styleOrgBold) for k in data]] return opinion def gen_table(opinion, col_width, tbl_style, row_height=None): tbl = Table(opinion, colWidths=col_width, rowHeights=row_height, hAlign='LEFT', ) tbl.setStyle(TableStyle(tbl_style)) return tbl def fio_tbl(text, type, fio): opinion = gen_opinion([type, fio]) col_width = (80 * mm, 110 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def sex_tbl(text, sex): if sex == "м": sex_m = f'{op_bold_tag}<u>мужской</u>{cl_bold_tag}' else: sex_m = ' мужской' if sex == "ж": sex_w = f'{op_bold_tag}<u>женский</u>{cl_bold_tag}' else: sex_w = ', женский' opinion = gen_opinion(['2.Пол:', sex_m, '1', sex_w, '2']) col_width = (11 * mm, 17 * mm, 6 * mm, 19 * mm, 6 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (-1, -1), (-1, -1), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def born_tbl(text, born_data): # Дата рождения born = born_data.split('.') born_day = born[0] born_month = born[1] born_year = born[2] opinion = gen_opinion(['3.Дата рождения:', 'число', born_day, 'месяц', born_month, 'год', born_year]) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LEFTPADDING', (0, 1), (0, 1), 0 * mm), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LINEBELOW', (2, 0), (2, 0), 0.75, colors.black), ('LINEBELOW', (4, 0), (4, 0), 0.75, colors.black), ('LINEBELOW', (6, 0), (6, 0), 0.75, colors.black), ('LINEBELOW', (2, 1), (2, 1), 0.75, colors.black), ('LINEBELOW', (4, 1), (4, 1), 0.75, colors.black), ('LINEBELOW', (6, 1), (6, 1), 0.75, colors.black), ('LINEBELOW', (8, 1), (8, 1), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] col_width = (28 * mm, 14 * mm, 8 * mm, 14 * mm, 8 * mm, 10 * mm, 12 * mm) tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def death_tbl(text, number, death_data, death_time): #
ти death_data = death_data.split('.') death_day = death_data[0] death_month = death_data[1] death_year = death_data[2] death_hour, death_min = "", "" if death_time: death_time = death_time.split(":") death_hour = death_time[0] if len(death_time) >= 1 else " " death_min = death_time[1] if len(death_time) >= 2 else " " opinion = gen_opinion([number, 'число', death_day, 'месяц', death_month, 'год', death_year, 'час.', death_hour, 'мин.', death_min]) tbl_style = [ ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LEFTPADDING', (0, 1), (0, 1), 0 * mm), ('TOPPADDING', (0, 0), (-1, -1), -1 * mm), ('LINEBELOW', (2, 0), (2, 0), 0.75, colors.black), ('LINEBELOW', (4, 0), (4, 0), 0.75, colors.black), ('LINEBELOW', (6, 0), (6, 0), 0.75, colors.black), ('LINEBELOW', (8, 0), (8, 0), 0.75, colors.black), ('LINEBELOW', (10, 0), (10, 0), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] col_width = (28 * mm, 14 * mm, 8 * mm, 14 * mm, 8 * mm, 10 * mm, 12 * mm, 10 * mm, 8 * mm, 12 * mm, 8 * mm) tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def address_tbl(text, type_address, address): data_address = json.loads(address) address_details = data_address["details"] opinion = gen_opinion([f'{type_address} субъект Российской Федерации:', f"{address_details['region_type']} {address_details['region']}"]) col_widths = (135 * mm, 55 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_widths, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) # город opinion = gen_opinion(['район', f"{address_details['area_type']} {address_details['area']}", 'город', f"{address_details['city_type']} {address_details['city']}"]) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('LINEBELOW', (3, 0), (3, 0), 0.75, colors.black), ] col_width = (17 * mm, 77 * mm, 16 * mm, 80 * mm,) tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) # населенный пунк opinion = gen_opinion( ['населенный пункт', f"{address_details['settlement_type']} {address_details['settlement']}", 'улица', f"{address_details['street_type']} {address_details['street']}"]) col_width = (37 * mm, 67 * mm, 16 * mm, 70 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('LINEBELOW', (3, 0), (3, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) # дом, стр, корп, кв, комн opinion = gen_opinion(['дом', address_details['house'], 'стр.', '', 'корп.', '', 'кв.', address_details.get("flat", ""), 'комн.', '']) col_width = (14 * mm, 15 * mm, 12 * mm, 12 * mm, 14 * mm, 15 * mm, 12 * mm, 15 * mm, 14 * mm, 15 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('LINEBELOW', (3, 0), (3, 0), 0.75, colors.black), ('LINEBELOW', (5, 0), (5, 0), 0.75, colors.black), ('LINEBELOW', (7, 0), (7, 0), 0.75, colors.black), ('LINEBELOW', (9, 0), (9, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def where_death_start_tbl(text, params, item_param): whera_data = json.loads(params) place, car, hospital, home = ' на месте происшествия', ', в машине скорой помощи', ', в стационаре', ', дома' if whera_data["code"] == '1': place = f"<u>{op_bold_tag}{place}{cl_bold_tag}</u>" elif whera_data["code"] == '2': car = f"<u>{op_bold_tag}{car}{cl_bold_tag}</u>" elif whera_data["code"] == '3': hospital = f"<u>{op_bold_tag}{hospital}{cl_bold_tag}</u>" elif whera_data["code"] == '4': home = f"<u>{op_bold_tag}{home}{cl_bold_tag}</u>" opinion = gen_opinion([f'{item_param}.Смерть наступила:', place, '1', car, '2', hospital, '3', home, '4']) col_width = (32 * mm, 37 * mm, 6 * mm, 42 * mm, 6 * mm, 24 * mm, 6 * mm, 12 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ('GRID', (6, 0), (6, 0), 0.75, colors.black), ('GRID', (8, 0), (8, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) # Смерть наступила education_place, other_place = 'в образовательной организации', 'в другом месте' if whera_data["code"] == '7': education_place = f"<u>{op_bold_tag}{education_place}{cl_bold_tag}</u>" elif whera_data["code"] == '5': other_place = f"<u>{op_bold_tag}{other_place}{cl_bold_tag}</u>" opinion = gen_opinion([education_place, '5', other_place, '6']) col_width = (55 * mm, 6 * mm, 24 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) return text def line_split(text): step_round_dash = (1.5 * mm, 1 * mm) styleColor = deepcopy(style) styleColor.textColor = colors.gray opinion = [[Paragraph('', style), Paragraph('линия отреза', styleColor), Paragraph('', style), ], ] tbl = Table(opinion, hAlign='LEFT', rowHeights=5 * mm, colWidths=(80 * mm, 25 * mm, 80 * mm)) tbl.setStyle( TableStyle( [ ('LINEBELOW', (0, 0), (0, 0), 0.2 * mm, colors.gray, 'round', step_round_dash), ('LINEBELOW', (2, 0), (2, 0), 0.2 * mm, colors.gray, 'round', step_round_dash), ('BOTTOMPADDING', (1, 0), (1, 0), -0.5 * mm), ] ) ) text.append(tbl) return text def patient_passport(text, data_document): if "-" in data_document["type"]: document_type = data_document["type"].split("-") document_type_print = document_type[1] else: document_type_print = data_document["type"] opinion = gen_opinion(['4.Документ, удостоверяющий личность умершего:', document_type_print, 'серия', data_document["serial"], 'номер', data_document['number']]) tbl_style = [ ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('LINEBELOW', (3, 0), (3, 0), 0.75, colors.black), ('LINEBELOW', (5, 0), (5, 0), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] col_width = (71 * mm, 68 * mm, 12 * mm, 11 * mm, 14 * mm, 14 * mm) tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def who_issue_passport(text, data_document): opinion = gen_opinion(['кем и когда выдан', f"{data_document['who_issue']} {data_document['date_issue']}"]) tbl_style = [ ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] col_width = (33 * mm, 157 * mm) tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def patient_snils(text, snils_number): opinion = gen_opinion(['5.СНИЛС', snils_number]) tbl_style = [ ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] col_width = (23 * mm, 167 * mm) tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def patient_polis(text, polis_number): opinion = gen_opinion(['6.Полис ОМС:', polis_number]) tbl_style = [ ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] col_width = (23 * mm, 167 * mm) tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def type_city(text, type_value, type, ): type_gorod, type_selo = ' городская', ', сельская' type = json.loads(type) if type["code"] == "1": type_gorod = f'{op_bold_tag}<u>городская</u>{cl_bold_tag}' if type["code"] == "2": type_selo = f'{op_bold_tag}<u>сельская</u>{cl_bold_tag}' opinion = gen_opinion([type_value, type_gorod, '1', type_selo, '2']) col_width = (23 * mm, 19 * mm, 6 * mm, 18 * mm, 6 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (-1, -1), (-1, -1), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) return text def child_death_befor_month(text, params): params = json.loads(params) week37_41, week_smaller, week_more_42 = ' доношенный (37-41 недель)', ' , недоношенный (менее 37 недель)', ', переношенный (42 недель и более)' if params["code"] == "1": week37_41 = f"{op_bold_tag}<u>{week37_41}</u>{cl_bold_tag}" if params["code"] == "2": week_smaller = f"{op_bold_tag}<u>{week_smaller}</u>{cl_bold_tag}" if params["code"] == "3": week_more_42 = f"{op_bold_tag}<u>{week_more_42}</u>{cl_bold_tag}" opinion = gen_opinion(['13. * Для детей, умерших в возрасте от 168 час. до 1 месяца:', week37_41, '1']) col_width = (85 * mm, 42 * mm, 6 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) opinion = gen_opinion([week_smaller, '2', week_more_42, '3']) col_width = (57 * mm, 6 * mm, 55 * mm, 6 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (4, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) return text def child_death_befor_year(text, params): opinion = gen_opinion(['14.*Для детей, умерших в возрасте от 168 час. до 1 года:', ' масса тела ребёнка при рождении', params["weight"], ' грамм', '1']) col_width = (82 * mm, 50 * mm, 12 * mm, 12 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('LINEBELOW', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) opinion = gen_opinion(['каким по счету был ребенок у матери (считая умерших и не считая мертворождённых)', params["child_count"], '', '2']) col_width = (125 * mm, 6 * mm, 5 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) opinion = gen_opinion(['дата рождения матери', params["mother_born"], '', '3', 'возраст матери (полных лет)', params["mother_age"], '', '4']) col_width = (40 * mm, 19 * mm, 5 * mm, 6 * mm, 45 * mm, 15 * mm, 5 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ('LINEBELOW', (5, 0), (5, 0), 0.75, colors.black), ('GRID', (7, 0), (7, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.5 * mm)) text.append(tbl) opinion = gen_opinion(['фамилия матери', params["mother_family"], '', '5', ', имя', params["mother_name"], '', '6', ' , отчество (при наличии)', params["mother_patronimyc"], '', '7']) col_width = (30 * mm, 25 * mm, 5 * mm, 6 * mm, 14 * mm, 20 * mm, 5 * mm, 6 * mm, 40 * mm, 25 * mm, 5 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ('LINEBELOW', (5, 0), (5, 0), 0.75, colors.black), ('GRID', (7, 0), (7, 0), 0.75, colors.black), ('LINEBELOW', (9, 0), (9, 0), 0.75, colors.black), ('GRID', (11, 0), (11, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.5 * mm)) text.append(tbl) return text def family_status(text, params): params = json.loads(params) brak, not_brak, not_known = "состоял(а) в зарегистрированном браке", "не состоял(а) в зарегистрированном браке", "неизвестно" if params["code"] == '3': not_known = f"{op_bold_tag}<u>{not_known}</u>{cl_bold_tag}" elif params["code"] == '4': brak = f"{op_bold_tag}<u>{brak}</u>{cl_bold_tag}" elif params["code"] == '5': not_brak = f"{op_bold_tag}<u>{not_brak}</u>{cl_bold_tag}" opinion = gen_opinion(['15.*Семейное положение:', brak, '1', not_brak, '2', not_known, '3']) col_width = (38 * mm, 60 * mm, 6 * mm, 60 * mm, 6 * mm, 18 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ('GRID', (6, 0), (6, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) return text def education(text, params): high_prof, not_high_prof, middle_prof, middle_common = "профессиональное: высшее", ", неполное высшее", ", среднее профессиональное", "общее: среднее" params = json.loads(params) if params["code"] == '1': high_prof = f"{op_bold_tag}<u>{high_prof}</u>{cl_bold_tag}" elif params["code"] == '2': not_high_prof = f"{op_bold_tag}<u>{not_high_prof}</u>{cl_bold_tag}" elif params["code"] == '3': middle_prof = f"{op_bold_tag}<u>{middle_prof}</u>{cl_bold_tag}" elif params["code"] == '5': middle_common = f"{op_bold_tag}<u>{middle_common}</u>{cl_bold_tag}" opinion = gen_opinion(['16.* Образование:', high_prof, '1', not_high_prof, '2', middle_prof, '3', middle_common, '4']) col_width = (29 * mm, 42 * mm, 6 * mm, 30 * mm, 6 * mm, 41 * mm, 6 * mm, 25 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -1 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ('GRID', (6, 0), (6, 0), 0.75, colors.black), ('GRID', (8, 0), (8, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) common, start, before_school, not_has_start, not_known = "основное", ", начальное", ", дошкольное", ", не имеет начального образования", ", неизвестно" if params["code"] == '6': common = f"{op_bold_tag}<u>{common}</u>{cl_bold_tag}" elif params["code"] == '7': start = f"{op_bold_tag}<u>{start}</u>{cl_bold_tag}" elif params["code"] == '10': before_school = f"{op_bold_tag}<u>{before_school}</u>{cl_bold_tag}" elif params["code"] == '11': not_has_start = f"{op_bold_tag}<u>{not_has_start}</u>{cl_bold_tag}" elif params["code"] == '9': not_known = f"{op_bold_tag}<u>{not_known}</u>{cl_bold_tag}" opinion = gen_opinion([common, '5', start, '6', before_school, '7', not_has_start, '8', not_known, '9']) col_width = (20 * mm, 6 * mm, 20 * mm, 6 * mm, 21 * mm, 6 * mm, 50 * mm, 6 * mm, 19 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ('GRID', (5, 0), (5, 0), 0.75, colors.black), ('GRID', (7, 0), (7, 0), 0.75, colors.black), ('GRID', (9, 0), (9, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) return text def work_position(text, params): params = json.loads(params) worked, military, pensioner, student = "работал(а)", ", проходил(а) военную или приравненную к ней службу", ", пенсионер(ка)", "студент(ка)" if params["code"] == '5': worked = f"{op_bold_tag}<u>{worked}</u>{cl_bold_tag}" elif params["code"] == '17': military = f"{op_bold_tag}<u>{military}</u>{cl_bold_tag}" elif params["code"] == '7': pensioner = f"{op_bold_tag}<u>{pensioner}</u>{cl_bold_tag}" elif params["code"] == '4': student = f"{op_bold_tag}<u>{student}</u>{cl_bold_tag}" opinion = gen_opinion(['17. * Занятость:', worked, '1', military, '2', pensioner, '3', student, '4']) col_width = (24 * mm, 18 * mm, 6 * mm, 80 * mm, 6 * mm, 24 * mm, 6 * mm, 20 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ('GRID', (6, 0), (6, 0), 0.75, colors.black), ('GRID', (8, 0), (8, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) not_work, others, not_known = "не работал(а)", ", прочие", ", неизвестно" if params["code"] == '8': not_work = f"{op_bold_tag}<u>{not_work}</u>{cl_bold_tag}" elif params["code"] == '10': others = f"{op_bold_tag}<u>{others}</u>{cl_bold_tag}" elif params["code"] == '22': not_known = f"{op_bold_tag}<u>{not_known}</u>{cl_bold_tag}" opinion = gen_opinion([not_work, '5', others, '6', not_known, '7']) col_width = (28 * mm, 6 * mm, 17 * mm, 6 * mm, 21 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ('GRID', (5, 0), (5, 0), 0.75, colors.black), ('GRID', (7, 0), (7, 0), 0.75, colors.black), ('GRID', (9, 0), (9, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) return text def title_med_organization(text, params): opinion = [ [ Paragraph(f'{params["full_title"]}<br/>' f'адрес места нахождения {params["org_address"]}<br/>' f'Код по ОКПО {params["org_okpo"]}<br/>' f'Номер и дата выдачи лицензии на осуществление медицинской деятельности: <br/>{params["org_license"]}<br/>', styleOrg), Paragraph('', styleOrg), Paragraph('Код формы по ОКУД _______<br/>Медицинская документация<br/>Учётная форма № 106/У<br/>Утверждена приказом Минздрава России <br/>от «15» апреля 2021 г. № 352н', styleOrg), ], ] col_width = (125 * mm, 5 * mm, 60 * mm,) tbl_style = [ ('GRID', (0, 0), (0, 0), 0.75, colors.black), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (-1, -1), 1 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) return text def bottom_colontitul(text, params): opinion = [[Paragraph(f'{params}', styleColontitul), ], ] col_width = (190 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 10 * mm), ('LEFTPADDING', (0, 0), (-1, -1), 1 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) return text def back_size(text): opinion = [[Paragraph('Оборотная сторона', styleColontitulBold), ], ] col_width = (190 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (-1, -1), (-1, -1), 166 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) return text def why_death(text, params, item_why, item_dtp, item_pregnant, item_doc): opinion = [ [ Paragraph(f"{item_why}. Причины смерти:", styleT), Paragraph('Приблизительный период времени между началом патологического процесса и смертью', styleOrg), Paragraph('Коды по МКБ', styleOrg), ], ] col_width = (114 * mm, 36 * mm, 40 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (-1, -1), (-1, -1), 1 * mm), ('LEFTPADDING', (2, 0), (2, 0), 8 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) tbl = diagnos_tbl({"para": "I", "item": "а)", "result": params["а"]["rows"][0]}) text.append(Spacer(1, 0.3 * mm)) text.append(tbl) tbl = about_diagnos("(болезнь или состояние, непосредственно приведшее к смерти)") text.append(Spacer(1, 0.1 * mm)) text.append(tbl) tbl = diagnos_tbl({"para": "", "item": "б)", "result": params["б"]["rows"][0]}) text.append(Spacer(1, 0 * mm)) text.append(tbl) tbl = about_diagnos("(патологическое состояние, которое привело к возникновению причины, указанной в пункте «а»)") text.append(Spacer(1, 0 * mm)) text.append(tbl) tbl = diagnos_tbl({"para": "", "item": "в)", "result": params["в"]["rows"][0]}) text.append(Spacer(1, 0 * mm)) text.append(tbl) tbl = about_diagnos("(первоначальная причина смерти указывается последней)") text.append(Spacer(1, 0 * mm)) text.append(tbl) tbl = diagnos_tbl({"para": "", "item": "г)", "result": params["г"]["rows"][0]}) text.append(Spacer(1, 0 * mm)) text.append(tbl) tbl = about_diagnos("(внешняя причина при травмах и отравлениях)") text.append(Spacer(1, 0 * mm)) text.append(tbl) opinion = [ [ Paragraph('II. Прочие важные состояния, способствовавшие смерти, но не связанные с болезнью или патологическим состоянием, приведшим к ней, включая употребление ' 'алкоголя, наркотических средств, психотропных и других токсических веществ, содержание их в крови, а также операции (название, дата)', styleColontitul), ], ] col_width = (190 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (-1, -1), (-1, -1), 1 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.1 * mm)) text.append(tbl) text.append(Spacer(1, 0.6 * mm)) data_ii = params["ii"]["rows"] for k in range(len(data_ii)): tbl = diagnos_tbl({"para": "", "item": "", "result": data_ii[k], "top_padd": -1.2 * mm}) text.append(Spacer(1, 0 * mm)) text.append(tbl) days30, days7 = "смерть наступила - в течение 30 суток", ", из них в течение 7 суток" dtp_death = json.loads(params["Связь смерти с ДТП"]) if dtp_death["code"] == "1": days30 = f"{op_bold_tag}<u>{days30}</u>{cl_bold_tag}" elif dtp_death["code"] == "2": days7 = f"{op_bold_tag}<u>{days7}</u>{cl_bold_tag}" opinion = gen_opinion([f'{item_dtp}.В случае смерти в результате ДТП:', days30, '1', days7, '2']) col_width = (55 * mm, 55 * mm, 6 * mm, 40 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) pregnant, process_birth = "(независимо от срока и локализации)", ", в процессе родов" pregnant_data = json.loads(params["Связь смерти с беременностью"]) if pregnant_data["code"] == "1": pregnant = f"{op_bold_tag}<u>{pregnant}</u>{cl_bold_tag}" elif pregnant_data["code"] == "2": process_birth = f"{op_bold_tag}<u>{process_birth}</u>{cl_bold_tag}" opinion = gen_opinion([f'{item_pregnant}.В случае смерти беременной', pregnant, '1', process_birth, '2']) col_width = (50 * mm, 52 * mm, 6 * mm, 30 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LEFTPADDING', (1, 0), (1, 0), -2 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) final_process_birth_42days, final_process_birth_365days = "в течение 42 дней после окончания беременности, родов", ", кроме того в течение 43-365 дней после окончания беременности" if pregnant_data["code"] == "3": final_process_birth_42days = f"{op_bold_tag}<u>{final_process_birth_42days}</u>{cl_bold_tag}" elif pregnant_data["code"] == "4": final_process_birth_365days = f"{op_bold_tag}<u>{final_process_birth_365days}</u>{cl_bold_tag}" opinion = gen_opinion([final_process_birth_42days, '3', final_process_birth_365days, '4']) col_width = (84 * mm, 6 * mm, 98 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 4 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) opinion = gen_opinion([f'{item_doc}.Фамилия, имя, отчество (при наличии) врача (фельдшера, акушерки), заполнившего Медицинское свидетельство о смерти']) col_width = (190 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) opinion = gen_opinion([f'{params["Заполнил"]}', 'Подпись', '']) col_width = (140 * mm, 20 * mm, 30 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LINEBELOW', (0, 0), (0, 0), 0.75, colors.black), ('LINEBELOW', (2, 0), (2, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def diagnos_tbl(data): description_diag = data["result"][2] description_diag_json = None if len(description_diag) > 1: description_diag_json = json.loads(description_diag) decription = '' period = "" top_padd = 0 * mm mkb10 = ["", "", "", "", ""] if len(description_diag) > 1: decription = description_diag_json["title"] mkb10 = list(description_diag_json["code"]) if len(list(decription)) > 72: top_padd = -2 * mm period = f'{data["result"][0]} {data["result"][1]}' if data.get("top_padd", None): top_padd = data.get("top_padd") elements = [] for element in range(5): try: elements.insert(element, mkb10[element]) except: elements.insert(element, "") opinion = gen_opinion_diag([data["para"], data["item"], decription, period, '', elements[0], elements[1], elements[2], '.', elements[4]]) col_width = (6 * mm, 7 * mm, 102 * mm, 36 * mm, 5 * mm, 8 * mm, 7 * mm, 7 * mm, 6 * mm, 7 * mm,) tbl_style = [ ('GRID', (5, 0), (5, 0), 0.75, colors.black), ('GRID', (6, 0), (6, 0), 0.75, colors.black), ('GRID', (7, 0), (7, 0), 0.75, colors.black), ('GRID', (9, 0), (9, 0), 0.75, colors.black), ('LINEBELOW', (0, 0), (3, 0), 0.75, colors.black), ('LINEBEFORE', (3, 0), (3, 0), 0.75, colors.black), ('LINEAFTER', (3, 0), (3, 0), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('TOPPADDING', (2, 0), (2, 0), top_padd), ('LEFTPADDING', (2, 0), (2, 0), -2 * mm), ('LEFTPADDING', (3, 0), (3, 0), 10 * mm), ] tbl = gen_table(opinion, col_width, tbl_style, 4 * mm) return tbl def about_diagnos(data): styleMicro = deepcopy(styleT) styleMicro.fontSize = 5.5 styleMicro.alignment = TA_CENTER opinion = [ [ Paragraph('', styleT), Paragraph('', styleT), Paragraph(f'{data}', styleMicro), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT), ], ] col_width = (6 * mm, 7 * mm, 102 * mm, 36 * mm, 5 * mm, 7 * mm, 7 * mm, 7 * mm, 6 * mm, 7 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), -0.5 * mm), ('LINEBEFORE', (3, 0), (3, 0), 0.75, colors.black), ('LINEAFTER', (3, 0), (3, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) return tbl def destination_person_passport(text, data): opinion = gen_opinion([data]) tbl_style = [ ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LINEBELOW', (0, 0), (-1, -1), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] col_width = (190 * mm) tbl = gen_table(opinion, col_width, tbl_style, 4 * mm) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def destination_person_snils(text, data): opinion = gen_opinion(['СНИЛС получателя (при наличии)', data]) tbl_style = [ ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ] col_width = (50 * mm, 140 * mm) tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.2 * mm)) text.append(tbl) return text def death_happaned(text, params): ill, unfortunate_not_work, unfortunate_work = "от заболевания", "несчастного случая: не связанного с производством", "связанного с производством" type_happend = json.loads(params) if type_happend["code"] == "1": ill = f"{op_bold_tag}<u>{ill}</u>{cl_bold_tag}" elif type_happend["code"] == "2": unfortunate_not_work = f"{op_bold_tag}<u>{unfortunate_not_work}</u>{cl_bold_tag}" elif type_happend["code"] == "3": unfortunate_work = f"{op_bold_tag}<u>{unfortunate_work}</u>{cl_bold_tag}" opinion = gen_opinion(['18. Смерть произошла:', ill, '1', unfortunate_not_work, '2', unfortunate_work, '3']) col_width = (34 * mm, 24 * mm, 6 * mm, 74 * mm, 6 * mm, 43 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ('GRID', (6, 0), (6, 0), 0.75, colors.black), ('GRID', (8, 0), (8, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) kill, self_kill, military, terrorist, not_know = "убийства", "самоубийства", ", в ходе действий: военных", "террористических", ", род смерти не установлен" if type_happend["code"] == "4": kill = f"{op_bold_tag}<u>{kill}</u>{cl_bold_tag}" elif type_happend["code"] == "5": self_kill = f"{op_bold_tag}<u>{self_kill}</u>{cl_bold_tag}" elif type_happend["code"] == "6": military = f"{op_bold_tag}<u>{military}</u>{cl_bold_tag}" elif type_happend["code"] == "7": terrorist = f"{op_bold_tag}<u>{terrorist}</u>{cl_bold_tag}" elif type_happend["code"] == "8": not_know = f"{op_bold_tag}<u>{not_know}</u>{cl_bold_tag}" opinion = gen_opinion([kill, '4', self_kill, '5', military, '6', terrorist, '7', not_know, '8']) col_width = (22 * mm, 6 * mm, 23 * mm, 6 * mm, 40 * mm, 6 * mm, 30 * mm, 6 * mm, 40 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ('GRID', (5, 0), (5, 0), 0.75, colors.black), ('GRID', (7, 0), (7, 0), 0.75, colors.black), ('GRID', (9, 0), (9, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) return text def who_set_death(text, params): only_doc_death, doc_work, paramedic = "врачом, только установившем смерть", "лечащим врачом", "фельдшером (акушеркой)" param_who_set = json.loads(params) if param_who_set["code"] == "1": only_doc_death = f"{op_bold_tag}<u>{only_doc_death}</u>{cl_bold_tag}" elif param_who_set["code"] == "2" or param_who_set["code"] == "7": doc_work = f"{op_bold_tag}<u>{doc_work}</u>{cl_bold_tag}" elif param_who_set["code"] == "3" or param_who_set["code"] == "8" or param_who_set["code"] == "9": paramedic = f"{op_bold_tag}<u>{paramedic}</u>{cl_bold_tag}" opinion = gen_opinion(['20. Причины смерти установлены:', only_doc_death, '1', doc_work, '2', paramedic, '3']) col_width = (49 * mm, 58 * mm, 6 * mm, 27 * mm, 6 * mm, 40 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ('GRID', (6, 0), (6, 0), 0.75, colors.black), ('GRID', (8, 0), (8, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.9 * mm)) text.append(tbl) doc_anatomy, expert = "врачом-патологоанатомом", "судебно-медицинским экспертом" if param_who_set["code"] == "4": doc_anatomy = f"{op_bold_tag}<u>{doc_anatomy}</u>{cl_bold_tag}" elif param_who_set["code"] == "5" or param_who_set["code"] == "7": expert = f"{op_bold_tag}<u>{expert}</u>{cl_bold_tag}" opinion = gen_opinion([doc_anatomy, '4', expert, '5']) col_width = (50 * mm, 6 * mm, 50 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('RIGHTPADDING', (1, 0), (-1, -1), -2 * mm), ('GRID', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ('GRID', (5, 0), (5, 0), 0.75, colors.black), ('GRID', (7, 0), (7, 0), 0.75, colors.black), ('GRID', (9, 0), (9, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) return text def doctor_fio(text, params, iss: Issledovaniya): doc_fio = params["Заполнил"] opinion = gen_opinion(['21. Я, врач (фельдшер, акушерка)', doc_fio]) col_width = (50 * mm, 140 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 0 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) doc_position = params["Должность"] opinion = gen_opinion(['должность', doc_position]) col_width = (25 * mm, 165 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) see_body, write_medical_dicument = 'осмотра трупа', ', записей в медицинской документации', base_diagnos = json.loads(params["Основания для определения причины смерти"]) if base_diagnos["code"] == "1": see_body = f"{op_bold_tag}<u>{see_body}</u>{cl_bold_tag}" elif base_diagnos["code"] == "2": write_medical_dicument = f"{op_bold_tag}<u>{write_medical_dicument}</u>{cl_bold_tag}" opinion = gen_opinion(['удостоверяю, что на основании:', see_body, '1', write_medical_dicument, '2']) col_width = (53 * mm, 26 * mm, 6 * mm, 61 * mm, 6 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('GRID', (2, 0), (2, 0), 0.75, colors.black), ('GRID', (4, 0), (4, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) see_patient, open_body = 'предшествующего наблюдения за больным(ой)', ', вскрытия', if base_diagnos["code"] == "3" or base_diagnos["code"] == "5": see_patient = f"{op_bold_tag}<u>{see_patient}</u>{cl_bold_tag}" elif base_diagnos["code"] == "4": open_body = f"{op_bold_tag}<u>{open_body}</u>{cl_bold_tag}" opinion = gen_opinion([see_patient, '3', open_body, '4', ' мною установлены причины смерти']) col_width = (75 * mm, 6 * mm, 21 * mm, 6 * mm, 70 * mm) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('GRID', (1, 0), (1, 0), 0.75, colors.black), ('GRID', (3, 0), (3, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) return text def hospital_manager_stamp(text, fio_manager): opinion = gen_opinion(['', '', '', '', fio_manager]) col_width = (45 * mm, 5 * mm, 45 * mm, 5 * mm, 90 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('LINEBELOW', (0, 0), (0, 0), 0.75, colors.black), ('LINEBELOW', (2, 0), (2, 0), 0.75, colors.black), ('LINEBELOW', (4, 0), (4, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 3 * mm)) text.append(tbl) opinion = gen_opinion(['печать', 'подпись', '(фамилия, имя, отчество (при наличии)']) col_width = (45 * mm, 45 * mm, 100 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 15 * mm), ('LEFTPADDING', (1, 0), (1, 0), 15 * mm), ('LEFTPADDING', (2, 0), (2, 0), 15 * mm), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 0.4 * mm)) text.append(tbl) return text def check_person_data(text, fio_check): date_value = "«___» ___________ 20 ___ г." opinion = gen_opinion([date_value, fio_check]) col_width = (60 * mm, 130 * mm,) tbl_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 0 * mm), ('LEFTPADDING', (0, 0), (0, 0), 5 * mm), ('LINEBELOW', (1, 0), (1, 0), 0.75, colors.black), ] tbl = gen_table(opinion, col_width, tbl_style) text.append(Spacer(1, 3 * mm)) text.append(tbl) return text
Дата смер
umychart.regressiontest.js
/* Copyright (c) 2018 jones http://www.apache.org/licenses/LICENSE-2.0 开源项目 https://github.com/jones2000/HQChart [email protected] 个股指标回测 */ /* 指标回测 计算: Trade: {Count 交易次数 Days:交易天数 Success:成功交易次数 Fail:失败交易次数} Day: {Count:总运行 Max:最长运行 Min:最短运行 Average:平均运行} Profit: 总收益 StockProfit:个股收益 Excess:超额收益 MaxDropdown:最大回撤 Beta:β(Beta)系数(指标里面需要又大盘数据) NetValue: [ {Date:日期, Net:净值, Close:股票收盘价, IndexClose:大盘的收盘价}, ] */ function RegressionTest() { //只读数据不能修改 this.HistoryData; //K线数据 this.BuyData; //策略买数据 this.SellData; //策略卖数据 this.IndexClose; //大盘收盘价 this.NetCalculateModel=0; //净值及收益计算模型 0=使用B点开盘价计算 1=使用B点下一天的开盘价计算 this.InitialCapital=10000; //初始资金1W //计算结果数据 this.Data=new Map(); //key:DATA_NAME value:数据 this.SetPolicyData=function(obj) //设置策略结果的数据 {KLineData:个股K线数据, BuyData:策略买数据, SellData:策略卖数据, IndexClose:大盘收盘价} { this.HistoryData=obj.KLineData; //K线数据 this.BuyData=obj.BuyData; //策略买数据 this.SellData=obj.SellData; //策略卖数据 if (obj.IndexClose) this.IndexClose=obj.IndexClose; //大盘收盘价 如果没有大盘数据 就不计算β(Beta)系数 和指数涨幅数据 } this.ClearData=function() //清空所有的结果数据 { this.Data=new Map() } this.GetBSData=function(startDate) //BS点配对 { B:[{Data:K线数据, Count:天数, NextOpen:下一天的开盘价 }], S:{Data:K线数据}} { var index=null; for(var i=0;i<this.HistoryData.length;++i) { var item=this.HistoryData[i]; if (item.Date>=startDate) { index=i; break; } } if (index===null) return null; console.log(`[RegressionTest::GetBSData] startDate=${startDate} index=${index}`); var aryBS=[]; var bsItem=null; for(var i=index;i<this.HistoryData.length;++i) { var buyItem=this.BuyData[i]; var sellItem=this.SellData[i]; var kLineItem=this.HistoryData[i]; if (bsItem===null) { if (buyItem>0) { var bItem={Data:kLineItem, Count:0 }; if (i+1<this.HistoryData.length) bItem.NextOpen=this.HistoryData[i+1].Open; //获取下一天的开盘价 bsItem={ B:[bItem], S:null}; //B可以多个,S一个 } } else { for(var j in bsItem.B) ++bsItem.B[j].Count; //天数+1 if (buyItem>0) { var bItem={Data:kLineItem, Count:0}; if (i+1<this.HistoryData.length) bItem.NextOpen=this.HistoryData[i+1].Open; //获取下一天的开盘价 bsItem.B.push(bItem); } else if (sellItem>0) { bsItem.S={Data:kLineItem}; aryBS.push(bsItem); bsItem=null; } } } var data={StartDate:this.HistoryData[index].Date, StartIndex:index, Count:this.HistoryData.length-index, BSData:aryBS }; console.log('[RegressionTest::GetBSData] data',data); return data; } this.Calculate=function(data) { var day={ Count:data.Count, Max:null, Min:null, Average:null }; //Count:总运行 Max:最长运行 Min:最短运行 Average:平均运行 var trade={Count:0, Days:0, Success:0 , Fail:0, SuccessRate:0}; //Count 交易次数 Days:交易天数 Success:成功交易次数 Fail:失败交易次数 for(var i in data.BSData) { var item=data.BSData[i]; for(var j in item.B) { var bItem=item.B[j]; if (day.Max===null) day.Max=bItem.Count; else if (day.Max<bItem.Count) day.Max=bItem.Count; if (day.Min===null) day.Min=bItem.Count; else if (day.Min>bItem.Count) day.Min=bItem.Count; ++trade.Count; trade.Days+=bItem.Count; if (item.S.Data.Close>bItem.Data.Open) ++trade.Success; else ++trade.Fail; } } if (trade.Count>0) { day.Average=trade.Days/trade.Count; trade.SuccessRate=trade.Success/trade.Count; } //计算收益(总收益)
var profit=1,buyPrice; for(var i in data.BSData) { var item=data.BSData[i]; if (this.NetCalculateModel===1 && item.B[0].NextOpen>0 ) buyPrice=item.B[0].NextOpen; else buyPrice=item.B[0].Data.Open; var sellPrice=item.S.Data.Close; var value=(sellPrice-buyPrice)/buyPrice+1; profit*=value; } profit-=1; //公式:[(1+收益1)*(1+收益2)*(1+收益3)……(1+收益n)-1] x 100% //标的证券收益 var yClose=this.HistoryData[data.StartIndex].Close; //使用前收盘 var close=this.HistoryData[this.HistoryData.length-1].Close; //最后一个大盘收盘价 var stockProfit=(close-yClose)/yClose; console.log(`[RegressionTest::Calculate] stock profit first[${this.HistoryData[data.StartIndex].Date}, YClose=${this.HistoryData[data.StartIndex].YClose}] end[${this.HistoryData[this.HistoryData.length-1].Date}, Close=${this.HistoryData[this.HistoryData.length-1].Close}]`); var netValue=this.CaclulateNetValue(data); var maxDropdown=null, beta=null; if (netValue && netValue.length>0) { maxDropdown=this.CaclulateMaxDropdown(netValue); if (this.IndexClose) beta=this.CaclulateBeta(netValue); } //Profit:收益 StockProfit:标的证券收益 Excess:超额收益 var result={ Day:day, Trade:trade, Profit:profit, StockProfit:stockProfit, Excess:profit-stockProfit, NetValue:netValue, MaxDropdown:maxDropdown, Beta:beta }; console.log('[RegressionTest::Calculate] NetCalculateModel, result ',this.NetCalculateModel, result); return result; } this.CaclulateNetValue=function(data) //计算净值 { var index=data.StartIndex; var aryDay=[]; //{Close:收盘 , Open:开盘, Position:持仓数量, Cache:现金 , MarketValue:总市值} var lastDayItem={Position:0, Cache:this.InitialCapital }; var bsItem=null, buyPrice; for(var i=index;i<this.HistoryData.length;++i) { var buyItem=this.BuyData[i]; var sellItem=this.SellData[i]; var kLineItem=this.HistoryData[i]; var dayItem={Date:kLineItem.Date, Position:lastDayItem.Position, Cache:lastDayItem.Cache, Open:kLineItem.Open, Close:kLineItem.Close}; dayItem.MarketValue=dayItem.Position*dayItem.Close+dayItem.Cache; //市值 股票+现金 if (bsItem===null) { if (buyItem>0) //买 { bsItem={ B:{Data:kLineItem}, S:null}; if (this.NetCalculateModel===1 && i+1<this.HistoryData.length && this.HistoryData[i+1].Open>0) buyPrice=this.HistoryData[i+1].Open; //使用B点下一天的开盘价买 else buyPrice=dayItem.Open; let position=parseInt(dayItem.Cache/buyPrice); //开盘价买 let cache=dayItem.Cache-buyPrice*position; //剩余的现金 dayItem.Position=position; dayItem.Cache=cache; dayItem.MarketValue=dayItem.Position*dayItem.Close+dayItem.Cache; //市值 股票+现金 } } else { if (sellItem>0) //卖 { bsItem.S={Data:kLineItem}; bsItem=null; let stockValue=dayItem.Position*dayItem.Close; //卖掉的股票钱 dayItem.Position=0; dayItem.Cache+=stockValue; //卖掉的钱放到现金里面 dayItem.MarketValue=dayItem.Position*dayItem.Close+dayItem.Cache; //市值 股票+现金 } } //缓存上一天的数据 lastDayItem.Position=dayItem.Position; lastDayItem.Cache=dayItem.Cache; dayItem.Net=dayItem.MarketValue/this.InitialCapital; //净值 if (this.IndexClose) dayItem.IndexClose=this.IndexClose[i]; //指数收盘价 aryDay.push(dayItem); } //console.log('[RegressionTest::CaclulateNetValue] aryDay',aryDay); if (aryDay.length<=0) return []; var netValue=[]; //净值 {Date:日期, Net:净值, Close:股票收盘价, IndexClose:大盘的收盘价} for(var i=0;i<aryDay.length;++i) { var item=aryDay[i]; var dataItem={ Net:item.Net, Date:item.Date, Close:item.Close }; if (item.IndexClose) dataItem.IndexClose=item.IndexClose; netValue.push(dataItem); } //console.log('[RegressionTest::CaclulateNetValue] netValue',netValue); return netValue; } this.CaclulateMaxDropdown=function(data) //最大回撤 { var maxNet=data[0].Net; //最大净值 var maxValue=0; var maxDay; for(var i=1;i<data.length;++i) { var item=data[i]; var value=1-(item.Net/maxNet); //1-策略当日净值 / 当日之前策略最大净值 if (maxValue<value) { maxValue=value; maxDay=item; } if (maxNet<item.Net) maxNet=item.Net; //取当前最大的净值 } console.log('[RegressionTest::CaclulateMaxDropdown] maxDay',maxDay); return maxValue; } this.CaclulateBeta=function(data) //β(Beta)系数,参数是净值数组NetValue { var lastItem=data[0]; //上一天的数据 var indexProfit=[]; //大盘涨幅 var bsProfit=[]; //策略涨幅 var indexProfitTotal=0, bsProfitTotal=0; for(var i=1; i<data.length; ++i) { indexProfit[i-1]=0; bsProfit[i-1]=0; var item=data[i]; if (item.IndexClose>0 && lastItem.IndexClose>0) indexProfit[i-1]=(item.IndexClose-lastItem.IndexClose)/lastItem.IndexClose; if (item.Net>0 && lastItem.Net>0) bsProfit[i-1]=(item.Net-lastItem.Net)/lastItem.Net; //if (item.Close>0 && lastItem.Close>0) bsProfit[i-1]=(item.Close-lastItem.Close)/lastItem.Close; indexProfitTotal+=indexProfit[i-1]; bsProfitTotal+=bsProfit[i-1]; lastItem=item; } var averageIndexProfit=indexProfitTotal/indexProfit.length; var averageBSProfit=bsProfitTotal/bsProfit.length; var betaCOV=0; //协方差 for(var i=0;i<indexProfit.length;++i) { betaCOV+=(bsProfit[i]-averageBSProfit)*(indexProfit[i]-averageIndexProfit); } var betaVAR=0; //标准差:方差的开2次方 for(var i=0;i<indexProfit.length;++i) { betaVAR+=(indexProfit[i]-averageIndexProfit)*(indexProfit[i]-averageIndexProfit); } return betaCOV/betaVAR; } this.Execute=function(obj) //开始计算[ { Name:名字 , Date:起始日期 格式(20180101) }, ....] { for(var i in obj ) { var item=obj[i]; if (this.Data.has(item.Name)) //已经计算过了不计算 { console.log(`[RegressionTest::Execute] id=${i} Name=${item.Name} Date:${item.Date} is exsit.`); continue; } console.log(`[RegressionTest::Execute] id=${i} Name=${item.Name} Date:${item.Date}`); var data=this.GetBSData(item.Date); var result=this.Calculate(data); this.Data.set(item.Name, result); } } } //计算叠加数据 (日期必须匹配) RegressionTest.CaclulateOverlayData=function(obj) //{Main:主数据, Sub:[]//多组叠加数据} { if (!obj.Main || !obj.Sub) return null; var count=obj.Main.length; for(var i in obj.Sub) { var item=obj.Sub[i]; if (item.length!=count) { console.log(`[RegressionTest::OverlayData] id=${i} data count not match. MainData count=${count}`); return null; } } var result=[]; //[0]:主数据 , [1...]:叠加数据 var firstData={Sub:[]}; firstData.Main=obj.Main[0]; result.push([]); for(var i=0;i<obj.Sub.length;++i) { var subData=obj.Sub[i]; firstData.Sub[i]=subData[0]; result.push([]); } for(var i=0;i<obj.Main.length;++i) { var value=obj.Main[i]; var valuePer=(value-firstData.Main)/firstData.Main; result[0][i]=valuePer; for(var j=0;j<obj.Sub.length;++j) { var subData=obj.Sub[j]; var subValue=subData[i]; var subValuePer=(subValue-firstData.Sub[j])/firstData.Sub[j]; result[j+1][i]=subValuePer; } } return result; } RegressionTest.GetPolicyData=function(data) //获取指标数据里面需要计算回测的数据 { var policyData={KLineData:null, IndexClose:null, BuyData:null, SellData:null}; policyData.KLineData=data.HistoryData.Data; //个股K线数据, for(var i in data.OutVar) { var item=data.OutVar[i]; if (item.Name=='INDEXCLOSE') { policyData.IndexClose=item.Data; //绑定大盘收盘数据 } else if (item.Name=='DRAWICON') //买卖盘BS函数 { if (item.Draw && item.Draw.Icon) { if (item.Draw.Icon.ID===13) policyData.BuyData=item.Draw.DrawData; //买 else if (item.Draw.Icon.ID===14) policyData.SellData=item.Draw.DrawData; //卖 } } } if (policyData.KLineData && policyData.BuyData && policyData.SellData) return policyData; return null; }
esmvaltool_testlib.py
"""Provide a class for testing esmvaltool.""" import glob
import os import shutil import sys from unittest import SkipTest import numpy as np import yaml # from easytest import EasyTest import esmvaltool def _load_config(filename=None): """Load test configuration""" if filename is None: # look in default locations for config-test.yml config_file = 'config-test.yml' default_locations = [ '.', '~/.esmvaltool', os.path.dirname(__file__), ] for path in default_locations: filepath = os.path.join(os.path.expanduser(path), config_file) if os.path.exists(filepath): filename = os.path.abspath(filepath) break with open(filename, 'r') as file: cfg = yaml.safe_load(file) cfg['configfile'] = filename cfg['reference']['output'] = os.path.abspath( os.path.expanduser(cfg['reference']['output'])) if cfg['test'].get('recipes', []) == []: script_root = esmvaltool.get_script_root() recipe_glob = os.path.join(script_root, 'nml', 'recipe_*.yml') cfg['test']['recipes'] = glob.glob(recipe_glob) return cfg _CFG = _load_config() RECIPES = _CFG['test']['recipes'] def _create_config_user_file(output_directory): """Write a config-user.yml file. Write a configuration file for running ESMValTool such that it writes all output to `output_directory`. """ cfg = _CFG['user'] cfg['output_dir'] = output_directory # write to file filename = os.path.join(output_directory, 'config-user.yml') with open(filename, 'w') as file: yaml.safe_dump(cfg, file) return filename class ESMValToolTest: # was ESMValToolTest(EasyTest) """Main class for ESMValTool test runs.""" def __init__(self, recipe, output_directory, ignore='', **kwargs): """ Create ESMValToolTest instance recipe: str The filename of the recipe that should be tested. output_directory : str The name of a directory where results can be stored. ignore: str or iterable of str Glob patterns of files to be ignored when testing. """ if not _CFG['test']['run']: raise SkipTest("System tests disabled in {}".format( _CFG['configfile'])) self.ignore = (ignore, ) if isinstance(ignore, str) else ignore script_root = esmvaltool.get_script_root() # Set recipe path if not os.path.exists(recipe): recipe = os.path.join( os.path.dirname(script_root), 'recipes', recipe) self.recipe_file = os.path.abspath(recipe) # Simulate input data? self.simulate_input = _CFG['test']['simulate_input'] # Create reference output? self.create_reference_output = _CFG['reference']['generate'] # Define reference output path reference_dir = os.path.join( _CFG['reference']['output'], os.path.splitext(os.path.basename(self.recipe_file))[0]) # If reference data is neither available nor should be generated, skip if not (os.path.exists(reference_dir) or self.create_reference_output): raise SkipTest( "No reference data available for recipe {} in {}".format( recipe, _CFG['reference']['output'])) # Write ESMValTool configuration file self.config_user_file = _create_config_user_file(output_directory) super(ESMValToolTest, self).__init__( exe='esmvaltool', args=['-n', self.recipe_file, '-c', self.config_user_file], output_directory=output_directory, refdirectory=reference_dir, **kwargs) def run(self, **kwargs): """Run tests or generate reference data.""" if self.simulate_input: from .data_simulator import simulate_input_data simulate_input_data( recipe_file=self.recipe_file, config_user_file=self.config_user_file) if self.create_reference_output: self.generate_reference_output() raise SkipTest("Generated reference data instead of running test") else: super(ESMValToolTest, self).run_tests(**kwargs) def generate_reference_output(self): """Generate reference output. Generate reference data by executing the recipe and then moving results to the output directory. """ if not os.path.exists(self.refdirectory): self._execute() shutil.move(self.output_directory, os.path.dirname(self.refdirectory)) else: print("Warning: not generating reference data, reference " "directory {} already exists.".format(self.refdirectory)) def _execute(self): """Execute ESMValTool Override the _execute method because we want to run in our own Python instance to get coverage reporting and we want to update the location of `self.output_directory` afterwards. """ # run ESMValTool sys.argv[1:] = self.args esmvaltool.main.run() # Update the output directory to point to the output of the run output_directory = self.output_directory # noqa output = [] for path in os.listdir(output_directory): path = os.path.join(output_directory, path) if os.path.isdir(path): output.append(path) if not output: raise OSError( "Output directory not found in location {}. " "Probably ESMValTool failed to create any output.".format( output_directory)) if len(output) > 1: print("Warning: found multiple output directories:\n{}\nin output " "location {}\nusing the first one.".format( output, output_directory)) self.output_directory = output[0] + os.sep # noqa def _get_files_from_refdir(self): """Get a list of files from reference directory. Ignore files that match patterns in self.ignore. Override this method of easytest.EasyTest to be able to ignore certain files. """ from fnmatch import fnmatchcase matches = [] for root, _, filenames in os.walk(self.refdirectory): for filename in filenames: path = os.path.join(root, filename) relpath = os.path.relpath(path, start=self.refdirectory) for pattern in self.ignore: if fnmatchcase(relpath, pattern): break else: matches.append(path) return matches def _compare_netcdf_values(self, f1, f2, allow_subset=False): """Compare two netCDF4 Dataset instances. Check if dataset2 contains the same variable values as dataset1. Override this method of easytest.EasyTest because it is broken for the case where value1 and value2 have no length. """ if allow_subset: # allow that only a subset of data is compared raise NotImplementedError for key in f1.variables: values1 = f1.variables[key][:] values2 = f2.variables[key][:] if not np.array_equal(values1, values2): return False return True
__init__.py
__version__ = "0.4.4"
_OPT_DEFAULTS: Dict[str, bool] = dict( specialized_code=True, optimize_einsums=True, jit_script_fx=True, ) def set_optimization_defaults(**kwargs) -> None: r"""Globally set the default optimization settings. Parameters ---------- **kwargs Keyword arguments to set the default optimization settings. """ for k, v in kwargs.items(): if k not in _OPT_DEFAULTS: raise ValueError(f"Unknown optimization option: {k}") _OPT_DEFAULTS[k] = v def get_optimization_defaults() -> Dict[str, bool]: r"""Get the global default optimization settings.""" return dict(_OPT_DEFAULTS)
from typing import Dict
mod.rs
pub mod builder; pub mod impls; pub mod initializer; pub mod utils; use serial_test::serial; use crate::{ state_machine::{ events::Event, phases::PhaseName, tests::{ builder::StateMachineBuilder, utils::{enable_logging, generate_summer, generate_updater, mask_config, Participant}, }, }, storage::{tests::init_store, CoordinatorStorage}, }; use xaynet_core::{ common::{RoundParameters, RoundSeed}, crypto::{ByteObject, EncryptKeyPair}, mask::{FromPrimitives, Model}, }; #[tokio::test] #[serial] async fn
() { enable_logging(); let model_length = 4; let round_params = RoundParameters { pk: EncryptKeyPair::generate().public, sum: 0.5, update: 1.0, seed: RoundSeed::generate(), mask_config: mask_config(), model_length, }; let n_updaters = 3; let n_summers = 2; let mut store = init_store().await; let (state_machine, requests, events) = StateMachineBuilder::new(store.clone()) .with_round_id(42) .with_seed(round_params.seed.clone()) .with_sum_ratio(round_params.sum) .with_update_ratio(round_params.update) .with_min_sum_count(n_summers) .with_max_sum_count(n_summers + 10) .with_min_update_count(n_updaters) .with_max_update_count(n_updaters + 10) .with_min_sum_time(1) .with_max_sum_time(2) .with_min_update_time(1) .with_max_update_time(2) .with_model_length(model_length) .build(); assert!(state_machine.is_idle()); // Idle phase let state_machine = state_machine.next().await.unwrap(); assert!(state_machine.is_sum()); // Sum phase let summer_1 = generate_summer(round_params.clone()); let summer_2 = generate_summer(round_params.clone()); let msg_1 = summer_1.compose_sum_message(); let msg_2 = summer_2.compose_sum_message(); let req_1 = async { requests.msg(&msg_1).await.unwrap() }; let req_2 = async { requests.msg(&msg_2).await.unwrap() }; let transition = async { state_machine.next().await.unwrap() }; let ((), (), state_machine) = tokio::join!(req_1, req_2, transition); assert!(state_machine.is_update()); // Update phase let transition_task = tokio::spawn(async { state_machine.next().await.unwrap() }); let sum_dict = events.sum_dict_listener().get_latest().event.unwrap(); let scalar = 1.0 / (n_updaters as f64 * round_params.update); let model = Model::from_primitives(vec![0; model_length].into_iter()).unwrap(); for _ in 0..3 { let updater = generate_updater(round_params.clone()); let (mask_seed, masked_model) = updater.compute_masked_model(&model, scalar); let local_seed_dict = Participant::build_seed_dict(&sum_dict, &mask_seed); let msg = updater.compose_update_message(masked_model.clone(), local_seed_dict.clone()); requests.msg(&msg).await.unwrap(); } let state_machine = transition_task.await.unwrap(); assert!(state_machine.is_sum2()); // Sum2 phase let seed_dict = events.seed_dict_listener().get_latest().event.unwrap(); let seeds_1 = summer_1.decrypt_seeds(&seed_dict.get(&summer_1.keys.public).unwrap()); let aggregation_1 = summer_1.aggregate_masks(model_length, &seeds_1); let msg_1 = summer_1.compose_sum2_message(aggregation_1.into()); let seeds_2 = summer_2.decrypt_seeds(&seed_dict.get(&summer_2.keys.public).unwrap()); let aggregation_2 = summer_2.aggregate_masks(model_length, &seeds_2); let msg_2 = summer_2.compose_sum2_message(aggregation_2.into()); let req_1 = async { requests.msg(&msg_1).await.unwrap() }; let req_2 = async { requests.msg(&msg_2).await.unwrap() }; let transition = async { state_machine.next().await.unwrap() }; let ((), (), state_machine) = tokio::join!(req_1, req_2, transition); assert!(state_machine.is_unmask()); // Unmask phase let state_machine = state_machine.next().await.unwrap(); // check if a global model exist #[cfg(feature = "model-persistence")] { use crate::storage::ModelStorage; let global_model_id = store.latest_global_model_id().await.unwrap().unwrap(); let store_model = store.global_model(&global_model_id).await.unwrap().unwrap(); assert!( matches!(events.model_listener().get_latest().event, super::events::ModelUpdate::New(broadcasted_model) if store_model == *broadcasted_model) ); let get_global_model_id = store.latest_global_model_id().await.unwrap().unwrap(); assert_eq!(global_model_id, get_global_model_id); } assert!(state_machine.is_idle()); // New idle phase let state_machine = state_machine.next().await.unwrap(); // During the idle phase, a new phase event with an updated round // id should have been emitted. assert_eq!( Event { round_id: 43, event: PhaseName::Idle, }, events.phase_listener().get_latest() ); // check if the dicts have been removed assert!(store.sum_dict().await.unwrap().is_none()); assert!(store.seed_dict().await.unwrap().is_none()); assert!(store.best_masks().await.unwrap().is_none()); // dropping the request sender should make the state machine // error out drop(requests); let state_machine = state_machine.next().await.unwrap(); assert!(state_machine.is_error()); // then the state machine should enter the shutdown state let state_machine = state_machine.next().await.unwrap(); assert!(state_machine.is_shutdown()); assert!(state_machine.next().await.is_none()) }
integration_full_round
layer.go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package localcachelayer import ( "runtime" "time" "github.com/mattermost/mattermost-server/v6/einterfaces" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/services/cache" "github.com/mattermost/mattermost-server/v6/store" ) const ( ReactionCacheSize = 20000 ReactionCacheSec = 30 * 60 RoleCacheSize = 20000 RoleCacheSec = 30 * 60 SchemeCacheSize = 20000 SchemeCacheSec = 30 * 60 FileInfoCacheSize = 25000 FileInfoCacheSec = 30 * 60 ChannelGuestCountCacheSize = model.ChannelCacheSize ChannelGuestCountCacheSec = 30 * 60 WebhookCacheSize = 25000 WebhookCacheSec = 15 * 60 EmojiCacheSize = 5000 EmojiCacheSec = 30 * 60 ChannelPinnedPostsCountsCacheSize = model.ChannelCacheSize ChannelPinnedPostsCountsCacheSec = 30 * 60 ChannelMembersCountsCacheSize = model.ChannelCacheSize ChannelMembersCountsCacheSec = 30 * 60 LastPostsCacheSize = 20000 LastPostsCacheSec = 30 * 60 TermsOfServiceCacheSize = 20000 TermsOfServiceCacheSec = 30 * 60 LastPostTimeCacheSize = 25000 LastPostTimeCacheSec = 15 * 60 UserProfileByIDCacheSize = 20000 UserProfileByIDSec = 30 * 60 ProfilesInChannelCacheSize = model.ChannelCacheSize ProfilesInChannelCacheSec = 15 * 60 TeamCacheSize = 20000 TeamCacheSec = 30 * 60 ChannelCacheSec = 15 * 60 // 15 mins ) var clearCacheMessageData = []byte("") type LocalCacheStore struct { store.Store metrics einterfaces.MetricsInterface cluster einterfaces.ClusterInterface reaction LocalCacheReactionStore reactionCache cache.Cache fileInfo LocalCacheFileInfoStore fileInfoCache cache.Cache role LocalCacheRoleStore roleCache cache.Cache rolePermissionsCache cache.Cache scheme LocalCacheSchemeStore schemeCache cache.Cache emoji *LocalCacheEmojiStore emojiCacheById cache.Cache emojiIdCacheByName cache.Cache channel LocalCacheChannelStore channelMemberCountsCache cache.Cache channelGuestCountCache cache.Cache channelPinnedPostCountsCache cache.Cache channelByIdCache cache.Cache webhook LocalCacheWebhookStore webhookCache cache.Cache post LocalCachePostStore postLastPostsCache cache.Cache lastPostTimeCache cache.Cache user *LocalCacheUserStore userProfileByIdsCache cache.Cache profilesInChannelCache cache.Cache team LocalCacheTeamStore teamAllTeamIdsForUserCache cache.Cache termsOfService LocalCacheTermsOfServiceStore termsOfServiceCache cache.Cache } func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterface, cluster einterfaces.ClusterInterface, cacheProvider cache.Provider) (localCacheStore LocalCacheStore, err error) { localCacheStore = LocalCacheStore{ Store: baseStore, cluster: cluster, metrics: metrics, } // Reactions if localCacheStore.reactionCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: ReactionCacheSize, Name: "Reaction", DefaultExpiry: ReactionCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForReactions, }); err != nil { return } localCacheStore.reaction = LocalCacheReactionStore{ReactionStore: baseStore.Reaction(), rootStore: &localCacheStore} // Roles if localCacheStore.roleCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: RoleCacheSize, Name: "Role", DefaultExpiry: RoleCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForRoles, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), }); err != nil { return } if localCacheStore.rolePermissionsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: RoleCacheSize, Name: "RolePermission", DefaultExpiry: RoleCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForRolePermissions, }); err != nil { return } localCacheStore.role = LocalCacheRoleStore{RoleStore: baseStore.Role(), rootStore: &localCacheStore} // Schemes if localCacheStore.schemeCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: SchemeCacheSize, Name: "Scheme", DefaultExpiry: SchemeCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForSchemes, }); err != nil { return } localCacheStore.scheme = LocalCacheSchemeStore{SchemeStore: baseStore.Scheme(), rootStore: &localCacheStore} // FileInfo if localCacheStore.fileInfoCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: FileInfoCacheSize, Name: "FileInfo", DefaultExpiry: FileInfoCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForFileInfos, }); err != nil { return } localCacheStore.fileInfo = LocalCacheFileInfoStore{FileInfoStore: baseStore.FileInfo(), rootStore: &localCacheStore} // Webhooks if localCacheStore.webhookCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: WebhookCacheSize, Name: "Webhook", DefaultExpiry: WebhookCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForWebhooks, }); err != nil { return } localCacheStore.webhook = LocalCacheWebhookStore{WebhookStore: baseStore.Webhook(), rootStore: &localCacheStore} // Emojis if localCacheStore.emojiCacheById, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: EmojiCacheSize, Name: "EmojiById", DefaultExpiry: EmojiCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForEmojisById, }); err != nil { return } if localCacheStore.emojiIdCacheByName, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: EmojiCacheSize, Name: "EmojiByName", DefaultExpiry: EmojiCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForEmojisIdByName, }); err != nil { return } localCacheStore.emoji = &LocalCacheEmojiStore{ EmojiStore: baseStore.Emoji(), rootStore: &localCacheStore, emojiByIdInvalidations: make(map[string]bool), emojiByNameInvalidations: make(map[string]bool), } // Channels if localCacheStore.channelPinnedPostCountsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: ChannelPinnedPostsCountsCacheSize, Name: "ChannelPinnedPostsCounts", DefaultExpiry: ChannelPinnedPostsCountsCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForChannelPinnedpostsCounts, }); err != nil { return } if localCacheStore.channelMemberCountsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: ChannelMembersCountsCacheSize, Name: "ChannelMemberCounts", DefaultExpiry: ChannelMembersCountsCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForChannelMemberCounts, }); err != nil { return } if localCacheStore.channelGuestCountCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: ChannelGuestCountCacheSize, Name: "ChannelGuestsCount", DefaultExpiry: ChannelGuestCountCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForChannelGuestCount, }); err != nil { return } if localCacheStore.channelByIdCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: model.ChannelCacheSize, Name: "channelById", DefaultExpiry: ChannelCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForChannel, }); err != nil { return } localCacheStore.channel = LocalCacheChannelStore{ChannelStore: baseStore.Channel(), rootStore: &localCacheStore} // Posts if localCacheStore.postLastPostsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: LastPostsCacheSize, Name: "LastPost", DefaultExpiry: LastPostsCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForLastPosts, }); err != nil { return } if localCacheStore.lastPostTimeCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: LastPostTimeCacheSize, Name: "LastPostTime", DefaultExpiry: LastPostTimeCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForLastPostTime, }); err != nil { return } localCacheStore.post = LocalCachePostStore{PostStore: baseStore.Post(), rootStore: &localCacheStore} // TOS if localCacheStore.termsOfServiceCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: TermsOfServiceCacheSize, Name: "TermsOfService", DefaultExpiry: TermsOfServiceCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForTermsOfService, }); err != nil { return } localCacheStore.termsOfService = LocalCacheTermsOfServiceStore{TermsOfServiceStore: baseStore.TermsOfService(), rootStore: &localCacheStore} // Users if localCacheStore.userProfileByIdsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: UserProfileByIDCacheSize, Name: "UserProfileByIds", DefaultExpiry: UserProfileByIDSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForProfileByIds, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), }); err != nil { return } if localCacheStore.profilesInChannelCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: ProfilesInChannelCacheSize, Name: "ProfilesInChannel", DefaultExpiry: ProfilesInChannelCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForProfileInChannel, }); err != nil { return } localCacheStore.user = &LocalCacheUserStore{ UserStore: baseStore.User(), rootStore: &localCacheStore, userProfileByIdsInvalidations: make(map[string]bool), } // Teams if localCacheStore.teamAllTeamIdsForUserCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: TeamCacheSize, Name: "Team", DefaultExpiry: TeamCacheSec * time.Second, InvalidateClusterEvent: model.ClusterEventInvalidateCacheForTeams, }); err != nil { return } localCacheStore.team = LocalCacheTeamStore{TeamStore: baseStore.Team(), rootStore: &localCacheStore} if cluster != nil { cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForReactions, localCacheStore.reaction.handleClusterInvalidateReaction) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForRoles, localCacheStore.role.handleClusterInvalidateRole) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForRolePermissions, localCacheStore.role.handleClusterInvalidateRolePermissions) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForSchemes, localCacheStore.scheme.handleClusterInvalidateScheme) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForFileInfos, localCacheStore.fileInfo.handleClusterInvalidateFileInfo) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForLastPostTime, localCacheStore.post.handleClusterInvalidateLastPostTime) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForWebhooks, localCacheStore.webhook.handleClusterInvalidateWebhook) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForEmojisById, localCacheStore.emoji.handleClusterInvalidateEmojiById) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForEmojisIdByName, localCacheStore.emoji.handleClusterInvalidateEmojiIdByName) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelPinnedpostsCounts, localCacheStore.channel.handleClusterInvalidateChannelPinnedPostCount) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelMemberCounts, localCacheStore.channel.handleClusterInvalidateChannelMemberCounts) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelGuestCount, localCacheStore.channel.handleClusterInvalidateChannelGuestCounts) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannel, localCacheStore.channel.handleClusterInvalidateChannelById) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForLastPosts, localCacheStore.post.handleClusterInvalidateLastPosts) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForTermsOfService, localCacheStore.termsOfService.handleClusterInvalidateTermsOfService) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForProfileByIds, localCacheStore.user.handleClusterInvalidateScheme) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForProfileInChannel, localCacheStore.user.handleClusterInvalidateProfilesInChannel) cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForTeams, localCacheStore.team.handleClusterInvalidateTeam) } return } func maxInt(a, b int) int { if a > b { return a } return b } func (s LocalCacheStore) Reaction() store.ReactionStore { return s.reaction } func (s LocalCacheStore) Role() store.RoleStore { return s.role } func (s LocalCacheStore) Scheme() store.SchemeStore { return s.scheme } func (s LocalCacheStore) FileInfo() store.FileInfoStore { return s.fileInfo } func (s LocalCacheStore) Webhook() store.WebhookStore { return s.webhook } func (s LocalCacheStore) Emoji() store.EmojiStore { return s.emoji } func (s LocalCacheStore) Channel() store.ChannelStore { return s.channel } func (s LocalCacheStore) Post() store.PostStore { return s.post } func (s LocalCacheStore) TermsOfService() store.TermsOfServiceStore { return s.termsOfService } func (s LocalCacheStore) User() store.UserStore { return s.user } func (s LocalCacheStore) Team() store.TeamStore { return s.team } func (s LocalCacheStore) DropAllTables() { s.Invalidate() s.Store.DropAllTables() } func (s *LocalCacheStore) doInvalidateCacheCluster(cache cache.Cache, key string) { cache.Remove(key) if s.cluster != nil { msg := &model.ClusterMessage{
SendType: model.ClusterSendBestEffort, Data: []byte(key), } s.cluster.SendClusterMessage(msg) } } func (s *LocalCacheStore) doStandardAddToCache(cache cache.Cache, key string, value interface{}) { cache.SetWithDefaultExpiry(key, value) } func (s *LocalCacheStore) doStandardReadCache(cache cache.Cache, key string, value interface{}) error { err := cache.Get(key, value) if err == nil { if s.metrics != nil { s.metrics.IncrementMemCacheHitCounter(cache.Name()) } return nil } if s.metrics != nil { s.metrics.IncrementMemCacheMissCounter(cache.Name()) } return err } func (s *LocalCacheStore) doClearCacheCluster(cache cache.Cache) { cache.Purge() if s.cluster != nil { msg := &model.ClusterMessage{ Event: cache.GetInvalidateClusterEvent(), SendType: model.ClusterSendBestEffort, Data: clearCacheMessageData, } s.cluster.SendClusterMessage(msg) } } func (s *LocalCacheStore) Invalidate() { s.doClearCacheCluster(s.reactionCache) s.doClearCacheCluster(s.schemeCache) s.doClearCacheCluster(s.roleCache) s.doClearCacheCluster(s.fileInfoCache) s.doClearCacheCluster(s.webhookCache) s.doClearCacheCluster(s.emojiCacheById) s.doClearCacheCluster(s.emojiIdCacheByName) s.doClearCacheCluster(s.channelMemberCountsCache) s.doClearCacheCluster(s.channelPinnedPostCountsCache) s.doClearCacheCluster(s.channelGuestCountCache) s.doClearCacheCluster(s.channelByIdCache) s.doClearCacheCluster(s.postLastPostsCache) s.doClearCacheCluster(s.termsOfServiceCache) s.doClearCacheCluster(s.lastPostTimeCache) s.doClearCacheCluster(s.userProfileByIdsCache) s.doClearCacheCluster(s.profilesInChannelCache) s.doClearCacheCluster(s.teamAllTeamIdsForUserCache) s.doClearCacheCluster(s.rolePermissionsCache) }
Event: cache.GetInvalidateClusterEvent(),
escape.rs
use std::path::Path; /// from a path, build a string usable in a shell command, wrapping /// it in quotes if necessary (and then escaping internal quotes). /// Don't do unnecessary transformation, so that the produced string /// is prettier on screen. pub fn escape_for_shell(path: &Path) -> String { let path = path.to_string_lossy(); if regex!(r"^[\w/.-]*$").is_match(&path) { path.to_string() } else
}
{ format!("'{}'", &path.replace('\'', r"'\''")) }
liveness.rs
//! A classic liveness analysis based on dataflow over the AST. Computes, //! for each local variable in a function, whether that variable is live //! at a given point. Program execution points are identified by their //! IDs. //! //! # Basic idea //! //! The basic model is that each local variable is assigned an index. We //! represent sets of local variables using a vector indexed by this //! index. The value in the vector is either 0, indicating the variable //! is dead, or the ID of an expression that uses the variable. //! //! We conceptually walk over the AST in reverse execution order. If we //! find a use of a variable, we add it to the set of live variables. If //! we find an assignment to a variable, we remove it from the set of live //! variables. When we have to merge two flows, we take the union of //! those two flows -- if the variable is live on both paths, we simply //! pick one ID. In the event of loops, we continue doing this until a //! fixed point is reached. //! //! ## Checking initialization //! //! At the function entry point, all variables must be dead. If this is //! not the case, we can report an error using the ID found in the set of //! live variables, which identifies a use of the variable which is not //! dominated by an assignment. //! //! ## Checking moves //! //! After each explicit move, the variable must be dead. //! //! ## Computing last uses //! //! Any use of the variable where the variable is dead afterwards is a //! last use. //! //! # Implementation details //! //! The actual implementation contains two (nested) walks over the AST. //! The outer walk has the job of building up the ir_maps instance for the //! enclosing function. On the way down the tree, it identifies those AST //! nodes and variable IDs that will be needed for the liveness analysis //! and assigns them contiguous IDs. The liveness ID for an AST node is //! called a `live_node` (it's a newtype'd `u32`) and the ID for a variable //! is called a `variable` (another newtype'd `u32`). //! //! On the way back up the tree, as we are about to exit from a function //! declaration we allocate a `liveness` instance. Now that we know //! precisely how many nodes and variables we need, we can allocate all //! the various arrays that we will need to precisely the right size. We then //! perform the actual propagation on the `liveness` instance. //! //! This propagation is encoded in the various `propagate_through_*()` //! methods. It effectively does a reverse walk of the AST; whenever we //! reach a loop node, we iterate until a fixed point is reached. //! //! ## The `RWU` struct //! //! At each live node `N`, we track three pieces of information for each //! variable `V` (these are encapsulated in the `RWU` struct): //! //! - `reader`: the `LiveNode` ID of some node which will read the value //! that `V` holds on entry to `N`. Formally: a node `M` such //! that there exists a path `P` from `N` to `M` where `P` does not //! write `V`. If the `reader` is `invalid_node()`, then the current //! value will never be read (the variable is dead, essentially). //! //! - `writer`: the `LiveNode` ID of some node which will write the //! variable `V` and which is reachable from `N`. Formally: a node `M` //! such that there exists a path `P` from `N` to `M` and `M` writes //! `V`. If the `writer` is `invalid_node()`, then there is no writer //! of `V` that follows `N`. //! //! - `used`: a boolean value indicating whether `V` is *used*. We //! distinguish a *read* from a *use* in that a *use* is some read that //! is not just used to generate a new value. For example, `x += 1` is //! a read but not a use. This is used to generate better warnings. //! //! ## Special nodes and variables //! //! We generate various special nodes for various, well, special purposes. //! These are described in the `Specials` struct. use self::LiveNodeKind::*; use self::VarKind::*; use rustc_ast::ast::InlineAsmOptions; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::def::*; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, FnKind, NestedVisitorMap, Visitor}; use rustc_hir::{Expr, HirId, HirIdMap, HirIdSet, Node}; use rustc_middle::hir::map::Map; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::lint; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; use std::collections::VecDeque; use std::fmt; use std::io; use std::io::prelude::*; use std::rc::Rc; #[derive(Copy, Clone, PartialEq)] struct Variable(u32); #[derive(Copy, Clone, PartialEq)] struct LiveNode(u32); impl Variable { fn get(&self) -> usize { self.0 as usize } } impl LiveNode { fn get(&self) -> usize { self.0 as usize } } #[derive(Copy, Clone, PartialEq, Debug)] enum LiveNodeKind { UpvarNode(Span), ExprNode(Span), VarDefNode(Span), ClosureNode, ExitNode, } fn live_node_kind_to_string(lnk: LiveNodeKind, tcx: TyCtxt<'_>) -> String { let sm = tcx.sess.source_map(); match lnk { UpvarNode(s) => format!("Upvar node [{}]", sm.span_to_string(s)), ExprNode(s) => format!("Expr node [{}]", sm.span_to_string(s)), VarDefNode(s) => format!("Var def node [{}]", sm.span_to_string(s)), ClosureNode => "Closure node".to_owned(), ExitNode => "Exit node".to_owned(), } } impl<'tcx> Visitor<'tcx> for IrMaps<'tcx> { type Map = Map<'tcx>; fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { NestedVisitorMap::OnlyBodies(self.tcx.hir()) } fn visit_fn( &mut self, fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl<'tcx>, b: hir::BodyId, s: Span, id: HirId, ) { visit_fn(self, fk, fd, b, s, id); } fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { visit_local(self, l); } fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { visit_expr(self, ex); } fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { visit_arm(self, a); } } fn check_mod_liveness(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { tcx.hir().visit_item_likes_in_module( module_def_id, &mut IrMaps::new(tcx, module_def_id).as_deep_visitor(), ); } pub fn provide(providers: &mut Providers<'_>) { *providers = Providers { check_mod_liveness, ..*providers }; } impl fmt::Debug for LiveNode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "ln({})", self.get()) } } impl fmt::Debug for Variable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "v({})", self.get()) } } // ______________________________________________________________________ // Creating ir_maps // // This is the first pass and the one that drives the main // computation. It walks up and down the IR once. On the way down, // we count for each function the number of variables as well as // liveness nodes. A liveness node is basically an expression or // capture clause that does something of interest: either it has // interesting control flow or it uses/defines a local variable. // // On the way back up, at each function node we create liveness sets // (we now know precisely how big to make our various vectors and so // forth) and then do the data-flow propagation to compute the set // of live variables at each program point. // // Finally, we run back over the IR one last time and, using the // computed liveness, check various safety conditions. For example, // there must be no live nodes at the definition site for a variable // unless it has an initializer. Similarly, each non-mutable local // variable must not be assigned if there is some successor // assignment. And so forth. impl LiveNode { fn is_valid(&self) -> bool { self.0 != u32::MAX } } fn invalid_node() -> LiveNode { LiveNode(u32::MAX) } struct CaptureInfo { ln: LiveNode, var_hid: HirId, } #[derive(Copy, Clone, Debug)] struct LocalInfo { id: HirId, name: Symbol, is_shorthand: bool, } #[derive(Copy, Clone, Debug)] enum VarKind { Param(HirId, Symbol), Local(LocalInfo), Upvar(HirId, Symbol), } struct IrMaps<'tcx> { tcx: TyCtxt<'tcx>, body_owner: LocalDefId, num_live_nodes: usize, num_vars: usize, live_node_map: HirIdMap<LiveNode>, variable_map: HirIdMap<Variable>, capture_info_map: HirIdMap<Rc<Vec<CaptureInfo>>>, var_kinds: Vec<VarKind>, lnks: Vec<LiveNodeKind>, } impl IrMaps<'tcx> { fn new(tcx: TyCtxt<'tcx>, body_owner: LocalDefId) -> IrMaps<'tcx> { IrMaps { tcx, body_owner, num_live_nodes: 0, num_vars: 0, live_node_map: HirIdMap::default(), variable_map: HirIdMap::default(), capture_info_map: Default::default(), var_kinds: Vec::new(), lnks: Vec::new(), } } fn add_live_node(&mut self, lnk: LiveNodeKind) -> LiveNode { let ln = LiveNode(self.num_live_nodes as u32); self.lnks.push(lnk); self.num_live_nodes += 1; debug!("{:?} is of kind {}", ln, live_node_kind_to_string(lnk, self.tcx)); ln } fn add_live_node_for_node(&mut self, hir_id: HirId, lnk: LiveNodeKind) { let ln = self.add_live_node(lnk); self.live_node_map.insert(hir_id, ln); debug!("{:?} is node {:?}", ln, hir_id); } fn add_variable(&mut self, vk: VarKind) -> Variable { let v = Variable(self.num_vars as u32); self.var_kinds.push(vk); self.num_vars += 1; match vk { Local(LocalInfo { id: node_id, .. }) | Param(node_id, _) | Upvar(node_id, _) => { self.variable_map.insert(node_id, v); } } debug!("{:?} is {:?}", v, vk); v } fn variable(&self, hir_id: HirId, span: Span) -> Variable { match self.variable_map.get(&hir_id) { Some(&var) => var, None => { span_bug!(span, "no variable registered for id {:?}", hir_id); } } } fn variable_name(&self, var: Variable) -> String { match self.var_kinds[var.get()] { Local(LocalInfo { name, .. }) | Param(_, name) | Upvar(_, name) => name.to_string(), } } fn variable_is_shorthand(&self, var: Variable) -> bool { match self.var_kinds[var.get()] { Local(LocalInfo { is_shorthand, .. }) => is_shorthand, Param(..) | Upvar(..) => false, } } fn set_captures(&mut self, hir_id: HirId, cs: Vec<CaptureInfo>) { self.capture_info_map.insert(hir_id, Rc::new(cs)); } fn
(&self, ln: LiveNode) -> LiveNodeKind { self.lnks[ln.get()] } } fn visit_fn<'tcx>( ir: &mut IrMaps<'tcx>, fk: FnKind<'tcx>, decl: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, sp: Span, id: hir::HirId, ) { debug!("visit_fn {:?}", id); // swap in a new set of IR maps for this function body: let def_id = ir.tcx.hir().local_def_id(id); let mut fn_maps = IrMaps::new(ir.tcx, def_id); // Don't run unused pass for #[derive()] if let FnKind::Method(..) = fk { let parent = ir.tcx.hir().get_parent_item(id); if let Some(Node::Item(i)) = ir.tcx.hir().find(parent) { if i.attrs.iter().any(|a| a.check_name(sym::automatically_derived)) { return; } } } debug!("creating fn_maps: {:p}", &fn_maps); let body = ir.tcx.hir().body(body_id); if let Some(upvars) = ir.tcx.upvars_mentioned(def_id) { for (&var_hir_id, _upvar) in upvars { debug!("adding upvar {:?}", var_hir_id); let var_name = ir.tcx.hir().name(var_hir_id); fn_maps.add_variable(Upvar(var_hir_id, var_name)); } } for param in body.params { let is_shorthand = match param.pat.kind { rustc_hir::PatKind::Struct(..) => true, _ => false, }; param.pat.each_binding(|_bm, hir_id, _x, ident| { debug!("adding parameters {:?}", hir_id); let var = if is_shorthand { Local(LocalInfo { id: hir_id, name: ident.name, is_shorthand: true }) } else { Param(hir_id, ident.name) }; fn_maps.add_variable(var); }) } // gather up the various local variables, significant expressions, // and so forth: intravisit::walk_fn(&mut fn_maps, fk, decl, body_id, sp, id); // compute liveness let mut lsets = Liveness::new(&mut fn_maps, def_id); let entry_ln = lsets.compute(fk, &body, sp, id); lsets.log_liveness(entry_ln, id); // check for various error conditions lsets.visit_body(body); lsets.warn_about_unused_upvars(entry_ln); lsets.warn_about_unused_args(body, entry_ln); } fn add_from_pat(ir: &mut IrMaps<'_>, pat: &hir::Pat<'_>) { // For struct patterns, take note of which fields used shorthand // (`x` rather than `x: x`). let mut shorthand_field_ids = HirIdSet::default(); let mut pats = VecDeque::new(); pats.push_back(pat); while let Some(pat) = pats.pop_front() { use rustc_hir::PatKind::*; match &pat.kind { Binding(.., inner_pat) => { pats.extend(inner_pat.iter()); } Struct(_, fields, _) => { let ids = fields.iter().filter(|f| f.is_shorthand).map(|f| f.pat.hir_id); shorthand_field_ids.extend(ids); } Ref(inner_pat, _) | Box(inner_pat) => { pats.push_back(inner_pat); } TupleStruct(_, inner_pats, _) | Tuple(inner_pats, _) | Or(inner_pats) => { pats.extend(inner_pats.iter()); } Slice(pre_pats, inner_pat, post_pats) => { pats.extend(pre_pats.iter()); pats.extend(inner_pat.iter()); pats.extend(post_pats.iter()); } _ => {} } } pat.each_binding(|_, hir_id, _, ident| { ir.add_live_node_for_node(hir_id, VarDefNode(ident.span)); ir.add_variable(Local(LocalInfo { id: hir_id, name: ident.name, is_shorthand: shorthand_field_ids.contains(&hir_id), })); }); } fn visit_local<'tcx>(ir: &mut IrMaps<'tcx>, local: &'tcx hir::Local<'tcx>) { add_from_pat(ir, &local.pat); intravisit::walk_local(ir, local); } fn visit_arm<'tcx>(ir: &mut IrMaps<'tcx>, arm: &'tcx hir::Arm<'tcx>) { add_from_pat(ir, &arm.pat); intravisit::walk_arm(ir, arm); } fn visit_expr<'tcx>(ir: &mut IrMaps<'tcx>, expr: &'tcx Expr<'tcx>) { match expr.kind { // live nodes required for uses or definitions of variables: hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { debug!("expr {}: path that leads to {:?}", expr.hir_id, path.res); if let Res::Local(_var_hir_id) = path.res { ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); } intravisit::walk_expr(ir, expr); } hir::ExprKind::Closure(..) => { // Interesting control flow (for loops can contain labeled // breaks or continues) ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); // Make a live_node for each captured variable, with the span // being the location that the variable is used. This results // in better error messages than just pointing at the closure // construction site. let mut call_caps = Vec::new(); let closure_def_id = ir.tcx.hir().local_def_id(expr.hir_id); if let Some(upvars) = ir.tcx.upvars_mentioned(closure_def_id) { call_caps.extend(upvars.iter().map(|(&var_id, upvar)| { let upvar_ln = ir.add_live_node(UpvarNode(upvar.span)); CaptureInfo { ln: upvar_ln, var_hid: var_id } })); } ir.set_captures(expr.hir_id, call_caps); let old_body_owner = ir.body_owner; ir.body_owner = closure_def_id; intravisit::walk_expr(ir, expr); ir.body_owner = old_body_owner; } // live nodes required for interesting control flow: hir::ExprKind::Match(..) | hir::ExprKind::Loop(..) => { ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); intravisit::walk_expr(ir, expr); } hir::ExprKind::Binary(op, ..) if op.node.is_lazy() => { ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span)); intravisit::walk_expr(ir, expr); } // otherwise, live nodes are not required: hir::ExprKind::Index(..) | hir::ExprKind::Field(..) | hir::ExprKind::Array(..) | hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) | hir::ExprKind::Tup(..) | hir::ExprKind::Binary(..) | hir::ExprKind::AddrOf(..) | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Break(..) | hir::ExprKind::Continue(_) | hir::ExprKind::Lit(_) | hir::ExprKind::Ret(..) | hir::ExprKind::Block(..) | hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) | hir::ExprKind::InlineAsm(..) | hir::ExprKind::LlvmInlineAsm(..) | hir::ExprKind::Box(..) | hir::ExprKind::Yield(..) | hir::ExprKind::Type(..) | hir::ExprKind::Err | hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => { intravisit::walk_expr(ir, expr); } } } // ______________________________________________________________________ // Computing liveness sets // // Actually we compute just a bit more than just liveness, but we use // the same basic propagation framework in all cases. #[derive(Clone, Copy)] struct RWU { reader: LiveNode, writer: LiveNode, used: bool, } /// Conceptually, this is like a `Vec<RWU>`. But the number of `RWU`s can get /// very large, so it uses a more compact representation that takes advantage /// of the fact that when the number of `RWU`s is large, most of them have an /// invalid reader and an invalid writer. struct RWUTable { /// Each entry in `packed_rwus` is either INV_INV_FALSE, INV_INV_TRUE, or /// an index into `unpacked_rwus`. In the common cases, this compacts the /// 65 bits of data into 32; in the uncommon cases, it expands the 65 bits /// in 96. /// /// More compact representations are possible -- e.g., use only 2 bits per /// packed `RWU` and make the secondary table a HashMap that maps from /// indices to `RWU`s -- but this one strikes a good balance between size /// and speed. packed_rwus: Vec<u32>, unpacked_rwus: Vec<RWU>, } // A constant representing `RWU { reader: invalid_node(); writer: invalid_node(); used: false }`. const INV_INV_FALSE: u32 = u32::MAX; // A constant representing `RWU { reader: invalid_node(); writer: invalid_node(); used: true }`. const INV_INV_TRUE: u32 = u32::MAX - 1; impl RWUTable { fn new(num_rwus: usize) -> RWUTable { Self { packed_rwus: vec![INV_INV_FALSE; num_rwus], unpacked_rwus: vec![] } } fn get(&self, idx: usize) -> RWU { let packed_rwu = self.packed_rwus[idx]; match packed_rwu { INV_INV_FALSE => RWU { reader: invalid_node(), writer: invalid_node(), used: false }, INV_INV_TRUE => RWU { reader: invalid_node(), writer: invalid_node(), used: true }, _ => self.unpacked_rwus[packed_rwu as usize], } } fn get_reader(&self, idx: usize) -> LiveNode { let packed_rwu = self.packed_rwus[idx]; match packed_rwu { INV_INV_FALSE | INV_INV_TRUE => invalid_node(), _ => self.unpacked_rwus[packed_rwu as usize].reader, } } fn get_writer(&self, idx: usize) -> LiveNode { let packed_rwu = self.packed_rwus[idx]; match packed_rwu { INV_INV_FALSE | INV_INV_TRUE => invalid_node(), _ => self.unpacked_rwus[packed_rwu as usize].writer, } } fn get_used(&self, idx: usize) -> bool { let packed_rwu = self.packed_rwus[idx]; match packed_rwu { INV_INV_FALSE => false, INV_INV_TRUE => true, _ => self.unpacked_rwus[packed_rwu as usize].used, } } #[inline] fn copy_packed(&mut self, dst_idx: usize, src_idx: usize) { self.packed_rwus[dst_idx] = self.packed_rwus[src_idx]; } fn assign_unpacked(&mut self, idx: usize, rwu: RWU) { if rwu.reader == invalid_node() && rwu.writer == invalid_node() { // When we overwrite an indexing entry in `self.packed_rwus` with // `INV_INV_{TRUE,FALSE}` we don't remove the corresponding entry // from `self.unpacked_rwus`; it's not worth the effort, and we // can't have entries shifting around anyway. self.packed_rwus[idx] = if rwu.used { INV_INV_TRUE } else { INV_INV_FALSE } } else { // Add a new RWU to `unpacked_rwus` and make `packed_rwus[idx]` // point to it. self.packed_rwus[idx] = self.unpacked_rwus.len() as u32; self.unpacked_rwus.push(rwu); } } fn assign_inv_inv(&mut self, idx: usize) { self.packed_rwus[idx] = if self.get_used(idx) { INV_INV_TRUE } else { INV_INV_FALSE }; } } #[derive(Copy, Clone)] struct Specials { /// A live node representing a point of execution before closure entry & /// after closure exit. Used to calculate liveness of captured variables /// through calls to the same closure. Used for Fn & FnMut closures only. closure_ln: LiveNode, /// A live node representing every 'exit' from the function, whether it be /// by explicit return, panic, or other means. exit_ln: LiveNode, } const ACC_READ: u32 = 1; const ACC_WRITE: u32 = 2; const ACC_USE: u32 = 4; struct Liveness<'a, 'tcx> { ir: &'a mut IrMaps<'tcx>, tables: &'a ty::TypeckTables<'tcx>, param_env: ty::ParamEnv<'tcx>, s: Specials, successors: Vec<LiveNode>, rwu_table: RWUTable, // mappings from loop node ID to LiveNode // ("break" label should map to loop node ID, // it probably doesn't now) break_ln: HirIdMap<LiveNode>, cont_ln: HirIdMap<LiveNode>, } impl<'a, 'tcx> Liveness<'a, 'tcx> { fn new(ir: &'a mut IrMaps<'tcx>, def_id: LocalDefId) -> Liveness<'a, 'tcx> { let specials = Specials { closure_ln: ir.add_live_node(ClosureNode), exit_ln: ir.add_live_node(ExitNode), }; let tables = ir.tcx.typeck_tables_of(def_id); let param_env = ir.tcx.param_env(def_id); let num_live_nodes = ir.num_live_nodes; let num_vars = ir.num_vars; Liveness { ir, tables, param_env, s: specials, successors: vec![invalid_node(); num_live_nodes], rwu_table: RWUTable::new(num_live_nodes * num_vars), break_ln: Default::default(), cont_ln: Default::default(), } } fn live_node(&self, hir_id: HirId, span: Span) -> LiveNode { match self.ir.live_node_map.get(&hir_id) { Some(&ln) => ln, None => { // This must be a mismatch between the ir_map construction // above and the propagation code below; the two sets of // code have to agree about which AST nodes are worth // creating liveness nodes for. span_bug!(span, "no live node registered for node {:?}", hir_id); } } } fn variable(&self, hir_id: HirId, span: Span) -> Variable { self.ir.variable(hir_id, span) } fn define_bindings_in_pat(&mut self, pat: &hir::Pat<'_>, mut succ: LiveNode) -> LiveNode { // In an or-pattern, only consider the first pattern; any later patterns // must have the same bindings, and we also consider the first pattern // to be the "authoritative" set of ids. pat.each_binding_or_first(&mut |_, hir_id, pat_sp, ident| { let ln = self.live_node(hir_id, pat_sp); let var = self.variable(hir_id, ident.span); self.init_from_succ(ln, succ); self.define(ln, var); succ = ln; }); succ } fn idx(&self, ln: LiveNode, var: Variable) -> usize { ln.get() * self.ir.num_vars + var.get() } fn live_on_entry(&self, ln: LiveNode, var: Variable) -> Option<LiveNodeKind> { assert!(ln.is_valid()); let reader = self.rwu_table.get_reader(self.idx(ln, var)); if reader.is_valid() { Some(self.ir.lnk(reader)) } else { None } } // Is this variable live on entry to any of its successor nodes? fn live_on_exit(&self, ln: LiveNode, var: Variable) -> Option<LiveNodeKind> { let successor = self.successors[ln.get()]; self.live_on_entry(successor, var) } fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool { assert!(ln.is_valid()); self.rwu_table.get_used(self.idx(ln, var)) } fn assigned_on_entry(&self, ln: LiveNode, var: Variable) -> Option<LiveNodeKind> { assert!(ln.is_valid()); let writer = self.rwu_table.get_writer(self.idx(ln, var)); if writer.is_valid() { Some(self.ir.lnk(writer)) } else { None } } fn assigned_on_exit(&self, ln: LiveNode, var: Variable) -> Option<LiveNodeKind> { let successor = self.successors[ln.get()]; self.assigned_on_entry(successor, var) } fn indices2<F>(&mut self, ln: LiveNode, succ_ln: LiveNode, mut op: F) where F: FnMut(&mut Liveness<'a, 'tcx>, usize, usize), { let node_base_idx = self.idx(ln, Variable(0)); let succ_base_idx = self.idx(succ_ln, Variable(0)); for var_idx in 0..self.ir.num_vars { op(self, node_base_idx + var_idx, succ_base_idx + var_idx); } } fn write_vars<F>(&self, wr: &mut dyn Write, ln: LiveNode, mut test: F) -> io::Result<()> where F: FnMut(usize) -> bool, { let node_base_idx = self.idx(ln, Variable(0)); for var_idx in 0..self.ir.num_vars { let idx = node_base_idx + var_idx; if test(idx) { write!(wr, " {:?}", Variable(var_idx as u32))?; } } Ok(()) } #[allow(unused_must_use)] fn ln_str(&self, ln: LiveNode) -> String { let mut wr = Vec::new(); { let wr = &mut wr as &mut dyn Write; write!(wr, "[ln({:?}) of kind {:?} reads", ln.get(), self.ir.lnk(ln)); self.write_vars(wr, ln, |idx| self.rwu_table.get_reader(idx).is_valid()); write!(wr, " writes"); self.write_vars(wr, ln, |idx| self.rwu_table.get_writer(idx).is_valid()); write!(wr, " uses"); self.write_vars(wr, ln, |idx| self.rwu_table.get_used(idx)); write!(wr, " precedes {:?}]", self.successors[ln.get()]); } String::from_utf8(wr).unwrap() } fn log_liveness(&self, entry_ln: LiveNode, hir_id: hir::HirId) { // hack to skip the loop unless debug! is enabled: debug!( "^^ liveness computation results for body {} (entry={:?})", { for ln_idx in 0..self.ir.num_live_nodes { debug!("{:?}", self.ln_str(LiveNode(ln_idx as u32))); } hir_id }, entry_ln ); } fn init_empty(&mut self, ln: LiveNode, succ_ln: LiveNode) { self.successors[ln.get()] = succ_ln; // It is not necessary to initialize the RWUs here because they are all // set to INV_INV_FALSE when they are created, and the sets only grow // during iterations. } fn init_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode) { // more efficient version of init_empty() / merge_from_succ() self.successors[ln.get()] = succ_ln; self.indices2(ln, succ_ln, |this, idx, succ_idx| { this.rwu_table.copy_packed(idx, succ_idx); }); debug!("init_from_succ(ln={}, succ={})", self.ln_str(ln), self.ln_str(succ_ln)); } fn merge_from_succ(&mut self, ln: LiveNode, succ_ln: LiveNode, first_merge: bool) -> bool { if ln == succ_ln { return false; } let mut any_changed = false; self.indices2(ln, succ_ln, |this, idx, succ_idx| { // This is a special case, pulled out from the code below, where we // don't have to do anything. It occurs about 60-70% of the time. if this.rwu_table.packed_rwus[succ_idx] == INV_INV_FALSE { return; } let mut changed = false; let mut rwu = this.rwu_table.get(idx); let succ_rwu = this.rwu_table.get(succ_idx); if succ_rwu.reader.is_valid() && !rwu.reader.is_valid() { rwu.reader = succ_rwu.reader; changed = true } if succ_rwu.writer.is_valid() && !rwu.writer.is_valid() { rwu.writer = succ_rwu.writer; changed = true } if succ_rwu.used && !rwu.used { rwu.used = true; changed = true; } if changed { this.rwu_table.assign_unpacked(idx, rwu); any_changed = true; } }); debug!( "merge_from_succ(ln={:?}, succ={}, first_merge={}, changed={})", ln, self.ln_str(succ_ln), first_merge, any_changed ); any_changed } // Indicates that a local variable was *defined*; we know that no // uses of the variable can precede the definition (resolve checks // this) so we just clear out all the data. fn define(&mut self, writer: LiveNode, var: Variable) { let idx = self.idx(writer, var); self.rwu_table.assign_inv_inv(idx); debug!("{:?} defines {:?} (idx={}): {}", writer, var, idx, self.ln_str(writer)); } // Either read, write, or both depending on the acc bitset fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) { debug!("{:?} accesses[{:x}] {:?}: {}", ln, acc, var, self.ln_str(ln)); let idx = self.idx(ln, var); let mut rwu = self.rwu_table.get(idx); if (acc & ACC_WRITE) != 0 { rwu.reader = invalid_node(); rwu.writer = ln; } // Important: if we both read/write, must do read second // or else the write will override. if (acc & ACC_READ) != 0 { rwu.reader = ln; } if (acc & ACC_USE) != 0 { rwu.used = true; } self.rwu_table.assign_unpacked(idx, rwu); } fn compute( &mut self, fk: FnKind<'_>, body: &hir::Body<'_>, span: Span, id: hir::HirId, ) -> LiveNode { debug!("compute: using id for body, {:?}", body.value); // # Liveness of captured variables // // When computing the liveness for captured variables we take into // account how variable is captured (ByRef vs ByValue) and what is the // closure kind (Generator / FnOnce vs Fn / FnMut). // // Variables captured by reference are assumed to be used on the exit // from the closure. // // In FnOnce closures, variables captured by value are known to be dead // on exit since it is impossible to call the closure again. // // In Fn / FnMut closures, variables captured by value are live on exit // if they are live on the entry to the closure, since only the closure // itself can access them on subsequent calls. if let Some(upvars) = self.ir.tcx.upvars_mentioned(self.ir.body_owner) { // Mark upvars captured by reference as used after closure exits. for (&var_hir_id, upvar) in upvars.iter().rev() { let upvar_id = ty::UpvarId { var_path: ty::UpvarPath { hir_id: var_hir_id }, closure_expr_id: self.ir.body_owner, }; match self.tables.upvar_capture(upvar_id) { ty::UpvarCapture::ByRef(_) => { let var = self.variable(var_hir_id, upvar.span); self.acc(self.s.exit_ln, var, ACC_READ | ACC_USE); } ty::UpvarCapture::ByValue => {} } } } let succ = self.propagate_through_expr(&body.value, self.s.exit_ln); match fk { FnKind::Method(..) | FnKind::ItemFn(..) => return succ, FnKind::Closure(..) => {} } let ty = self.tables.node_type(id); match ty.kind { ty::Closure(_def_id, substs) => match substs.as_closure().kind() { ty::ClosureKind::Fn => {} ty::ClosureKind::FnMut => {} ty::ClosureKind::FnOnce => return succ, }, ty::Generator(..) => return succ, _ => { span_bug!(span, "type of closure expr {:?} is not a closure {:?}", id, ty,); } }; // Propagate through calls to the closure. let mut first_merge = true; loop { self.init_from_succ(self.s.closure_ln, succ); for param in body.params { param.pat.each_binding(|_bm, hir_id, _x, ident| { let var = self.variable(hir_id, ident.span); self.define(self.s.closure_ln, var); }) } if !self.merge_from_succ(self.s.exit_ln, self.s.closure_ln, first_merge) { break; } first_merge = false; assert_eq!(succ, self.propagate_through_expr(&body.value, self.s.exit_ln)); } succ } fn propagate_through_block(&mut self, blk: &hir::Block<'_>, succ: LiveNode) -> LiveNode { if blk.targeted_by_break { self.break_ln.insert(blk.hir_id, succ); } let succ = self.propagate_through_opt_expr(blk.expr.as_deref(), succ); blk.stmts.iter().rev().fold(succ, |succ, stmt| self.propagate_through_stmt(stmt, succ)) } fn propagate_through_stmt(&mut self, stmt: &hir::Stmt<'_>, succ: LiveNode) -> LiveNode { match stmt.kind { hir::StmtKind::Local(ref local) => { // Note: we mark the variable as defined regardless of whether // there is an initializer. Initially I had thought to only mark // the live variable as defined if it was initialized, and then we // could check for uninit variables just by scanning what is live // at the start of the function. But that doesn't work so well for // immutable variables defined in a loop: // loop { let x; x = 5; } // because the "assignment" loops back around and generates an error. // // So now we just check that variables defined w/o an // initializer are not live at the point of their // initialization, which is mildly more complex than checking // once at the func header but otherwise equivalent. let succ = self.propagate_through_opt_expr(local.init.as_deref(), succ); self.define_bindings_in_pat(&local.pat, succ) } hir::StmtKind::Item(..) => succ, hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => { self.propagate_through_expr(&expr, succ) } } } fn propagate_through_exprs(&mut self, exprs: &[Expr<'_>], succ: LiveNode) -> LiveNode { exprs.iter().rev().fold(succ, |succ, expr| self.propagate_through_expr(&expr, succ)) } fn propagate_through_opt_expr( &mut self, opt_expr: Option<&Expr<'_>>, succ: LiveNode, ) -> LiveNode { opt_expr.map_or(succ, |expr| self.propagate_through_expr(expr, succ)) } fn propagate_through_expr(&mut self, expr: &Expr<'_>, succ: LiveNode) -> LiveNode { debug!("propagate_through_expr: {:?}", expr); match expr.kind { // Interesting cases with control flow or which gen/kill hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { self.access_path(expr.hir_id, path, succ, ACC_READ | ACC_USE) } hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(&e, succ), hir::ExprKind::Closure(..) => { debug!("{:?} is an ExprKind::Closure", expr); // the construction of a closure itself is not important, // but we have to consider the closed over variables. let caps = self .ir .capture_info_map .get(&expr.hir_id) .cloned() .unwrap_or_else(|| span_bug!(expr.span, "no registered caps")); caps.iter().rev().fold(succ, |succ, cap| { self.init_from_succ(cap.ln, succ); let var = self.variable(cap.var_hid, expr.span); self.acc(cap.ln, var, ACC_READ | ACC_USE); cap.ln }) } // Note that labels have been resolved, so we don't need to look // at the label ident hir::ExprKind::Loop(ref blk, _, _) => self.propagate_through_loop(expr, &blk, succ), hir::ExprKind::Match(ref e, arms, _) => { // // (e) // | // v // (expr) // / | \ // | | | // v v v // (..arms..) // | | | // v v v // ( succ ) // // let ln = self.live_node(expr.hir_id, expr.span); self.init_empty(ln, succ); let mut first_merge = true; for arm in arms { let body_succ = self.propagate_through_expr(&arm.body, succ); let guard_succ = self.propagate_through_opt_expr( arm.guard.as_ref().map(|hir::Guard::If(e)| *e), body_succ, ); let arm_succ = self.define_bindings_in_pat(&arm.pat, guard_succ); self.merge_from_succ(ln, arm_succ, first_merge); first_merge = false; } self.propagate_through_expr(&e, ln) } hir::ExprKind::Ret(ref o_e) => { // ignore succ and subst exit_ln: let exit_ln = self.s.exit_ln; self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), exit_ln) } hir::ExprKind::Break(label, ref opt_expr) => { // Find which label this break jumps to let target = match label.target_id { Ok(hir_id) => self.break_ln.get(&hir_id), Err(err) => span_bug!(expr.span, "loop scope error: {}", err), } .cloned(); // Now that we know the label we're going to, // look it up in the break loop nodes table match target { Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b), None => { // FIXME: This should have been checked earlier. Once this is fixed, // replace with `delay_span_bug`. (#62480) self.ir .tcx .sess .struct_span_err(expr.span, "`break` to unknown label") .emit(); rustc_errors::FatalError.raise() } } } hir::ExprKind::Continue(label) => { // Find which label this expr continues to let sc = label .target_id .unwrap_or_else(|err| span_bug!(expr.span, "loop scope error: {}", err)); // Now that we know the label we're going to, // look it up in the continue loop nodes table self.cont_ln .get(&sc) .cloned() .unwrap_or_else(|| span_bug!(expr.span, "continue to unknown label")) } hir::ExprKind::Assign(ref l, ref r, _) => { // see comment on places in // propagate_through_place_components() let succ = self.write_place(&l, succ, ACC_WRITE); let succ = self.propagate_through_place_components(&l, succ); self.propagate_through_expr(&r, succ) } hir::ExprKind::AssignOp(_, ref l, ref r) => { // an overloaded assign op is like a method call if self.tables.is_method_call(expr) { let succ = self.propagate_through_expr(&l, succ); self.propagate_through_expr(&r, succ) } else { // see comment on places in // propagate_through_place_components() let succ = self.write_place(&l, succ, ACC_WRITE | ACC_READ); let succ = self.propagate_through_expr(&r, succ); self.propagate_through_place_components(&l, succ) } } // Uninteresting cases: just propagate in rev exec order hir::ExprKind::Array(ref exprs) => self.propagate_through_exprs(exprs, succ), hir::ExprKind::Struct(_, ref fields, ref with_expr) => { let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ); fields .iter() .rev() .fold(succ, |succ, field| self.propagate_through_expr(&field.expr, succ)) } hir::ExprKind::Call(ref f, ref args) => { let m = self.ir.tcx.parent_module(expr.hir_id).to_def_id(); let succ = if self.ir.tcx.is_ty_uninhabited_from( m, self.tables.expr_ty(expr), self.param_env, ) { self.s.exit_ln } else { succ }; let succ = self.propagate_through_exprs(args, succ); self.propagate_through_expr(&f, succ) } hir::ExprKind::MethodCall(.., ref args, _) => { let m = self.ir.tcx.parent_module(expr.hir_id).to_def_id(); let succ = if self.ir.tcx.is_ty_uninhabited_from( m, self.tables.expr_ty(expr), self.param_env, ) { self.s.exit_ln } else { succ }; self.propagate_through_exprs(args, succ) } hir::ExprKind::Tup(ref exprs) => self.propagate_through_exprs(exprs, succ), hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => { let r_succ = self.propagate_through_expr(&r, succ); let ln = self.live_node(expr.hir_id, expr.span); self.init_from_succ(ln, succ); self.merge_from_succ(ln, r_succ, false); self.propagate_through_expr(&l, ln) } hir::ExprKind::Index(ref l, ref r) | hir::ExprKind::Binary(_, ref l, ref r) => { let r_succ = self.propagate_through_expr(&r, succ); self.propagate_through_expr(&l, r_succ) } hir::ExprKind::Box(ref e) | hir::ExprKind::AddrOf(_, _, ref e) | hir::ExprKind::Cast(ref e, _) | hir::ExprKind::Type(ref e, _) | hir::ExprKind::DropTemps(ref e) | hir::ExprKind::Unary(_, ref e) | hir::ExprKind::Yield(ref e, _) | hir::ExprKind::Repeat(ref e, _) => self.propagate_through_expr(&e, succ), hir::ExprKind::InlineAsm(ref asm) => { // Handle non-returning asm let mut succ = if asm.options.contains(InlineAsmOptions::NORETURN) { self.s.exit_ln } else { succ }; // Do a first pass for writing outputs only for op in asm.operands.iter().rev() { match op { hir::InlineAsmOperand::In { .. } | hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {} hir::InlineAsmOperand::Out { expr, .. } => { if let Some(expr) = expr { succ = self.write_place(expr, succ, ACC_WRITE); } } hir::InlineAsmOperand::InOut { expr, .. } => { succ = self.write_place(expr, succ, ACC_READ | ACC_WRITE); } hir::InlineAsmOperand::SplitInOut { out_expr, .. } => { if let Some(expr) = out_expr { succ = self.write_place(expr, succ, ACC_WRITE); } } } } // Then do a second pass for inputs let mut succ = succ; for op in asm.operands.iter().rev() { match op { hir::InlineAsmOperand::In { expr, .. } | hir::InlineAsmOperand::Const { expr, .. } | hir::InlineAsmOperand::Sym { expr, .. } => { succ = self.propagate_through_expr(expr, succ) } hir::InlineAsmOperand::Out { expr, .. } => { if let Some(expr) = expr { succ = self.propagate_through_place_components(expr, succ); } } hir::InlineAsmOperand::InOut { expr, .. } => { succ = self.propagate_through_place_components(expr, succ); } hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => { if let Some(expr) = out_expr { succ = self.propagate_through_place_components(expr, succ); } succ = self.propagate_through_expr(in_expr, succ); } } } succ } hir::ExprKind::LlvmInlineAsm(ref asm) => { let ia = &asm.inner; let outputs = asm.outputs_exprs; let inputs = asm.inputs_exprs; let succ = ia.outputs.iter().zip(outputs).rev().fold(succ, |succ, (o, output)| { // see comment on places // in propagate_through_place_components() if o.is_indirect { self.propagate_through_expr(output, succ) } else { let acc = if o.is_rw { ACC_WRITE | ACC_READ } else { ACC_WRITE }; let succ = self.write_place(output, succ, acc); self.propagate_through_place_components(output, succ) } }); // Inputs are executed first. Propagate last because of rev order self.propagate_through_exprs(inputs, succ) } hir::ExprKind::Lit(..) | hir::ExprKind::Err | hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => succ, // Note that labels have been resolved, so we don't need to look // at the label ident hir::ExprKind::Block(ref blk, _) => self.propagate_through_block(&blk, succ), } } fn propagate_through_place_components(&mut self, expr: &Expr<'_>, succ: LiveNode) -> LiveNode { // # Places // // In general, the full flow graph structure for an // assignment/move/etc can be handled in one of two ways, // depending on whether what is being assigned is a "tracked // value" or not. A tracked value is basically a local // variable or argument. // // The two kinds of graphs are: // // Tracked place Untracked place // ----------------------++----------------------- // || // | || | // v || v // (rvalue) || (rvalue) // | || | // v || v // (write of place) || (place components) // | || | // v || v // (succ) || (succ) // || // ----------------------++----------------------- // // I will cover the two cases in turn: // // # Tracked places // // A tracked place is a local variable/argument `x`. In // these cases, the link_node where the write occurs is linked // to node id of `x`. The `write_place()` routine generates // the contents of this node. There are no subcomponents to // consider. // // # Non-tracked places // // These are places like `x[5]` or `x.f`. In that case, we // basically ignore the value which is written to but generate // reads for the components---`x` in these two examples. The // components reads are generated by // `propagate_through_place_components()` (this fn). // // # Illegal places // // It is still possible to observe assignments to non-places; // these errors are detected in the later pass borrowck. We // just ignore such cases and treat them as reads. match expr.kind { hir::ExprKind::Path(_) => succ, hir::ExprKind::Field(ref e, _) => self.propagate_through_expr(&e, succ), _ => self.propagate_through_expr(expr, succ), } } // see comment on propagate_through_place() fn write_place(&mut self, expr: &Expr<'_>, succ: LiveNode, acc: u32) -> LiveNode { match expr.kind { hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { self.access_path(expr.hir_id, path, succ, acc) } // We do not track other places, so just propagate through // to their subcomponents. Also, it may happen that // non-places occur here, because those are detected in the // later pass borrowck. _ => succ, } } fn access_var( &mut self, hir_id: HirId, var_hid: HirId, succ: LiveNode, acc: u32, span: Span, ) -> LiveNode { let ln = self.live_node(hir_id, span); if acc != 0 { self.init_from_succ(ln, succ); let var = self.variable(var_hid, span); self.acc(ln, var, acc); } ln } fn access_path( &mut self, hir_id: HirId, path: &hir::Path<'_>, succ: LiveNode, acc: u32, ) -> LiveNode { match path.res { Res::Local(hid) => self.access_var(hir_id, hid, succ, acc, path.span), _ => succ, } } fn propagate_through_loop( &mut self, expr: &Expr<'_>, body: &hir::Block<'_>, succ: LiveNode, ) -> LiveNode { /* We model control flow like this: (expr) <-+ | | v | (body) --+ Note that a `continue` expression targeting the `loop` will have a successor of `expr`. Meanwhile, a `break` expression will have a successor of `succ`. */ // first iteration: let mut first_merge = true; let ln = self.live_node(expr.hir_id, expr.span); self.init_empty(ln, succ); debug!("propagate_through_loop: using id for loop body {} {:?}", expr.hir_id, body); self.break_ln.insert(expr.hir_id, succ); self.cont_ln.insert(expr.hir_id, ln); let body_ln = self.propagate_through_block(body, ln); // repeat until fixed point is reached: while self.merge_from_succ(ln, body_ln, first_merge) { first_merge = false; assert_eq!(body_ln, self.propagate_through_block(body, ln)); } ln } } // _______________________________________________________________________ // Checking for error conditions impl<'a, 'tcx> Visitor<'tcx> for Liveness<'a, 'tcx> { type Map = intravisit::ErasedMap<'tcx>; fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { NestedVisitorMap::None } fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { self.check_unused_vars_in_pat(&local.pat, None, |spans, hir_id, ln, var| { if local.init.is_some() { self.warn_about_dead_assign(spans, hir_id, ln, var); } }); intravisit::walk_local(self, local); } fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { check_expr(self, ex); } fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { self.check_unused_vars_in_pat(&arm.pat, None, |_, _, _, _| {}); intravisit::walk_arm(self, arm); } } fn check_expr<'tcx>(this: &mut Liveness<'_, 'tcx>, expr: &'tcx Expr<'tcx>) { match expr.kind { hir::ExprKind::Assign(ref l, ..) => { this.check_place(&l); } hir::ExprKind::AssignOp(_, ref l, _) => { if !this.tables.is_method_call(expr) { this.check_place(&l); } } hir::ExprKind::InlineAsm(ref asm) => { for op in asm.operands { match op { hir::InlineAsmOperand::Out { expr, .. } => { if let Some(expr) = expr { this.check_place(expr); } } hir::InlineAsmOperand::InOut { expr, .. } => { this.check_place(expr); } hir::InlineAsmOperand::SplitInOut { out_expr, .. } => { if let Some(out_expr) = out_expr { this.check_place(out_expr); } } _ => {} } } } hir::ExprKind::LlvmInlineAsm(ref asm) => { for input in asm.inputs_exprs { this.visit_expr(input); } // Output operands must be places for (o, output) in asm.inner.outputs.iter().zip(asm.outputs_exprs) { if !o.is_indirect { this.check_place(output); } this.visit_expr(output); } } // no correctness conditions related to liveness hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) | hir::ExprKind::Match(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Index(..) | hir::ExprKind::Field(..) | hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) | hir::ExprKind::Binary(..) | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) | hir::ExprKind::Continue(..) | hir::ExprKind::Lit(_) | hir::ExprKind::Block(..) | hir::ExprKind::AddrOf(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) | hir::ExprKind::Closure(..) | hir::ExprKind::Path(_) | hir::ExprKind::Yield(..) | hir::ExprKind::Box(..) | hir::ExprKind::Type(..) | hir::ExprKind::Err => {} } intravisit::walk_expr(this, expr); } impl<'tcx> Liveness<'_, 'tcx> { fn check_place(&mut self, expr: &'tcx Expr<'tcx>) { match expr.kind { hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { if let Res::Local(var_hid) = path.res { // Assignment to an immutable variable or argument: only legal // if there is no later assignment. If this local is actually // mutable, then check for a reassignment to flag the mutability // as being used. let ln = self.live_node(expr.hir_id, expr.span); let var = self.variable(var_hid, expr.span); self.warn_about_dead_assign(vec![expr.span], expr.hir_id, ln, var); } } _ => { // For other kinds of places, no checks are required, // and any embedded expressions are actually rvalues intravisit::walk_expr(self, expr); } } } fn should_warn(&self, var: Variable) -> Option<String> { let name = self.ir.variable_name(var); if name.is_empty() || name.as_bytes()[0] == b'_' { None } else { Some(name) } } fn warn_about_unused_upvars(&self, entry_ln: LiveNode) { let upvars = match self.ir.tcx.upvars_mentioned(self.ir.body_owner) { None => return, Some(upvars) => upvars, }; for (&var_hir_id, upvar) in upvars.iter() { let var = self.variable(var_hir_id, upvar.span); let upvar_id = ty::UpvarId { var_path: ty::UpvarPath { hir_id: var_hir_id }, closure_expr_id: self.ir.body_owner, }; match self.tables.upvar_capture(upvar_id) { ty::UpvarCapture::ByValue => {} ty::UpvarCapture::ByRef(..) => continue, }; if self.used_on_entry(entry_ln, var) { if self.live_on_entry(entry_ln, var).is_none() { if let Some(name) = self.should_warn(var) { self.ir.tcx.struct_span_lint_hir( lint::builtin::UNUSED_ASSIGNMENTS, var_hir_id, vec![upvar.span], |lint| { lint.build(&format!("value captured by `{}` is never read", name)) .help("did you mean to capture by reference instead?") .emit(); }, ); } } } else { if let Some(name) = self.should_warn(var) { self.ir.tcx.struct_span_lint_hir( lint::builtin::UNUSED_VARIABLES, var_hir_id, vec![upvar.span], |lint| { lint.build(&format!("unused variable: `{}`", name)) .help("did you mean to capture by reference instead?") .emit(); }, ); } } } } fn warn_about_unused_args(&self, body: &hir::Body<'_>, entry_ln: LiveNode) { for p in body.params { self.check_unused_vars_in_pat(&p.pat, Some(entry_ln), |spans, hir_id, ln, var| { if self.live_on_entry(ln, var).is_none() { self.report_unsed_assign(hir_id, spans, var, |name| { format!("value passed to `{}` is never read", name) }); } }); } } fn check_unused_vars_in_pat( &self, pat: &hir::Pat<'_>, entry_ln: Option<LiveNode>, on_used_on_entry: impl Fn(Vec<Span>, HirId, LiveNode, Variable), ) { // In an or-pattern, only consider the variable; any later patterns must have the same // bindings, and we also consider the first pattern to be the "authoritative" set of ids. // However, we should take the ids and spans of variables with the same name from the later // patterns so the suggestions to prefix with underscores will apply to those too. let mut vars: FxIndexMap<String, (LiveNode, Variable, Vec<(HirId, Span)>)> = <_>::default(); pat.each_binding(|_, hir_id, pat_sp, ident| { let ln = entry_ln.unwrap_or_else(|| self.live_node(hir_id, pat_sp)); let var = self.variable(hir_id, ident.span); let id_and_sp = (hir_id, pat_sp); vars.entry(self.ir.variable_name(var)) .and_modify(|(.., hir_ids_and_spans)| hir_ids_and_spans.push(id_and_sp)) .or_insert_with(|| (ln, var, vec![id_and_sp])); }); for (_, (ln, var, hir_ids_and_spans)) in vars { if self.used_on_entry(ln, var) { let id = hir_ids_and_spans[0].0; let spans = hir_ids_and_spans.into_iter().map(|(_, sp)| sp).collect(); on_used_on_entry(spans, id, ln, var); } else { self.report_unused(hir_ids_and_spans, ln, var); } } } fn report_unused(&self, hir_ids_and_spans: Vec<(HirId, Span)>, ln: LiveNode, var: Variable) { let first_hir_id = hir_ids_and_spans[0].0; if let Some(name) = self.should_warn(var).filter(|name| name != "self") { // annoying: for parameters in funcs like `fn(x: i32) // {ret}`, there is only one node, so asking about // assigned_on_exit() is not meaningful. let is_assigned = if ln == self.s.exit_ln { false } else { self.assigned_on_exit(ln, var).is_some() }; if is_assigned { self.ir.tcx.struct_span_lint_hir( lint::builtin::UNUSED_VARIABLES, first_hir_id, hir_ids_and_spans.into_iter().map(|(_, sp)| sp).collect::<Vec<_>>(), |lint| { lint.build(&format!("variable `{}` is assigned to, but never used", name)) .note(&format!("consider using `_{}` instead", name)) .emit(); }, ) } else { self.ir.tcx.struct_span_lint_hir( lint::builtin::UNUSED_VARIABLES, first_hir_id, hir_ids_and_spans.iter().map(|(_, sp)| *sp).collect::<Vec<_>>(), |lint| { let mut err = lint.build(&format!("unused variable: `{}`", name)); let (shorthands, non_shorthands): (Vec<_>, Vec<_>) = hir_ids_and_spans.into_iter().partition(|(hir_id, span)| { let var = self.variable(*hir_id, *span); self.ir.variable_is_shorthand(var) }); let mut shorthands = shorthands .into_iter() .map(|(_, span)| (span, format!("{}: _", name))) .collect::<Vec<_>>(); // If we have both shorthand and non-shorthand, prefer the "try ignoring // the field" message, and suggest `_` for the non-shorthands. If we only // have non-shorthand, then prefix with an underscore instead. if !shorthands.is_empty() { shorthands.extend( non_shorthands .into_iter() .map(|(_, span)| (span, "_".to_string())) .collect::<Vec<_>>(), ); err.multipart_suggestion( "try ignoring the field", shorthands, Applicability::MachineApplicable, ); } else { err.multipart_suggestion( "if this is intentional, prefix it with an underscore", non_shorthands .into_iter() .map(|(_, span)| (span, format!("_{}", name))) .collect::<Vec<_>>(), Applicability::MachineApplicable, ); } err.emit() }, ); } } } fn warn_about_dead_assign(&self, spans: Vec<Span>, hir_id: HirId, ln: LiveNode, var: Variable) { if self.live_on_exit(ln, var).is_none() { self.report_unsed_assign(hir_id, spans, var, |name| { format!("value assigned to `{}` is never read", name) }); } } fn report_unsed_assign( &self, hir_id: HirId, spans: Vec<Span>, var: Variable, message: impl Fn(&str) -> String, ) { if let Some(name) = self.should_warn(var) { self.ir.tcx.struct_span_lint_hir( lint::builtin::UNUSED_ASSIGNMENTS, hir_id, spans, |lint| { lint.build(&message(&name)) .help("maybe it is overwritten before being read?") .emit(); }, ) } } }
lnk
__init__.py
default_app_config = "grandchallenge.evaluation.apps.EvaluationConfig"
utils.py
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # 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 json import time import attr from synapse.api.constants import Membership from tests.server import make_request, render @attr.s class RestHelper(object): """Contains extra helper functions to quickly and clearly perform a given REST action, which isn't the focus of the test. """ hs = attr.ib() resource = attr.ib() auth_user_id = attr.ib() def create_room_as(self, room_creator, is_public=True, tok=None): temp_id = self.auth_user_id self.auth_user_id = room_creator path = "/_matrix/client/r0/createRoom" content = {} if not is_public: content["visibility"] = "private" if tok: path = path + "?access_token=%s" % tok request, channel = make_request( self.hs.get_reactor(), "POST", path, json.dumps(content).encode('utf8') ) render(request, self.resource, self.hs.get_reactor()) assert channel.result["code"] == b"200", channel.result self.auth_user_id = temp_id return channel.json_body["room_id"] def invite(self, room=None, src=None, targ=None, expect_code=200, tok=None): self.change_membership( room=room, src=src, targ=targ, tok=tok, membership=Membership.INVITE, expect_code=expect_code, ) def join(self, room=None, user=None, expect_code=200, tok=None): self.change_membership( room=room, src=user, targ=user, tok=tok, membership=Membership.JOIN, expect_code=expect_code, ) def leave(self, room=None, user=None, expect_code=200, tok=None): self.change_membership( room=room, src=user, targ=user, tok=tok, membership=Membership.LEAVE, expect_code=expect_code, ) def change_membership(self, room, src, targ, membership, tok=None, expect_code=200): temp_id = self.auth_user_id self.auth_user_id = src path = "/_matrix/client/r0/rooms/%s/state/m.room.member/%s" % (room, targ) if tok: path = path + "?access_token=%s" % tok data = {"membership": membership} request, channel = make_request( self.hs.get_reactor(), "PUT", path, json.dumps(data).encode('utf8') ) render(request, self.resource, self.hs.get_reactor()) assert int(channel.result["code"]) == expect_code, ( "Expected: %d, got: %d, resp: %r" % (expect_code, int(channel.result["code"]), channel.result["body"]) ) self.auth_user_id = temp_id def send(self, room_id, body=None, txn_id=None, tok=None, expect_code=200): if txn_id is None: txn_id = "m%s" % (str(time.time())) if body is None: body = "body_text_here" path = "/_matrix/client/r0/rooms/%s/send/m.room.message/%s" % (room_id, txn_id) content = {"msgtype": "m.text", "body": body} if tok: path = path + "?access_token=%s" % tok request, channel = make_request( self.hs.get_reactor(), "PUT", path, json.dumps(content).encode('utf8') ) render(request, self.resource, self.hs.get_reactor()) assert int(channel.result["code"]) == expect_code, ( "Expected: %d, got: %d, resp: %r" % (expect_code, int(channel.result["code"]), channel.result["body"]) ) return channel.json_body def send_state(self, room_id, event_type, body, tok, expect_code=200):
path = "/_matrix/client/r0/rooms/%s/state/%s" % (room_id, event_type) if tok: path = path + "?access_token=%s" % tok request, channel = make_request( self.hs.get_reactor(), "PUT", path, json.dumps(body).encode('utf8') ) render(request, self.resource, self.hs.get_reactor()) assert int(channel.result["code"]) == expect_code, ( "Expected: %d, got: %d, resp: %r" % (expect_code, int(channel.result["code"]), channel.result["body"]) ) return channel.json_body
volumes.go
package netapp // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // VolumesClient is the microsoft NetApp Azure Resource Provider specification type VolumesClient struct { BaseClient } // NewVolumesClient creates an instance of the VolumesClient client. func NewVolumesClient(subscriptionID string) VolumesClient { return NewVolumesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewVolumesClientWithBaseURI creates an instance of the VolumesClient client using a custom endpoint. Use this when // interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func
(baseURI string, subscriptionID string) VolumesClient { return VolumesClient{NewWithBaseURI(baseURI, subscriptionID)} } // AuthorizeReplication authorize the replication connection on the source volume // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume // body - authorize request object supplied in the body of the operation. func (client VolumesClient) AuthorizeReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body AuthorizeRequest) (result VolumesAuthorizeReplicationFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.AuthorizeReplication") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "AuthorizeReplication", err.Error()) } req, err := client.AuthorizeReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, body) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "AuthorizeReplication", nil, "Failure preparing request") return } result, err = client.AuthorizeReplicationSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "AuthorizeReplication", result.Response(), "Failure sending request") return } return } // AuthorizeReplicationPreparer prepares the AuthorizeReplication request. func (client VolumesClient) AuthorizeReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body AuthorizeRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/authorizeReplication", pathParameters), autorest.WithJSON(body), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // AuthorizeReplicationSender sends the AuthorizeReplication request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) AuthorizeReplicationSender(req *http.Request) (future VolumesAuthorizeReplicationFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // AuthorizeReplicationResponder handles the response to the AuthorizeReplication request. The method always // closes the http.Response Body. func (client VolumesClient) AuthorizeReplicationResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // BreakReplication break the replication connection on the destination volume // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume // body - optional body to force break the replication. func (client VolumesClient) BreakReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body *BreakReplicationRequest) (result VolumesBreakReplicationFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.BreakReplication") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "BreakReplication", err.Error()) } req, err := client.BreakReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, body) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "BreakReplication", nil, "Failure preparing request") return } result, err = client.BreakReplicationSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "BreakReplication", result.Response(), "Failure sending request") return } return } // BreakReplicationPreparer prepares the BreakReplication request. func (client VolumesClient) BreakReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body *BreakReplicationRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/breakReplication", pathParameters), autorest.WithQueryParameters(queryParameters)) if body != nil { preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(body)) } return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // BreakReplicationSender sends the BreakReplication request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) BreakReplicationSender(req *http.Request) (future VolumesBreakReplicationFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // BreakReplicationResponder handles the response to the BreakReplication request. The method always // closes the http.Response Body. func (client VolumesClient) BreakReplicationResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // CreateOrUpdate create or update the specified volume within the capacity pool // Parameters: // body - volume object supplied in the body of the operation. // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume func (client VolumesClient) CreateOrUpdate(ctx context.Context, body Volume, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.CreateOrUpdate") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: body, Constraints: []validation.Constraint{{Target: "body.Location", Name: validation.Null, Rule: true, Chain: nil}, {Target: "body.VolumeProperties", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "body.VolumeProperties.FileSystemID", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "body.VolumeProperties.FileSystemID", Name: validation.MaxLength, Rule: 36, Chain: nil}, {Target: "body.VolumeProperties.FileSystemID", Name: validation.MinLength, Rule: 36, Chain: nil}, {Target: "body.VolumeProperties.FileSystemID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`, Chain: nil}, }}, {Target: "body.VolumeProperties.CreationToken", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "body.VolumeProperties.CreationToken", Name: validation.MaxLength, Rule: 80, Chain: nil}, {Target: "body.VolumeProperties.CreationToken", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "body.VolumeProperties.CreationToken", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-]{0,79}$`, Chain: nil}, }}, {Target: "body.VolumeProperties.UsageThreshold", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "body.VolumeProperties.UsageThreshold", Name: validation.InclusiveMaximum, Rule: int64(109951162777600), Chain: nil}, {Target: "body.VolumeProperties.UsageThreshold", Name: validation.InclusiveMinimum, Rule: int64(107374182400), Chain: nil}, }}, {Target: "body.VolumeProperties.SnapshotID", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "body.VolumeProperties.SnapshotID", Name: validation.MaxLength, Rule: 36, Chain: nil}, {Target: "body.VolumeProperties.SnapshotID", Name: validation.MinLength, Rule: 36, Chain: nil}, {Target: "body.VolumeProperties.SnapshotID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}|(\\?([^\/]*[\/])*)([^\/]+)$`, Chain: nil}, }}, {Target: "body.VolumeProperties.BackupID", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "body.VolumeProperties.BackupID", Name: validation.MaxLength, Rule: 36, Chain: nil}, {Target: "body.VolumeProperties.BackupID", Name: validation.MinLength, Rule: 36, Chain: nil}, {Target: "body.VolumeProperties.BackupID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}|(\\?([^\/]*[\/])*)([^\/]+)$`, Chain: nil}, }}, {Target: "body.VolumeProperties.BaremetalTenantID", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "body.VolumeProperties.BaremetalTenantID", Name: validation.MaxLength, Rule: 36, Chain: nil}, {Target: "body.VolumeProperties.BaremetalTenantID", Name: validation.MinLength, Rule: 36, Chain: nil}, {Target: "body.VolumeProperties.BaremetalTenantID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`, Chain: nil}, }}, {Target: "body.VolumeProperties.SubnetID", Name: validation.Null, Rule: true, Chain: nil}, {Target: "body.VolumeProperties.DataProtection", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "body.VolumeProperties.DataProtection.Replication", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "body.VolumeProperties.DataProtection.Replication.RemoteVolumeResourceID", Name: validation.Null, Rule: true, Chain: nil}}}, }}, {Target: "body.VolumeProperties.ThroughputMibps", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "body.VolumeProperties.ThroughputMibps", Name: validation.InclusiveMaximum, Rule: float64(4500), Chain: nil}, {Target: "body.VolumeProperties.ThroughputMibps", Name: validation.InclusiveMinimum, Rule: float64(1), Chain: nil}, {Target: "body.VolumeProperties.ThroughputMibps", Name: validation.MultipleOf, Rule: 0.001, Chain: nil}, }}, }}}}, {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "CreateOrUpdate", err.Error()) } req, err := client.CreateOrUpdatePreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client VolumesClient) CreateOrUpdatePreparer(ctx context.Context, body Volume, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } body.ID = nil body.Name = nil body.Type = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", pathParameters), autorest.WithJSON(body), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) CreateOrUpdateSender(req *http.Request) (future VolumesCreateOrUpdateFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client VolumesClient) CreateOrUpdateResponder(resp *http.Response) (result Volume, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete delete the specified volume // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume func (client VolumesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "Delete", err.Error()) } req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, poolName, volumeName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client VolumesClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) DeleteSender(req *http.Request) (future VolumesDeleteFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client VolumesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // DeleteReplication delete the replication connection on the destination volume, and send release to the source // replication // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume func (client VolumesClient) DeleteReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesDeleteReplicationFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.DeleteReplication") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "DeleteReplication", err.Error()) } req, err := client.DeleteReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "DeleteReplication", nil, "Failure preparing request") return } result, err = client.DeleteReplicationSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "DeleteReplication", result.Response(), "Failure sending request") return } return } // DeleteReplicationPreparer prepares the DeleteReplication request. func (client VolumesClient) DeleteReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/deleteReplication", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteReplicationSender sends the DeleteReplication request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) DeleteReplicationSender(req *http.Request) (future VolumesDeleteReplicationFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // DeleteReplicationResponder handles the response to the DeleteReplication request. The method always // closes the http.Response Body. func (client VolumesClient) DeleteReplicationResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Get get the details of the specified volume // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume func (client VolumesClient) Get(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result Volume, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client VolumesClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client VolumesClient) GetResponder(resp *http.Response) (result Volume, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List list all volumes within the capacity pool // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool func (client VolumesClient) List(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result VolumeList, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.List") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "List", err.Error()) } req, err := client.ListPreparer(ctx, resourceGroupName, accountName, poolName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client VolumesClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client VolumesClient) ListResponder(resp *http.Response) (result VolumeList, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // PoolChange moves volume to another pool // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume // body - move volume to the pool supplied in the body of the operation. func (client VolumesClient) PoolChange(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body PoolChangeRequest) (result VolumesPoolChangeFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.PoolChange") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: body, Constraints: []validation.Constraint{{Target: "body.NewPoolResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "PoolChange", err.Error()) } req, err := client.PoolChangePreparer(ctx, resourceGroupName, accountName, poolName, volumeName, body) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "PoolChange", nil, "Failure preparing request") return } result, err = client.PoolChangeSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "PoolChange", result.Response(), "Failure sending request") return } return } // PoolChangePreparer prepares the PoolChange request. func (client VolumesClient) PoolChangePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body PoolChangeRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/poolChange", pathParameters), autorest.WithJSON(body), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // PoolChangeSender sends the PoolChange request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) PoolChangeSender(req *http.Request) (future VolumesPoolChangeFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // PoolChangeResponder handles the response to the PoolChange request. The method always // closes the http.Response Body. func (client VolumesClient) PoolChangeResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // ReInitializeReplication re-Initializes the replication connection on the destination volume // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume func (client VolumesClient) ReInitializeReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesReInitializeReplicationFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.ReInitializeReplication") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "ReInitializeReplication", err.Error()) } req, err := client.ReInitializeReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReInitializeReplication", nil, "Failure preparing request") return } result, err = client.ReInitializeReplicationSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReInitializeReplication", result.Response(), "Failure sending request") return } return } // ReInitializeReplicationPreparer prepares the ReInitializeReplication request. func (client VolumesClient) ReInitializeReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/reinitializeReplication", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ReInitializeReplicationSender sends the ReInitializeReplication request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) ReInitializeReplicationSender(req *http.Request) (future VolumesReInitializeReplicationFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // ReInitializeReplicationResponder handles the response to the ReInitializeReplication request. The method always // closes the http.Response Body. func (client VolumesClient) ReInitializeReplicationResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // ReplicationStatusMethod get the status of the replication // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume func (client VolumesClient) ReplicationStatusMethod(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result ReplicationStatus, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.ReplicationStatusMethod") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "ReplicationStatusMethod", err.Error()) } req, err := client.ReplicationStatusMethodPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReplicationStatusMethod", nil, "Failure preparing request") return } resp, err := client.ReplicationStatusMethodSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReplicationStatusMethod", resp, "Failure sending request") return } result, err = client.ReplicationStatusMethodResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReplicationStatusMethod", resp, "Failure responding to request") } return } // ReplicationStatusMethodPreparer prepares the ReplicationStatusMethod request. func (client VolumesClient) ReplicationStatusMethodPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/replicationStatus", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ReplicationStatusMethodSender sends the ReplicationStatusMethod request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) ReplicationStatusMethodSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ReplicationStatusMethodResponder handles the response to the ReplicationStatusMethod request. The method always // closes the http.Response Body. func (client VolumesClient) ReplicationStatusMethodResponder(resp *http.Response) (result ReplicationStatus, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ResyncReplication resync the connection on the destination volume. If the operation is ran on the source volume it // will reverse-resync the connection and sync from source to destination. // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume func (client VolumesClient) ResyncReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesResyncReplicationFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.ResyncReplication") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "ResyncReplication", err.Error()) } req, err := client.ResyncReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ResyncReplication", nil, "Failure preparing request") return } result, err = client.ResyncReplicationSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ResyncReplication", result.Response(), "Failure sending request") return } return } // ResyncReplicationPreparer prepares the ResyncReplication request. func (client VolumesClient) ResyncReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/resyncReplication", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ResyncReplicationSender sends the ResyncReplication request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) ResyncReplicationSender(req *http.Request) (future VolumesResyncReplicationFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // ResyncReplicationResponder handles the response to the ResyncReplication request. The method always // closes the http.Response Body. func (client VolumesClient) ResyncReplicationResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Revert revert a volume to the snapshot specified in the body // Parameters: // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume // body - object for snapshot to revert supplied in the body of the operation. func (client VolumesClient) Revert(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body VolumeRevert) (result VolumesRevertFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.Revert") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "Revert", err.Error()) } req, err := client.RevertPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, body) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Revert", nil, "Failure preparing request") return } result, err = client.RevertSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Revert", result.Response(), "Failure sending request") return } return } // RevertPreparer prepares the Revert request. func (client VolumesClient) RevertPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body VolumeRevert) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/revert", pathParameters), autorest.WithJSON(body), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RevertSender sends the Revert request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) RevertSender(req *http.Request) (future VolumesRevertFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // RevertResponder handles the response to the Revert request. The method always // closes the http.Response Body. func (client VolumesClient) RevertResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Update patch the specified volume // Parameters: // body - volume object supplied in the body of the operation. // resourceGroupName - the name of the resource group. // accountName - the name of the NetApp account // poolName - the name of the capacity pool // volumeName - the name of the volume func (client VolumesClient) Update(ctx context.Context, body VolumePatch, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.Update") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: poolName, Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, {TargetValue: volumeName, Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { return result, validation.NewError("netapp.VolumesClient", "Update", err.Error()) } req, err := client.UpdatePreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Update", nil, "Failure preparing request") return } result, err = client.UpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Update", result.Response(), "Failure sending request") return } return } // UpdatePreparer prepares the Update request. func (client VolumesClient) UpdatePreparer(ctx context.Context, body VolumePatch, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "poolName": autorest.Encode("path", poolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "volumeName": autorest.Encode("path", volumeName), } const APIVersion = "2020-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } body.ID = nil body.Name = nil body.Type = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", pathParameters), autorest.WithJSON(body), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client VolumesClient) UpdateSender(req *http.Request) (future VolumesUpdateFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client VolumesClient) UpdateResponder(resp *http.Response) (result Volume, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
NewVolumesClientWithBaseURI
decode.rs
use std::convert::{TryFrom, TryInto}; use bstr::BString; use git_hash::ObjectId; use nom::{ bytes::complete::{tag, take_while}, combinator::{map, opt}, sequence::terminated, IResult, }; use quick_error::quick_error; use crate::{ mutable, parse::{hex_hash, newline}, store::file::loose::Reference, }; enum MaybeUnsafeState { Id(ObjectId), UnvalidatedPath(BString), } quick_error! { /// The error returned by [`Reference::try_from_path()`]. #[derive(Debug)] #[allow(missing_docs)] pub enum Error { Parse(content: BString) { display("{:?} could not be parsed", content) } RefnameValidation{err: git_validate::reference::name::Error, path: BString} { display("The path to a symbolic reference within a ref file is invalid") source(err) } } } impl TryFrom<MaybeUnsafeState> for mutable::Target { type Error = Error; fn try_from(v: MaybeUnsafeState) -> Result<Self, Self::Error> { Ok(match v { MaybeUnsafeState::Id(id) => mutable::Target::Peeled(id), MaybeUnsafeState::UnvalidatedPath(name) => { mutable::Target::Symbolic(match git_validate::refname(name.as_ref()) { Ok(_) => mutable::FullName(name), Err(err) => return Err(Error::RefnameValidation { err, path: name }), }) } }) } } impl Reference { /// Create a new reference of the given `parent` store with `relative_path` service as unique identifier /// at which the `path_contents` was read to obtain the refs value. pub fn try_from_path(name: mutable::FullName, path_contents: &[u8]) -> Result<Self, Error>
} fn parse(bytes: &[u8]) -> IResult<&[u8], MaybeUnsafeState> { let is_space = |b: u8| b == b' '; if let (path, Some(_ref_prefix)) = opt(terminated(tag("ref: "), take_while(is_space)))(bytes)? { map( terminated(take_while(|b| b != b'\r' && b != b'\n'), opt(newline)), |path| MaybeUnsafeState::UnvalidatedPath(path.into()), )(path) } else { map(terminated(hex_hash, opt(newline)), |hex| { MaybeUnsafeState::Id(ObjectId::from_hex(hex).expect("prior validation")) })(bytes) } }
{ Ok(Reference { name, target: parse(path_contents) .map_err(|_| Error::Parse(path_contents.into()))? .1 .try_into()?, }) }
forms.py
from django import forms from django.core.validators import MinValueValidator from django.utils.translation import gettext_lazy as _ from .models import DayType, Day class DayTypeForm(forms.ModelForm): class Meta: model = DayType fields = '__all__' class DayForm(forms.ModelForm): class Meta: model = Day fields = '__all__' class CalendarUploadForm(forms.Form): year = forms.IntegerField( required=True,
MinValueValidator(1999), ], label=_('Year'), help_text=_('Pick a year to import'), ) file = forms.FileField( required=True, label=_('File'), help_text=_('Pick a CSV file containing work calendar'), ) def clean_file(self): if any(self.errors): return None file = self.cleaned_data['file'] if not file.name.endswith('.csv'): raise forms.ValidationError(_('CSV file required')) return file
validators=[
dashboard.init.js
!function(d){"use strict";function t(){this.$body=d("body"),this.charts=[]}t.prototype.respChart=function(a,r,o,e){var n=Chart.controllers.line.prototype.draw;Chart.controllers.line.prototype.draw=function(){n.apply(this,arguments);var t=this.chart.chart.ctx,a=t.stroke;t.stroke=function(){t.save(),t.shadowBlur=10,t.shadowOffsetX=0,t.shadowOffsetY=4,a.apply(this,arguments),t.restore()}};var i=a.get(0).getContext("2d"),s=d(a).parent();return function(){var t;switch(a.attr("width",d(s).width()),r){case"Line":t=new Chart(i,{type:"line",data:o,options:e});break;case"Doughnut":t=new Chart(i,{type:"doughnut",data:o,options:e});break;case"Pie":t=new Chart(i,{type:"pie",data:o,options:e});break;case"Bar":t=new Chart(i,{type:"bar",data:o,options:e});break;case"Radar":t=new Chart(i,{type:"radar",data:o,options:e});break;case"PolarArea":t=new Chart(i,{data:o,type:"polarArea",options:e})}return t}()},t.prototype.initCharts=function(){var t=[],a=(o=document.getElementById("product-chart").getContext("2d")).createLinearGradient(0,300,0,100);a.addColorStop(0,"#51A1DD"),a.addColorStop(1,"#71D0F2");var r={labels:["01","02","03","04","05","06"],datasets:[{label:"Chart Analytics",backgroundColor:a,borderColor:a,borderWidth:1,hoverBackgroundColor:a,hoverBorderColor:a,data:[75,59,76,90,56,75]}]};t.push(this.respChart(d("#product-chart"),"Bar",r,{maintainAspectRatio:!1,legend:{display:!1},scales:{yAxes:[{gridLines:{display:!1},ticks:{max:100,min:20,fontColor:"#fff",stepSize:20}}],xAxes:[{barPercentage:.7,gridLines:{color:"rgba(27,29,100,0.2)"},ticks:{fontColor:"#fff"}}]}}));var o,e=(o=document.getElementById("line-chart-static").getContext("2d")).createLinearGradient(500,0,100,0);e.addColorStop(0,"#1a1b62"),e.addColorStop(1,"#4483c6");var n=o.createLinearGradient(500,0,100,0);n.addColorStop(0,"#4483c6"),n.addColorStop(1,"#1a1b62");var i={labels:["01","02","03","04","05","06","07"],datasets:[{label:"Views",fill:!1,borderColor:e,pointBorderColor:e,pointBackgroundColor:e,pointHoverBackgroundColor:e,pointHoverBorderColor:e,data:[88,92,61,5,49,92,54]},{label:"Earning",fill:!1,borderColor:n,pointBorderColor:n,pointBackgroundColor:n,pointHoverBackgroundColor:n,pointHoverBorderColor:n,data:[44,10,81,61,63,5,85]}]};t.push(this.respChart(d("#line-chart-static"),"Line",i,{maintainAspectRatio:!1,responsive:!0,legend:{display:!1},animation:{easing:"easeInOutBack"},scales:{yAxes:[{display:!1,ticks:{fontColor:"rgba(0,0,0,0.5)",fontStyle:"bold",beginAtZero:!0,maxTicksLimit:5,padding:0},gridLines:{drawTicks:!1,display:!1}}],xAxes:[{display:!1,gridLines:{zeroLineColor:"transparent"},ticks:{padding:0,fontColor:"rgba(0,0,0,0.5)",fontStyle:"bold"}}]}}));t.push(this.respChart(d("#doughnut"),"Doughnut",{labels:["Upload","Download"],datasets:[{data:[40,60],backgroundColor:["#67C2EB","#FF679B"],borderColor:"transparent",borderWidth:"3"}]},{maintainAspectRatio:!1,cutoutPercentage:80,legend:{display:!1}}))},t.prototype.init=function(){d("#datatable").DataTable({pageLength:5,searching:!1,lengthChange:!1});var a=this;a.charts=this.initCharts(),d(window).on("resize",function(t){d.each(a.charts,function(t,a){try{a.destroy()}catch(t){console.log(t)}}),a.charts=a.initCharts()})},d.Dashboard=new t,d.Dashboard.Constructor=t}(window.jQuery),function(t){"use strict";t(function(){t("#inline-datepicker-example").length&&t("#inline-datepicker-example").datepicker({enableOnReadonly:!0,todayHighlight:!0,templates:{leftArrow:'<i class="mdi mdi-chevron-left"></i>',rightArrow:'<i class="mdi mdi-chevron-right"></i>'}})})}(jQuery),function(){"use strict";window.jQuery.Dashboard.init()}();
Greeting.tsx
import { Scene } from '@stableinf/io'; import { Widget } from '@stableinf/rx-react'; import * as React from 'react'; import type { GreetingWordsGateway } from '../Private/GreetingWordsGateway'; function
(scene: Scene) { return scene.useServices<typeof GreetingWordsGateway>(); } export class Greeting extends Widget { private words = this.subscribe(async (scene) => { return await $(scene).getGreetingWords(); }); public render() { return <h1>{this.words}</h1>; } }
$
test_messages.py
import six if six.PY3: import unittest else: import unittest2 as unittest from datetime import date from mock import Mock from six import u from twilio.rest.resources import Messages DEFAULT = { 'From': None, 'DateSent<': None, 'DateSent>': None, 'DateSent': None, } class MessageTest(unittest.TestCase): def setUp(self): self.resource = Messages("foo", ("sid", "token")) self.params = DEFAULT.copy() def test_list_on(self): self.resource.get_instances = Mock() self.resource.list(date_sent=date(2011, 1, 1)) self.params['DateSent'] = "2011-01-01"
self.resource.list(after=date(2011, 1, 1)) self.params['DateSent>'] = "2011-01-01" self.resource.get_instances.assert_called_with(self.params) def test_list_before(self): self.resource.get_instances = Mock() self.resource.list(before=date(2011, 1, 1)) self.params['DateSent<'] = "2011-01-01" self.resource.get_instances.assert_called_with(self.params) def test_create(self): self.resource.create_instance = Mock() self.resource.create( from_='+14155551234', to='+14155556789', body=u('ahoy hoy'), ) self.resource.create_instance.assert_called_with( { 'from': '+14155551234', 'to': '+14155556789', 'body': u('ahoy hoy'), }, )
self.resource.get_instances.assert_called_with(self.params) def test_list_after(self): self.resource.get_instances = Mock()
boolean.rs
use algebra::{BitIterator, Field, FpParameters, PrimeField}; use crate::{prelude::*, Assignment}; use r1cs_core::{ConstraintSystem, LinearCombination, SynthesisError, Variable}; use std::borrow::Borrow; /// Represents a variable in the constraint system which is guaranteed /// to be either zero or one. #[derive(Copy, Clone, Debug)] pub struct AllocatedBit { variable: Variable, value: Option<bool>, } impl AllocatedBit { pub fn get_value(&self) -> Option<bool> { self.value } pub fn get_variable(&self) -> Variable { self.variable } /// Performs an XOR operation over the two operands, returning /// an `AllocatedBit`. pub fn xor<ConstraintF, CS>(mut cs: CS, a: &Self, b: &Self) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { let mut result_value = None; let result_var = cs.alloc( || "xor result", || { if a.value.get()? ^ b.value.get()? { result_value = Some(true); Ok(ConstraintF::one()) } else { result_value = Some(false); Ok(ConstraintF::zero()) } }, )?; // Constrain (a + a) * (b) = (a + b - c) // Given that a and b are boolean constrained, if they // are equal, the only solution for c is 0, and if they // are different, the only solution for c is 1. // // ¬(a ∧ b) ∧ ¬(¬a ∧ ¬b) = c // (1 - (a * b)) * (1 - ((1 - a) * (1 - b))) = c // (1 - ab) * (1 - (1 - a - b + ab)) = c // (1 - ab) * (a + b - ab) = c // a + b - ab - (a^2)b - (b^2)a + (a^2)(b^2) = c // a + b - ab - ab - ab + ab = c // a + b - 2ab = c // -2a * b = c - a - b // 2a * b = a + b - c // (a + a) * b = a + b - c cs.enforce( || "xor constraint", |lc| lc + a.variable + a.variable, |lc| lc + b.variable, |lc| lc + a.variable + b.variable - result_var, ); Ok(AllocatedBit { variable: result_var, value: result_value, }) } /// Performs an AND operation over the two operands, returning /// an `AllocatedBit`. pub fn and<ConstraintF, CS>(mut cs: CS, a: &Self, b: &Self) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { let mut result_value = None; let result_var = cs.alloc( || "and result", || { if a.value.get()? & b.value.get()? { result_value = Some(true); Ok(ConstraintF::one()) } else { result_value = Some(false); Ok(ConstraintF::zero()) } }, )?; // Constrain (a) * (b) = (c), ensuring c is 1 iff // a AND b are both 1. cs.enforce( || "and constraint", |lc| lc + a.variable, |lc| lc + b.variable, |lc| lc + result_var, ); Ok(AllocatedBit { variable: result_var, value: result_value, }) } /// Performs an OR operation over the two operands, returning /// an `AllocatedBit`. pub fn or<ConstraintF, CS>(cs: CS, a: &Self, b: &Self) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { Self::conditionally_select(cs, &Boolean::from(*a), a, b) } /// Calculates `a AND (NOT b)`. pub fn and_not<ConstraintF, CS>(mut cs: CS, a: &Self, b: &Self) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { let mut result_value = None; let result_var = cs.alloc( || "and not result", || { if a.value.get()? & !b.value.get()? { result_value = Some(true); Ok(ConstraintF::one()) } else { result_value = Some(false); Ok(ConstraintF::zero()) } }, )?; // Constrain (a) * (1 - b) = (c), ensuring c is 1 iff // a is true and b is false, and otherwise c is 0. cs.enforce( || "and not constraint", |lc| lc + a.variable, |lc| lc + CS::one() - b.variable, |lc| lc + result_var, ); Ok(AllocatedBit { variable: result_var, value: result_value, }) } /// Calculates `(NOT a) AND (NOT b)`. pub fn nor<ConstraintF, CS>(mut cs: CS, a: &Self, b: &Self) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { let mut result_value = None; let result_var = cs.alloc( || "nor result", || { if !a.value.get()? & !b.value.get()? { result_value = Some(true); Ok(ConstraintF::one()) } else { result_value = Some(false); Ok(ConstraintF::zero()) } }, )?; // Constrain (1 - a) * (1 - b) = (c), ensuring c is 1 iff // a and b are both false, and otherwise c is 0. cs.enforce( || "nor constraint", |lc| lc + CS::one() - a.variable, |lc| lc + CS::one() - b.variable, |lc| lc + result_var, ); Ok(AllocatedBit { variable: result_var, value: result_value, }) } } impl PartialEq for AllocatedBit { fn eq(&self, other: &Self) -> bool { self.value.is_some() && other.value.is_some() && self.value == other.value } } impl Eq for AllocatedBit {} impl<ConstraintF: Field> AllocGadget<bool, ConstraintF> for AllocatedBit { fn alloc<F, T, CS: ConstraintSystem<ConstraintF>>( mut cs: CS, value_gen: F, ) -> Result<Self, SynthesisError> where F: FnOnce() -> Result<T, SynthesisError>, T: Borrow<bool>, { let mut value = None; let var = cs.alloc( || "boolean", || { value = Some(*value_gen()?.borrow()); if value.get()? { Ok(ConstraintF::one()) } else { Ok(ConstraintF::zero()) } }, )?; // Constrain: (1 - a) * a = 0 // This constrains a to be either 0 or 1. cs.enforce( || "boolean constraint", |lc| lc + CS::one() - var, |lc| lc + var, |lc| lc, ); Ok(AllocatedBit { variable: var, value, }) } fn alloc_input<F, T, CS: ConstraintSystem<ConstraintF>>( mut cs: CS, value_gen: F, ) -> Result<Self, SynthesisError> where F: FnOnce() -> Result<T, SynthesisError>, T: Borrow<bool>, { let mut value = None; let var = cs.alloc_input( || "boolean", || { value = Some(*value_gen()?.borrow()); if value.get()? { Ok(ConstraintF::one()) } else { Ok(ConstraintF::zero()) } }, )?; // Constrain: (1 - a) * a = 0 // This constrains a to be either 0 or 1. cs.enforce( || "boolean constraint", |lc| lc + CS::one() - var, |lc| lc + var, |lc| lc, ); Ok(AllocatedBit { variable: var, value, }) } } impl<ConstraintF: Field> CondSelectGadget<ConstraintF> for AllocatedBit { fn conditionally_select<CS: ConstraintSystem<ConstraintF>>( mut cs: CS, cond: &Boolean, first: &Self, second: &Self, ) -> Result<Self, SynthesisError> { let result = Self::alloc(cs.ns(|| ""), || { cond.get_value() .and_then(|cond| { { if cond { first } else { second } } .get_value() }) .get() })?; // a = self; b = other; c = cond; // // r = c * a + (1 - c) * b // r = b + c * (a - b) // c * (a - b) = r - b let one = CS::one(); cs.enforce( || "conditionally_select", |_| cond.lc(one, ConstraintF::one()), |lc| lc + first.variable - second.variable, |lc| lc + result.variable - second.variable, ); Ok(result) } fn cost() -> usize { 1 } } /// This is a boolean value which may be either a constant or /// an interpretation of an `AllocatedBit`. #[derive(Copy, Clone, Debug)] pub enum Boolean { /// Existential view of the boolean variable Is(AllocatedBit), /// Negated view of the boolean variable Not(AllocatedBit), /// Constant (not an allocated variable) Constant(bool), } impl Boolean { pub fn get_value(
Option<bool> { match *self { Boolean::Constant(c) => Some(c), Boolean::Is(ref v) => v.get_value(), Boolean::Not(ref v) => v.get_value().map(|b| !b), } } pub fn lc<ConstraintF: Field>( &self, one: Variable, coeff: ConstraintF, ) -> LinearCombination<ConstraintF> { match *self { Boolean::Constant(c) => { if c { (coeff, one).into() } else { LinearCombination::<ConstraintF>::zero() } }, Boolean::Is(ref v) => (coeff, v.get_variable()).into(), Boolean::Not(ref v) => { LinearCombination::<ConstraintF>::zero() + (coeff, one) - (coeff, v.get_variable()) }, } } /// Construct a boolean vector from a vector of u8 pub fn constant_u8_vec<ConstraintF: Field, CS: ConstraintSystem<ConstraintF>>( cs: &mut CS, values: &[u8], ) -> Vec<Self> { let mut input_bits = vec![]; for (byte_i, input_byte) in values.iter().enumerate() { for bit_i in (0..8).rev() { let cs = cs.ns(|| format!("input_bit_gadget {} {}", byte_i, bit_i)); input_bits.push( AllocatedBit::alloc(cs, || Ok((input_byte >> bit_i) & 1u8 == 1u8)) .unwrap() .into(), ); } } input_bits } /// Construct a boolean from a known constant pub fn constant(b: bool) -> Self { Boolean::Constant(b) } /// Return a negated interpretation of this boolean. pub fn not(&self) -> Self { match *self { Boolean::Constant(c) => Boolean::Constant(!c), Boolean::Is(ref v) => Boolean::Not(*v), Boolean::Not(ref v) => Boolean::Is(*v), } } /// Perform XOR over two boolean operands pub fn xor<'a, ConstraintF, CS>( cs: CS, a: &'a Self, b: &'a Self, ) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { match (a, b) { (&Boolean::Constant(false), x) | (x, &Boolean::Constant(false)) => Ok(*x), (&Boolean::Constant(true), x) | (x, &Boolean::Constant(true)) => Ok(x.not()), // a XOR (NOT b) = NOT(a XOR b) (is @ &Boolean::Is(_), not @ &Boolean::Not(_)) | (not @ &Boolean::Not(_), is @ &Boolean::Is(_)) => { Ok(Boolean::xor(cs, is, &not.not())?.not()) }, // a XOR b = (NOT a) XOR (NOT b) (&Boolean::Is(ref a), &Boolean::Is(ref b)) | (&Boolean::Not(ref a), &Boolean::Not(ref b)) => { Ok(Boolean::Is(AllocatedBit::xor(cs, a, b)?)) }, } } /// Perform OR over two boolean operands pub fn or<'a, ConstraintF, CS>(cs: CS, a: &'a Self, b: &'a Self) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { match (a, b) { (&Boolean::Constant(false), x) | (x, &Boolean::Constant(false)) => Ok(*x), (&Boolean::Constant(true), _) | (_, &Boolean::Constant(true)) => { Ok(Boolean::Constant(true)) }, // a OR b = NOT ((NOT a) AND b) (a @ &Boolean::Is(_), b @ &Boolean::Not(_)) | (b @ &Boolean::Not(_), a @ &Boolean::Is(_)) | (b @ &Boolean::Not(_), a @ &Boolean::Not(_)) => { Ok(Boolean::and(cs, &a.not(), &b.not())?.not()) }, (&Boolean::Is(ref a), &Boolean::Is(ref b)) => { AllocatedBit::or(cs, a, b).map(Boolean::from) }, } } /// Perform AND over two boolean operands pub fn and<'a, ConstraintF, CS>( cs: CS, a: &'a Self, b: &'a Self, ) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { match (a, b) { // false AND x is always false (&Boolean::Constant(false), _) | (_, &Boolean::Constant(false)) => { Ok(Boolean::Constant(false)) }, // true AND x is always x (&Boolean::Constant(true), x) | (x, &Boolean::Constant(true)) => Ok(*x), // a AND (NOT b) (&Boolean::Is(ref is), &Boolean::Not(ref not)) | (&Boolean::Not(ref not), &Boolean::Is(ref is)) => { Ok(Boolean::Is(AllocatedBit::and_not(cs, is, not)?)) }, // (NOT a) AND (NOT b) = a NOR b (&Boolean::Not(ref a), &Boolean::Not(ref b)) => { Ok(Boolean::Is(AllocatedBit::nor(cs, a, b)?)) }, // a AND b (&Boolean::Is(ref a), &Boolean::Is(ref b)) => { Ok(Boolean::Is(AllocatedBit::and(cs, a, b)?)) }, } } pub fn kary_and<ConstraintF, CS>(mut cs: CS, bits: &[Self]) -> Result<Self, SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { assert!(!bits.is_empty()); let mut bits = bits.iter(); let mut cur: Self = *bits.next().unwrap(); for (i, next) in bits.enumerate() { cur = Boolean::and(cs.ns(|| format!("AND {}", i)), &cur, next)?; } Ok(cur) } /// Asserts that at least one operand is false. pub fn enforce_nand<ConstraintF, CS>(mut cs: CS, bits: &[Self]) -> Result<(), SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { let res = Self::kary_and(&mut cs, bits)?; match res { Boolean::Constant(false) => Ok(()), Boolean::Constant(true) => Err(SynthesisError::AssignmentMissing), Boolean::Is(ref res) => { cs.enforce( || "enforce nand", |lc| lc, |lc| lc, |lc| lc + res.get_variable(), ); Ok(()) }, Boolean::Not(ref res) => { cs.enforce( || "enforce nand", |lc| lc, |lc| lc, |lc| lc + CS::one() - res.get_variable(), ); Ok(()) }, } } /// Asserts that this bit_gadget representation is "in /// the field" when interpreted in big endian. pub fn enforce_in_field<ConstraintF, CS, F: PrimeField>( mut cs: CS, bits: &[Self], ) -> Result<(), SynthesisError> where ConstraintF: Field, CS: ConstraintSystem<ConstraintF>, { let mut bits_iter = bits.iter(); // b = char() - 1 let mut b = F::characteristic().to_vec(); assert_eq!(b[0] % 2, 1); b[0] -= 1; // Runs of ones in r let mut last_run = Boolean::constant(true); let mut current_run = vec![]; let mut found_one = false; let mut run_i = 0; let mut nand_i = 0; let char_num_bits = <F as PrimeField>::Params::MODULUS_BITS as usize; if bits.len() > char_num_bits { let num_extra_bits = bits.len() - char_num_bits; let mut or_result = Boolean::constant(false); for (i, should_be_zero) in bits[0..num_extra_bits].iter().enumerate() { or_result = Boolean::or( &mut cs.ns(|| format!("Check {}-th or", i)), &or_result, should_be_zero, )?; let _ = bits_iter.next().unwrap(); } or_result.enforce_equal( &mut cs.ns(|| "Check that or of extra bits is zero"), &Boolean::constant(false), )?; } for b in BitIterator::new(b) { // Skip over unset bits at the beginning found_one |= b; if !found_one { continue; } let a = bits_iter.next().unwrap(); if b { // This is part of a run of ones. current_run.push(a.clone()); } else { if !current_run.is_empty() { // This is the start of a run of zeros, but we need // to k-ary AND against `last_run` first. current_run.push(last_run); last_run = Self::kary_and(cs.ns(|| format!("run {}", run_i)), &current_run)?; run_i += 1; current_run.truncate(0); } // If `last_run` is true, `a` must be false, or it would // not be in the field. // // If `last_run` is false, `a` can be true or false. // // Ergo, at least one of `last_run` and `a` must be false. Self::enforce_nand(cs.ns(|| format!("nand {}", nand_i)), &[last_run, *a])?; nand_i += 1; } } assert!(bits_iter.next().is_none()); // We should always end in a "run" of zeros, because // the characteristic is an odd prime. So, this should // be empty. assert!(current_run.is_empty()); Ok(()) } } impl PartialEq for Boolean { fn eq(&self, other: &Self) -> bool { use self::Boolean::*; match (*self, *other) { (Is(a), Is(b)) | (Not(a), Not(b)) => a == b, (Is(a), Not(b)) | (Not(a), Is(b)) => a != b, (Is(a), Constant(b)) | (Constant(b), Is(a)) => a.value.unwrap() == b, (Not(a), Constant(b)) | (Constant(b), Not(a)) => a.value.unwrap() != b, (Constant(a), Constant(b)) => a == b, } } } impl Eq for Boolean {} impl From<AllocatedBit> for Boolean { fn from(b: AllocatedBit) -> Boolean { Boolean::Is(b) } } impl<ConstraintF: Field> AllocGadget<bool, ConstraintF> for Boolean { fn alloc<F, T, CS: ConstraintSystem<ConstraintF>>( cs: CS, value_gen: F, ) -> Result<Self, SynthesisError> where F: FnOnce() -> Result<T, SynthesisError>, T: Borrow<bool>, { AllocatedBit::alloc(cs, value_gen).map(Boolean::from) } fn alloc_input<F, T, CS: ConstraintSystem<ConstraintF>>( cs: CS, value_gen: F, ) -> Result<Self, SynthesisError> where F: FnOnce() -> Result<T, SynthesisError>, T: Borrow<bool>, { AllocatedBit::alloc_input(cs, value_gen).map(Boolean::from) } } impl<ConstraintF: Field> EqGadget<ConstraintF> for Boolean {} impl<ConstraintF: Field> ConditionalEqGadget<ConstraintF> for Boolean { fn conditional_enforce_equal<CS>( &self, mut cs: CS, other: &Self, condition: &Boolean, ) -> Result<(), SynthesisError> where CS: ConstraintSystem<ConstraintF>, { use self::Boolean::*; let one = CS::one(); let difference: LinearCombination<ConstraintF> = match (self, other) { // 1 - 1 = 0 - 0 = 0 (Constant(true), Constant(true)) | (Constant(false), Constant(false)) => return Ok(()), // false != true (Constant(_), Constant(_)) => return Err(SynthesisError::AssignmentMissing), // 1 - a (Constant(true), Is(a)) | (Is(a), Constant(true)) => { LinearCombination::zero() + one - a.get_variable() }, // a - 0 = a (Constant(false), Is(a)) | (Is(a), Constant(false)) => { LinearCombination::zero() + a.get_variable() }, // 1 - !a = 1 - (1 - a) = a (Constant(true), Not(a)) | (Not(a), Constant(true)) => { LinearCombination::zero() + a.get_variable() }, // !a - 0 = !a = 1 - a (Constant(false), Not(a)) | (Not(a), Constant(false)) => { LinearCombination::zero() + one - a.get_variable() }, // b - a, (Is(a), Is(b)) => LinearCombination::zero() + b.get_variable() - a.get_variable(), // !b - a = (1 - b) - a (Is(a), Not(b)) | (Not(b), Is(a)) => { LinearCombination::zero() + one - b.get_variable() - a.get_variable() }, // !b - !a = (1 - b) - (1 - a) = a - b, (Not(a), Not(b)) => LinearCombination::zero() + a.get_variable() - b.get_variable(), }; if let Constant(false) = condition { Ok(()) } else { cs.enforce( || "conditional_equals", |lc| difference + &lc, |lc| condition.lc(one, ConstraintF::one()) + &lc, |lc| lc, ); Ok(()) } } fn cost() -> usize { 1 } } impl<ConstraintF: Field> ToBytesGadget<ConstraintF> for Boolean { fn to_bytes<CS: ConstraintSystem<ConstraintF>>( &self, _cs: CS, ) -> Result<Vec<UInt8>, SynthesisError> { let mut bits = vec![Boolean::constant(false); 7]; bits.push(*self); bits.reverse(); let value = self.get_value().map(|val| val as u8); let byte = UInt8 { bits, value }; Ok(vec![byte]) } /// Additionally checks if the produced list of booleans is 'valid'. fn to_bytes_strict<CS: ConstraintSystem<ConstraintF>>( &self, cs: CS, ) -> Result<Vec<UInt8>, SynthesisError> { self.to_bytes(cs) } } #[cfg(test)] mod test { use super::{AllocatedBit, Boolean}; use crate::{prelude::*, test_constraint_system::TestConstraintSystem}; use algebra::{fields::bls12_381::Fr, BitIterator, Field, PrimeField, UniformRand}; use r1cs_core::ConstraintSystem; use rand::SeedableRng; use rand_xorshift::XorShiftRng; use std::str::FromStr; #[test] fn test_boolean_to_byte() { for val in [true, false].iter() { let mut cs = TestConstraintSystem::<Fr>::new(); let a: Boolean = AllocatedBit::alloc(&mut cs, || Ok(*val)).unwrap().into(); let bytes = a.to_bytes(&mut cs.ns(|| "ToBytes")).unwrap(); assert_eq!(bytes.len(), 1); let byte = &bytes[0]; assert_eq!(byte.value.unwrap(), *val as u8); for (i, bit_gadget) in byte.bits.iter().enumerate() { assert_eq!( bit_gadget.get_value().unwrap(), (byte.value.unwrap() >> i) & 1 == 1 ); } } } #[test] fn test_allocated_bit() { let mut cs = TestConstraintSystem::<Fr>::new(); AllocatedBit::alloc(&mut cs, || Ok(true)).unwrap(); assert!(cs.get("boolean") == Fr::one()); assert!(cs.is_satisfied()); cs.set("boolean", Fr::zero()); assert!(cs.is_satisfied()); cs.set("boolean", Fr::from_str("2").unwrap()); assert!(!cs.is_satisfied()); assert!(cs.which_is_unsatisfied() == Some("boolean constraint")); } #[test] fn test_xor() { for a_val in [false, true].iter() { for b_val in [false, true].iter() { let mut cs = TestConstraintSystem::<Fr>::new(); let a = AllocatedBit::alloc(cs.ns(|| "a"), || Ok(*a_val)).unwrap(); let b = AllocatedBit::alloc(cs.ns(|| "b"), || Ok(*b_val)).unwrap(); let c = AllocatedBit::xor(&mut cs, &a, &b).unwrap(); assert_eq!(c.value.unwrap(), *a_val ^ *b_val); assert!(cs.is_satisfied()); } } } #[test] fn test_or() { for a_val in [false, true].iter() { for b_val in [false, true].iter() { let mut cs = TestConstraintSystem::<Fr>::new(); let a = AllocatedBit::alloc(cs.ns(|| "a"), || Ok(*a_val)).unwrap(); let b = AllocatedBit::alloc(cs.ns(|| "b"), || Ok(*b_val)).unwrap(); let c = AllocatedBit::or(&mut cs, &a, &b).unwrap(); assert_eq!(c.value.unwrap(), *a_val | *b_val); assert!(cs.is_satisfied()); assert!(cs.get("a/boolean") == if *a_val { Field::one() } else { Field::zero() }); assert!(cs.get("b/boolean") == if *b_val { Field::one() } else { Field::zero() }); } } } #[test] fn test_and() { for a_val in [false, true].iter() { for b_val in [false, true].iter() { let mut cs = TestConstraintSystem::<Fr>::new(); let a = AllocatedBit::alloc(cs.ns(|| "a"), || Ok(*a_val)).unwrap(); let b = AllocatedBit::alloc(cs.ns(|| "b"), || Ok(*b_val)).unwrap(); let c = AllocatedBit::and(&mut cs, &a, &b).unwrap(); assert_eq!(c.value.unwrap(), *a_val & *b_val); assert!(cs.is_satisfied()); assert!(cs.get("a/boolean") == if *a_val { Field::one() } else { Field::zero() }); assert!(cs.get("b/boolean") == if *b_val { Field::one() } else { Field::zero() }); assert!( cs.get("and result") == if *a_val & *b_val { Field::one() } else { Field::zero() } ); // Invert the result and check if the constraint system is still satisfied cs.set( "and result", if *a_val & *b_val { Field::zero() } else { Field::one() }, ); assert!(!cs.is_satisfied()); } } } #[test] fn test_and_not() { for a_val in [false, true].iter() { for b_val in [false, true].iter() { let mut cs = TestConstraintSystem::<Fr>::new(); let a = AllocatedBit::alloc(cs.ns(|| "a"), || Ok(*a_val)).unwrap(); let b = AllocatedBit::alloc(cs.ns(|| "b"), || Ok(*b_val)).unwrap(); let c = AllocatedBit::and_not(&mut cs, &a, &b).unwrap(); assert_eq!(c.value.unwrap(), *a_val & !*b_val); assert!(cs.is_satisfied()); assert!(cs.get("a/boolean") == if *a_val { Field::one() } else { Field::zero() }); assert!(cs.get("b/boolean") == if *b_val { Field::one() } else { Field::zero() }); assert!( cs.get("and not result") == if *a_val & !*b_val { Field::one() } else { Field::zero() } ); // Invert the result and check if the constraint system is still satisfied cs.set( "and not result", if *a_val & !*b_val { Field::zero() } else { Field::one() }, ); assert!(!cs.is_satisfied()); } } } #[test] fn test_nor() { for a_val in [false, true].iter() { for b_val in [false, true].iter() { let mut cs = TestConstraintSystem::<Fr>::new(); let a = AllocatedBit::alloc(cs.ns(|| "a"), || Ok(*a_val)).unwrap(); let b = AllocatedBit::alloc(cs.ns(|| "b"), || Ok(*b_val)).unwrap(); let c = AllocatedBit::nor(&mut cs, &a, &b).unwrap(); assert_eq!(c.value.unwrap(), !*a_val & !*b_val); assert!(cs.is_satisfied()); assert!(cs.get("a/boolean") == if *a_val { Field::one() } else { Field::zero() }); assert!(cs.get("b/boolean") == if *b_val { Field::one() } else { Field::zero() }); assert!( cs.get("nor result") == if !*a_val & !*b_val { Field::one() } else { Field::zero() } ); // Invert the result and check if the constraint system is still satisfied cs.set( "nor result", if !*a_val & !*b_val { Field::zero() } else { Field::one() }, ); assert!(!cs.is_satisfied()); } } } #[test] fn test_enforce_equal() { for a_bool in [false, true].iter().cloned() { for b_bool in [false, true].iter().cloned() { for a_neg in [false, true].iter().cloned() { for b_neg in [false, true].iter().cloned() { let mut cs = TestConstraintSystem::<Fr>::new(); let mut a: Boolean = AllocatedBit::alloc(cs.ns(|| "a"), || Ok(a_bool)) .unwrap() .into(); let mut b: Boolean = AllocatedBit::alloc(cs.ns(|| "b"), || Ok(b_bool)) .unwrap() .into(); if a_neg { a = a.not(); } if b_neg { b = b.not(); } a.enforce_equal(&mut cs, &b).unwrap(); assert_eq!(cs.is_satisfied(), (a_bool ^ a_neg) == (b_bool ^ b_neg)); } } } } } #[test] fn test_conditional_enforce_equal() { for a_bool in [false, true].iter().cloned() { for b_bool in [false, true].iter().cloned() { for a_neg in [false, true].iter().cloned() { for b_neg in [false, true].iter().cloned() { let mut cs = TestConstraintSystem::<Fr>::new(); // First test if constraint system is satisfied // when we do want to enforce the condition. let mut a: Boolean = AllocatedBit::alloc(cs.ns(|| "a"), || Ok(a_bool)) .unwrap() .into(); let mut b: Boolean = AllocatedBit::alloc(cs.ns(|| "b"), || Ok(b_bool)) .unwrap() .into(); if a_neg { a = a.not(); } if b_neg { b = b.not(); } a.conditional_enforce_equal(&mut cs, &b, &Boolean::constant(true)) .unwrap(); assert_eq!(cs.is_satisfied(), (a_bool ^ a_neg) == (b_bool ^ b_neg)); // Now test if constraint system is satisfied even // when we don't want to enforce the condition. let mut cs = TestConstraintSystem::<Fr>::new(); let mut a: Boolean = AllocatedBit::alloc(cs.ns(|| "a"), || Ok(a_bool)) .unwrap() .into(); let mut b: Boolean = AllocatedBit::alloc(cs.ns(|| "b"), || Ok(b_bool)) .unwrap() .into(); if a_neg { a = a.not(); } if b_neg { b = b.not(); } let false_cond = AllocatedBit::alloc(cs.ns(|| "cond"), || Ok(false)) .unwrap() .into(); a.conditional_enforce_equal(&mut cs, &b, &false_cond) .unwrap(); assert!(cs.is_satisfied()); } } } } } #[test] fn test_boolean_negation() { let mut cs = TestConstraintSystem::<Fr>::new(); let mut b = Boolean::from(AllocatedBit::alloc(&mut cs, || Ok(true)).unwrap()); match b { Boolean::Is(_) => {}, _ => panic!("unexpected value"), } b = b.not(); match b { Boolean::Not(_) => {}, _ => panic!("unexpected value"), } b = b.not(); match b { Boolean::Is(_) => {}, _ => panic!("unexpected value"), } b = Boolean::constant(true); match b { Boolean::Constant(true) => {}, _ => panic!("unexpected value"), } b = b.not(); match b { Boolean::Constant(false) => {}, _ => panic!("unexpected value"), } b = b.not(); match b { Boolean::Constant(true) => {}, _ => panic!("unexpected value"), } } #[derive(Copy, Clone, Debug)] enum OperandType { True, False, AllocatedTrue, AllocatedFalse, NegatedAllocatedTrue, NegatedAllocatedFalse, } #[test] fn test_boolean_xor() { let variants = [ OperandType::True, OperandType::False, OperandType::AllocatedTrue, OperandType::AllocatedFalse, OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedFalse, ]; for first_operand in variants.iter().cloned() { for second_operand in variants.iter().cloned() { let mut cs = TestConstraintSystem::<Fr>::new(); let a; let b; { let mut dyn_construct = |operand, name| { let cs = cs.ns(|| name); match operand { OperandType::True => Boolean::constant(true), OperandType::False => Boolean::constant(false), OperandType::AllocatedTrue => { Boolean::from(AllocatedBit::alloc(cs, || Ok(true)).unwrap()) }, OperandType::AllocatedFalse => { Boolean::from(AllocatedBit::alloc(cs, || Ok(false)).unwrap()) }, OperandType::NegatedAllocatedTrue => { Boolean::from(AllocatedBit::alloc(cs, || Ok(true)).unwrap()).not() }, OperandType::NegatedAllocatedFalse => { Boolean::from(AllocatedBit::alloc(cs, || Ok(false)).unwrap()).not() }, } }; a = dyn_construct(first_operand, "a"); b = dyn_construct(second_operand, "b"); } let c = Boolean::xor(&mut cs, &a, &b).unwrap(); assert!(cs.is_satisfied()); match (first_operand, second_operand, c) { (OperandType::True, OperandType::True, Boolean::Constant(false)) => {}, (OperandType::True, OperandType::False, Boolean::Constant(true)) => {}, (OperandType::True, OperandType::AllocatedTrue, Boolean::Not(_)) => {}, (OperandType::True, OperandType::AllocatedFalse, Boolean::Not(_)) => {}, (OperandType::True, OperandType::NegatedAllocatedTrue, Boolean::Is(_)) => {}, (OperandType::True, OperandType::NegatedAllocatedFalse, Boolean::Is(_)) => {}, (OperandType::False, OperandType::True, Boolean::Constant(true)) => {}, (OperandType::False, OperandType::False, Boolean::Constant(false)) => {}, (OperandType::False, OperandType::AllocatedTrue, Boolean::Is(_)) => {}, (OperandType::False, OperandType::AllocatedFalse, Boolean::Is(_)) => {}, (OperandType::False, OperandType::NegatedAllocatedTrue, Boolean::Not(_)) => {}, (OperandType::False, OperandType::NegatedAllocatedFalse, Boolean::Not(_)) => {}, (OperandType::AllocatedTrue, OperandType::True, Boolean::Not(_)) => {}, (OperandType::AllocatedTrue, OperandType::False, Boolean::Is(_)) => {}, ( OperandType::AllocatedTrue, OperandType::AllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("xor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedTrue, OperandType::AllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("xor result") == Field::one()); assert_eq!(v.value, Some(true)); }, ( OperandType::AllocatedTrue, OperandType::NegatedAllocatedTrue, Boolean::Not(ref v), ) => { assert!(cs.get("xor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedTrue, OperandType::NegatedAllocatedFalse, Boolean::Not(ref v), ) => { assert!(cs.get("xor result") == Field::one()); assert_eq!(v.value, Some(true)); }, (OperandType::AllocatedFalse, OperandType::True, Boolean::Not(_)) => {}, (OperandType::AllocatedFalse, OperandType::False, Boolean::Is(_)) => {}, ( OperandType::AllocatedFalse, OperandType::AllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("xor result") == Field::one()); assert_eq!(v.value, Some(true)); }, ( OperandType::AllocatedFalse, OperandType::AllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("xor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedFalse, OperandType::NegatedAllocatedTrue, Boolean::Not(ref v), ) => { assert!(cs.get("xor result") == Field::one()); assert_eq!(v.value, Some(true)); }, ( OperandType::AllocatedFalse, OperandType::NegatedAllocatedFalse, Boolean::Not(ref v), ) => { assert!(cs.get("xor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, (OperandType::NegatedAllocatedTrue, OperandType::True, Boolean::Is(_)) => {}, (OperandType::NegatedAllocatedTrue, OperandType::False, Boolean::Not(_)) => {}, ( OperandType::NegatedAllocatedTrue, OperandType::AllocatedTrue, Boolean::Not(ref v), ) => { assert!(cs.get("xor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedTrue, OperandType::AllocatedFalse, Boolean::Not(ref v), ) => { assert!(cs.get("xor result") == Field::one()); assert_eq!(v.value, Some(true)); }, ( OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("xor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("xor result") == Field::one()); assert_eq!(v.value, Some(true)); }, (OperandType::NegatedAllocatedFalse, OperandType::True, Boolean::Is(_)) => {}, (OperandType::NegatedAllocatedFalse, OperandType::False, Boolean::Not(_)) => {}, ( OperandType::NegatedAllocatedFalse, OperandType::AllocatedTrue, Boolean::Not(ref v), ) => { assert!(cs.get("xor result") == Field::one()); assert_eq!(v.value, Some(true)); }, ( OperandType::NegatedAllocatedFalse, OperandType::AllocatedFalse, Boolean::Not(ref v), ) => { assert!(cs.get("xor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedFalse, OperandType::NegatedAllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("xor result") == Field::one()); assert_eq!(v.value, Some(true)); }, ( OperandType::NegatedAllocatedFalse, OperandType::NegatedAllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("xor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, _ => panic!("this should never be encountered"), } } } } #[test] fn test_boolean_or() { let variants = [ OperandType::True, OperandType::False, OperandType::AllocatedTrue, OperandType::AllocatedFalse, OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedFalse, ]; for first_operand in variants.iter().cloned() { for second_operand in variants.iter().cloned() { let mut cs = TestConstraintSystem::<Fr>::new(); let a; let b; { let mut dyn_construct = |operand, name| { let cs = cs.ns(|| name); match operand { OperandType::True => Boolean::constant(true), OperandType::False => Boolean::constant(false), OperandType::AllocatedTrue => { Boolean::from(AllocatedBit::alloc(cs, || Ok(true)).unwrap()) }, OperandType::AllocatedFalse => { Boolean::from(AllocatedBit::alloc(cs, || Ok(false)).unwrap()) }, OperandType::NegatedAllocatedTrue => { Boolean::from(AllocatedBit::alloc(cs, || Ok(true)).unwrap()).not() }, OperandType::NegatedAllocatedFalse => { Boolean::from(AllocatedBit::alloc(cs, || Ok(false)).unwrap()).not() }, } }; a = dyn_construct(first_operand, "a"); b = dyn_construct(second_operand, "b"); } let c = Boolean::or(&mut cs, &a, &b).unwrap(); assert!(cs.is_satisfied()); match (first_operand, second_operand, c) { (OperandType::True, OperandType::True, Boolean::Constant(true)) => {}, (OperandType::True, OperandType::False, Boolean::Constant(true)) => {}, (OperandType::True, OperandType::AllocatedTrue, Boolean::Constant(true)) => {}, (OperandType::True, OperandType::AllocatedFalse, Boolean::Constant(true)) => {}, ( OperandType::True, OperandType::NegatedAllocatedTrue, Boolean::Constant(true), ) => {}, ( OperandType::True, OperandType::NegatedAllocatedFalse, Boolean::Constant(true), ) => {}, (OperandType::False, OperandType::True, Boolean::Constant(true)) => {}, (OperandType::False, OperandType::False, Boolean::Constant(false)) => {}, (OperandType::False, OperandType::AllocatedTrue, Boolean::Is(_)) => {}, (OperandType::False, OperandType::AllocatedFalse, Boolean::Is(_)) => {}, (OperandType::False, OperandType::NegatedAllocatedTrue, Boolean::Not(_)) => {}, (OperandType::False, OperandType::NegatedAllocatedFalse, Boolean::Not(_)) => {}, (OperandType::AllocatedTrue, OperandType::True, Boolean::Constant(true)) => {}, (OperandType::AllocatedTrue, OperandType::False, Boolean::Is(_)) => {}, ( OperandType::AllocatedTrue, OperandType::AllocatedTrue, Boolean::Is(ref v), ) => { assert_eq!(v.value, Some(true)); }, ( OperandType::AllocatedTrue, OperandType::AllocatedFalse, Boolean::Is(ref v), ) => { assert_eq!(v.value, Some(true)); }, ( OperandType::AllocatedTrue, OperandType::NegatedAllocatedTrue, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedTrue, OperandType::NegatedAllocatedFalse, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, (OperandType::AllocatedFalse, OperandType::True, Boolean::Constant(true)) => {}, (OperandType::AllocatedFalse, OperandType::False, Boolean::Is(_)) => {}, ( OperandType::AllocatedFalse, OperandType::AllocatedTrue, Boolean::Is(ref v), ) => { assert_eq!(v.value, Some(true)); }, ( OperandType::AllocatedFalse, OperandType::AllocatedFalse, Boolean::Is(ref v), ) => { assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedFalse, OperandType::NegatedAllocatedTrue, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(true)); }, ( OperandType::AllocatedFalse, OperandType::NegatedAllocatedFalse, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedTrue, OperandType::True, Boolean::Constant(true), ) => {}, (OperandType::NegatedAllocatedTrue, OperandType::False, Boolean::Not(_)) => {}, ( OperandType::NegatedAllocatedTrue, OperandType::AllocatedTrue, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedTrue, OperandType::AllocatedFalse, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(true)); }, ( OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedTrue, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(true)); }, ( OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedFalse, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedFalse, OperandType::True, Boolean::Constant(true), ) => {}, (OperandType::NegatedAllocatedFalse, OperandType::False, Boolean::Not(_)) => {}, ( OperandType::NegatedAllocatedFalse, OperandType::AllocatedTrue, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedFalse, OperandType::AllocatedFalse, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedFalse, OperandType::NegatedAllocatedTrue, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedFalse, OperandType::NegatedAllocatedFalse, Boolean::Not(ref v), ) => { assert_eq!(v.value, Some(false)); }, _ => panic!( "this should never be encountered, in case: (a = {:?}, b = {:?}, c = {:?})", a, b, c ), } } } } #[test] fn test_boolean_and() { let variants = [ OperandType::True, OperandType::False, OperandType::AllocatedTrue, OperandType::AllocatedFalse, OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedFalse, ]; for first_operand in variants.iter().cloned() { for second_operand in variants.iter().cloned() { let mut cs = TestConstraintSystem::<Fr>::new(); let a; let b; { let mut dyn_construct = |operand, name| { let cs = cs.ns(|| name); match operand { OperandType::True => Boolean::constant(true), OperandType::False => Boolean::constant(false), OperandType::AllocatedTrue => { Boolean::from(AllocatedBit::alloc(cs, || Ok(true)).unwrap()) }, OperandType::AllocatedFalse => { Boolean::from(AllocatedBit::alloc(cs, || Ok(false)).unwrap()) }, OperandType::NegatedAllocatedTrue => { Boolean::from(AllocatedBit::alloc(cs, || Ok(true)).unwrap()).not() }, OperandType::NegatedAllocatedFalse => { Boolean::from(AllocatedBit::alloc(cs, || Ok(false)).unwrap()).not() }, } }; a = dyn_construct(first_operand, "a"); b = dyn_construct(second_operand, "b"); } let c = Boolean::and(&mut cs, &a, &b).unwrap(); assert!(cs.is_satisfied()); match (first_operand, second_operand, c) { (OperandType::True, OperandType::True, Boolean::Constant(true)) => {}, (OperandType::True, OperandType::False, Boolean::Constant(false)) => {}, (OperandType::True, OperandType::AllocatedTrue, Boolean::Is(_)) => {}, (OperandType::True, OperandType::AllocatedFalse, Boolean::Is(_)) => {}, (OperandType::True, OperandType::NegatedAllocatedTrue, Boolean::Not(_)) => {}, (OperandType::True, OperandType::NegatedAllocatedFalse, Boolean::Not(_)) => {}, (OperandType::False, OperandType::True, Boolean::Constant(false)) => {}, (OperandType::False, OperandType::False, Boolean::Constant(false)) => {}, (OperandType::False, OperandType::AllocatedTrue, Boolean::Constant(false)) => { }, (OperandType::False, OperandType::AllocatedFalse, Boolean::Constant(false)) => { }, ( OperandType::False, OperandType::NegatedAllocatedTrue, Boolean::Constant(false), ) => {}, ( OperandType::False, OperandType::NegatedAllocatedFalse, Boolean::Constant(false), ) => {}, (OperandType::AllocatedTrue, OperandType::True, Boolean::Is(_)) => {}, (OperandType::AllocatedTrue, OperandType::False, Boolean::Constant(false)) => { }, ( OperandType::AllocatedTrue, OperandType::AllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("and result") == Field::one()); assert_eq!(v.value, Some(true)); }, ( OperandType::AllocatedTrue, OperandType::AllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("and result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedTrue, OperandType::NegatedAllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("and not result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedTrue, OperandType::NegatedAllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("and not result") == Field::one()); assert_eq!(v.value, Some(true)); }, (OperandType::AllocatedFalse, OperandType::True, Boolean::Is(_)) => {}, (OperandType::AllocatedFalse, OperandType::False, Boolean::Constant(false)) => { }, ( OperandType::AllocatedFalse, OperandType::AllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("and result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedFalse, OperandType::AllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("and result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedFalse, OperandType::NegatedAllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("and not result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::AllocatedFalse, OperandType::NegatedAllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("and not result") == Field::zero()); assert_eq!(v.value, Some(false)); }, (OperandType::NegatedAllocatedTrue, OperandType::True, Boolean::Not(_)) => {}, ( OperandType::NegatedAllocatedTrue, OperandType::False, Boolean::Constant(false), ) => {}, ( OperandType::NegatedAllocatedTrue, OperandType::AllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("and not result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedTrue, OperandType::AllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("and not result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("nor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedTrue, OperandType::NegatedAllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("nor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, (OperandType::NegatedAllocatedFalse, OperandType::True, Boolean::Not(_)) => {}, ( OperandType::NegatedAllocatedFalse, OperandType::False, Boolean::Constant(false), ) => {}, ( OperandType::NegatedAllocatedFalse, OperandType::AllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("and not result") == Field::one()); assert_eq!(v.value, Some(true)); }, ( OperandType::NegatedAllocatedFalse, OperandType::AllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("and not result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedFalse, OperandType::NegatedAllocatedTrue, Boolean::Is(ref v), ) => { assert!(cs.get("nor result") == Field::zero()); assert_eq!(v.value, Some(false)); }, ( OperandType::NegatedAllocatedFalse, OperandType::NegatedAllocatedFalse, Boolean::Is(ref v), ) => { assert!(cs.get("nor result") == Field::one()); assert_eq!(v.value, Some(true)); }, _ => { panic!( "unexpected behavior at {:?} AND {:?}", first_operand, second_operand ); }, } } } } #[test] fn test_enforce_in_field() { { let mut cs = TestConstraintSystem::<Fr>::new(); let mut bits = vec![]; for (i, b) in BitIterator::new(Fr::characteristic()).skip(1).enumerate() { bits.push(Boolean::from( AllocatedBit::alloc(cs.ns(|| format!("bit_gadget {}", i)), || Ok(b)).unwrap(), )); } Boolean::enforce_in_field::<_, _, Fr>(&mut cs, &bits).unwrap(); assert!(!cs.is_satisfied()); } let mut rng = XorShiftRng::seed_from_u64(1231275789u64); for _ in 0..1000 { let r = Fr::rand(&mut rng); let mut cs = TestConstraintSystem::<Fr>::new(); let mut bits = vec![]; for (i, b) in BitIterator::new(r.into_repr()).skip(1).enumerate() { bits.push(Boolean::from( AllocatedBit::alloc(cs.ns(|| format!("bit_gadget {}", i)), || Ok(b)).unwrap(), )); } Boolean::enforce_in_field::<_, _, Fr>(&mut cs, &bits).unwrap(); assert!(cs.is_satisfied()); } // for _ in 0..1000 { // // Sample a random element not in the field // let r = loop { // let mut a = Fr::rand(&mut rng).into_repr(); // let b = Fr::rand(&mut rng).into_repr(); // a.add_nocarry(&b); // // we're shaving off the high bit_gadget later // a.as_mut()[3] &= 0x7fffffffffffffff; // if Fr::from_repr(a).is_err() { // break a; // } // }; // let mut cs = TestConstraintSystem::<Fr>::new(); // let mut bits = vec![]; // for (i, b) in BitIterator::new(r).skip(1).enumerate() { // bits.push(Boolean::from( // AllocatedBit::alloc(cs.ns(|| format!("bit_gadget {}", // i)), Some(b)) .unwrap(), // )); // } // Boolean::enforce_in_field::<_, _, Fr>(&mut cs, &bits).unwrap(); // assert!(!cs.is_satisfied()); // } } #[test] fn test_enforce_nand() { { let mut cs = TestConstraintSystem::<Fr>::new(); assert!(Boolean::enforce_nand(&mut cs, &[Boolean::constant(false)]).is_ok()); assert!(Boolean::enforce_nand(&mut cs, &[Boolean::constant(true)]).is_err()); } for i in 1..5 { // with every possible assignment for them for mut b in 0..(1 << i) { // with every possible negation for mut n in 0..(1 << i) { let mut cs = TestConstraintSystem::<Fr>::new(); let mut expected = true; let mut bits = vec![]; for j in 0..i { expected &= b & 1 == 1; if n & 1 == 1 { bits.push(Boolean::from( AllocatedBit::alloc(cs.ns(|| format!("bit_gadget {}", j)), || { Ok(b & 1 == 1) }) .unwrap(), )); } else { bits.push( Boolean::from( AllocatedBit::alloc( cs.ns(|| format!("bit_gadget {}", j)), || Ok(b & 1 == 0), ) .unwrap(), ) .not(), ); } b >>= 1; n >>= 1; } let expected = !expected; Boolean::enforce_nand(&mut cs, &bits).unwrap(); if expected { assert!(cs.is_satisfied()); } else { assert!(!cs.is_satisfied()); } } } } } #[test] fn test_kary_and() { // test different numbers of operands for i in 1..15 { // with every possible assignment for them for mut b in 0..(1 << i) { let mut cs = TestConstraintSystem::<Fr>::new(); let mut expected = true; let mut bits = vec![]; for j in 0..i { expected &= b & 1 == 1; bits.push(Boolean::from( AllocatedBit::alloc(cs.ns(|| format!("bit_gadget {}", j)), || { Ok(b & 1 == 1) }) .unwrap(), )); b >>= 1; } let r = Boolean::kary_and(&mut cs, &bits).unwrap(); assert!(cs.is_satisfied()); match r { Boolean::Is(ref r) => { assert_eq!(r.value.unwrap(), expected); }, _ => unreachable!(), } } } } }
&self) ->
test_locks.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from time import sleep import unittest from azure.cli.testsdk import ScenarioTest, JMESPathCheck, ResourceGroupPreparer, record_only from azure.cli.command_modules.resource.custom import _parse_lock_id class ResourceLockTests(ScenarioTest):
def test_list_locks(self): # just make sure this doesn't throw self.cmd('az lock list').get_output_in_json() @record_only() def test_subscription_locks(self): for lock_type in ['ReadOnly', 'CanNotDelete']: lock_name = self.create_random_name('cli-test-lock', 48) lock = self.cmd('az lock create -n {} --lock-type {}'.format(lock_name, lock_type)).get_output_in_json() lock_id = lock.get('id') self._sleep_for_lock_operation() locks_list = self.cmd('az lock list').get_output_in_json() self.assertTrue(locks_list) self.assertIn(lock_name, [l['name'] for l in locks_list]) lock = self.cmd('az lock show -n {}'.format(lock_name)).get_output_in_json() lock_from_id = self.cmd('az lock show --ids {}'.format(lock_id)).get_output_in_json() self.assertEqual(lock.get('name', None), lock_name) self.assertEqual(lock_from_id.get('name', None), lock_name) self.assertEqual(lock.get('level', None), lock_type) notes = self.create_random_name('notes', 20) new_lvl = 'ReadOnly' if lock_type == 'CanNotDelete' else 'CanNotDelete' lock = self.cmd('az lock update -n {} --notes {} --lock-type {}' .format(lock_name, notes, new_lvl)).get_output_in_json() self.assertEqual(lock.get('notes', None), notes) self.assertEqual(lock.get('level', None), new_lvl) lock = self.cmd('az lock update --ids {} --lock-type {}' .format(lock_id, lock_type)).get_output_in_json() self.assertEqual(lock.get('level', None), lock_type) self.cmd('az lock delete -n {}'.format(lock_name)) self._sleep_for_lock_operation() @ResourceGroupPreparer(name_prefix='cli_test_readonly_resource_group_lock') def test_readonly_resource_group_lock(self, resource_group): self._lock_operation_with_resource_group('ReadOnly', resource_group) @ResourceGroupPreparer(name_prefix='cli_test_cannotdelete_resource_group_lock') def test_cannotdelete_resource_group_lock(self, resource_group): self._lock_operation_with_resource_group('CanNotDelete', resource_group) @ResourceGroupPreparer(name_prefix='cli_test_readonly_resource_lock') def test_readonly_resource_lock(self, resource_group): self._lock_operation_with_resource('ReadOnly', resource_group) @ResourceGroupPreparer(name_prefix='cli_test_cannotdelete_resource_lock') def test_cannotdelete_resource_lock(self, resource_group): self._lock_operation_with_resource('CanNotDelete', resource_group) def _lock_operation_with_resource_group(self, lock_type, resource_group): lock_name = self.create_random_name('cli-test-lock', 48) self.cmd('az lock create -n {} -g {} --lock-type {}'.format(lock_name, resource_group, lock_type)) self._sleep_for_lock_operation() self.cmd('az lock show -g {} -n {}'.format(resource_group, lock_name)).assert_with_checks([ JMESPathCheck('name', lock_name), JMESPathCheck('level', lock_type)]) locks_list = self.cmd("az lock list -g {} --query '[].name' -ojson".format(resource_group)).get_output_in_json() self.assertTrue(locks_list) self.assertIn(lock_name, locks_list) notes = self.create_random_name('notes', 20) new_lvl = 'ReadOnly' if lock_type == 'CanNotDelete' else 'CanNotDelete' lock = self.cmd('az lock update -n {} -g {} --notes {} --lock-type {}' .format(lock_name, resource_group, notes, new_lvl)).get_output_in_json() self.assertEqual(lock.get('notes', None), notes) self.assertEqual(lock.get('level', None), new_lvl) self.cmd('az lock delete -g {} -n {}'.format(resource_group, lock_name)) self._sleep_for_lock_operation() def _lock_operation_with_resource(self, lock_type, resource_group): rsrc_name = self.create_random_name('cli.lock.rsrc', 30) rsrc_type = 'Microsoft.Network/virtualNetworks' lock_name = self.create_random_name('cli-test-lock', 74) self.cmd('az network vnet create -n {} -g {}'.format(rsrc_name, resource_group)) self.cmd('az lock create -n {} -g {} --resource-type {} --resource-name {} --lock-type {}' .format(lock_name, resource_group, rsrc_type, rsrc_name, lock_type)) self._sleep_for_lock_operation() self.cmd('az lock show --name {} -g {} --resource-type {} --resource-name {}' .format(lock_name, resource_group, rsrc_type, rsrc_name)).assert_with_checks([ JMESPathCheck('name', lock_name), JMESPathCheck('level', lock_type)]) locks_list = self.cmd("az lock list --query '[].name' -ojson").get_output_in_json() self.assertTrue(locks_list) self.assertIn(lock_name, locks_list) notes = self.create_random_name('notes', 20) new_lvl = 'ReadOnly' if lock_type == 'CanNotDelete' else 'CanNotDelete' lock = self.cmd('az lock update -n {} -g {} --resource-type {} --resource-name {} --notes {} --lock-type {}' .format(lock_name, resource_group, rsrc_type, rsrc_name, notes, new_lvl)).get_output_in_json() self.assertEqual(lock.get('notes', None), notes) self.assertEqual(lock.get('level', None), new_lvl) self.cmd('az lock delete --name {} -g {} --resource-name {} --resource-type {}' .format(lock_name, resource_group, rsrc_name, rsrc_type)) self._sleep_for_lock_operation() @ResourceGroupPreparer(name_prefix='cli_test_group_lock') def test_group_lock_commands(self, resource_group): lock_name = self.create_random_name('cli-test-lock', 48) self.cmd('group lock create -n {} -g {} --lock-type CanNotDelete'.format(lock_name, resource_group)) self._sleep_for_lock_operation() self.cmd('group lock show -g {} -n {}'.format(resource_group, lock_name)).assert_with_checks([ JMESPathCheck('name', lock_name), JMESPathCheck('level', 'CanNotDelete')]).get_output_in_json() locks_list = self.cmd("group lock list -g {} --query [].name -ojson" .format(resource_group)).get_output_in_json() self.assertTrue(locks_list) self.assertIn(lock_name, locks_list) notes = self.create_random_name('notes', 20) lock = self.cmd('group lock update -n {} -g {} --notes {} --lock-type ReadOnly' .format(lock_name, resource_group, notes)).get_output_in_json() self.assertEqual(lock.get('notes', None), notes) self.assertEqual(lock.get('level', None), 'ReadOnly') self.cmd('group lock delete -g {} -n {}'.format(resource_group, lock_name)) self._sleep_for_lock_operation() @ResourceGroupPreparer(name_prefix='cli_test_resource_lock') def test_resource_lock_commands(self, resource_group): rsrc_name = self.create_random_name('cli.lock.rsrc', 30) rsrc_type = 'Microsoft.Network/virtualNetworks' lock_name = self.create_random_name('cli-test-lock', 74) lock_type = 'CanNotDelete' self.cmd('network vnet create -n {} -g {}'.format(rsrc_name, resource_group)) self.cmd('resource lock create -n {} -g {} --resource-type {} --resource-name {} --lock-type {}' .format(lock_name, resource_group, rsrc_type, rsrc_name, lock_type)) self._sleep_for_lock_operation() self.cmd('resource lock show --name {} -g {} --resource-type {} --resource-name {}' .format(lock_name, resource_group, rsrc_type, rsrc_name)).assert_with_checks([ JMESPathCheck('name', lock_name), JMESPathCheck('level', lock_type)]) list_cmd = "resource lock list -g {} --resource-type {} --resource-name {} " \ "--query [].name -ojson".format(resource_group, rsrc_type, rsrc_name) locks_list = self.cmd(list_cmd).get_output_in_json() self.assertTrue(locks_list) self.assertIn(lock_name, locks_list) notes = self.create_random_name('notes', 20) lock = self.cmd('resource lock update -n {} -g {} --resource-type {} --resource-name {} --notes {} ' '--lock-type ReadOnly' .format(lock_name, resource_group, rsrc_type, rsrc_name, notes)).get_output_in_json() self.assertEqual(lock.get('notes', None), notes) self.assertEqual(lock.get('level', None), 'ReadOnly') self.cmd('resource lock delete --name {} -g {} --resource-name {} --resource-type {}' .format(lock_name, resource_group, rsrc_name, rsrc_type)) self._sleep_for_lock_operation() @record_only() def test_subscription_locks(self): lock_name = self.create_random_name('cli-test-lock', 48) lock = self.cmd('az account lock create -n {} --lock-type CanNotDelete'.format(lock_name)).get_output_in_json() lock_id = lock.get('id') locks_list = self.cmd('az account lock list --query [].name').get_output_in_json() self.assertTrue(locks_list) self.assertIn(lock_name, locks_list) lock = self.cmd('az account lock show -n {}'.format(lock_name)).get_output_in_json() lock_from_id = self.cmd('az account lock show --ids {}'.format(lock_id)).get_output_in_json() self.assertEqual(lock.get('name', None), lock_name) self.assertEqual(lock_from_id.get('name', None), lock_name) self.assertEqual(lock.get('level', None), 'CanNotDelete') notes = self.create_random_name('notes', 20) lock = self.cmd('az account lock update -n {} --notes {} --lock-type {}' .format(lock_name, notes, 'ReadOnly')).get_output_in_json() self.assertEqual(lock.get('notes', None), notes) self.assertEqual(lock.get('level', None), 'ReadOnly') lock = self.cmd('az account lock update --ids {} --lock-type {}' .format(lock_id, 'CanNotDelete')).get_output_in_json() self.assertEqual(lock.get('level', None), 'CanNotDelete') self.cmd('az account lock delete -n {}'.format(lock_name)) @ResourceGroupPreparer(name_prefix='cli_test_lock_commands_with_ids') def test_lock_commands_with_ids(self, resource_group): vnet_name = self.create_random_name('cli-lock-vnet', 30) subnet_name = self.create_random_name('cli-lock-subnet', 30) group_lock_name = self.create_random_name('cli-test-lock', 50) vnet_lock_name = self.create_random_name('cli-test-lock', 50) subnet_lock_name = self.create_random_name('cli-test-lock', 20) vnet = self.cmd('az network vnet create -n {} -g {}'.format(vnet_name, resource_group)).get_output_in_json() subnetaddress = vnet.get('newVNet').get('addressSpace').get('addressPrefixes')[0] self.cmd('az network vnet subnet create -n {} --address-prefix {} --vnet-name {} -g {}' .format(subnet_name, subnetaddress, vnet_name, resource_group)) locks = [] locks.append(self.cmd('az lock create -n {} -g {} --lock-type CanNotDelete' .format(group_lock_name, resource_group)).get_output_in_json()) locks.append(self.cmd('az lock create -n {} -g {} --resource-type Microsoft.Network/virtualNetworks' ' --resource-name {} --lock-type CanNotDelete' .format(vnet_lock_name, resource_group, vnet_name)).get_output_in_json()) locks.append(self.cmd('az lock create -n {} -g {} --resource-name {} --resource-type subnets ' '--namespace Microsoft.Network --parent virtualNetworks/{} --lock-type CanNotDelete' .format(subnet_lock_name, resource_group, subnet_name, vnet_name)).get_output_in_json()) self._sleep_for_lock_operation() space_delimited_ids = ' '.join([lock.get('id', None) for lock in locks]) my_locks = self.cmd('az lock show --ids {} --query [].name'.format(space_delimited_ids)).get_output_in_json() self.assertTrue(len(my_locks) == 3) for lock in my_locks: self.assertIn(lock, [group_lock_name, vnet_lock_name, subnet_lock_name]) my_locks = self.cmd('az lock update --ids {} --notes somenotes --lock-type ReadOnly' .format(space_delimited_ids)).get_output_in_json() self.assertTrue(len(my_locks) == 3) for lock in my_locks: self.assertEqual(lock.get('notes', None), 'somenotes') self.assertEqual(lock.get('level', None), 'ReadOnly') self.cmd('az lock delete --ids {}'.format(space_delimited_ids)) self._sleep_for_lock_operation() my_locks = self.cmd("az lock list -g {} -ojson".format(resource_group)).get_output_in_json() self.assertFalse(my_locks) def _sleep_for_lock_operation(self): if self.is_live: sleep(5) class ParseIdTests(unittest.TestCase): def test_parsing_lock_ids(self): tests = [ { 'input': "/subscriptions/subId/providers/" "Microsoft.Authorization/locks/sublock", 'expected': { 'resource_group': None, 'resource_provider_namespace': None, 'parent_resource_path': None, 'resource_type': None, 'resource_name': None, 'lock_name': 'sublock' } }, { 'input': "/subscriptions/subId/resourceGroups/examplegroup/providers/" "Microsoft.Authorization/locks/grouplock", 'expected': { 'resource_group': 'examplegroup', 'resource_provider_namespace': None, 'parent_resource_path': None, 'resource_type': None, 'resource_name': None, 'lock_name': 'grouplock' } }, { 'input': "/subscriptions/subId/resourcegroups/mygroup/providers/" "Microsoft.Network/virtualNetworks/myvnet/providers/" "Microsoft.Authorization/locks/vnetlock", 'expected': { 'resource_group': 'mygroup', 'resource_provider_namespace': 'Microsoft.Network', 'parent_resource_path': None, 'resource_type': 'virtualNetworks', 'resource_name': 'myvnet', 'lock_name': 'vnetlock' } }, { 'input': "/subscriptions/subId/resourceGroups/mygroup/providers/" "Microsoft.Network/virtualNetworks/myvnet/subnets/subnet/providers/" "Microsoft.Authorization/locks/subnetlock", 'expected': { 'resource_group': 'mygroup', 'resource_provider_namespace': 'Microsoft.Network', 'parent_resource_path': 'virtualNetworks/myvnet', 'resource_type': 'subnets', 'resource_name': 'subnet', 'lock_name': 'subnetlock' } }, { 'input': "/subscriptions/subId/resourceGroups/mygroup/providers/" "Microsoft.Provider1/resourceType1/name1/providers/" "Microsoft.Provider2/resourceType2/name2/providers/" "Microsoft.Authorization/locks/somelock", 'expected': { 'resource_group': 'mygroup', 'resource_provider_namespace': 'Microsoft.Provider1', 'parent_resource_path': 'resourceType1/name1/providers/Microsoft.Provider2', 'resource_type': 'resourceType2', 'resource_name': 'name2', 'lock_name': 'somelock' } } ] for test in tests: kwargs = _parse_lock_id(test['input']) self.assertDictEqual(kwargs, test['expected']) fail_tests = [ "/notsubscriptions/subId/providers/Microsoft.Authorization/locks/sublock", "/subscriptions/subId/notResourceGroups/examplegroup/providers/Microsoft.Authorization/locks/grouplock", "/subscriptions/subId/resourceGroups/examplegroup/providers/Microsoft.NotAuthorization/not_locks/grouplock", "/subscriptions/subId/resourcegroups/mygroup/Microsoft.Network/virtualNetworks/myvnet/providers/" "Microsoft.Authorization/locks/missingProvidersLock", "/subscriptions/subId/resourcegroups/mygroup/providers/Microsoft.Network/myvnet/providers/" "Microsoft.Authorization/locks/missingRsrcTypeLock", "/subscriptions/subId/providers/Microsoft.Network/virtualNetworks/myvnet/subnets/subnet/providers/" "Microsoft.Authorization/locks/missingRsrcGroupLock", "not_a_id_at_all" ] for test in fail_tests: with self.assertRaises(AttributeError): _parse_lock_id(test) if __name__ == '__main__': unittest.main()
TabRegister.js
import React, { useEffect, useState } from 'react'; import Input from './Input'; import Radio from './Radio'; import DropDown from './DropDown'; import { generatorArrayDays, generatorArrayMonths, generatorArrayYears } from '../initialize/generator'; const AR_GENDER = [ { "className": "input__radio circle__radio", "value": "male", "label": "Nam", "id": "male", "name": "gender" }, { "className": "input__radio circle__radio", "value": "female", "label": "Nữ", "id": "female", "name": "gender" } ] const AR_ROLE = [ { "className": "input__radio career__radio", "value": "owner", "label": "Chủ nhà thuốc", "id": "owner", "name": "role" }, { "className": "input__radio career__radio", "value": "staff", "label": "Nhân viên bán thuốc", "id": "staff", "name": "role" } ] function RadioList({
kedVal, array }) { let list = array.map((val, index) => { return ( <Radio key={index} fnc={fnc} checked={checkedVal === val.value} className={val.className} id={val.id} label={val.label} val={val.value} name={val.name} /> ) }) return list; } const TabRegister = ({ register, setRole, setGender, setFullname, setPhone, setBirthDay, setBirthMonth, setBirthYear, submit, loading }) => { const [isError, setError] = useState(false); const { fullname, phone, gender, role, birthday, error } = register; const day = { text: birthday.day === "" ? "Ngày" : birthday.day, value: birthday.day }; const month = { text: birthday.month === "" ? "Tháng" : birthday.month, value: birthday.month }; const year = { text: birthday.year === "" ? "Năm" : birthday.year, value: birthday.year }; const classLoading = loading ? "load-screen active" : "load-screen"; useEffect(() => { let timeout; if (isError && !loading) { timeout = setTimeout(() => { setError(false); clearTimeout(timeout) }, 2000); } return function cleanup(){ // unsubscribe when componentWillUnmount /**/ clearTimeout(timeout); } }, [register, loading]); const submitFn = () => { submit(register); if (!isError) { setError(true); } } return ( <article className="registration__holder register active content__article"> <p className="reminder"> NẾU BẠN ĐÃ TẠO TÀI KHOẢN,<br /> VUI LÒNG BẤM <span className="reminder--login" id="reminder-login">ĐĂNG NHẬP.</span> </p> <div className="inline__block career"> <span>Bạn là</span> <RadioList fnc={setRole} checkedVal={role} array={AR_ROLE} /> </div> <div className="inline__block gender"> <RadioList fnc={setGender} checkedVal={gender} array={AR_GENDER} /> </div> <div className="block fullname"> <p className="field__label">HỌ VÀ TÊN <span className="asterisk">*</span></p> <Input className="field__input" fnc={setFullname} val={fullname} placeholder="" /> </div> <div className="block dob"> <p className="field__label">NGÀY/THÁNG/NĂM SINH<span className="asterisk">*</span></p> <div className="dob__day dropdown"> <DropDown array={generatorArrayDays()} onClick={setBirthDay} value={day} /> </div> <div className="dob__month dropdown"> <DropDown array={generatorArrayMonths()} onClick={setBirthMonth} value={month} /> </div> <div className="dob__year dropdown"> <DropDown array={generatorArrayYears()} onClick={setBirthYear} value={year} /> </div> </div> <div className="block fullname"> <p className="field__label">SỐ ĐIỆN THOẠI <span className="asterisk">*</span></p> <Input className="field__input" fnc={setPhone} val={phone} placeholder="" /> </div> <p className="error__message" style={{ "opacity": isError ? "1" : 0 }}>{error ? error : " "}</p> <button className="submit__button green__button submit__button--register" id="register-button" onClick={ submitFn }> <p className="core">TIẾP TỤC</p> </button> <div className={classLoading}> <div className="load-circle active"></div> </div> </article> ); } export default TabRegister;
fnc, chec
reference_test.go
/** * Copyright (C) 2015 Red Hat, 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. */ // Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) // // 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. // author sigu-399 // author-github https://github.com/sigu-399 // author-mail [email protected] // // repository-name jsonreference // repository-desc An implementation of JSON Reference - Go language // // description Automated tests on package. // // created 03-03-2013 package jsonreference import ( "testing" "github.com/go-openapi/jsonpointer" "github.com/stretchr/testify/assert" ) func TestIsRoot(t *testing.T) { in := "#" r1, err := New(in) assert.NoError(t, err) assert.True(t, r1.IsRoot()) in = "#/ok" r1 = MustCreateRef(in) assert.False(t, r1.IsRoot()) assert.Panics(t, assert.PanicTestFunc(func() { MustCreateRef("%2") })) } func TestFull(t *testing.T) { in := "http://host/path/a/b/c#/f/a/b" r1, err := New(in) if err != nil { t.Errorf("New(%v) error %s", in, err.Error()) } if in != r1.String() { t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) } if r1.HasFragmentOnly != false { t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) } if r1.HasFullURL != true { t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true) } if r1.HasURLPathOnly != false { t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) } if r1.HasFileScheme != false { t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) } if r1.GetPointer().String() != "/f/a/b" { t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/f/a/b") } } func TestFullURL(t *testing.T) { in := "http://host/path/a/b/c" r1, err := New(in) if err != nil { t.Errorf("New(%v) error %s", in, err.Error()) } if in != r1.String() { t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) } if r1.HasFragmentOnly != false { t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) } if r1.HasFullURL != true { t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true) } if r1.HasURLPathOnly != false { t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) } if r1.HasFileScheme != false { t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) } if r1.GetPointer().String() != "" { t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") } } func TestFragmentOnly(t *testing.T) { in := "#/fragment/only" r1, err := New(in) if err != nil { t.Errorf("New(%v) error %s", in, err.Error()) } if in != r1.String() { t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) } if r1.HasFragmentOnly != true { t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, true) } if r1.HasFullURL != false { t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) } if r1.HasURLPathOnly != false { t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) } if r1.HasFileScheme != false { t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) } if r1.GetPointer().String() != "/fragment/only" { t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/fragment/only") } p, _ := jsonpointer.New(r1.referenceURL.Fragment) r2 := Ref{referencePointer: p, HasFragmentOnly: true} assert.Equal(t, r2.String(), in) r3 := Ref{referencePointer: p, HasFragmentOnly: false} assert.Equal(t, r3.String(), in[1:]) } func TestURLPathOnly(t *testing.T) { in := "/documents/document.json" r1, err := New(in) if err != nil { t.Errorf("New(%v) error %s", in, err.Error()) } if in != r1.String() { t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) } if r1.HasFragmentOnly != false { t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) } if r1.HasFullURL != false { t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) } if r1.HasURLPathOnly != true { t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true) } if r1.HasFileScheme != false { t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) } if r1.GetPointer().String() != "" { t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") } } func TestURLRelativePathOnly(t *testing.T) { in := "document.json" r1, err := New(in) if err != nil { t.Errorf("New(%v) error %s", in, err.Error()) } if in != r1.String() { t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) } if r1.HasFragmentOnly != false { t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) } if r1.HasFullURL != false { t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) } if r1.HasURLPathOnly != true { t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true) } if r1.HasFileScheme != false { t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) } if r1.GetPointer().String() != "" { t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") } } func TestInheritsInValid(t *testing.T) { in1 := "http://www.test.com/doc.json" in2 := "#/a/b" r1, _ := New(in1) r2 := Ref{} result, err := r1.Inherits(r2) assert.Error(t, err) assert.Nil(t, result) r1 = Ref{} r2, _ = New(in2) result, err = r1.Inherits(r2) assert.NoError(t, err) assert.Equal(t, r2, *result) } func TestInheritsValid(t *testing.T) { in1 := "http://www.test.com/doc.json" in2 := "#/a/b" out := in1 + in2 r1, _ := New(in1) r2, _ := New(in2) result, err := r1.Inherits(r2) if err != nil { t.Errorf("Inherits(%s,%s) error %s", r1.String(), r2.String(), err.Error()) } if result.String() != out { t.Errorf("Inherits(%s,%s) = %s, expect %s", r1.String(), r2.String(), result.String(), out) } if result.GetPointer().String() != "/a/b" { t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "/a/b") } } func TestInheritsDifferentHost(t *testing.T) { in1 := "http://www.test.com/doc.json" in2 := "http://www.test2.com/doc.json#bla" r1, _ := New(in1) r2, _ := New(in2) result, err := r1.Inherits(r2) if err != nil { t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) } if result.String() != in2 { t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) } if result.GetPointer().String() != "" { t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") } } func TestFileScheme(t *testing.T) { in1 := "file:///Users/mac/1.json#a" in2 := "file:///Users/mac/2.json#b" r1, _ := New(in1) r2, _ := New(in2) if r1.HasFragmentOnly != false { t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in1, r1.HasFragmentOnly, false) } if r1.HasFileScheme != true { t.Errorf("New(%v)::HasFileScheme %v expect %v", in1, r1.HasFileScheme, true) } if r1.HasFullFilePath != true { t.Errorf("New(%v)::HasFullFilePath %v expect %v", in1, r1.HasFullFilePath, true) } if r1.IsCanonical() != true { t.Errorf("New(%v)::IsCanonical %v expect %v", in1, r1.IsCanonical, true) } result, err := r1.Inherits(r2) if err != nil { t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) } if result.String() != in2 { t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) } if result.GetPointer().String() != "" { t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") } } func TestReferenceResolution(t *testing.T)
{ // 5.4. Reference Resolution Examples // http://tools.ietf.org/html/rfc3986#section-5.4 base := "http://a/b/c/d;p?q" baseRef, err := New(base) if err != nil { t.Errorf("New(%s) failed error: %s", base, err.Error()) } if baseRef.String() != base { t.Errorf("New(%s) %s expected %s", base, baseRef.String(), base) } checks := []string{ // 5.4.1. Normal Examples // http://tools.ietf.org/html/rfc3986#section-5.4.1 "g:h", "g:h", "g", "http://a/b/c/g", "./g", "http://a/b/c/g", "g/", "http://a/b/c/g/", "/g", "http://a/g", "//g", "http://g", "?y", "http://a/b/c/d;p?y", "g?y", "http://a/b/c/g?y", "#s", "http://a/b/c/d;p?q#s", "g#s", "http://a/b/c/g#s", "g?y#s", "http://a/b/c/g?y#s", ";x", "http://a/b/c/;x", "g;x", "http://a/b/c/g;x", "g;x?y#s", "http://a/b/c/g;x?y#s", "", "http://a/b/c/d;p?q", ".", "http://a/b/c/", "./", "http://a/b/c/", "..", "http://a/b/", "../", "http://a/b/", "../g", "http://a/b/g", "../..", "http://a/", "../../", "http://a/", "../../g", "http://a/g", // 5.4.2. Abnormal Examples // http://tools.ietf.org/html/rfc3986#section-5.4.2 "../../../g", "http://a/g", "../../../../g", "http://a/g", "/./g", "http://a/g", "/../g", "http://a/g", "g.", "http://a/b/c/g.", ".g", "http://a/b/c/.g", "g..", "http://a/b/c/g..", "..g", "http://a/b/c/..g", "./../g", "http://a/b/g", "./g/.", "http://a/b/c/g/", "g/./h", "http://a/b/c/g/h", "g/../h", "http://a/b/c/h", "g;x=1/./y", "http://a/b/c/g;x=1/y", "g;x=1/../y", "http://a/b/c/y", "g?y/./x", "http://a/b/c/g?y/./x", "g?y/../x", "http://a/b/c/g?y/../x", "g#s/./x", "http://a/b/c/g#s/./x", "g#s/../x", "http://a/b/c/g#s/../x", "http:g", "http:g", // for strict parsers //"http:g", "http://a/b/c/g", // for backward compatibility } for i := 0; i < len(checks); i += 2 { child := checks[i] expected := checks[i+1] // fmt.Printf("%d: %v -> %v\n", i/2, child, expected) childRef, e := New(child) if e != nil { t.Errorf("%d: New(%s) failed error: %s", i/2, child, e.Error()) } res, e := baseRef.Inherits(childRef) if res == nil { t.Errorf("%d: Inherits(%s, %s) nil not expected", i/2, base, child) } if e != nil { t.Errorf("%d: Inherits(%s) failed error: %s", i/2, child, e.Error()) } if res.String() != expected { t.Errorf("%d: Inherits(%s, %s) %s expected %s", i/2, base, child, res.String(), expected) } } }
version.go
package main import ( // "fmt" "github.com/golang/protobuf/ptypes/empty" "github.com/rs/zerolog/log" "golang.org/x/net/context" "github.com/stevepartridge/versions" pb "github.com/stevepartridge/versions/protos" ) func (v *versionService) GetVersion(c context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) { if req == nil { return nil, handleError(ErrVersionCreateMissingVersion) } if req.VersionId == 0 { return nil, handleError(ErrVersionCreateMissingVersion) } log.Debug().Msgf("payload %+v", req) version, err := versionStore.GetById(int(req.VersionId)) if err != nil { ifError(err) return nil, handleError(err) } return &pb.VersionResponse{ Version: version.ToProto(), }, nil } func (v *versionService) GetLatestVersion(c context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) { if req == nil { return nil, handleError(ErrVersionCreateMissingVersion) } if req.ApplicationId == "" { return nil, handleError(ErrGetLatestVersionMissingApplicationId) } log.Debug().Msgf("payload %+v", req) version, err := versionStore.GetLatest(req.ApplicationId) if err != nil { ifError(err) return nil, handleError(err) } return &pb.VersionResponse{ Version: version.ToProto(), }, nil } func (v *versionService) GetVersions(c context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) { if req == nil { return nil, handleError(ErrVersionCreateMissingVersion) } if req.ApplicationId == "" { return nil, handleError(ErrGetLatestVersionMissingApplicationId) } list, err := versionStore.GetByApplication( req.ApplicationId, int(req.Limit), int(req.Offset), ) if err != nil { ifError(err) return nil, handleError(err) } resp := &pb.VersionResponse{ Versions: versions.VersionsToProtos(list), Limit: req.Limit, Offset: req.Offset, } return resp, nil } func (v *versionService) CreateVersion(c context.Context, req *pb.Version) (*pb.VersionResponse, error) { if req == nil { return nil, handleError(ErrVersionCreateMissingVersion) } ver := versions.FromProto(req) if req.Application != nil { app := versions.ApplicationFromProto(req.Application) err := versionStore.CreateApplication(&app) if err != nil { return nil, handleError(err) } if app.Id != "" { ver.ApplicationId = app.Id } } err := versionStore.Create(&ver) if err != nil { ifError(err) return nil, handleError(err) } resp := &pb.VersionResponse{ Version: ver.ToProto(), } return resp, nil } func (v *versionService) UpdateVersion(c context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) { if req.Version == nil { return nil, handleError(ErrVersionCreateMissingVersion) } if req.VersionId > 0 && req.Version.Id == 0 { req.Version.Id = req.VersionId } ver := versions.FromProto(req.Version) if req.Version.Application != nil { app := versions.ApplicationFromProto(req.Version.Application) err := versionStore.CreateApplication(&app) if err != nil { return nil, handleError(err) } if app.Id != "" { ver.ApplicationId = app.Id } } err := versionStore.Update(&ver) if err != nil {
Version: ver.ToProto(), }, nil } func (v *versionService) DeleteVersion(c context.Context, req *pb.VersionRequest) (*empty.Empty, error) { log.Debug().Msgf("payload %+v", req) if req.VersionId == 0 { return nil, handleError(ErrMissingVersionId) } ver, err := versionStore.GetById(int(req.VersionId)) if err != nil { ifError(err) return nil, handleError(err) } if ver.Id == 0 { return nil, handleError(ErrVersionInvalidVersionId) } err = versionStore.Delete(ver.Id) ifError(err) return &empty.Empty{}, err }
return nil, handleError(err) } return &pb.VersionResponse{
report.rs
// Copyright (c) The Dijets Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::tx_emitter::TxStats; use serde::Serialize; use std::{fmt, time::Duration}; #[derive(Default, Debug, Serialize)] pub struct SuiteReport { metrics: Vec<ReportedMetric>, text: String, } #[derive(Debug, Serialize)] pub struct ReportedMetric { pub experiment: String, pub metric: String, pub value: f64, } impl SuiteReport { pub fn new() -> Self { Default::default()
} pub fn report_metric<E: ToString, M: ToString>( &mut self, experiment: E, metric: M, value: f64, ) { self.metrics.push(ReportedMetric { experiment: experiment.to_string(), metric: metric.to_string(), value, }); } pub fn report_text(&mut self, text: String) { if !self.text.is_empty() { self.text.push('\n'); } self.text.push_str(&text); } pub fn report_text_same_line(&mut self, text: String) { self.text.push_str(&text); } pub fn report_txn_stats( &mut self, experiment: String, stats: TxStats, window: Duration, additional: &str, ) { let submitted_txn = stats.submitted; let expired_txn = stats.expired; let avg_tps = stats.committed / window.as_secs(); let avg_latency_client = if stats.committed == 0 { 0u64 } else { stats.latency / stats.committed }; let p99_latency = stats.latency_buckets.percentile(99, 100); self.report_metric(experiment.clone(), "submitted_txn", submitted_txn as f64); self.report_metric(experiment.clone(), "expired_txn", expired_txn as f64); self.report_metric(experiment.clone(), "avg_tps", avg_tps as f64); self.report_metric(experiment.clone(), "avg_latency", avg_latency_client as f64); self.report_metric(experiment.clone(), "p99_latency", p99_latency as f64); let expired_text = if expired_txn == 0 { "no expired txns".to_string() } else { format!("(!) expired {} out of {} txns", expired_txn, submitted_txn) }; self.report_text(format!( "{} : {:.0} TPS, {:.1} ms latency, {:.1} ms p99 latency,{} {}", experiment, avg_tps, avg_latency_client, p99_latency, additional, expired_text )); } } impl fmt::Display for SuiteReport { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.text) } }
sandbox_manager.rs
//! The sandbox manager provides the actual functionality of the sandbox //! process. It allows the replica controller process to manage //! everything required in order to execute code. It holds three //! kinds of resources that it manages on behalf of the replica //! controller process: //! //! - CanisterWasm: The (wasm) code corresponding to one canister //! - State: The heap and other (mutable) user state associated with a canister //! - Execution: An ongoing execution of a canister, using one wasm and state //! object //! //! All of the above objects as well as the functionality provided //! towards the controller are found in this module. use std::collections::HashMap; use std::fmt::{Debug, Formatter}; use std::sync::{Arc, Mutex}; use ic_canister_sandbox_common::protocol::id::{ExecId, MemoryId, WasmId}; use ic_canister_sandbox_common::protocol::sbxsvc::{ CreateExecutionStateSuccessReply, OpenMemoryRequest, }; use ic_canister_sandbox_common::protocol::structs::{ MemoryModifications, SandboxExecInput, SandboxExecOutput, StateModifications, }; use ic_canister_sandbox_common::{controller_service::ControllerService, protocol}; use ic_config::embedders::Config as EmbeddersConfig; use ic_embedders::{ wasm_executor::WasmStateChanges, wasm_utils::{ instrumentation::{instrument, InstructionCostTable}, validation::validate_wasm_binary, }, WasmtimeEmbedder, }; use ic_interfaces::execution_environment::{ ExecutionMode, HypervisorError, HypervisorResult, WasmExecutionOutput, }; use ic_logger::replica_logger::no_op_logger; use ic_replicated_state::page_map::PageMapSerialization; use ic_replicated_state::{EmbedderCache, Memory, PageMap}; use ic_types::CanisterId; use ic_wasm_types::BinaryEncodedWasm; struct ExecutionInstantiateError; impl Debug for ExecutionInstantiateError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("Failed to instantatiate execution.") } } /// A canister execution currently in progress. struct Execution { /// Id of the execution. This is used in communicating back to /// the replica (e.g. for syscalls) such that replica can associate /// events with the correct execution. exec_id: ExecId, /// The canister wasm used in this execution. canister_wasm: Arc<CanisterWasm>, /// The sandbox manager that is responsible for /// 1) Providing the controller to talk to the replica process. /// 2) Creating a new execution state. sandbox_manager: Arc<SandboxManager>, } impl Execution { /// Creates new execution based on canister wasm and state. In order /// to start the execution, the given state object will be "locked" -- /// if that cannot be done, then creation of execution will fail. /// The actual code to be run will be scheduled to the given /// thread pool. /// /// This will *actually* schedule and initiate a new execution. #[allow(clippy::too_many_arguments)] pub(crate) fn start_on_worker_thread( exec_id: ExecId, canister_wasm: Arc<CanisterWasm>, wasm_memory: Arc<Memory>, stable_memory: Arc<Memory>, sandbox_manager: Arc<SandboxManager>, workers: &mut threadpool::ThreadPool, exec_input: SandboxExecInput, total_timer: std::time::Instant, ) { let wasm_memory = (*wasm_memory).clone(); let stable_memory = (*stable_memory).clone(); let execution = Arc::new(Self { exec_id, canister_wasm, sandbox_manager, }); workers.execute(move || execution.run(exec_input, wasm_memory, stable_memory, total_timer)); } // Actual wasm code execution -- this is run on the target thread // in the thread pool. fn run( &self, exec_input: SandboxExecInput, mut wasm_memory: Memory, mut stable_memory: Memory, total_timer: std::time::Instant, ) { let run_timer = std::time::Instant::now(); let subnet_available_memory = exec_input .execution_parameters .subnet_available_memory .clone(); let ( WasmExecutionOutput { wasm_result, num_instructions_left, instance_stats, }, deltas, instance_or_system_api, ) = ic_embedders::wasm_executor::process( exec_input.func_ref, exec_input.api_type, exec_input.canister_current_memory_usage, exec_input.execution_parameters, exec_input.sandox_safe_system_state, &self.canister_wasm.compilate, &self.sandbox_manager.embedder, &mut wasm_memory, &mut stable_memory, &exec_input.globals, no_op_logger(), exec_input.wasm_reserved_pages, ); match wasm_result { Ok(_) => { let state_modifications = deltas.map( |WasmStateChanges { dirty_page_indices, globals, }| { let system_state_changes = match instance_or_system_api { // Here we use `store_data_mut` instead of // `into_store_data` because the later will drop the // wasmtime Instance which can be an expensive // operation. Mutating the store instead allows us // to delay the drop until after the execution // completed message is sent back to the main // process. Ok(mut instance) => instance .store_data_mut() .system_api .take_system_state_changes(), Err(system_api) => system_api.into_system_state_changes(), }; StateModifications::new( globals, &wasm_memory, &stable_memory, &dirty_page_indices.wasm_memory_delta, &dirty_page_indices.stable_memory_delta, subnet_available_memory.get(), system_state_changes, ) }, ); if state_modifications.is_some() { self.sandbox_manager .add_memory(exec_input.next_wasm_memory_id, wasm_memory); self.sandbox_manager .add_memory(exec_input.next_stable_memory_id, stable_memory); } let wasm_output = WasmExecutionOutput { wasm_result, num_instructions_left, instance_stats, }; self.sandbox_manager.controller.execution_finished( protocol::ctlsvc::ExecutionFinishedRequest { exec_id: self.exec_id, exec_output: SandboxExecOutput { wasm: wasm_output, state: state_modifications, execute_total_duration: total_timer.elapsed(), execute_run_duration: run_timer.elapsed(), }, }, ); } Err(err) => { let wasm_output = WasmExecutionOutput { wasm_result: Err(err), num_instructions_left, instance_stats, }; self.sandbox_manager.controller.execution_finished( protocol::ctlsvc::ExecutionFinishedRequest { exec_id: self.exec_id, exec_output: SandboxExecOutput { wasm: wasm_output, state: None, execute_total_duration: total_timer.elapsed(), execute_run_duration: run_timer.elapsed(), }, }, ); } } } } /// Represents a wasm object of a canister. This is the executable code /// of the canister. struct CanisterWasm { compilate: Arc<EmbedderCache>, } impl CanisterWasm { /// Validates and compiles the given Wasm binary. pub fn compile( config: &ic_config::embedders::Config, embedder: &Arc<WasmtimeEmbedder>, wasm_src: Vec<u8>, ) -> HypervisorResult<Self> { let wasm = BinaryEncodedWasm::new(wasm_src); let instrumentation_output = validate_wasm_binary(&wasm, config) .map_err(HypervisorError::from) .and_then(|_| { instrument(&wasm, &InstructionCostTable::new()).map_err(HypervisorError::from) })?; let compilate = embedder.compile(&instrumentation_output.binary)?; let compilate = Arc::new(compilate); Ok(Self { compilate }) } } /// Manages the entirety of the sandbox process. It provides the methods /// through which the controller process (the replica) manages the /// sandboxed execution. pub struct SandboxManager { repr: Mutex<SandboxManagerInt>, controller: Arc<dyn ControllerService>, embedder: Arc<WasmtimeEmbedder>, config: ic_config::embedders::Config, } struct SandboxManagerInt { canister_wasms: std::collections::HashMap<WasmId, Arc<CanisterWasm>>, memories: std::collections::HashMap<MemoryId, Arc<Memory>>, workers_for_replicated_execution: threadpool::ThreadPool, workers_for_non_replicated_execution: threadpool::ThreadPool, workers_for_cleanup: threadpool::ThreadPool, } impl SandboxManager { /// Creates new sandbox manager. In order to operate, it needs /// an established backward RPC channel to the controller process /// to relay e.g. syscalls and completions. pub fn new(controller: Arc<dyn ControllerService>, config: EmbeddersConfig) -> Self { let log = ic_logger::replica_logger::no_op_logger(); let embedder = Arc::new(WasmtimeEmbedder::new(config.clone(), log)); SandboxManager { repr: Mutex::new(SandboxManagerInt { canister_wasms: HashMap::new(), memories: HashMap::new(), workers_for_replicated_execution: threadpool::ThreadPool::new(1), workers_for_non_replicated_execution: threadpool::ThreadPool::new( config.query_execution_threads, ), workers_for_cleanup: threadpool::ThreadPool::new(1), }), controller, embedder, config, } } /// Compiles the given Wasm binary and registers it under the given id. /// The function may fail if the Wasm binary is invalid. pub fn open_wasm(&self, wasm_id: WasmId, wasm_src: Vec<u8>) -> HypervisorResult<()> { let mut guard = self.repr.lock().unwrap(); assert!( !guard.canister_wasms.contains_key(&wasm_id), "Failed to open wasm session {}: id is already in use", wasm_id, ); let wasm = CanisterWasm::compile(&self.config, &self.embedder, wasm_src)?; // Return as much memory as possible because compiling seems to use up // some extra memory that can be returned. // // SAFETY: 0 is always a valid argument to `malloc_trim`. #[cfg(target_os = "linux")] unsafe { libc::malloc_trim(0); } guard.canister_wasms.insert(wasm_id, Arc::new(wasm)); Ok(()) } /// Closes previously opened wasm instance, by id. pub fn close_wasm(&self, wasm_id: WasmId) { let mut guard = self.repr.lock().unwrap(); let removed = guard.canister_wasms.remove(&wasm_id); assert!( removed.is_some(), "Failed to close wasm session {}: id not found", wasm_id ); } /// Opens a new memory requested by the replica process. pub fn open_memory(&self, request: OpenMemoryRequest) { let mut guard = self.repr.lock().unwrap(); guard.open_memory(request); } /// Adds a new memory after sandboxed execution. fn add_memory(&self, memory_id: MemoryId, memory: Memory) { let mut guard = self.repr.lock().unwrap(); guard.add_memory(memory_id, memory); } /// Closes previously opened memory instance, by id. pub fn close_memory(&self, memory_id: MemoryId) { let mut guard = self.repr.lock().unwrap(); let removed = guard.memories.remove(&memory_id); assert!( removed.is_some(), "Failed to close state {}: id not found", memory_id ); // Dropping memory may be expensive. Do it on a worker thread to avoid // blocking the main thread of the sandbox process. guard.workers_for_cleanup.execute(move || drop(removed)); } /// Starts Wasm execution using specific code and state, passing /// execution input. /// /// Note that inside here we start a transaction and the state of /// execution can not and does not change while we are processing /// this particular session. pub fn start_execution( sandbox_manager: &Arc<SandboxManager>, exec_id: ExecId, wasm_id: WasmId, wasm_memory_id: MemoryId, stable_memory_id: MemoryId, exec_input: SandboxExecInput, )
pub fn create_execution_state( &self, wasm_id: WasmId, wasm_source: Vec<u8>, wasm_page_map: PageMapSerialization, next_wasm_memory_id: MemoryId, canister_id: CanisterId, ) -> HypervisorResult<CreateExecutionStateSuccessReply> { // Get the compiled binary from the cache. let binary_encoded_wasm = BinaryEncodedWasm::new(wasm_source); let (embedder_cache, embedder) = { let guard = self.repr.lock().unwrap(); let canister_wasm = guard.canister_wasms.get(&wasm_id).unwrap_or_else(|| { unreachable!( "Failed to create execution state for {}: wasm {} not found", canister_id, wasm_id ) }); ( Arc::clone(&canister_wasm.compilate), Arc::clone(&self.embedder), ) }; let mut wasm_page_map = PageMap::deserialize(wasm_page_map).unwrap(); let ( exported_functions, exported_globals, wasm_memory_delta, wasm_memory_size, wasm_validation_details, ) = ic_embedders::wasm_executor::get_initial_globals_and_memory( &binary_encoded_wasm, &embedder_cache, &embedder, &self.config, &mut wasm_page_map, canister_id, )?; let wasm_memory = Memory::new(wasm_page_map, wasm_memory_size); // Send all necessary data for creating the execution state to replica. let wasm_memory_modifications = MemoryModifications { page_delta: wasm_memory.page_map.serialize_delta(&wasm_memory_delta), size: wasm_memory_size, }; // Save the memory for future message executions. self.add_memory(next_wasm_memory_id, wasm_memory); Ok(CreateExecutionStateSuccessReply { wasm_memory_modifications, exported_globals, exported_functions, wasm_metadata: wasm_validation_details.wasm_metadata, }) } } impl SandboxManagerInt { fn open_memory(&mut self, request: OpenMemoryRequest) { let page_map = PageMap::deserialize(request.memory.page_map).unwrap(); let memory = Memory::new(page_map, request.memory.num_wasm_pages); self.add_memory(request.memory_id, memory); } fn add_memory(&mut self, memory_id: MemoryId, memory: Memory) { assert!( !self.memories.contains_key(&memory_id), "Failed to open memory {}: id is already in use", memory_id ); let memory = Arc::new(memory); self.memories.insert(memory_id, memory); } }
{ let total_timer = std::time::Instant::now(); let mut guard = sandbox_manager.repr.lock().unwrap(); let wasm_runner = guard.canister_wasms.get(&wasm_id).unwrap_or_else(|| { unreachable!( "Failed to open exec session {}: wasm {} not found", exec_id, wasm_id ) }); let wasm_memory = guard.memories.get(&wasm_memory_id).unwrap_or_else(|| { unreachable!( "Failed to open exec session {}: wasm memory {} not found", exec_id, wasm_memory_id, ) }); let stable_memory = guard.memories.get(&stable_memory_id).unwrap_or_else(|| { unreachable!( "Failed to open exec session {}: stable memory {} not found", exec_id, stable_memory_id, ) }); match exec_input.execution_parameters.execution_mode { ExecutionMode::Replicated => Execution::start_on_worker_thread( exec_id, Arc::clone(wasm_runner), Arc::clone(wasm_memory), Arc::clone(stable_memory), Arc::clone(sandbox_manager), &mut guard.workers_for_replicated_execution, exec_input, total_timer, ), ExecutionMode::NonReplicated => Execution::start_on_worker_thread( exec_id, Arc::clone(wasm_runner), Arc::clone(wasm_memory), Arc::clone(stable_memory), Arc::clone(sandbox_manager), &mut guard.workers_for_non_replicated_execution, exec_input, total_timer, ), }; }
pltcp.py
import numpy as np import matplotlib.patches as patches import matplotlib.pyplot as plt ax = plt.axes(polar = True)
theta = np.linspace(0, 2 * np.pi, 8, endpoint = False) radius = .25 + .75 * np.random.random(size = len(theta)) points = np.vstack((theta, radius)).transpose() plt.gca().add_patch(patches.Polygon(points, color = '.75')) plt.show()
index.js
var getOwnPropertyDescriptors = (function (Object) { var gOPDs = Object.getOwnPropertyDescriptors; if (gOPDs) return gOPDs; var dP = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var gOPN = Object.getOwnPropertyNames;
key, descriptors = {}, keys = gOPN(object).concat(gOPS ? gOPS(object) : []), i = 0, length = keys.length; i < length; i++ ) { key = keys[i]; dP(descriptors, key, { enumerable: true, value: gOPD(object, key) }); } return descriptors; }; }(Object)); module.exports = getOwnPropertyDescriptors;
var gOPS = Object.getOwnPropertySymbols; return function (object) { for (var
topic.rs
// Copyright 2020 Sigma Prime Pty Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. use crate::rpc_proto; use base64::encode; use open_metrics_client::encoding::text::Encode; use prost::Message; use sha2::{Digest, Sha256}; use std::fmt; /// A generic trait that can be extended for various hashing types for a topic. pub trait Hasher { /// The function that takes a topic string and creates a topic hash. fn hash(topic_string: String) -> TopicHash; } /// A type for representing topics who use the identity hash. #[derive(Debug, Clone)] pub struct IdentityHash {} impl Hasher for IdentityHash { /// Creates a [`TopicHash`] as a raw string.
} } #[derive(Debug, Clone)] pub struct Sha256Hash {} impl Hasher for Sha256Hash { /// Creates a [`TopicHash`] by SHA256 hashing the topic then base64 encoding the /// hash. fn hash(topic_string: String) -> TopicHash { let topic_descripter = rpc_proto::TopicDescriptor { name: Some(topic_string), auth: None, enc: None, }; let mut bytes = Vec::with_capacity(topic_descripter.encoded_len()); topic_descripter .encode(&mut bytes) .expect("buffer is large enough"); let hash = encode(Sha256::digest(&bytes).as_slice()); TopicHash { hash } } } #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Encode)] pub struct TopicHash { /// The topic hash. Stored as a string to align with the protobuf API. hash: String, } impl TopicHash { pub fn from_raw(hash: impl Into<String>) -> TopicHash { TopicHash { hash: hash.into() } } pub fn into_string(self) -> String { self.hash } pub fn as_str(&self) -> &str { &self.hash } } /// A gossipsub topic. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Topic<H: Hasher> { topic: String, phantom_data: std::marker::PhantomData<H>, } impl<H: Hasher> From<Topic<H>> for TopicHash { fn from(topic: Topic<H>) -> TopicHash { topic.hash() } } impl<H: Hasher> Topic<H> { pub fn new(topic: impl Into<String>) -> Self { Topic { topic: topic.into(), phantom_data: std::marker::PhantomData, } } pub fn hash(&self) -> TopicHash { H::hash(self.topic.clone()) } } impl<H: Hasher> fmt::Display for Topic<H> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.topic) } } impl fmt::Display for TopicHash { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.hash) } }
fn hash(topic_string: String) -> TopicHash { TopicHash { hash: topic_string }
github.rs
use once_cell::sync::Lazy; use regex::Regex; use reqwest::blocking::Client; use serde::{Deserialize, Serialize}; use std::env::{var, VarError}; static CLIENT: Lazy<Client> = Lazy::new(|| { Client::builder() .user_agent("rust-lang/glacier") .build() .unwrap() }); pub(crate) struct Config { token: String, } impl Config { pub(crate) fn from_env() -> Result<Self, VarError> {
token: var("LABEL_TOKEN")?, }) } } pub(crate) fn label_issue( config: &Config, labels: &Labels, issue_number: usize, ) -> Result<(), reqwest::Error> { let url = format!( "https://api.github.com/repos/rust-lang/rust/issues/{}/labels", issue_number ); CLIENT .post(&url) .bearer_auth(&config.token) .json(&labels) .send()? .error_for_status()?; Ok(()) } pub(crate) fn get_labeled_issues( config: &Config, label_name: String, ) -> Result<Vec<Issue>, reqwest::Error> { let url = format!( "https://api.github.com/repos/rust-lang/rust/issues?labels={}&state=all", label_name ); let mut issues: Vec<Issue> = CLIENT .get(&url) .bearer_auth(&config.token) .send()? .error_for_status()? .json()?; let pages = get_result_length(&config, &url).unwrap(); if pages > 1 { for i in 2..=pages { let url = format!( "https://api.github.com/repos/rust-lang/rust/issues?labels={}&state=all&page={}", label_name, i ); let mut paged_issues: Vec<Issue> = CLIENT .get(&url) .bearer_auth(&config.token) .send()? .error_for_status()? .json()?; issues.append(&mut paged_issues); } } Ok(issues) } fn get_result_length(config: &Config, url: &str) -> Result<usize, Box<dyn std::error::Error>> { let res = CLIENT.get(url).bearer_auth(&config.token).send()?; if res.status().is_success() { if let Some(link) = res.headers().get("Link") { let link_string = String::from_utf8(link.as_bytes().to_vec()).unwrap(); let re_last_page = Regex::new(r#"page=[0-9]+>; rel="last""#).unwrap(); let re_page_number = Regex::new(r"[0-9]+").unwrap(); let last_page = re_last_page .captures(&link_string) .unwrap() .get(0) .unwrap() .as_str(); let page_number = re_page_number.captures(&last_page).unwrap(); let pages: usize = page_number.get(0).unwrap().as_str().parse().unwrap(); Ok(pages) } else { Ok(0) } } else { Ok(0) } } #[derive(Serialize, Debug)] pub(crate) struct Labels { pub(crate) labels: Vec<String>, } #[derive(Deserialize, Debug)] pub(crate) struct Issue { pub(crate) number: usize, pub(crate) labels: Vec<Label>, } #[derive(Deserialize, Debug)] pub(crate) struct Label { pub(crate) name: String, }
Ok(Self {
alembic.py
import os import pathlib import shutil import typing import alembic.command import alembic.config from mlrun import mlconf class AlembicUtil(object): def __init__(self, alembic_config_path: pathlib.Path): self._alembic_config_path = str(alembic_config_path) self._alembic_config = alembic.config.Config(self._alembic_config_path) self._alembic_output = "" def init_alembic(self, from_scratch: bool = False):
@staticmethod def _get_db_file_path() -> str: """ Get the db file path from the dsn. Converts the dsn to the file path. e.g.: sqlite:////mlrun/db/mlrun.db?check_same_thread=false -> /mlrun/db/mlrun.db """ return mlconf.httpdb.dsn.split("?")[0].split("sqlite:///")[-1] def _get_current_revision(self) -> typing.Optional[str]: # create separate config in order to catch the stdout catch_stdout_config = alembic.config.Config(self._alembic_config_path) catch_stdout_config.print_stdout = self._save_output self._flush_output() try: alembic.command.current(catch_stdout_config) return self._alembic_output.strip().replace(" (head)", "") except Exception as exc: if "Can't locate revision identified by" in exc.args[0]: # DB has a revision that isn't known to us, extracting it from the exception. return exc.args[0].split("'")[2] return None def _get_revision_history_list(self) -> typing.List[str]: """ Returns a list of the revision history sorted from latest to oldest. """ # create separate config in order to catch the stdout catch_stdout_config = alembic.config.Config(self._alembic_config_path) catch_stdout_config.print_stdout = self._save_output self._flush_output() alembic.command.history(catch_stdout_config) return self._parse_revision_history(self._alembic_output) @staticmethod def _parse_revision_history(output: str) -> typing.List[str]: return [line.split(" ")[2].replace(",", "") for line in output.splitlines()] @staticmethod def _backup_revision(db_file_path: str, current_version: str): if db_file_path == ":memory:": return db_dir_path = pathlib.Path(os.path.dirname(db_file_path)) backup_path = db_dir_path / f"{current_version}.db" shutil.copy2(db_file_path, backup_path) @staticmethod def _downgrade_to_revision( db_file_path: str, current_revision: str, fallback_version: str ): db_dir_path = pathlib.Path(os.path.dirname(db_file_path)) backup_path = db_dir_path / f"{fallback_version}.db" if not os.path.isfile(backup_path): raise RuntimeError( f"Cannot fall back to revision {fallback_version}, " f"no back up exists. Current revision: {current_revision}" ) # backup the current DB current_backup_path = db_dir_path / f"{current_revision}.db" shutil.copy2(db_file_path, current_backup_path) shutil.copy2(backup_path, db_file_path) def _save_output(self, text: str, *_): self._alembic_output += f"{text}\n" def _flush_output(self): self._alembic_output = ""
revision_history = self._get_revision_history_list() latest_revision = revision_history[0] initial_alembic_revision = revision_history[-1] db_file_path = self._get_db_file_path() db_path_exists = os.path.isfile(db_file_path) # this command for some reason creates a dummy db file so it has to be after db_path_exists current_revision = self._get_current_revision() if not from_scratch and db_path_exists and not current_revision: # if database file exists but no alembic version exists, stamp the existing # database with the initial alembic version, so we can upgrade it later alembic.command.stamp(self._alembic_config, initial_alembic_revision) elif ( db_path_exists and current_revision and current_revision not in revision_history ): self._downgrade_to_revision(db_file_path, current_revision, latest_revision) # get current revision again if it changed during the last commands current_revision = self._get_current_revision() if current_revision: self._backup_revision(db_file_path, current_revision) alembic.command.upgrade(self._alembic_config, "head")
TestController.py
from flask import request from injector import inject from controllers.common.models.CommonModels import CommonModels from controllers.test.models.TestModels import TestModels from infrastructor.IocManager import IocManager from infrastructor.api.ResourceBase import ResourceBase @TestModels.ns.route('/path/<int:value>/<int:value_for_sum>', doc=False) class TestResource(ResourceBase): @inject def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @TestModels.ns.marshal_with(CommonModels.SuccessModel) def get(self, value, value_for_sum): result = {'sum': value + value_for_sum} return CommonModels.get_response(result=result) @TestModels.ns.route('/query', doc=False) class TestResource(ResourceBase): @inject def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @TestModels.ns.expect(TestModels.parser, validate=True) @TestModels.ns.marshal_with(CommonModels.SuccessModel) def get(self): data = TestModels.parser.parse_args(request) value = data.get('value') # value_for_sum = data.get('value_for_sum') # This is FileStorage instance # url = do_something_with_file(uploaded_file) result = {'sum': value + value_for_sum} return CommonModels.get_response(result=result) @TestModels.ns.expect(TestModels.sum_model, validate=True) @TestModels.ns.marshal_with(CommonModels.SuccessModel) def post(self): data = IocManager.api.payload value = data.get('value') # value_for_sum = data.get('value_for_sum') # This is FileStorage instance
result = {'sum': value + value_for_sum, "test": [{"test": 1}, {"test": 2}]} return CommonModels.get_response(result=result)
icon.js
'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') const browser = require('webextension-polyfill') function
({ svg, title, active, action, className }) { return html` <button class="header-icon pa0 ma0 dib bn bg-transparent transition-all ${className} ${action ? 'pointer' : null} ${active ? 'aqua' : 'gray'}" style="outline:none;" title="${browser.i18n.getMessage(title) || title}" onclick=${action}> ${svg} </button> ` } module.exports = icon
icon
common.go
package types import ( "github.com/Ontology/common" "math/big" ) func ConvertBigIntegerToBytes(data *big.Int) []byte
func ConvertBytesToBigInteger(ba []byte) *big.Int { res := big.NewInt(0) l := len(ba) if l == 0 { return res } bytes := make([]byte, 0, l) bytes = append(bytes, ba...) common.BytesReverse(bytes) if bytes[0]>>7 == 1 { for i, b := range bytes { bytes[i] = ^b } temp := big.NewInt(0) temp.SetBytes(bytes) temp2 := big.NewInt(0) temp2.Add(temp, big.NewInt(1)) bytes = temp2.Bytes() res.SetBytes(bytes) return res.Neg(res) } res.SetBytes(bytes) return res }
{ if data.Int64() == 0 { return []byte{} } bs := data.Bytes() b := bs[0] if data.Sign() < 0 { for i, b := range bs { bs[i] = ^b } temp := big.NewInt(0) temp.SetBytes(bs) temp2 := big.NewInt(0) temp2.Add(temp, big.NewInt(1)) bs = temp2.Bytes() common.BytesReverse(bs) if b>>7 == 1 { bs = append(bs, 255) } } else { common.BytesReverse(bs) if b>>7 == 1 { bs = append(bs, 0) } } return bs }
tooltip.component.ts
import { Component, OnInit, Output } from '@angular/core'; import { TooltipDirective } from '../tooltip.directive';
}) export class TooltipComponent implements OnInit { placement: string; constructor() { } ngOnInit() { } }
@Component({ selector: 'app-tooltip', templateUrl: './tooltip.component.html', styleUrls: ['./tooltip.component.css']
index.tsx
import { FormHandles } from '@unform/core'; import { useCallback, useEffect, useRef, useState } from 'react'; import { parseISO } from 'date-fns'; import { FiCheckCircle, FiEdit, FiXCircle } from 'react-icons/fi'; import { AiOutlineDelete } from 'react-icons/ai'; import { toast } from 'react-toastify'; import { CheckBox } from '../../component/CheckBox'; import { Input } from '../../component/Input'; import { Select } from '../../component/Select'; import { api } from '../../services/api'; import { Container, Form, ContainerButton, Table } from './styles'; interface IAnimal { id: string; name: string; id_people: string; breed: string; sex: 'm' | 'f'; weigth: number; born: string; } interface IBatch { id: string; name: string; description: string; } interface IBatchAnimal { id: string; dt_entry: string; dt_exit: string; dt_last_movement: string; calf: boolean; animal: { name: string; breed: string; sex: string; weigth: string; born: string; }; batch: { name: string; }; } interface IFormBatchAnimal { dtEntry: string; dtExit: string; dtLastMove: string; haveCalf: boolean; id_batch: string; id_animal: string; } export function BatchAnimal() { const formRef = useRef<FormHandles>(null); const [labelButton, setLabelButton] = useState<string>('Cadastrar'); const [ batchAnimalSelect, setAnimalBatchSelect, ] = useState<IBatchAnimal | null>(null); const [batchAnimals, setBatchAnimals] = useState<IBatchAnimal[]>([]); const [animals, setAnimals] = useState<IAnimal[]>([]); const [batchs, setBatchs] = useState<IBatch[]>([]); useEffect(() => { async function
() { const [animalsList, batchList, batchAnimalsList] = await Promise.all([ api.get('/animal'), api.get('/batch'), api.get('/animal_batch'), ]); setAnimals(animalsList.data); setBatchs(batchList.data); setBatchAnimals(batchAnimalsList.data); } getAnimalAndBatch(); }, []); const handleFormSubmit = useCallback( async (formBatchAnimal: IFormBatchAnimal, { reset }) => { if (labelButton) { try { const objSave = { id_animal: formBatchAnimal.id_animal, id_batch: formBatchAnimal.id_batch, dt_entry: parseISO(formBatchAnimal.dtEntry), dt_exit: parseISO(formBatchAnimal.dtExit), calf: formBatchAnimal.haveCalf, }; const { data } = await api.post('/animal_batch', objSave); setBatchAnimals([...batchAnimals, data]); toast.success('Animal x lote cadastrado com sucesso'); reset(); } catch (error) { toast.error('Não foi possível cadastrar o animal x lote'); } } console.log(formBatchAnimal); }, [batchAnimals, labelButton], ); const handleDeleteBatchAnimal = useCallback( async (idBatchAnimal: string) => { try { await api.delete(`/animal_batch/${idBatchAnimal}`); const newArrayBatchAnimal = batchAnimals.filter( batchAnimal => batchAnimal.id !== idBatchAnimal, ); setBatchAnimals(newArrayBatchAnimal); toast.success('Lote deletado com sucesso'); } catch (error) { toast.error('Ocorreu um problema ao deletar lote, tente novamente'); } }, [batchAnimals], ); const handleResetForm = useCallback(() => { setAnimalBatchSelect(null); setLabelButton('Cadastrar'); formRef.current?.reset(); }, []); return ( <Container> <h1>Animal x Lote</h1> <Form ref={formRef} initialData={batchAnimalSelect || {}} onSubmit={handleFormSubmit} > <div className="animalBreed"> <Select name="id_animal" label="Selecione o animal"> {animals.map(option => ( <option key={option.id} value={option.id}> {option.name} </option> ))} </Select> <Select name="id_batch" label="Selecione o lote"> {batchs.map(option => ( <option key={option.id} value={option.id}> {option.name} </option> ))} </Select> </div> <div className="abacaxi"> <Input id="dtEntry" nameInput="dtEntry" nameLabel="Data de entrada" type="date" placeholder="Data de entrada" /> <Input id="dtExit" nameInput="dtExit" nameLabel="Data saída" type="date" placeholder="Data de saída" /> <Input id="dtLastMove" nameInput="dtLastMove" nameLabel="Data ultima movimentação" type="date" placeholder="Data ultima movimentação" /> </div> <div className="inputCheck"> <CheckBox name="haveCalf" label="Tem bezerro" /> </div> <ContainerButton> <button type="submit">{labelButton}</button> {batchAnimalSelect && ( <button type="button" onClick={handleResetForm}> Cancelar </button> )} </ContainerButton> </Form> {batchAnimals.length > 0 && ( <Table> <thead> <tr> <th scope="col">Nome lote</th> <th scope="col">Nome do animal</th> <th scope="col">Raça</th> <th scope="col">Peso</th> <th scope="col">Nascimento</th> <th scope="col">Possui bezerro</th> <th scope="col">Deletar</th> </tr> </thead> <tbody> {batchAnimals.map(batchAnimal => ( <tr key={batchAnimal.id}> <th>{batchAnimal.batch.name}</th> <td>{batchAnimal.animal.name}</td> <td>{batchAnimal.animal.breed}</td> <td>{batchAnimal.animal.weigth}</td> <td> {new Intl.DateTimeFormat('pt-br').format( new Date(batchAnimal.animal.born), )} </td> <td> {batchAnimal.calf ? ( <FiCheckCircle size="20" /> ) : ( <FiXCircle size="20" /> )} </td> <td> {/* <button onClick={() => handleChangeAnimalBatch(batchAnimal)} type="button" > <FiEdit size="20" /> </button> */} <button onClick={() => handleDeleteBatchAnimal(batchAnimal.id)} type="button" > <AiOutlineDelete size="20" /> </button> </td> </tr> ))} </tbody> </Table> )} </Container> ); }
getAnimalAndBatch
mod.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Code to validate patterns/matches mod _match; mod check_match; pub use self::check_match::check_crate; pub(crate) use self::check_match::check_match; use const_eval::{const_field, const_variant_index}; use hair::util::UserAnnotatedTyHelpers; use hair::constant::*; use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability}; use rustc::mir::{ProjectionElem, UserTypeAnnotation, UserTypeProjection, UserTypeProjections}; use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend}; use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, Lift}; use rustc::ty::subst::{Substs, Kind}; use rustc::ty::layout::VariantIdx; use rustc::hir::{self, PatKind, RangeEnd}; use rustc::hir::def::{Def, CtorKind}; use rustc::hir::pat_util::EnumerateAndAdjustIterator; use rustc_data_structures::indexed_vec::Idx; use std::cmp::Ordering; use std::fmt; use syntax::ast; use syntax::ptr::P; use syntax_pos::Span; #[derive(Clone, Debug)] pub enum PatternError { AssociatedConstInPattern(Span), StaticInPattern(Span), FloatBug, NonConstPath(Span), } #[derive(Copy, Clone, Debug)] pub enum BindingMode<'tcx> { ByValue, ByRef(Region<'tcx>, BorrowKind), } #[derive(Clone, Debug)] pub struct FieldPattern<'tcx> { pub field: Field, pub pattern: Pattern<'tcx>, } #[derive(Clone, Debug)] pub struct Pattern<'tcx> { pub ty: Ty<'tcx>, pub span: Span, pub kind: Box<PatternKind<'tcx>>, } #[derive(Clone, Debug)] pub(crate) struct PatternTypeProjections<'tcx> { contents: Vec<(PatternTypeProjection<'tcx>, Span)>, } impl<'tcx> PatternTypeProjections<'tcx> { pub(crate) fn user_ty(self) -> UserTypeProjections<'tcx> { UserTypeProjections::from_projections( self.contents.into_iter().map(|(pat_ty_proj, span)| (pat_ty_proj.user_ty(), span))) } pub(crate) fn none() -> Self { PatternTypeProjections { contents: vec![] } } pub(crate) fn ref_binding(&self) -> Self { // FIXME(#47184): ignore for now PatternTypeProjections { contents: vec![] } } fn map_projs(&self, mut f: impl FnMut(&PatternTypeProjection<'tcx>) -> PatternTypeProjection<'tcx>) -> Self { PatternTypeProjections { contents: self.contents .iter() .map(|(proj, span)| (f(proj), *span)) .collect(), } } pub(crate) fn index(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.index()) } pub(crate) fn subslice(&self, from: u32, to: u32) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.subslice(from, to)) } pub(crate) fn deref(&self) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.deref()) } pub(crate) fn leaf(&self, field: Field) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.leaf(field)) } pub(crate) fn variant(&self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self { self.map_projs(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field)) } pub(crate) fn add_user_type(&self, user_ty: &PatternTypeProjection<'tcx>, sp: Span) -> Self { let mut new = self.clone(); new.contents.push((user_ty.clone(), sp)); new } } #[derive(Clone, Debug)] pub struct PatternTypeProjection<'tcx>(UserTypeProjection<'tcx>); impl<'tcx> PatternTypeProjection<'tcx> { pub(crate) fn index(&self) -> Self { let mut new = self.clone(); new.0.projs.push(ProjectionElem::Index(())); new } pub(crate) fn subslice(&self, from: u32, to: u32) -> Self { let mut new = self.clone(); new.0.projs.push(ProjectionElem::Subslice { from, to }); new } pub(crate) fn deref(&self) -> Self
pub(crate) fn leaf(&self, field: Field) -> Self { let mut new = self.clone(); new.0.projs.push(ProjectionElem::Field(field, ())); new } pub(crate) fn variant(&self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self { let mut new = self.clone(); new.0.projs.push(ProjectionElem::Downcast(adt_def, variant_index)); new.0.projs.push(ProjectionElem::Field(field, ())); new } pub(crate) fn from_canonical_ty(c_ty: ty::CanonicalTy<'tcx>) -> Self { Self::from_user_type(UserTypeAnnotation::Ty(c_ty)) } pub(crate) fn from_user_type(u_ty: UserTypeAnnotation<'tcx>) -> Self { Self::from_user_type_proj(UserTypeProjection { base: u_ty, projs: vec![], }) } pub(crate) fn from_user_type_proj(u_ty: UserTypeProjection<'tcx>) -> Self { PatternTypeProjection(u_ty) } pub(crate) fn user_ty(self) -> UserTypeProjection<'tcx> { self.0 } } #[derive(Clone, Debug)] pub enum PatternKind<'tcx> { Wild, AscribeUserType { user_ty: PatternTypeProjection<'tcx>, subpattern: Pattern<'tcx>, user_ty_span: Span, }, /// x, ref x, x @ P, etc Binding { mutability: Mutability, name: ast::Name, mode: BindingMode<'tcx>, var: ast::NodeId, ty: Ty<'tcx>, subpattern: Option<Pattern<'tcx>>, }, /// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants Variant { adt_def: &'tcx AdtDef, substs: &'tcx Substs<'tcx>, variant_index: VariantIdx, subpatterns: Vec<FieldPattern<'tcx>>, }, /// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant Leaf { subpatterns: Vec<FieldPattern<'tcx>>, }, /// box P, &P, &mut P, etc Deref { subpattern: Pattern<'tcx>, }, Constant { value: &'tcx ty::Const<'tcx>, }, Range(PatternRange<'tcx>), /// matches against a slice, checking the length and extracting elements. /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty. /// e.g., `&[ref xs..]`. Slice { prefix: Vec<Pattern<'tcx>>, slice: Option<Pattern<'tcx>>, suffix: Vec<Pattern<'tcx>>, }, /// fixed match against an array, irrefutable Array { prefix: Vec<Pattern<'tcx>>, slice: Option<Pattern<'tcx>>, suffix: Vec<Pattern<'tcx>>, }, } #[derive(Clone, Copy, Debug, PartialEq)] pub struct PatternRange<'tcx> { pub lo: &'tcx ty::Const<'tcx>, pub hi: &'tcx ty::Const<'tcx>, pub ty: Ty<'tcx>, pub end: RangeEnd, } impl<'tcx> fmt::Display for Pattern<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self.kind { PatternKind::Wild => write!(f, "_"), PatternKind::AscribeUserType { ref subpattern, .. } => write!(f, "{}: _", subpattern), PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => { let is_mut = match mode { BindingMode::ByValue => mutability == Mutability::Mut, BindingMode::ByRef(_, bk) => { write!(f, "ref ")?; match bk { BorrowKind::Mut { .. } => true, _ => false } } }; if is_mut { write!(f, "mut ")?; } write!(f, "{}", name)?; if let Some(ref subpattern) = *subpattern { write!(f, " @ {}", subpattern)?; } Ok(()) } PatternKind::Variant { ref subpatterns, .. } | PatternKind::Leaf { ref subpatterns } => { let variant = match *self.kind { PatternKind::Variant { adt_def, variant_index, .. } => { Some(&adt_def.variants[variant_index]) } _ => if let ty::Adt(adt, _) = self.ty.sty { if !adt.is_enum() { Some(&adt.variants[VariantIdx::new(0)]) } else { None } } else { None } }; let mut first = true; let mut start_or_continue = || if first { first = false; "" } else { ", " }; if let Some(variant) = variant { write!(f, "{}", variant.name)?; // Only for Adt we can have `S {...}`, // which we handle separately here. if variant.ctor_kind == CtorKind::Fictive { write!(f, " {{ ")?; let mut printed = 0; for p in subpatterns { if let PatternKind::Wild = *p.pattern.kind { continue; } let name = variant.fields[p.field.index()].ident; write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?; printed += 1; } if printed < variant.fields.len() { write!(f, "{}..", start_or_continue())?; } return write!(f, " }}"); } } let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len()); if num_fields != 0 || variant.is_none() { write!(f, "(")?; for i in 0..num_fields { write!(f, "{}", start_or_continue())?; // Common case: the field is where we expect it. if let Some(p) = subpatterns.get(i) { if p.field.index() == i { write!(f, "{}", p.pattern)?; continue; } } // Otherwise, we have to go looking for it. if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) { write!(f, "{}", p.pattern)?; } else { write!(f, "_")?; } } write!(f, ")")?; } Ok(()) } PatternKind::Deref { ref subpattern } => { match self.ty.sty { ty::Adt(def, _) if def.is_box() => write!(f, "box ")?, ty::Ref(_, _, mutbl) => { write!(f, "&")?; if mutbl == hir::MutMutable { write!(f, "mut ")?; } } _ => bug!("{} is a bad Deref pattern type", self.ty) } write!(f, "{}", subpattern) } PatternKind::Constant { value } => { fmt_const_val(f, value) } PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => { fmt_const_val(f, lo)?; match end { RangeEnd::Included => write!(f, "..=")?, RangeEnd::Excluded => write!(f, "..")?, } fmt_const_val(f, hi) } PatternKind::Slice { ref prefix, ref slice, ref suffix } | PatternKind::Array { ref prefix, ref slice, ref suffix } => { let mut first = true; let mut start_or_continue = || if first { first = false; "" } else { ", " }; write!(f, "[")?; for p in prefix { write!(f, "{}{}", start_or_continue(), p)?; } if let Some(ref slice) = *slice { write!(f, "{}", start_or_continue())?; match *slice.kind { PatternKind::Wild => {} _ => write!(f, "{}", slice)? } write!(f, "..")?; } for p in suffix { write!(f, "{}{}", start_or_continue(), p)?; } write!(f, "]") } } } } pub struct PatternContext<'a, 'tcx: 'a> { pub tcx: TyCtxt<'a, 'tcx, 'tcx>, pub param_env: ty::ParamEnv<'tcx>, pub tables: &'a ty::TypeckTables<'tcx>, pub substs: &'tcx Substs<'tcx>, pub errors: Vec<PatternError>, } impl<'a, 'tcx> Pattern<'tcx> { pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>, param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>, tables: &'a ty::TypeckTables<'tcx>, pat: &'tcx hir::Pat) -> Self { let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables); let result = pcx.lower_pattern(pat); if !pcx.errors.is_empty() { let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors); tcx.sess.delay_span_bug(pat.span, &msg); } debug!("Pattern::from_hir({:?}) = {:?}", pat, result); result } } impl<'a, 'tcx> PatternContext<'a, 'tcx> { pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>, tables: &'a ty::TypeckTables<'tcx>) -> Self { PatternContext { tcx, param_env: param_env_and_substs.param_env, tables, substs: param_env_and_substs.value, errors: vec![] } } pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> { // When implicit dereferences have been inserted in this pattern, the unadjusted lowered // pattern has the type that results *after* dereferencing. For example, in this code: // // ``` // match &&Some(0i32) { // Some(n) => { ... }, // _ => { ... }, // } // ``` // // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is // determined in rustc_typeck::check::match). The adjustments would be // // `vec![&&Option<i32>, &Option<i32>]`. // // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted // gets the least-dereferenced type). let unadjusted_pat = self.lower_pattern_unadjusted(pat); self.tables .pat_adjustments() .get(pat.hir_id) .unwrap_or(&vec![]) .iter() .rev() .fold(unadjusted_pat, |pat, ref_ty| { debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty); Pattern { span: pat.span, ty: ref_ty, kind: Box::new(PatternKind::Deref { subpattern: pat }), } }, ) } fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> { let mut ty = self.tables.node_id_to_type(pat.hir_id); let kind = match pat.node { PatKind::Wild => PatternKind::Wild, PatKind::Lit(ref value) => self.lower_lit(value), PatKind::Range(ref lo_expr, ref hi_expr, end) => { match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) { (PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => { use std::cmp::Ordering; let cmp = compare_const_vals( self.tcx, lo, hi, self.param_env.and(ty), ); match (end, cmp) { (RangeEnd::Excluded, Some(Ordering::Less)) => PatternKind::Range(PatternRange { lo, hi, ty, end }), (RangeEnd::Excluded, _) => { span_err!( self.tcx.sess, lo_expr.span, E0579, "lower range bound must be less than upper", ); PatternKind::Wild } (RangeEnd::Included, Some(Ordering::Equal)) => { PatternKind::Constant { value: lo } } (RangeEnd::Included, Some(Ordering::Less)) => { PatternKind::Range(PatternRange { lo, hi, ty, end }) } (RangeEnd::Included, _) => { let mut err = struct_span_err!( self.tcx.sess, lo_expr.span, E0030, "lower range bound must be less than or equal to upper" ); err.span_label( lo_expr.span, "lower bound larger than upper bound", ); if self.tcx.sess.teach(&err.get_code().unwrap()) { err.note("When matching against a range, the compiler \ verifies that the range is non-empty. Range \ patterns include both end-points, so this is \ equivalent to requiring the start of the range \ to be less than or equal to the end of the range."); } err.emit(); PatternKind::Wild } } } _ => PatternKind::Wild } } PatKind::Path(ref qpath) => { return self.lower_path(qpath, pat.hir_id, pat.span); } PatKind::Ref(ref subpattern, _) | PatKind::Box(ref subpattern) => { PatternKind::Deref { subpattern: self.lower_pattern(subpattern) } } PatKind::Slice(ref prefix, ref slice, ref suffix) => { match ty.sty { ty::Ref(_, ty, _) => PatternKind::Deref { subpattern: Pattern { ty, span: pat.span, kind: Box::new(self.slice_or_array_pattern( pat.span, ty, prefix, slice, suffix)) }, }, ty::Slice(..) | ty::Array(..) => self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix), ty::Error => { // Avoid ICE return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) }; } ref sty => span_bug!( pat.span, "unexpanded type for vector pattern: {:?}", sty), } } PatKind::Tuple(ref subpatterns, ddpos) => { match ty.sty { ty::Tuple(ref tys) => { let subpatterns = subpatterns.iter() .enumerate_and_adjust(tys.len(), ddpos) .map(|(i, subpattern)| FieldPattern { field: Field::new(i), pattern: self.lower_pattern(subpattern) }) .collect(); PatternKind::Leaf { subpatterns } } ty::Error => { // Avoid ICE (#50577) return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) }; } ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty), } } PatKind::Binding(_, id, ident, ref sub) => { let var_ty = self.tables.node_id_to_type(pat.hir_id); let region = match var_ty.sty { ty::Ref(r, _, _) => Some(r), ty::Error => { // Avoid ICE return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) }; } _ => None, }; let bm = *self.tables.pat_binding_modes().get(pat.hir_id) .expect("missing binding mode"); let (mutability, mode) = match bm { ty::BindByValue(hir::MutMutable) => (Mutability::Mut, BindingMode::ByValue), ty::BindByValue(hir::MutImmutable) => (Mutability::Not, BindingMode::ByValue), ty::BindByReference(hir::MutMutable) => (Mutability::Not, BindingMode::ByRef( region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })), ty::BindByReference(hir::MutImmutable) => (Mutability::Not, BindingMode::ByRef( region.unwrap(), BorrowKind::Shared)), }; // A ref x pattern is the same node used for x, and as such it has // x's type, which is &T, where we want T (the type being matched). if let ty::BindByReference(_) = bm { if let ty::Ref(_, rty, _) = ty.sty { ty = rty; } else { bug!("`ref {}` has wrong type {}", ident, ty); } } PatternKind::Binding { mutability, mode, name: ident.name, var: id, ty: var_ty, subpattern: self.lower_opt_pattern(sub), } } PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => { let def = self.tables.qpath_def(qpath, pat.hir_id); let adt_def = match ty.sty { ty::Adt(adt_def, _) => adt_def, ty::Error => { // Avoid ICE (#50585) return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) }; } _ => span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty.sty), }; let variant_def = adt_def.variant_of_def(def); let subpatterns = subpatterns.iter() .enumerate_and_adjust(variant_def.fields.len(), ddpos) .map(|(i, field)| FieldPattern { field: Field::new(i), pattern: self.lower_pattern(field), }) .collect(); self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns) } PatKind::Struct(ref qpath, ref fields, _) => { let def = self.tables.qpath_def(qpath, pat.hir_id); let subpatterns = fields.iter() .map(|field| { FieldPattern { field: Field::new(self.tcx.field_index(field.node.id, self.tables)), pattern: self.lower_pattern(&field.node.pat), } }) .collect(); self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns) } }; Pattern { span: pat.span, ty, kind: Box::new(kind), } } fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> { pats.iter().map(|p| self.lower_pattern(p)).collect() } fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>> { pat.as_ref().map(|p| self.lower_pattern(p)) } fn flatten_nested_slice_patterns( &mut self, prefix: Vec<Pattern<'tcx>>, slice: Option<Pattern<'tcx>>, suffix: Vec<Pattern<'tcx>>) -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>) { let orig_slice = match slice { Some(orig_slice) => orig_slice, None => return (prefix, slice, suffix) }; let orig_prefix = prefix; let orig_suffix = suffix; // dance because of intentional borrow-checker stupidity. let kind = *orig_slice.kind; match kind { PatternKind::Slice { prefix, slice, mut suffix } | PatternKind::Array { prefix, slice, mut suffix } => { let mut orig_prefix = orig_prefix; orig_prefix.extend(prefix); suffix.extend(orig_suffix); (orig_prefix, slice, suffix) } _ => { (orig_prefix, Some(Pattern { kind: box kind, ..orig_slice }), orig_suffix) } } } fn slice_or_array_pattern( &mut self, span: Span, ty: Ty<'tcx>, prefix: &'tcx [P<hir::Pat>], slice: &'tcx Option<P<hir::Pat>>, suffix: &'tcx [P<hir::Pat>]) -> PatternKind<'tcx> { let prefix = self.lower_patterns(prefix); let slice = self.lower_opt_pattern(slice); let suffix = self.lower_patterns(suffix); let (prefix, slice, suffix) = self.flatten_nested_slice_patterns(prefix, slice, suffix); match ty.sty { ty::Slice(..) => { // matching a slice or fixed-length array PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix } } ty::Array(_, len) => { // fixed-length array let len = len.unwrap_usize(self.tcx); assert!(len >= prefix.len() as u64 + suffix.len() as u64); PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix } } _ => { span_bug!(span, "bad slice pattern type {:?}", ty); } } } fn lower_variant_or_leaf( &mut self, def: Def, hir_id: hir::HirId, span: Span, ty: Ty<'tcx>, subpatterns: Vec<FieldPattern<'tcx>>, ) -> PatternKind<'tcx> { let mut kind = match def { Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => { let enum_id = self.tcx.parent_def_id(variant_id).unwrap(); let adt_def = self.tcx.adt_def(enum_id); if adt_def.is_enum() { let substs = match ty.sty { ty::Adt(_, substs) | ty::FnDef(_, substs) => substs, ty::Error => { // Avoid ICE (#50585) return PatternKind::Wild; } _ => bug!("inappropriate type for def: {:?}", ty.sty), }; PatternKind::Variant { adt_def, substs, variant_index: adt_def.variant_index_with_id(variant_id), subpatterns, } } else { PatternKind::Leaf { subpatterns } } } Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) | Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => { PatternKind::Leaf { subpatterns } } _ => { self.errors.push(PatternError::NonConstPath(span)); PatternKind::Wild } }; if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) { let subpattern = Pattern { span, ty, kind: Box::new(kind), }; debug!("pattern user_ty = {:?} for pattern at {:?}", user_ty, span); let pat_ty = PatternTypeProjection::from_user_type(user_ty); kind = PatternKind::AscribeUserType { subpattern, user_ty: pat_ty, user_ty_span: span, }; } kind } /// Takes a HIR Path. If the path is a constant, evaluates it and feeds /// it to `const_to_pat`. Any other path (like enum variants without fields) /// is converted to the corresponding pattern via `lower_variant_or_leaf` fn lower_path(&mut self, qpath: &hir::QPath, id: hir::HirId, span: Span) -> Pattern<'tcx> { let ty = self.tables.node_id_to_type(id); let def = self.tables.qpath_def(qpath, id); let is_associated_const = match def { Def::AssociatedConst(_) => true, _ => false, }; let kind = match def { Def::Const(def_id) | Def::AssociatedConst(def_id) => { let substs = self.tables.node_substs(id); match ty::Instance::resolve( self.tcx, self.param_env, def_id, substs, ) { Some(instance) => { let cid = GlobalId { instance, promoted: None, }; match self.tcx.at(span).const_eval(self.param_env.and(cid)) { Ok(value) => { return self.const_to_pat(instance, value, id, span) }, Err(_) => { self.tcx.sess.span_err( span, "could not evaluate constant pattern", ); PatternKind::Wild } } }, None => { self.errors.push(if is_associated_const { PatternError::AssociatedConstInPattern(span) } else { PatternError::StaticInPattern(span) }); PatternKind::Wild }, } } _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]), }; Pattern { span, ty, kind: Box::new(kind), } } /// Converts literals, paths and negation of literals to patterns. /// The special case for negation exists to allow things like -128i8 /// which would overflow if we tried to evaluate 128i8 and then negate /// afterwards. fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> { match expr.node { hir::ExprKind::Lit(ref lit) => { let ty = self.tables.expr_ty(expr); match lit_to_const(&lit.node, self.tcx, ty, false) { Ok(val) => { let instance = ty::Instance::new( self.tables.local_id_root.expect("literal outside any scope"), self.substs, ); *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind }, Err(LitToConstError::UnparseableFloat) => { self.errors.push(PatternError::FloatBug); PatternKind::Wild }, Err(LitToConstError::Reported) => PatternKind::Wild, } }, hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind, hir::ExprKind::Unary(hir::UnNeg, ref expr) => { let ty = self.tables.expr_ty(expr); let lit = match expr.node { hir::ExprKind::Lit(ref lit) => lit, _ => span_bug!(expr.span, "not a literal: {:?}", expr), }; match lit_to_const(&lit.node, self.tcx, ty, true) { Ok(val) => { let instance = ty::Instance::new( self.tables.local_id_root.expect("literal outside any scope"), self.substs, ); *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind }, Err(LitToConstError::UnparseableFloat) => { self.errors.push(PatternError::FloatBug); PatternKind::Wild }, Err(LitToConstError::Reported) => PatternKind::Wild, } } _ => span_bug!(expr.span, "not a literal: {:?}", expr), } } /// Converts an evaluated constant to a pattern (if possible). /// This means aggregate values (like structs and enums) are converted /// to a pattern that matches the value (as if you'd compare via eq). fn const_to_pat( &self, instance: ty::Instance<'tcx>, cv: &'tcx ty::Const<'tcx>, id: hir::HirId, span: Span, ) -> Pattern<'tcx> { debug!("const_to_pat: cv={:#?}", cv); let adt_subpattern = |i, variant_opt| { let field = Field::new(i); let val = const_field( self.tcx, self.param_env, instance, variant_opt, field, cv, ).expect("field access failed"); self.const_to_pat(instance, val, id, span) }; let adt_subpatterns = |n, variant_opt| { (0..n).map(|i| { let field = Field::new(i); FieldPattern { field, pattern: adt_subpattern(i, variant_opt), } }).collect::<Vec<_>>() }; let kind = match cv.ty.sty { ty::Float(_) => { let id = self.tcx.hir().hir_to_node_id(id); self.tcx.lint_node( ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN, id, span, "floating-point types cannot be used in patterns", ); PatternKind::Constant { value: cv, } }, ty::Adt(adt_def, _) if adt_def.is_union() => { // Matching on union fields is unsafe, we can't hide it in constants self.tcx.sess.span_err(span, "cannot use unions in constant patterns"); PatternKind::Wild } ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => { let msg = format!("to use a constant of type `{}` in a pattern, \ `{}` must be annotated with `#[derive(PartialEq, Eq)]`", self.tcx.item_path_str(adt_def.did), self.tcx.item_path_str(adt_def.did)); self.tcx.sess.span_err(span, &msg); PatternKind::Wild }, ty::Adt(adt_def, substs) if adt_def.is_enum() => { let variant_index = const_variant_index( self.tcx, self.param_env, instance, cv ).expect("const_variant_index failed"); let subpatterns = adt_subpatterns( adt_def.variants[variant_index].fields.len(), Some(variant_index), ); PatternKind::Variant { adt_def, substs, variant_index, subpatterns, } }, ty::Adt(adt_def, _) => { let struct_var = adt_def.non_enum_variant(); PatternKind::Leaf { subpatterns: adt_subpatterns(struct_var.fields.len(), None), } } ty::Tuple(fields) => { PatternKind::Leaf { subpatterns: adt_subpatterns(fields.len(), None), } } ty::Array(_, n) => { PatternKind::Array { prefix: (0..n.unwrap_usize(self.tcx)) .map(|i| adt_subpattern(i as usize, None)) .collect(), slice: None, suffix: Vec::new(), } } _ => { PatternKind::Constant { value: cv, } }, }; Pattern { span, ty: cv.ty, kind: Box::new(kind), } } } impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> { fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> { self.tcx } fn tables(&self) -> &ty::TypeckTables<'tcx> { self.tables } } pub trait PatternFoldable<'tcx> : Sized { fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self { self.super_fold_with(folder) } fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self; } pub trait PatternFolder<'tcx> : Sized { fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> { pattern.super_fold_with(self) } fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> { kind.super_fold_with(self) } } impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> { fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self { let content: T = (**self).fold_with(folder); box content } } impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> { fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self { self.iter().map(|t| t.fold_with(folder)).collect() } } impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> { fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{ self.as_ref().map(|t| t.fold_with(folder)) } } macro_rules! CloneImpls { (<$lt_tcx:tt> $($ty:ty),+) => { $( impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty { fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self { Clone::clone(self) } } )+ } } CloneImpls!{ <'tcx> Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>, Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef, &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserTypeAnnotation<'tcx>, UserTypeProjection<'tcx>, PatternTypeProjection<'tcx> } impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> { fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self { FieldPattern { field: self.field.fold_with(folder), pattern: self.pattern.fold_with(folder) } } } impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> { fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self { folder.fold_pattern(self) } fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self { Pattern { ty: self.ty.fold_with(folder), span: self.span.fold_with(folder), kind: self.kind.fold_with(folder) } } } impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> { fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self { folder.fold_pattern_kind(self) } fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self { match *self { PatternKind::Wild => PatternKind::Wild, PatternKind::AscribeUserType { ref subpattern, ref user_ty, user_ty_span, } => PatternKind::AscribeUserType { subpattern: subpattern.fold_with(folder), user_ty: user_ty.fold_with(folder), user_ty_span, }, PatternKind::Binding { mutability, name, mode, var, ty, ref subpattern, } => PatternKind::Binding { mutability: mutability.fold_with(folder), name: name.fold_with(folder), mode: mode.fold_with(folder), var: var.fold_with(folder), ty: ty.fold_with(folder), subpattern: subpattern.fold_with(folder), }, PatternKind::Variant { adt_def, substs, variant_index, ref subpatterns, } => PatternKind::Variant { adt_def: adt_def.fold_with(folder), substs: substs.fold_with(folder), variant_index, subpatterns: subpatterns.fold_with(folder) }, PatternKind::Leaf { ref subpatterns, } => PatternKind::Leaf { subpatterns: subpatterns.fold_with(folder), }, PatternKind::Deref { ref subpattern, } => PatternKind::Deref { subpattern: subpattern.fold_with(folder), }, PatternKind::Constant { value } => PatternKind::Constant { value: value.fold_with(folder) }, PatternKind::Range(PatternRange { lo, hi, ty, end, }) => PatternKind::Range(PatternRange { lo: lo.fold_with(folder), hi: hi.fold_with(folder), ty: ty.fold_with(folder), end, }), PatternKind::Slice { ref prefix, ref slice, ref suffix, } => PatternKind::Slice { prefix: prefix.fold_with(folder), slice: slice.fold_with(folder), suffix: suffix.fold_with(folder) }, PatternKind::Array { ref prefix, ref slice, ref suffix } => PatternKind::Array { prefix: prefix.fold_with(folder), slice: slice.fold_with(folder), suffix: suffix.fold_with(folder) }, } } } pub fn compare_const_vals<'a, 'gcx, 'tcx>( tcx: TyCtxt<'a, 'gcx, 'tcx>, a: &'tcx ty::Const<'tcx>, b: &'tcx ty::Const<'tcx>, ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>, ) -> Option<Ordering> { trace!("compare_const_vals: {:?}, {:?}", a, b); let from_bool = |v: bool| { if v { Some(Ordering::Equal) } else { None } }; let fallback = || from_bool(a == b); // Use the fallback if any type differs if a.ty != b.ty || a.ty != ty.value { return fallback(); } let tcx = tcx.global_tcx(); let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap(); // FIXME: This should use assert_bits(ty) instead of use_bits // but triggers possibly bugs due to mismatching of arrays and slices if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) { use ::rustc_apfloat::Float; return match ty.value.sty { ty::Float(ast::FloatTy::F32) => { let l = ::rustc_apfloat::ieee::Single::from_bits(a); let r = ::rustc_apfloat::ieee::Single::from_bits(b); l.partial_cmp(&r) }, ty::Float(ast::FloatTy::F64) => { let l = ::rustc_apfloat::ieee::Double::from_bits(a); let r = ::rustc_apfloat::ieee::Double::from_bits(b); l.partial_cmp(&r) }, ty::Int(_) => { let layout = tcx.layout_of(ty).ok()?; assert!(layout.abi.is_signed()); let a = sign_extend(a, layout.size); let b = sign_extend(b, layout.size); Some((a as i128).cmp(&(b as i128))) }, _ => Some(a.cmp(&b)), } } if let ty::Str = ty.value.sty { match (a.val, b.val) { ( ConstValue::ScalarPair( Scalar::Ptr(ptr_a), len_a, ), ConstValue::ScalarPair( Scalar::Ptr(ptr_b), len_b, ), ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => { if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) { if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) { if len_a == len_b { let map = tcx.alloc_map.lock(); let alloc_a = map.unwrap_memory(ptr_a.alloc_id); let alloc_b = map.unwrap_memory(ptr_b.alloc_id); if alloc_a.bytes.len() as u128 == len_a { return from_bool(alloc_a == alloc_b); } } } } } _ => (), } } fallback() }
{ let mut new = self.clone(); new.0.projs.push(ProjectionElem::Deref); new }
state.py
from statespacetimeseries.random_variables import MVN class State(MVN): """ The State object required for Kalman Filter. """ def __init__(self, mean, cov, variance):
super().__init__(mean, cov, variance) self.prediction = None
struct_pb.rs
// This file is generated by rust-protobuf 3.0.0-pre. Do not edit // .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![rustfmt::skip] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_results)] //! Generated file from `google/protobuf/struct.proto` /// `Struct` represents a structured data value, consisting of fields /// which map to dynamically typed values. In some languages, `Struct` /// might be supported by a native representation. For example, in /// scripting languages like JS a struct is represented as an /// object. The details of that representation are described together /// with the proto support for the language. /// /// The JSON representation for `Struct` is JSON object. #[derive(PartialEq,Clone,Default)] #[cfg_attr(serde, derive(Serialize, Deserialize))] pub struct Struct { // message fields /// Unordered map of dynamically typed values. #[cfg_attr(serde, serde(default))] pub fields: ::std::collections::HashMap<::std::string::String, Value>, // special fields #[cfg_attr(serde, serde(skip))] pub unknown_fields: crate::UnknownFields, #[cfg_attr(serde, serde(skip))] pub cached_size: crate::rt::CachedSize, } impl<'a> ::std::default::Default for &'a Struct { fn default() -> &'a Struct { <Struct as crate::Message>::default_instance() } } impl Struct { pub fn new() -> Struct { ::std::default::Default::default() } } impl crate::Message for Struct { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { crate::rt::read_map_into::<crate::reflect::types::ProtobufTypeString, crate::reflect::types::ProtobufTypeMessage<Value>>(wire_type, is, &mut self.fields)?; }, _ => { crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; my_size += crate::rt::compute_map_size::<crate::reflect::types::ProtobufTypeString, crate::reflect::types::ProtobufTypeMessage<Value>>(1, &self.fields); my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { crate::rt::write_map_with_cached_sizes::<crate::reflect::types::ProtobufTypeString, crate::reflect::types::ProtobufTypeMessage<Value>>(1, &self.fields, os)?; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &crate::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { &mut self.unknown_fields } fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> Struct { Struct::new() } fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(crate::reflect::rt::make_map_accessor::<_, crate::reflect::types::ProtobufTypeString, crate::reflect::types::ProtobufTypeMessage<Value>>( "fields", |m: &Struct| { &m.fields }, |m: &mut Struct| { &mut m.fields }, )); crate::reflect::MessageDescriptor::new::<Struct>( "Struct", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static Struct { static instance: crate::rt::LazyV2<Struct> = crate::rt::LazyV2::INIT; instance.get(Struct::new) } } impl crate::Clear for Struct { fn clear(&mut self) { self.fields.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for Struct { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Struct { } /// `Value` represents a dynamically typed value which can be either /// null, a number, a string, a boolean, a recursive struct value, or a /// list of values. A producer of value is expected to set one of that /// variants, absence of any variant indicates an error. /// /// The JSON representation for `Value` is JSON value. #[derive(PartialEq,Clone,Default)] #[cfg_attr(serde, derive(Serialize, Deserialize))] pub struct Value { // message oneof groups pub kind: ::std::option::Option<value::Kind>, // special fields #[cfg_attr(serde, serde(skip))] pub unknown_fields: crate::UnknownFields, #[cfg_attr(serde, serde(skip))] pub cached_size: crate::rt::CachedSize, } impl<'a> ::std::default::Default for &'a Value { fn default() -> &'a Value { <Value as crate::Message>::default_instance() } } impl Value { pub fn new() -> Value { ::std::default::Default::default() } // .google.protobuf.NullValue null_value = 1; pub fn get_null_value(&self) -> NullValue { match self.kind { ::std::option::Option::Some(value::Kind::null_value(v)) => crate::ProtobufEnumOrUnknown::enum_value_or_default(&v), _ => NullValue::NULL_VALUE, } } pub fn clear_null_value(&mut self) { self.kind = ::std::option::Option::None; }
match self.kind { ::std::option::Option::Some(value::Kind::null_value(..)) => true, _ => false, } } // Param is passed by value, moved pub fn set_null_value(&mut self, v: NullValue) { self.kind = ::std::option::Option::Some(value::Kind::null_value(crate::ProtobufEnumOrUnknown::new(v))) } // double number_value = 2; pub fn get_number_value(&self) -> f64 { match self.kind { ::std::option::Option::Some(value::Kind::number_value(v)) => v, _ => 0., } } pub fn clear_number_value(&mut self) { self.kind = ::std::option::Option::None; } pub fn has_number_value(&self) -> bool { match self.kind { ::std::option::Option::Some(value::Kind::number_value(..)) => true, _ => false, } } // Param is passed by value, moved pub fn set_number_value(&mut self, v: f64) { self.kind = ::std::option::Option::Some(value::Kind::number_value(v)) } // string string_value = 3; pub fn get_string_value(&self) -> &str { match self.kind { ::std::option::Option::Some(value::Kind::string_value(ref v)) => v, _ => "", } } pub fn clear_string_value(&mut self) { self.kind = ::std::option::Option::None; } pub fn has_string_value(&self) -> bool { match self.kind { ::std::option::Option::Some(value::Kind::string_value(..)) => true, _ => false, } } // Param is passed by value, moved pub fn set_string_value(&mut self, v: ::std::string::String) { self.kind = ::std::option::Option::Some(value::Kind::string_value(v)) } // Mutable pointer to the field. pub fn mut_string_value(&mut self) -> &mut ::std::string::String { if let ::std::option::Option::Some(value::Kind::string_value(_)) = self.kind { } else { self.kind = ::std::option::Option::Some(value::Kind::string_value(::std::string::String::new())); } match self.kind { ::std::option::Option::Some(value::Kind::string_value(ref mut v)) => v, _ => panic!(), } } // Take field pub fn take_string_value(&mut self) -> ::std::string::String { if self.has_string_value() { match self.kind.take() { ::std::option::Option::Some(value::Kind::string_value(v)) => v, _ => panic!(), } } else { ::std::string::String::new() } } // bool bool_value = 4; pub fn get_bool_value(&self) -> bool { match self.kind { ::std::option::Option::Some(value::Kind::bool_value(v)) => v, _ => false, } } pub fn clear_bool_value(&mut self) { self.kind = ::std::option::Option::None; } pub fn has_bool_value(&self) -> bool { match self.kind { ::std::option::Option::Some(value::Kind::bool_value(..)) => true, _ => false, } } // Param is passed by value, moved pub fn set_bool_value(&mut self, v: bool) { self.kind = ::std::option::Option::Some(value::Kind::bool_value(v)) } // .google.protobuf.Struct struct_value = 5; pub fn get_struct_value(&self) -> &Struct { match self.kind { ::std::option::Option::Some(value::Kind::struct_value(ref v)) => v, _ => <Struct as crate::Message>::default_instance(), } } pub fn clear_struct_value(&mut self) { self.kind = ::std::option::Option::None; } pub fn has_struct_value(&self) -> bool { match self.kind { ::std::option::Option::Some(value::Kind::struct_value(..)) => true, _ => false, } } // Param is passed by value, moved pub fn set_struct_value(&mut self, v: Struct) { self.kind = ::std::option::Option::Some(value::Kind::struct_value(v)) } // Mutable pointer to the field. pub fn mut_struct_value(&mut self) -> &mut Struct { if let ::std::option::Option::Some(value::Kind::struct_value(_)) = self.kind { } else { self.kind = ::std::option::Option::Some(value::Kind::struct_value(Struct::new())); } match self.kind { ::std::option::Option::Some(value::Kind::struct_value(ref mut v)) => v, _ => panic!(), } } // Take field pub fn take_struct_value(&mut self) -> Struct { if self.has_struct_value() { match self.kind.take() { ::std::option::Option::Some(value::Kind::struct_value(v)) => v, _ => panic!(), } } else { Struct::new() } } // .google.protobuf.ListValue list_value = 6; pub fn get_list_value(&self) -> &ListValue { match self.kind { ::std::option::Option::Some(value::Kind::list_value(ref v)) => v, _ => <ListValue as crate::Message>::default_instance(), } } pub fn clear_list_value(&mut self) { self.kind = ::std::option::Option::None; } pub fn has_list_value(&self) -> bool { match self.kind { ::std::option::Option::Some(value::Kind::list_value(..)) => true, _ => false, } } // Param is passed by value, moved pub fn set_list_value(&mut self, v: ListValue) { self.kind = ::std::option::Option::Some(value::Kind::list_value(v)) } // Mutable pointer to the field. pub fn mut_list_value(&mut self) -> &mut ListValue { if let ::std::option::Option::Some(value::Kind::list_value(_)) = self.kind { } else { self.kind = ::std::option::Option::Some(value::Kind::list_value(ListValue::new())); } match self.kind { ::std::option::Option::Some(value::Kind::list_value(ref mut v)) => v, _ => panic!(), } } // Take field pub fn take_list_value(&mut self) -> ListValue { if self.has_list_value() { match self.kind.take() { ::std::option::Option::Some(value::Kind::list_value(v)) => v, _ => panic!(), } } else { ListValue::new() } } } impl crate::Message for Value { fn is_initialized(&self) -> bool { if let Some(value::Kind::struct_value(ref v)) = self.kind { if !v.is_initialized() { return false; } } if let Some(value::Kind::list_value(ref v)) = self.kind { if !v.is_initialized() { return false; } } true } fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type != crate::wire_format::WireTypeVarint { return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); } self.kind = ::std::option::Option::Some(value::Kind::null_value(is.read_enum_or_unknown()?)); }, 2 => { if wire_type != crate::wire_format::WireTypeFixed64 { return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); } self.kind = ::std::option::Option::Some(value::Kind::number_value(is.read_double()?)); }, 3 => { if wire_type != crate::wire_format::WireTypeLengthDelimited { return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); } self.kind = ::std::option::Option::Some(value::Kind::string_value(is.read_string()?)); }, 4 => { if wire_type != crate::wire_format::WireTypeVarint { return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); } self.kind = ::std::option::Option::Some(value::Kind::bool_value(is.read_bool()?)); }, 5 => { if wire_type != crate::wire_format::WireTypeLengthDelimited { return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); } self.kind = ::std::option::Option::Some(value::Kind::struct_value(is.read_message()?)); }, 6 => { if wire_type != crate::wire_format::WireTypeLengthDelimited { return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); } self.kind = ::std::option::Option::Some(value::Kind::list_value(is.read_message()?)); }, _ => { crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if let ::std::option::Option::Some(ref v) = self.kind { match v { &value::Kind::null_value(v) => { my_size += crate::rt::enum_or_unknown_size(1, v); }, &value::Kind::number_value(v) => { my_size += 9; }, &value::Kind::string_value(ref v) => { my_size += crate::rt::string_size(3, &v); }, &value::Kind::bool_value(v) => { my_size += 2; }, &value::Kind::struct_value(ref v) => { let len = v.compute_size(); my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; }, &value::Kind::list_value(ref v) => { let len = v.compute_size(); my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; }, }; } my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { if let ::std::option::Option::Some(ref v) = self.kind { match v { &value::Kind::null_value(v) => { os.write_enum(1, crate::ProtobufEnumOrUnknown::value(&v))?; }, &value::Kind::number_value(v) => { os.write_double(2, v)?; }, &value::Kind::string_value(ref v) => { os.write_string(3, v)?; }, &value::Kind::bool_value(v) => { os.write_bool(4, v)?; }, &value::Kind::struct_value(ref v) => { crate::rt::write_message_field_with_cached_size(5, v, os)?; }, &value::Kind::list_value(ref v) => { crate::rt::write_message_field_with_cached_size(6, v, os)?; }, }; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &crate::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { &mut self.unknown_fields } fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> Value { Value::new() } fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(crate::reflect::rt::make_oneof_copy_has_get_set_accessors::<_, crate::reflect::types::ProtobufTypeEnum<NullValue>>( "null_value", Value::has_null_value, Value::get_null_value, Value::set_null_value, )); fields.push(crate::reflect::rt::make_oneof_copy_has_get_set_accessors::<_, crate::reflect::types::ProtobufTypeDouble>( "number_value", Value::has_number_value, Value::get_number_value, Value::set_number_value, )); fields.push(crate::reflect::rt::make_oneof_deref_has_get_set_accessor::<_, crate::reflect::types::ProtobufTypeString>( "string_value", Value::has_string_value, Value::get_string_value, Value::set_string_value, )); fields.push(crate::reflect::rt::make_oneof_copy_has_get_set_accessors::<_, crate::reflect::types::ProtobufTypeBool>( "bool_value", Value::has_bool_value, Value::get_bool_value, Value::set_bool_value, )); fields.push(crate::reflect::rt::make_oneof_message_has_get_mut_set_accessor::<_, Struct>( "struct_value", Value::has_struct_value, Value::get_struct_value, Value::mut_struct_value, Value::set_struct_value, )); fields.push(crate::reflect::rt::make_oneof_message_has_get_mut_set_accessor::<_, ListValue>( "list_value", Value::has_list_value, Value::get_list_value, Value::mut_list_value, Value::set_list_value, )); crate::reflect::MessageDescriptor::new::<Value>( "Value", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static Value { static instance: crate::rt::LazyV2<Value> = crate::rt::LazyV2::INIT; instance.get(Value::new) } } impl crate::Clear for Value { fn clear(&mut self) { self.kind = ::std::option::Option::None; self.kind = ::std::option::Option::None; self.kind = ::std::option::Option::None; self.kind = ::std::option::Option::None; self.kind = ::std::option::Option::None; self.kind = ::std::option::Option::None; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for Value { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Value { } /// Nested message and enums of message `Value` pub mod value { #[derive(Clone,PartialEq,Debug)] #[cfg_attr(serde, derive(Serialize, Deserialize))] pub enum Kind { null_value(crate::ProtobufEnumOrUnknown<super::NullValue>), number_value(f64), string_value(::std::string::String), bool_value(bool), struct_value(super::Struct), list_value(super::ListValue), } impl crate::Oneof for Kind { } } /// `ListValue` is a wrapper around a repeated field of values. /// /// The JSON representation for `ListValue` is JSON array. #[derive(PartialEq,Clone,Default)] #[cfg_attr(serde, derive(Serialize, Deserialize))] pub struct ListValue { // message fields /// Repeated field of dynamically typed values. pub values: crate::RepeatedField<Value>, // special fields #[cfg_attr(serde, serde(skip))] pub unknown_fields: crate::UnknownFields, #[cfg_attr(serde, serde(skip))] pub cached_size: crate::rt::CachedSize, } impl<'a> ::std::default::Default for &'a ListValue { fn default() -> &'a ListValue { <ListValue as crate::Message>::default_instance() } } impl ListValue { pub fn new() -> ListValue { ::std::default::Default::default() } } impl crate::Message for ListValue { fn is_initialized(&self) -> bool { for v in &self.values { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { crate::rt::read_repeated_message_into_repeated_field(wire_type, is, &mut self.values)?; }, _ => { crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; for value in &self.values { let len = value.compute_size(); my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; }; my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { for v in &self.values { crate::rt::write_message_field_with_cached_size(1, v, os)?; }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &crate::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { &mut self.unknown_fields } fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> ListValue { ListValue::new() } fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(crate::reflect::rt::make_repeated_field_accessor::<_, crate::reflect::types::ProtobufTypeMessage<Value>>( "values", |m: &ListValue| { &m.values }, |m: &mut ListValue| { &mut m.values }, )); crate::reflect::MessageDescriptor::new::<ListValue>( "ListValue", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static ListValue { static instance: crate::rt::LazyV2<ListValue> = crate::rt::LazyV2::INIT; instance.get(ListValue::new) } } impl crate::Clear for ListValue { fn clear(&mut self) { self.values.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for ListValue { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for ListValue { } /// `NullValue` is a singleton enumeration to represent the null value for the /// `Value` type union. /// /// The JSON representation for `NullValue` is JSON `null`. #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] #[cfg_attr(serde, derive(Serialize, Deserialize))] pub enum NullValue { NULL_VALUE = 0, } impl crate::ProtobufEnum for NullValue { fn value(&self) -> i32 { *self as i32 } fn from_i32(value: i32) -> ::std::option::Option<NullValue> { match value { 0 => ::std::option::Option::Some(NullValue::NULL_VALUE), _ => ::std::option::Option::None } } fn values() -> &'static [Self] { static values: &'static [NullValue] = &[ NullValue::NULL_VALUE, ]; values } fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; descriptor.get(|| { crate::reflect::EnumDescriptor::new::<NullValue>("NullValue", file_descriptor_proto()) }) } } impl ::std::default::Default for NullValue { fn default() -> Self { NullValue::NULL_VALUE } } impl crate::reflect::ProtobufValue for NullValue { } static file_descriptor_proto_data: &'static [u8] = b"\ \n\x1cgoogle/protobuf/struct.proto\x12\x0fgoogle.protobuf\"\x98\x01\n\ \x06Struct\x12;\n\x06fields\x18\x01\x20\x03(\x0b2#.google.protobuf.Struc\ t.FieldsEntryR\x06fields\x1aQ\n\x0bFieldsEntry\x12\x10\n\x03key\x18\x01\ \x20\x01(\tR\x03key\x12,\n\x05value\x18\x02\x20\x01(\x0b2\x16.google.pro\ tobuf.ValueR\x05value:\x028\x01\"\xb2\x02\n\x05Value\x12;\n\nnull_value\ \x18\x01\x20\x01(\x0e2\x1a.google.protobuf.NullValueH\0R\tnullValue\x12#\ \n\x0cnumber_value\x18\x02\x20\x01(\x01H\0R\x0bnumberValue\x12#\n\x0cstr\ ing_value\x18\x03\x20\x01(\tH\0R\x0bstringValue\x12\x1f\n\nbool_value\ \x18\x04\x20\x01(\x08H\0R\tboolValue\x12<\n\x0cstruct_value\x18\x05\x20\ \x01(\x0b2\x17.google.protobuf.StructH\0R\x0bstructValue\x12;\n\nlist_va\ lue\x18\x06\x20\x01(\x0b2\x1a.google.protobuf.ListValueH\0R\tlistValueB\ \x06\n\x04kind\";\n\tListValue\x12.\n\x06values\x18\x01\x20\x03(\x0b2\ \x16.google.protobuf.ValueR\x06values*\x1b\n\tNullValue\x12\x0e\n\nNULL_\ VALUE\x10\0B\x81\x01\n\x13com.google.protobufB\x0bStructProtoP\x01Z1gith\ ub.com/golang/protobuf/ptypes/struct;structpb\xf8\x01\x01\xa2\x02\x03GPB\ \xaa\x02\x1eGoogle.Protobuf.WellKnownTypesJ\x99\x1d\n\x06\x12\x04\x1e\0_\ \x01\n\xcc\x0c\n\x01\x0c\x12\x03\x1e\0\x122\xc1\x0c\x20Protocol\x20Buffe\ rs\x20-\x20Google's\x20data\x20interchange\x20format\n\x20Copyright\x202\ 008\x20Google\x20Inc.\x20\x20All\x20rights\x20reserved.\n\x20https://dev\ elopers.google.com/protocol-buffers/\n\n\x20Redistribution\x20and\x20use\ \x20in\x20source\x20and\x20binary\x20forms,\x20with\x20or\x20without\n\ \x20modification,\x20are\x20permitted\x20provided\x20that\x20the\x20foll\ owing\x20conditions\x20are\n\x20met:\n\n\x20\x20\x20\x20\x20*\x20Redistr\ ibutions\x20of\x20source\x20code\x20must\x20retain\x20the\x20above\x20co\ pyright\n\x20notice,\x20this\x20list\x20of\x20conditions\x20and\x20the\ \x20following\x20disclaimer.\n\x20\x20\x20\x20\x20*\x20Redistributions\ \x20in\x20binary\x20form\x20must\x20reproduce\x20the\x20above\n\x20copyr\ ight\x20notice,\x20this\x20list\x20of\x20conditions\x20and\x20the\x20fol\ lowing\x20disclaimer\n\x20in\x20the\x20documentation\x20and/or\x20other\ \x20materials\x20provided\x20with\x20the\n\x20distribution.\n\x20\x20\ \x20\x20\x20*\x20Neither\x20the\x20name\x20of\x20Google\x20Inc.\x20nor\ \x20the\x20names\x20of\x20its\n\x20contributors\x20may\x20be\x20used\x20\ to\x20endorse\x20or\x20promote\x20products\x20derived\x20from\n\x20this\ \x20software\x20without\x20specific\x20prior\x20written\x20permission.\n\ \n\x20THIS\x20SOFTWARE\x20IS\x20PROVIDED\x20BY\x20THE\x20COPYRIGHT\x20HO\ LDERS\x20AND\x20CONTRIBUTORS\n\x20\"AS\x20IS\"\x20AND\x20ANY\x20EXPRESS\ \x20OR\x20IMPLIED\x20WARRANTIES,\x20INCLUDING,\x20BUT\x20NOT\n\x20LIMITE\ D\x20TO,\x20THE\x20IMPLIED\x20WARRANTIES\x20OF\x20MERCHANTABILITY\x20AND\ \x20FITNESS\x20FOR\n\x20A\x20PARTICULAR\x20PURPOSE\x20ARE\x20DISCLAIMED.\ \x20IN\x20NO\x20EVENT\x20SHALL\x20THE\x20COPYRIGHT\n\x20OWNER\x20OR\x20C\ ONTRIBUTORS\x20BE\x20LIABLE\x20FOR\x20ANY\x20DIRECT,\x20INDIRECT,\x20INC\ IDENTAL,\n\x20SPECIAL,\x20EXEMPLARY,\x20OR\x20CONSEQUENTIAL\x20DAMAGES\ \x20(INCLUDING,\x20BUT\x20NOT\n\x20LIMITED\x20TO,\x20PROCUREMENT\x20OF\ \x20SUBSTITUTE\x20GOODS\x20OR\x20SERVICES;\x20LOSS\x20OF\x20USE,\n\x20DA\ TA,\x20OR\x20PROFITS;\x20OR\x20BUSINESS\x20INTERRUPTION)\x20HOWEVER\x20C\ AUSED\x20AND\x20ON\x20ANY\n\x20THEORY\x20OF\x20LIABILITY,\x20WHETHER\x20\ IN\x20CONTRACT,\x20STRICT\x20LIABILITY,\x20OR\x20TORT\n\x20(INCLUDING\ \x20NEGLIGENCE\x20OR\x20OTHERWISE)\x20ARISING\x20IN\x20ANY\x20WAY\x20OUT\ \x20OF\x20THE\x20USE\n\x20OF\x20THIS\x20SOFTWARE,\x20EVEN\x20IF\x20ADVIS\ ED\x20OF\x20THE\x20POSSIBILITY\x20OF\x20SUCH\x20DAMAGE.\n\n\x08\n\x01\ \x02\x12\x03\x20\0\x18\n\x08\n\x01\x08\x12\x03\"\0;\n\t\n\x02\x08%\x12\ \x03\"\0;\n\x08\n\x01\x08\x12\x03#\0\x1f\n\t\n\x02\x08\x1f\x12\x03#\0\ \x1f\n\x08\n\x01\x08\x12\x03$\0H\n\t\n\x02\x08\x0b\x12\x03$\0H\n\x08\n\ \x01\x08\x12\x03%\0,\n\t\n\x02\x08\x01\x12\x03%\0,\n\x08\n\x01\x08\x12\ \x03&\0,\n\t\n\x02\x08\x08\x12\x03&\0,\n\x08\n\x01\x08\x12\x03'\0\"\n\t\ \n\x02\x08\n\x12\x03'\0\"\n\x08\n\x01\x08\x12\x03(\0!\n\t\n\x02\x08$\x12\ \x03(\0!\n\xb3\x03\n\x02\x04\0\x12\x043\06\x01\x1a\xa6\x03\x20`Struct`\ \x20represents\x20a\x20structured\x20data\x20value,\x20consisting\x20of\ \x20fields\n\x20which\x20map\x20to\x20dynamically\x20typed\x20values.\ \x20In\x20some\x20languages,\x20`Struct`\n\x20might\x20be\x20supported\ \x20by\x20a\x20native\x20representation.\x20For\x20example,\x20in\n\x20s\ cripting\x20languages\x20like\x20JS\x20a\x20struct\x20is\x20represented\ \x20as\x20an\n\x20object.\x20The\x20details\x20of\x20that\x20representat\ ion\x20are\x20described\x20together\n\x20with\x20the\x20proto\x20support\ \x20for\x20the\x20language.\n\n\x20The\x20JSON\x20representation\x20for\ \x20`Struct`\x20is\x20JSON\x20object.\n\n\n\n\x03\x04\0\x01\x12\x033\x08\ \x0e\n9\n\x04\x04\0\x02\0\x12\x035\x02\x20\x1a,\x20Unordered\x20map\x20o\ f\x20dynamically\x20typed\x20values.\n\n\x0c\n\x05\x04\0\x02\0\x06\x12\ \x035\x02\x14\n\x0c\n\x05\x04\0\x02\0\x01\x12\x035\x15\x1b\n\x0c\n\x05\ \x04\0\x02\0\x03\x12\x035\x1e\x1f\n\xc3\x02\n\x02\x04\x01\x12\x04>\0N\ \x01\x1a\xb6\x02\x20`Value`\x20represents\x20a\x20dynamically\x20typed\ \x20value\x20which\x20can\x20be\x20either\n\x20null,\x20a\x20number,\x20\ a\x20string,\x20a\x20boolean,\x20a\x20recursive\x20struct\x20value,\x20o\ r\x20a\n\x20list\x20of\x20values.\x20A\x20producer\x20of\x20value\x20is\ \x20expected\x20to\x20set\x20one\x20of\x20that\n\x20variants,\x20absence\ \x20of\x20any\x20variant\x20indicates\x20an\x20error.\n\n\x20The\x20JSON\ \x20representation\x20for\x20`Value`\x20is\x20JSON\x20value.\n\n\n\n\x03\ \x04\x01\x01\x12\x03>\x08\r\n\"\n\x04\x04\x01\x08\0\x12\x04@\x02M\x03\ \x1a\x14\x20The\x20kind\x20of\x20value.\n\n\x0c\n\x05\x04\x01\x08\0\x01\ \x12\x03@\x08\x0c\n'\n\x04\x04\x01\x02\0\x12\x03B\x04\x1d\x1a\x1a\x20Rep\ resents\x20a\x20null\x20value.\n\n\x0c\n\x05\x04\x01\x02\0\x06\x12\x03B\ \x04\r\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03B\x0e\x18\n\x0c\n\x05\x04\ \x01\x02\0\x03\x12\x03B\x1b\x1c\n)\n\x04\x04\x01\x02\x01\x12\x03D\x04\ \x1c\x1a\x1c\x20Represents\x20a\x20double\x20value.\n\n\x0c\n\x05\x04\ \x01\x02\x01\x05\x12\x03D\x04\n\n\x0c\n\x05\x04\x01\x02\x01\x01\x12\x03D\ \x0b\x17\n\x0c\n\x05\x04\x01\x02\x01\x03\x12\x03D\x1a\x1b\n)\n\x04\x04\ \x01\x02\x02\x12\x03F\x04\x1c\x1a\x1c\x20Represents\x20a\x20string\x20va\ lue.\n\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03F\x04\n\n\x0c\n\x05\x04\ \x01\x02\x02\x01\x12\x03F\x0b\x17\n\x0c\n\x05\x04\x01\x02\x02\x03\x12\ \x03F\x1a\x1b\n*\n\x04\x04\x01\x02\x03\x12\x03H\x04\x18\x1a\x1d\x20Repre\ sents\x20a\x20boolean\x20value.\n\n\x0c\n\x05\x04\x01\x02\x03\x05\x12\ \x03H\x04\x08\n\x0c\n\x05\x04\x01\x02\x03\x01\x12\x03H\t\x13\n\x0c\n\x05\ \x04\x01\x02\x03\x03\x12\x03H\x16\x17\n-\n\x04\x04\x01\x02\x04\x12\x03J\ \x04\x1c\x1a\x20\x20Represents\x20a\x20structured\x20value.\n\n\x0c\n\ \x05\x04\x01\x02\x04\x06\x12\x03J\x04\n\n\x0c\n\x05\x04\x01\x02\x04\x01\ \x12\x03J\x0b\x17\n\x0c\n\x05\x04\x01\x02\x04\x03\x12\x03J\x1a\x1b\n-\n\ \x04\x04\x01\x02\x05\x12\x03L\x04\x1d\x1a\x20\x20Represents\x20a\x20repe\ ated\x20`Value`.\n\n\x0c\n\x05\x04\x01\x02\x05\x06\x12\x03L\x04\r\n\x0c\ \n\x05\x04\x01\x02\x05\x01\x12\x03L\x0e\x18\n\x0c\n\x05\x04\x01\x02\x05\ \x03\x12\x03L\x1b\x1c\n\xa9\x01\n\x02\x05\0\x12\x04T\0W\x01\x1a\x9c\x01\ \x20`NullValue`\x20is\x20a\x20singleton\x20enumeration\x20to\x20represen\ t\x20the\x20null\x20value\x20for\x20the\n\x20`Value`\x20type\x20union.\n\ \n\x20\x20The\x20JSON\x20representation\x20for\x20`NullValue`\x20is\x20J\ SON\x20`null`.\n\n\n\n\x03\x05\0\x01\x12\x03T\x05\x0e\n\x1a\n\x04\x05\0\ \x02\0\x12\x03V\x02\x11\x1a\r\x20Null\x20value.\n\n\x0c\n\x05\x05\0\x02\ \0\x01\x12\x03V\x02\x0c\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03V\x0f\x10\n\ \x82\x01\n\x02\x04\x02\x12\x04\\\0_\x01\x1av\x20`ListValue`\x20is\x20a\ \x20wrapper\x20around\x20a\x20repeated\x20field\x20of\x20values.\n\n\x20\ The\x20JSON\x20representation\x20for\x20`ListValue`\x20is\x20JSON\x20arr\ ay.\n\n\n\n\x03\x04\x02\x01\x12\x03\\\x08\x11\n:\n\x04\x04\x02\x02\0\x12\ \x03^\x02\x1c\x1a-\x20Repeated\x20field\x20of\x20dynamically\x20typed\ \x20values.\n\n\x0c\n\x05\x04\x02\x02\0\x04\x12\x03^\x02\n\n\x0c\n\x05\ \x04\x02\x02\0\x06\x12\x03^\x0b\x10\n\x0c\n\x05\x04\x02\x02\0\x01\x12\ \x03^\x11\x17\n\x0c\n\x05\x04\x02\x02\0\x03\x12\x03^\x1a\x1bb\x06proto3\ "; static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { crate::parse_from_bytes(file_descriptor_proto_data).unwrap() } /// `FileDescriptorProto` object which was a source for this generated file pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) }
pub fn has_null_value(&self) -> bool {
aws.rs
//! This module contains the IOx implementation for using S3 as the object //! store. use crate::{ buffer::slurp_stream_tempfile, path::{cloud::CloudPath, DELIMITER}, ListResult, ObjectMeta, ObjectStoreApi, }; use async_trait::async_trait; use bytes::Bytes; use chrono::{DateTime, Utc}; use futures::{ stream::{self, BoxStream}, Stream, StreamExt, TryStreamExt, }; use rusoto_core::ByteStream; use rusoto_credential::{InstanceMetadataProvider, StaticProvider}; use rusoto_s3::S3; use snafu::{futures::TryStreamExt as _, OptionExt, ResultExt, Snafu}; use std::convert::TryFrom; use std::{fmt, io}; /// A specialized `Result` for object store-related errors pub type Result<T, E = Error> = std::result::Result<T, E>; /// A specialized `Error` for object store-related errors #[derive(Debug, Snafu)] #[allow(missing_docs)] pub enum Error { #[snafu(display("Expected streamed data to have length {}, got {}", expected, actual))] DataDoesNotMatchLength { expected: usize, actual: usize }, #[snafu(display("Did not receive any data. Bucket: {}, Location: {}", bucket, location))] NoData { bucket: String, location: String }, #[snafu(display( "Unable to DELETE data. Bucket: {}, Location: {}, Error: {}", bucket, location, source, ))] UnableToDeleteData { source: rusoto_core::RusotoError<rusoto_s3::DeleteObjectError>, bucket: String, location: String, }, #[snafu(display( "Unable to GET data. Bucket: {}, Location: {}, Error: {}", bucket, location, source, ))] UnableToGetData { source: rusoto_core::RusotoError<rusoto_s3::GetObjectError>, bucket: String, location: String, }, #[snafu(display( "Unable to GET part of the data. Bucket: {}, Location: {}, Error: {}", bucket, location, source, ))] UnableToGetPieceOfData { source: std::io::Error, bucket: String, location: String, }, #[snafu(display( "Unable to PUT data. Bucket: {}, Location: {}, Error: {}", bucket, location, source, ))] UnableToPutData { source: rusoto_core::RusotoError<rusoto_s3::PutObjectError>, bucket: String, location: String, }, #[snafu(display("Unable to list data. Bucket: {}, Error: {}", bucket, source))] UnableToListData { source: rusoto_core::RusotoError<rusoto_s3::ListObjectsV2Error>, bucket: String, }, #[snafu(display( "Unable to parse last modified date. Bucket: {}, Error: {}", bucket, source ))] UnableToParseLastModified { source: chrono::ParseError, bucket: String, }, #[snafu(display("Unable to buffer data into temporary file, Error: {}", source))] UnableToBufferStream { source: std::io::Error }, #[snafu(display( "Could not parse `{}` as an AWS region. Regions should look like `us-east-2`. {:?}", region, source ))] InvalidRegion { region: String, source: rusoto_core::region::ParseRegionError, }, #[snafu(display("Missing aws-access-key"))] MissingAccessKey, #[snafu(display("Missing aws-secret-access-key"))] MissingSecretAccessKey, } /// Configuration for connecting to [Amazon S3](https://aws.amazon.com/s3/). pub struct AmazonS3 { client: rusoto_s3::S3Client, bucket_name: String, } impl fmt::Debug for AmazonS3 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("AmazonS3") .field("client", &"rusoto_s3::S3Client") .field("bucket_name", &self.bucket_name) .finish() } } #[async_trait] impl ObjectStoreApi for AmazonS3 { type Path = CloudPath; type Error = Error; fn new_path(&self) -> Self::Path { CloudPath::default() } async fn put<S>(&self, location: &Self::Path, bytes: S, length: Option<usize>) -> Result<()> where S: Stream<Item = io::Result<Bytes>> + Send + Sync + 'static, { let bytes = match length { Some(length) => ByteStream::new_with_size(bytes, length), None => { let bytes = slurp_stream_tempfile(bytes) .await .context(UnableToBufferStream)?; let length = bytes.size(); ByteStream::new_with_size(bytes, length) } }; let put_request = rusoto_s3::PutObjectRequest { bucket: self.bucket_name.clone(), key: location.to_raw(), body: Some(bytes), ..Default::default() }; self.client .put_object(put_request) .await .context(UnableToPutData { bucket: &self.bucket_name, location: location.to_raw(), })?; Ok(()) } async fn get(&self, location: &Self::Path) -> Result<BoxStream<'static, Result<Bytes>>> { let key = location.to_raw(); let get_request = rusoto_s3::GetObjectRequest { bucket: self.bucket_name.clone(), key: key.clone(), ..Default::default() }; Ok(self .client .get_object(get_request) .await .context(UnableToGetData { bucket: self.bucket_name.to_owned(), location: key.clone(), })? .body .context(NoData { bucket: self.bucket_name.to_owned(), location: key.clone(), })? .context(UnableToGetPieceOfData { bucket: self.bucket_name.to_owned(), location: key, }) .err_into() .boxed()) } async fn delete(&self, location: &Self::Path) -> Result<()> { let key = location.to_raw(); let delete_request = rusoto_s3::DeleteObjectRequest { bucket: self.bucket_name.clone(), key: key.clone(), ..Default::default() }; self.client .delete_object(delete_request) .await .context(UnableToDeleteData { bucket: self.bucket_name.to_owned(), location: key, })?; Ok(()) } async fn list<'a>( &'a self, prefix: Option<&'a Self::Path>, ) -> Result<BoxStream<'a, Result<Vec<Self::Path>>>> { #[derive(Clone)] enum ListState { Start, HasMore(String), Done, } use ListState::*; Ok(stream::unfold(ListState::Start, move |state| async move { let mut list_request = rusoto_s3::ListObjectsV2Request { bucket: self.bucket_name.clone(), prefix: prefix.map(|p| p.to_raw()), ..Default::default() }; match state.clone() { HasMore(continuation_token) => { list_request.continuation_token = Some(continuation_token); } Done => { return None; } // If this is the first request we've made, we don't need to make any modifications // to the request Start => {} } let resp = self .client .list_objects_v2(list_request) .await .context(UnableToListData { bucket: &self.bucket_name, }); let resp = match resp { Ok(resp) => resp, Err(e) => return Some((Err(e), state)), }; let contents = resp.contents.unwrap_or_default(); let names = contents .into_iter() .flat_map(|object| object.key.map(CloudPath::raw)) .collect(); // The AWS response contains a field named `is_truncated` as well as // `next_continuation_token`, and we're assuming that `next_continuation_token` // is only set when `is_truncated` is true (and therefore not // checking `is_truncated`). let next_state = if let Some(next_continuation_token) = resp.next_continuation_token { ListState::HasMore(next_continuation_token) } else { ListState::Done }; Some((Ok(names), next_state)) }) .boxed()) } async fn list_with_delimiter(&self, prefix: &Self::Path) -> Result<ListResult<Self::Path>> { self.list_with_delimiter_and_token(prefix, &None).await } } impl AmazonS3 { /// Configure a connection to Amazon S3 using the specified credentials in /// the specified Amazon region and bucket pub fn new( access_key_id: Option<impl Into<String>>, secret_access_key: Option<impl Into<String>>, region: impl Into<String>, bucket_name: impl Into<String>, ) -> Result<Self> { let region = region.into(); let region: rusoto_core::Region = region.parse().context(InvalidRegion { region })?; let http_client = rusoto_core::request::HttpClient::new() .expect("Current implementation of rusoto_core has no way for this to fail"); let client = match (access_key_id, secret_access_key) { (Some(access_key_id), Some(secret_access_key)) => { let credentials_provider = StaticProvider::new_minimal(access_key_id.into(), secret_access_key.into()); rusoto_s3::S3Client::new_with(http_client, credentials_provider, region) } (None, Some(_)) => return Err(Error::MissingAccessKey), (Some(_), None) => return Err(Error::MissingSecretAccessKey), _ => { let credentials_provider = InstanceMetadataProvider::new(); rusoto_s3::S3Client::new_with(http_client, credentials_provider, region) } }; Ok(Self { client, bucket_name: bucket_name.into(), }) } /// List objects with the given prefix and a set delimiter of `/`. Returns /// common prefixes (directories) in addition to object metadata. Optionally /// takes a continuation token for paging. pub async fn list_with_delimiter_and_token<'a>( &'a self, prefix: &'a CloudPath, next_token: &Option<String>, ) -> Result<ListResult<CloudPath>> { let converted_prefix = prefix.to_raw(); let mut list_request = rusoto_s3::ListObjectsV2Request { bucket: self.bucket_name.clone(), prefix: Some(converted_prefix), delimiter: Some(DELIMITER.to_string()), ..Default::default() }; if let Some(t) = next_token { list_request.continuation_token = Some(t.clone()); } let resp = self .client .list_objects_v2(list_request) .await .context(UnableToListData { bucket: &self.bucket_name, })?; let contents = resp.contents.unwrap_or_default(); let objects = contents .into_iter() .map(|object| { let location = CloudPath::raw(object.key.expect("object doesn't exist without a key")); let last_modified = match object.last_modified { Some(lm) => DateTime::parse_from_rfc3339(&lm) .context(UnableToParseLastModified { bucket: &self.bucket_name, })? .with_timezone(&Utc), None => Utc::now(), }; let size = usize::try_from(object.size.unwrap_or(0)) .expect("unsupported size on this platform"); Ok(ObjectMeta { location, last_modified, size, }) }) .collect::<Result<Vec<_>>>()?; let common_prefixes = resp .common_prefixes .unwrap_or_default() .into_iter() .map(|p| CloudPath::raw(p.prefix.expect("can't have a prefix without a value"))) .collect(); let result = ListResult { objects, common_prefixes, next_token: resp.next_continuation_token, }; Ok(result) } } impl Error { #[cfg(test)] fn s3_error_due_to_credentials(&self) -> bool { use rusoto_core::RusotoError; use Error::*; matches!( self, UnableToPutData { source: RusotoError::Credentials(_), bucket: _, location: _, } | UnableToGetData { source: RusotoError::Credentials(_), bucket: _, location: _, } | UnableToDeleteData { source: RusotoError::Credentials(_), bucket: _, location: _, } | UnableToListData { source: RusotoError::Credentials(_), bucket: _, } ) } } #[cfg(test)] mod tests { use super::*; use crate::{ tests::{get_nonexistent_object, list_with_delimiter, put_get_delete_list}, AmazonS3, Error as ObjectStoreError, ObjectStore, ObjectStoreApi, ObjectStorePath, }; use bytes::Bytes; use std::env; type TestError = Box<dyn std::error::Error + Send + Sync + 'static>; type Result<T, E = TestError> = std::result::Result<T, E>; const NON_EXISTENT_NAME: &str = "nonexistentname"; #[derive(Debug)] struct AwsConfig { access_key_id: String, secret_access_key: String, region: String, bucket: String, } // Helper macro to skip tests if TEST_INTEGRATION and the AWS environment variables are not set. macro_rules! maybe_skip_integration { () => {{ dotenv::dotenv().ok(); let required_vars = [ "AWS_DEFAULT_REGION", "INFLUXDB_IOX_BUCKET", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", ]; let unset_vars: Vec<_> = required_vars .iter() .filter_map(|&name| match env::var(name) { Ok(_) => None, Err(_) => Some(name), }) .collect(); let unset_var_names = unset_vars.join(", "); let force = env::var("TEST_INTEGRATION"); if force.is_ok() && !unset_var_names.is_empty() { panic!( "TEST_INTEGRATION is set, \ but variable(s) {} need to be set", unset_var_names ); } else if force.is_err() { eprintln!( "skipping AWS integration test - set {}TEST_INTEGRATION to run", if unset_var_names.is_empty() { String::new() } else { format!("{} and ", unset_var_names) } ); return; } else { AwsConfig { access_key_id: env::var("AWS_ACCESS_KEY_ID") .expect("already checked AWS_ACCESS_KEY_ID"), secret_access_key: env::var("AWS_SECRET_ACCESS_KEY") .expect("already checked AWS_SECRET_ACCESS_KEY"), region: env::var("AWS_DEFAULT_REGION") .expect("already checked AWS_DEFAULT_REGION"), bucket: env::var("INFLUXDB_IOX_BUCKET") .expect("already checked INFLUXDB_IOX_BUCKET"), } } }}; } fn check_credentials<T>(r: Result<T>) -> Result<T> { if let Err(e) = &r { let e = &**e; if let Some(e) = e.downcast_ref::<Error>() { if e.s3_error_due_to_credentials() { eprintln!( "Try setting the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY \ environment variables" ); } } } r } #[tokio::test] async fn s3_test() { let config = maybe_skip_integration!(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, config.bucket, ) .expect("Valid S3 config"), ); check_credentials(put_get_delete_list(&integration).await).unwrap(); check_credentials(list_with_delimiter(&integration).await).unwrap(); } #[tokio::test] async fn s3_test_get_nonexistent_region() { let mut config = maybe_skip_integration!(); // Assumes environment variables do not provide credentials to AWS US West 1 config.region = "us-west-1".into(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, &config.bucket, ) .expect("Valid S3 config"), ); let mut location = integration.new_path(); location.set_file_name(NON_EXISTENT_NAME); let err = get_nonexistent_object(&integration, Some(location)) .await .unwrap_err(); if let Some(ObjectStoreError::AwsObjectStoreError { source: Error::UnableToListData { source, bucket }, }) = err.downcast_ref::<ObjectStoreError>() { assert!(matches!(source, rusoto_core::RusotoError::Unknown(_))); assert_eq!(bucket, &config.bucket); } else { panic!("unexpected error type: {:?}", err); } } #[tokio::test] async fn s3_test_get_nonexistent_location() { let config = maybe_skip_integration!(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, &config.bucket, ) .expect("Valid S3 config"), ); let mut location = integration.new_path(); location.set_file_name(NON_EXISTENT_NAME); let err = get_nonexistent_object(&integration, Some(location)) .await .unwrap_err(); if let Some(ObjectStoreError::AwsObjectStoreError { source: Error::UnableToGetData { source, bucket, location, }, }) = err.downcast_ref::<ObjectStoreError>() { assert!(matches!( source, rusoto_core::RusotoError::Service(rusoto_s3::GetObjectError::NoSuchKey(_)) )); assert_eq!(bucket, &config.bucket); assert_eq!(location, NON_EXISTENT_NAME); } else { panic!("unexpected error type: {:?}", err); } } #[tokio::test] async fn
() { let mut config = maybe_skip_integration!(); config.bucket = NON_EXISTENT_NAME.into(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, &config.bucket, ) .expect("Valid S3 config"), ); let mut location = integration.new_path(); location.set_file_name(NON_EXISTENT_NAME); let err = get_nonexistent_object(&integration, Some(location)) .await .unwrap_err(); if let Some(ObjectStoreError::AwsObjectStoreError { source: Error::UnableToListData { source, bucket }, }) = err.downcast_ref::<ObjectStoreError>() { assert!(matches!( source, rusoto_core::RusotoError::Service(rusoto_s3::ListObjectsV2Error::NoSuchBucket(_)) )); assert_eq!(bucket, &config.bucket); } else { panic!("unexpected error type: {:?}", err); } } #[tokio::test] async fn s3_test_put_nonexistent_region() { let mut config = maybe_skip_integration!(); // Assumes environment variables do not provide credentials to AWS US West 1 config.region = "us-west-1".into(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, &config.bucket, ) .expect("Valid S3 config"), ); let mut location = integration.new_path(); location.set_file_name(NON_EXISTENT_NAME); let data = Bytes::from("arbitrary data"); let stream_data = std::io::Result::Ok(data.clone()); let err = integration .put( &location, futures::stream::once(async move { stream_data }), Some(data.len()), ) .await .unwrap_err(); if let ObjectStoreError::AwsObjectStoreError { source: Error::UnableToPutData { source, bucket, location, }, } = err { assert!(matches!(source, rusoto_core::RusotoError::Unknown(_))); assert_eq!(bucket, config.bucket); assert_eq!(location, NON_EXISTENT_NAME); } else { panic!("unexpected error type: {:?}", err); } } #[tokio::test] async fn s3_test_put_nonexistent_bucket() { let mut config = maybe_skip_integration!(); config.bucket = NON_EXISTENT_NAME.into(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, &config.bucket, ) .expect("Valid S3 config"), ); let mut location = integration.new_path(); location.set_file_name(NON_EXISTENT_NAME); let data = Bytes::from("arbitrary data"); let stream_data = std::io::Result::Ok(data.clone()); let err = integration .put( &location, futures::stream::once(async move { stream_data }), Some(data.len()), ) .await .unwrap_err(); if let ObjectStoreError::AwsObjectStoreError { source: Error::UnableToPutData { source, bucket, location, }, } = err { assert!(matches!(source, rusoto_core::RusotoError::Unknown(_))); assert_eq!(bucket, config.bucket); assert_eq!(location, NON_EXISTENT_NAME); } else { panic!("unexpected error type: {:?}", err); } } #[tokio::test] async fn s3_test_delete_nonexistent_location() { let config = maybe_skip_integration!(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, config.bucket, ) .expect("Valid S3 config"), ); let mut location = integration.new_path(); location.set_file_name(NON_EXISTENT_NAME); let result = integration.delete(&location).await; assert!(result.is_ok()); } #[tokio::test] async fn s3_test_delete_nonexistent_region() { let mut config = maybe_skip_integration!(); // Assumes environment variables do not provide credentials to AWS US West 1 config.region = "us-west-1".into(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, &config.bucket, ) .expect("Valid S3 config"), ); let mut location = integration.new_path(); location.set_file_name(NON_EXISTENT_NAME); let err = integration.delete(&location).await.unwrap_err(); if let ObjectStoreError::AwsObjectStoreError { source: Error::UnableToDeleteData { source, bucket, location, }, } = err { assert!(matches!(source, rusoto_core::RusotoError::Unknown(_))); assert_eq!(bucket, config.bucket); assert_eq!(location, NON_EXISTENT_NAME); } else { panic!("unexpected error type: {:?}", err); } } #[tokio::test] async fn s3_test_delete_nonexistent_bucket() { let mut config = maybe_skip_integration!(); config.bucket = NON_EXISTENT_NAME.into(); let integration = ObjectStore::new_amazon_s3( AmazonS3::new( Some(config.access_key_id), Some(config.secret_access_key), config.region, &config.bucket, ) .expect("Valid S3 config"), ); let mut location = integration.new_path(); location.set_file_name(NON_EXISTENT_NAME); let err = integration.delete(&location).await.unwrap_err(); if let ObjectStoreError::AwsObjectStoreError { source: Error::UnableToDeleteData { source, bucket, location, }, } = err { assert!(matches!(source, rusoto_core::RusotoError::Unknown(_))); assert_eq!(bucket, config.bucket); assert_eq!(location, NON_EXISTENT_NAME); } else { panic!("unexpected error type: {:?}", err); } } }
s3_test_get_nonexistent_bucket
PanelList.tsx
import React, { memo, useContext, useState } from 'react'; import { TableComposable, TableVariant, Tbody, Td, Th, Thead, Tr } from '@patternfly/react-table'; import { useQuery } from 'react-query'; import { ClustersContext, IClusterContext, IResourceRow, emptyState } from '@kobsio/plugin-core'; import Details from '../panel/details/Details'; import { TApiType } from '../../utils/interfaces'; interface IPanelListProps { name: string; title: string; cluster: string; namespace: string; selector?: string; type: TApiType; setDetails?: (details: React.ReactNode) => void; } const PanelList: React.FunctionComponent<IPanelListProps> = ({ name, title, type, cluster, namespace, selector, setDetails, }: IPanelListProps) => { const clustersContext = useContext<IClusterContext>(ClustersContext); const resource = clustersContext.resources && clustersContext.resources.hasOwnProperty(type) ? clustersContext.resources[type] : undefined; const [selectedRow, setSelectedRow] = useState<number>(-1); const { isError, isLoading, error, data, refetch } = useQuery<IResourceRow[], Error>( ['flux/list', name, cluster, type, namespace, selector], async () => { try { if (!resource) { throw new Error('Could not find resource'); } const response = await fetch( `/api/plugins/resources/resources?cluster=${cluster}&namespace=${namespace}${ selector ? `&paramName=labelSelector&param=${selector}` : '' }&resource=${resource.resource}&path=/apis/${resource.path}`, { method: 'get' }, ); const json = await response.json(); if (response.status >= 200 && response.status < 300) { return resource.rows(json); } else { if (json.error) { throw new Error(json.error);
} catch (err) { throw err; } }, ); // refetchhWithDelay is used to call the refetch function to get the resource, but with a delay of 3 seconds. This is // required, because sometime the Kubenretes isn't that fast after an action (edit, delete, ...) was triggered. const refetchhWithDelay = (): void => { setTimeout(() => { refetch(); }, 3000); }; const handleRowClick = (rowIndex: number, row: IResourceRow): void => { if (setDetails && resource) { setDetails( <Details name={name} type={type} request={resource} resource={row} close={(): void => { setDetails(undefined); setSelectedRow(-1); }} refetch={refetchhWithDelay} />, ); setSelectedRow(rowIndex); } }; return ( <TableComposable aria-label={title} variant={TableVariant.compact} borders={false}> <Thead> <Tr> {resource?.columns.map((column) => ( <Th key={column}>{column}</Th> ))} </Tr> </Thead> <Tbody> {data && data.length > 0 && data[0].cells?.length === resource?.columns.length ? data.map((row, rowIndex) => ( <Tr key={rowIndex} isHoverable={setDetails ? true : false} isRowSelected={selectedRow === rowIndex} onClick={(): void => setDetails && resource && data && data.length > 0 && data[0].cells?.length === resource.columns.length ? handleRowClick(rowIndex, row) : undefined } > {row.cells.map((cell, cellIndex) => ( <Td key={cellIndex}>{cell}</Td> ))} </Tr> )) : emptyState(resource?.columns.length || 3, isLoading, isError, error)} </Tbody> </TableComposable> ); }; export default memo(PanelList, (prevProps, nextProps) => { if (JSON.stringify(prevProps) === JSON.stringify(nextProps)) { return true; } return false; });
} else { throw new Error('An unknown error occured'); } }
Tests.py
import unittest from RegExpBuilder import RegExpBuilder class Test(unittest.TestCase): def test_startOfLine(self): regex = RegExpBuilder() regex.startOfLine() regex.exactly(1).of("p") regex = regex.getRegExp() self.assertTrue(regex.match("p") is not None) self.assertTrue(regex.match("qp") is None) def test_endOfLine(self): regex = RegExpBuilder() regex.exactly(1).of("p") regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("p") is not None) self.assertTrue(regex.match("pq") is None) def test_eitherLike_orLike(self): regex = RegExpBuilder() regex.startOfLine() regex.eitherLike(RegExpBuilder().exactly(1).of("p")) regex.orLike(RegExpBuilder().exactly(2).of("q")) regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("p") is not None) self.assertTrue(regex.match("qq") is not None) self.assertTrue(regex.match("pqq") is None) self.assertTrue(regex.match("qqp") is None) def test_orLike_chain(self):
def test_orString(self): regex = RegExpBuilder() regex.eitherString("p") regex.orString("q") regex = regex.getRegExp() self.assertTrue(regex.match("p") is not None) self.assertTrue(regex.match("q") is not None) self.assertTrue(regex.match("r") is None) def test_exactly(self): regex = RegExpBuilder() regex.startOfLine() regex.exactly(3).of("p") regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("ppp") is not None) self.assertTrue(regex.match("pp") is None) self.assertTrue(regex.match("pppp") is None) def test_min(self): regex = RegExpBuilder() regex.startOfLine() regex.min(2).of("p") regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("pp") is not None) self.assertTrue(regex.match("ppp") is not None) self.assertTrue(regex.match("ppppppp") is not None) self.assertTrue(regex.match("p") is None) def test_max(self): regex = RegExpBuilder() regex.startOfLine() regex.max(3).of("p") regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("p") is not None) self.assertTrue(regex.match("pp") is not None) self.assertTrue(regex.match("ppp") is not None) self.assertTrue(regex.match("pppp") is None) self.assertTrue(regex.match("pppppppp") is None) def test_min_max(self): regex = RegExpBuilder() regex.startOfLine() regex.min(3).max(7).of("p") regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("ppp") is not None) self.assertTrue(regex.match("ppppp") is not None) self.assertTrue(regex.match("ppppppp") is not None) self.assertTrue(regex.match("pp") is None) self.assertTrue(regex.match("p") is None) self.assertTrue(regex.match("pppppppp") is None) self.assertTrue(regex.match("pppppppppppp") is None) def test_of(self): regex = RegExpBuilder() regex.startOfLine() regex.exactly(2).of("p p p ") regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("p p p p p p ") is not None) self.assertTrue(regex.match("p p p p pp") is None) def test_ofAny(self): regex = RegExpBuilder() regex.startOfLine() regex.exactly(3).ofAny() regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("pqr") is not None) def test_ofGroup(self): regex = RegExpBuilder() regex.startOfLine() regex.exactly(3).of("p").asGroup() regex.exactly(1).of("q") regex.exactly(1).ofGroup(1) regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("pppqppp") is not None) def test_fromClass(self): someLetters = ["p", "q", "r"] regex = RegExpBuilder() regex.startOfLine() regex.exactly(3).fromClass(someLetters) regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("ppp") is not None) self.assertTrue(regex.match("qqq") is not None) self.assertTrue(regex.match("ppq") is not None) self.assertTrue(regex.match("rqp") is not None) self.assertTrue(regex.match("pyy") is None) def test_notFromClass(self): someLetters = ["p", "q", "r"] regex = RegExpBuilder() regex.startOfLine() regex.exactly(3).notFromClass(someLetters) regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("lmn") is not None) self.assertTrue(regex.match("mnq") is None) def test_like(self): pattern = RegExpBuilder().min(1).of("p").min(2).of("q") regex = RegExpBuilder() regex.startOfLine() regex.exactly(2).like(pattern) regex.endOfLine() regex = regex.getRegExp() self.assertTrue(regex.match("pqqpqq") is not None) self.assertTrue(regex.match("qppqpp") is None) def test_reluctantly(self): regex = RegExpBuilder() regex.exactly(2).of("p") regex.min(2).ofAny().reluctantly() regex.exactly(2).of("p") regex = regex.getRegExp() self.assertTrue(regex.match("pprrrrpprrpp").group() == "pprrrrpp") def test_ahead(self): regex = RegExpBuilder() regex.exactly(1).of("dart") regex.ahead(RegExpBuilder().exactly(1).of("lang")) regex = regex.getRegExp() self.assertTrue(regex.match("dartlang").group() == "dart") self.assertTrue(regex.match("dartpqr") is None) def test_notAhead(self): regex = RegExpBuilder() regex.exactly(1).of("dart") regex.notAhead(RegExpBuilder().exactly(1).of("pqr")) regex = regex.getRegExp() self.assertTrue(regex.match("dartlang") is not None) self.assertTrue(regex.match("dartpqr") is None) def test_asGroup(self): regex = RegExpBuilder() regex.min(1).max(3).of("p") regex.exactly(1).of("dart").asGroup() regex.exactly(1).fromClass(["p", "q", "r"]) regex = regex.getRegExp() self.assertTrue(regex.match("pdartq").group(1) == "dart") if __name__ == '__main__': unittest.main()
regex = RegExpBuilder() regex.eitherLike(RegExpBuilder().exactly(1).of("p")) regex.orLike(RegExpBuilder().exactly(1).of("q")) regex.orLike(RegExpBuilder().exactly(1).of("r")) regex = regex.getRegExp() self.assertTrue(regex.match("p") is not None) self.assertTrue(regex.match("q") is not None) self.assertTrue(regex.match("r") is not None) self.assertTrue(regex.match("s") is None)
ctrla.rs
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CTRLA { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits }; let mut w = W { bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct SWRSTR { bits: bool, } impl SWRSTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct ENABLER { bits: bool, } impl ENABLER { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct MODER { bits: u8, } impl MODER { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct RUNSTDBYR { bits: bool, } impl RUNSTDBYR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct IBONR { bits: bool, } impl IBONR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct DOPOR { bits: u8, } impl DOPOR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct DIPOR { bits: u8, } impl DIPOR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct FORMR { bits: u8, } impl FORMR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct CPHAR { bits: bool, } impl CPHAR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CPOLR { bits: bool, } impl CPOLR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct DORDR { bits: bool, } impl DORDR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _SWRSTW<'a> { w: &'a mut W, } impl<'a> _SWRSTW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _ENABLEW<'a> { w: &'a mut W, } impl<'a> _ENABLEW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _MODEW<'a> { w: &'a mut W, } impl<'a> _MODEW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _RUNSTDBYW<'a> { w: &'a mut W, } impl<'a> _RUNSTDBYW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _IBONW<'a> { w: &'a mut W, } impl<'a> _IBONW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DOPOW<'a> { w: &'a mut W, } impl<'a> _DOPOW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DIPOW<'a> { w: &'a mut W, } impl<'a> _DIPOW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _FORMW<'a> { w: &'a mut W, } impl<'a> _FORMW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CPHAW<'a> { w: &'a mut W, } impl<'a> _CPHAW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 28; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CPOLW<'a> { w: &'a mut W, } impl<'a> _CPOLW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 29; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DORDW<'a> { w: &'a mut W, } impl<'a> _DORDW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 30; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Software Reset"] #[inline] pub fn swrst(&self) -> SWRSTR { let bits = { const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }; SWRSTR { bits } } #[doc = "Bit 1 - Enable"] #[inline] pub fn enable(&self) -> ENABLER { let bits = { const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }; ENABLER { bits } } #[doc = "Bits 2:4 - Operating Mode"] #[inline] pub fn mode(&self) -> MODER { let bits = { const MASK: u8 = 7; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 }; MODER { bits } } #[doc = "Bit 7 - Run during Standby"] #[inline] pub fn runstdby(&self) -> RUNSTDBYR { let bits = { const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }; RUNSTDBYR { bits } } #[doc = "Bit 8 - Immediate Buffer Overflow Notification"] #[inline] pub fn ibon(&self) -> IBONR { let bits = { const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }; IBONR { bits } } #[doc = "Bits 16:17 - Data Out Pinout"] #[inline] pub fn dopo(&self) -> DOPOR { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; DOPOR { bits } } #[doc = "Bits 20:21 - Data In Pinout"] #[inline] pub fn dipo(&self) -> DIPOR { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 }; DIPOR { bits } } #[doc = "Bits 24:27 - Frame Format"] #[inline] pub fn form(&self) -> FORMR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 }; FORMR { bits } } #[doc = "Bit 28 - Clock Phase"] #[inline] pub fn cpha(&self) -> CPHAR { let bits = { const MASK: bool = true; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CPHAR { bits } } #[doc = "Bit 29 - Clock Polarity"] #[inline] pub fn cpol(&self) -> CPOLR { let bits = { const MASK: bool = true; const OFFSET: u8 = 29; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CPOLR { bits } } #[doc = "Bit 30 - Data Order"] #[inline] pub fn dord(&self) -> DORDR { let bits = { const MASK: bool = true; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DORDR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn
() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Software Reset"] #[inline] pub fn swrst(&mut self) -> _SWRSTW { _SWRSTW { w: self } } #[doc = "Bit 1 - Enable"] #[inline] pub fn enable(&mut self) -> _ENABLEW { _ENABLEW { w: self } } #[doc = "Bits 2:4 - Operating Mode"] #[inline] pub fn mode(&mut self) -> _MODEW { _MODEW { w: self } } #[doc = "Bit 7 - Run during Standby"] #[inline] pub fn runstdby(&mut self) -> _RUNSTDBYW { _RUNSTDBYW { w: self } } #[doc = "Bit 8 - Immediate Buffer Overflow Notification"] #[inline] pub fn ibon(&mut self) -> _IBONW { _IBONW { w: self } } #[doc = "Bits 16:17 - Data Out Pinout"] #[inline] pub fn dopo(&mut self) -> _DOPOW { _DOPOW { w: self } } #[doc = "Bits 20:21 - Data In Pinout"] #[inline] pub fn dipo(&mut self) -> _DIPOW { _DIPOW { w: self } } #[doc = "Bits 24:27 - Frame Format"] #[inline] pub fn form(&mut self) -> _FORMW { _FORMW { w: self } } #[doc = "Bit 28 - Clock Phase"] #[inline] pub fn cpha(&mut self) -> _CPHAW { _CPHAW { w: self } } #[doc = "Bit 29 - Clock Polarity"] #[inline] pub fn cpol(&mut self) -> _CPOLW { _CPOLW { w: self } } #[doc = "Bit 30 - Data Order"] #[inline] pub fn dord(&mut self) -> _DORDW { _DORDW { w: self } } }
reset_value
main.go
package main import ( "context" "fmt" "log" "time" types "github.com/endclothing/secret-manager-operator/pkg/apis/endclothing.com/v1" v1 "github.com/endclothing/secret-manager-operator/pkg/client/clientset/versioned/typed/endclothing.com/v1" secretmanager "cloud.google.com/go/secretmanager/apiv1beta1" secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" corev1 "k8s.io/api/core/v1" errorsv1 "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "net/http" ) func main() { config, err := rest.InClusterConfig() if err != nil { log.Fatalf("Couldn't retrieve in-cluster Kubernetes client config: %+v", err) } msClient, err := v1.NewForConfig(config) if err != nil { log.Fatalf("Couldn't construct CRD client: %+v", err) } k8sClient, err := kubernetes.NewForConfig(config) if err != nil { log.Fatalf("Couldn't construct Kubernetes API client: %+v", err) } ctx := context.Background() secretManagerClient, err := secretmanager.NewClient(ctx) if err != nil { log.Fatalf("Couldn't construct SecretManager client: %+v", err) } _, msController := cache.NewInformer( &cache.ListWatch{ ListFunc: func(lo metav1.ListOptions) (result runtime.Object, err error) { return msClient.ManagedSecrets("").List(lo) }, WatchFunc: func(lo metav1.ListOptions) (watch.Interface, error) { return msClient.ManagedSecrets("").Watch(lo) }, }, &types.ManagedSecret{}, 15*time.Second, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { asms, ok := obj.(*types.ManagedSecret) if !ok { log.Printf("This event isn't a ManagedSecret, passing on it") return } go reconcileReference(msClient, k8sClient, secretManagerClient, asms) }, UpdateFunc: func(_, obj interface{}) { asms, ok := obj.(*types.ManagedSecret) if !ok { log.Printf("This event isn't a ManagedSecret, passing on it") return } go reconcileReference(msClient, k8sClient, secretManagerClient, asms) }, }, ) go msController.Run(wait.NeverStop) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Help, I'm alive!")) }) log.Printf("ManagedSecret operator starting") http.ListenAndServe(":8080", nil) } func reconcileReference(msClient *v1.ComV1Client, k8sClient *kubernetes.Clientset, secretManagerClient *secretmanager.Client, ms *types.ManagedSecret) { // Handle deletions if !ms.ObjectMeta.DeletionTimestamp.IsZero() { finalize(msClient, k8sClient, ms) return } changed, err := reconcileReferenceHelper(msClient, k8sClient, secretManagerClient, ms) // UpdateFunc is called even if the object hasn't changed, so bail early if the managed secret has been reconciled already // to avoid spamming if !changed { return } if err != nil { ms.Status.Error = err.Error() log.Printf("Error reconciling ManagedSecret %s: %+v", ms.String(), err) } else { ms.Status.Project = ms.Spec.Project ms.Status.Secret = ms.Spec.Secret ms.Status.Generation = ms.Spec.Generation ms.Status.Error = "" log.Printf("Successfully reconciled ManagedSecret %s", ms.String()) } _, err = msClient.ManagedSecrets(ms.Namespace).Update(ms) if err != nil { log.Printf("Error updating ManagedSecret %s status: %+v", ms.String(), err) } } func reconcileReferenceHelper(msClient *v1.ComV1Client, k8sClient *kubernetes.Clientset, secretManagerClient *secretmanager.Client, ms *types.ManagedSecret) (bool, error) { if !isStale(ms) { return false, nil } req := &secretmanagerpb.AccessSecretVersionRequest{ Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%d", ms.Spec.Project, ms.Spec.Secret, ms.Spec.Generation), } ctx := context.Background() secret, err := secretManagerClient.AccessSecretVersion(ctx, req) if err != nil { return true, err } k8sSecret := &corev1.Secret{ TypeMeta: metav1.TypeMeta{ Kind: "Secret", APIVersion: "v1", }, ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("%s", ms.Spec.Secret), Namespace: ms.Namespace, }, Data: map[string][]byte{ "contents": []byte(secret.Payload.Data), }, Type: "Opaque", } err = createOrUpdateSecret(k8sClient, k8sSecret) if err != nil { return true, err } return true, nil } func finalize(msClient *v1.ComV1Client, k8sClient *kubernetes.Clientset, ms *types.ManagedSecret) { secretsClient := k8sClient.CoreV1().Secrets(ms.ObjectMeta.Namespace) err := secretsClient.Delete(ms.Status.Secret, &metav1.DeleteOptions{}) if err != nil { statusErr, ok := err.(*errorsv1.StatusError) if !ok || statusErr.ErrStatus.Code != 404 { // If we can't delete the secret and it actually exists (or might), log our error // and retry finalization later ms.Status.Error = err.Error() log.Printf("Error finalizing ManagedSecret %s: %+v", ms.String(), err) _, err = msClient.ManagedSecrets(ms.Namespace).Update(ms) if err != nil { // Log _something_ here to make this pile of tragic errors less baffling to the user // but don't handle it further because there isn’t a whole lot more we can do log.Printf("Error updating ManagedSecret %s with finalization error: %s", ms.String(), err) } return } err = removeFinalizer(msClient, ms) if err != nil { // Presumably we aren't going to successfully update the object status successfully since we _just_ // failed to update it, so log the error and move on log.Printf("Error removing finalizer from ManagedSecret %s: %s", ms.String(), err) return } log.Printf("Successfully finalized ManagedSecret %s", ms.String()) } } func removeFinalizer(msClient *v1.ComV1Client, ms *types.ManagedSecret) error { finalizers := ms.ObjectMeta.Finalizers newFinalizers := []string{} for _, finalizer := range finalizers { if finalizer != "managedsecrets.endclothing.com" { newFinalizers = append(newFinalizers, finalizer) } } ms.ObjectMeta.Finalizers = newFinalizers _, err := msClient.ManagedSecrets(ms.Namespace).Update(ms) if err != nil { return err } return nil } func isStale(ms *types.ManagedSecret) bool { return ms.Spec.Project != ms.Status.Project || ms.Spec.Secret != ms.Status.Secret || ms.Spec.Generation != ms.Status.Generation || ms.Status.Error != "" } func cr
lientset *kubernetes.Clientset, secret *corev1.Secret) error { secretsClient := clientset.CoreV1().Secrets(secret.ObjectMeta.Namespace) _, err := secretsClient.Create(secret) if err != nil { statusErr, ok := err.(*errorsv1.StatusError) if ok { if statusErr.ErrStatus.Code == 409 { _, err = secretsClient.Update(secret) } } } return err }
eateOrUpdateSecret(c
Uno.py
class UnoInfo: def __init__(self): self.dataPins = 13 self.analogInPins = 5 self.GND = 3 self.pow = [3.3, 5] self.TX = 1 self.RX = 0 def getMainInfo(self): return {"0": self.dataPins, "1": self.GND, "2": self.pow}
return self.dataPins def getAnalogPins(self): return self.analogInPins def getAmountGND(self): return self.GND def getPowOut(self): return self.pow def getTXSlot(self): return self.TX def getRXSlot(self): return self.RX
def getDigitalPins(self):
users.module.ts
import { Module } from '@nestjs/common'; import { UserService } from './users.service'; import { MongooseModule } from '@nestjs/mongoose'; import { UserSchema } from './schemas/user.schema'; import { UserResolver } from './user.resolver'; import { CounterSchema } from 'src/utils/counters/schemas/counter.schema';
MongooseModule.forFeature([ { name: 'User', schema: UserSchema }, { name: 'Counter', schema: CounterSchema } ]) ], exports: [UserService] }) export class UsersModule {}
@Module({ providers: [UserResolver, UserService], imports: [
resource-select.directive.ts
import { Directive, ViewContainerRef, TemplateRef, Input } from '@angular/core' import { Store } from '@ngrx/store' import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy' import { map } from 'rxjs/operators' import get from 'lodash-es/get' import { getSpringDataItems, Nullable } from 'ngx-mclabs-utils' import { RootState } from 'app/shared/ngrx/reducers' import { RESOURCE_SELECT_TRIGGER_ACTION_MAP } from 'app/shared/ngrx/resource/resource.actions' import { ResourceKeys } from 'app/shared/constants'
@Directive({ selector: '[resourceSelect]' }) export class ResourceSelectDirective { @Input() itemsKey = 'items' @Input() set resourceSelect(value: ResourceKeyType | [ResourceKeyType, TransformFnType]) { let resourceKey: ResourceKeyType let transformFn: Nullable<TransformFnType> if (typeof value === 'string') { resourceKey = value } else { resourceKey = value[0] as ResourceKeyType transformFn = value[1] as TransformFnType } const resourceKeyArr = resourceKey.split('.') as [ResourceKeys, ...string[]] // NOTE: subResourceKey is for multi-level resources only (rarely used such as Locations) const [mainResourceKey, ...subResourceKey] = resourceKeyArr // Only fetch resources from server if key is valid (non-static resources only) if (RESOURCE_SELECT_TRIGGER_ACTION_MAP[mainResourceKey]) { this._store.dispatch(new RESOURCE_SELECT_TRIGGER_ACTION_MAP[mainResourceKey](...subResourceKey)) } else { console.warn( `Update RESOURCE_SELECT_TRIGGER_ACTION_MAP for *resourceSelect to work with ${resourceKey}, ` + 'if it\'s a non-static resource.') } this._vcRef.clear() this._vcRef.createEmbeddedView(this._templateRef, { $implicit: this._store .select(s => get(s, ['resource', ...resourceKeyArr, 'data'])) .pipe( transformFn ? map(transformFn) : getSpringDataItems({ itemsKey: this.itemsKey }), untilDestroyed(this) ), isLoading$: this._store .select(s => get(s, ['resource', ...resourceKeyArr, 'isProcessing'])) .pipe(untilDestroyed(this)) }) } constructor( private _vcRef: ViewContainerRef, private _templateRef: TemplateRef<unknown>, private _store: Store<RootState> ) { } }
type ResourceKeyType = string type TransformFnType = (data: unknown) => unknown[] @UntilDestroy()
execin_test.go
package integration import ( "bytes" "fmt" "io" "os" "strconv" "strings" "syscall" "testing" "time" "github.com/opencontainers/runc/libcontainer" "github.com/opencontainers/runc/libcontainer/configs" ) func TestExecIn(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer stdinW.Close() ok(t, err) buffers := newStdBuffers() ps := &libcontainer.Process{ Cwd: "/", Args: []string{"ps"}, Env: standardEnvironment, Stdin: buffers.Stdin, Stdout: buffers.Stdout, Stderr: buffers.Stderr, } err = container.Run(ps) ok(t, err) waitProcess(ps, t) stdinW.Close() waitProcess(process, t) out := buffers.Stdout.String() if !strings.Contains(out, "cat") || !strings.Contains(out, "ps") { t.Fatalf("unexpected running process, output %q", out) } if strings.Contains(out, "\r") { t.Fatalf("unexpected carriage-return in output") } } func TestExecInUsernsRlimit(t *testing.T) { if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) { t.Skip("userns is unsupported") } testExecInRlimit(t, true) } func TestExecInRlimit(t *testing.T) { testExecInRlimit(t, false) } func testExecInRlimit(t *testing.T, userns bool) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) if userns { config.UidMappings = []configs.IDMap{{HostID: 0, ContainerID: 0, Size: 1000}} config.GidMappings = []configs.IDMap{{HostID: 0, ContainerID: 0, Size: 1000}} config.Namespaces = append(config.Namespaces, configs.Namespace{Type: configs.NEWUSER}) } container, err := newContainer(config) ok(t, err) defer container.Destroy() stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer stdinW.Close() ok(t, err) buffers := newStdBuffers() ps := &libcontainer.Process{ Cwd: "/", Args: []string{"/bin/sh", "-c", "ulimit -n"}, Env: standardEnvironment, Stdin: buffers.Stdin, Stdout: buffers.Stdout, Stderr: buffers.Stderr, Rlimits: []configs.Rlimit{ // increase process rlimit higher than container rlimit to test per-process limit {Type: syscall.RLIMIT_NOFILE, Hard: 1026, Soft: 1026}, }, } err = container.Run(ps) ok(t, err) waitProcess(ps, t) stdinW.Close() waitProcess(process, t) out := buffers.Stdout.String() if limit := strings.TrimSpace(out); limit != "1026" { t.Fatalf("expected rlimit to be 1026, got %s", limit) } } func TestExecInAdditionalGroups(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer stdinW.Close() ok(t, err) var stdout bytes.Buffer pconfig := libcontainer.Process{ Cwd: "/", Args: []string{"sh", "-c", "id", "-Gn"}, Env: standardEnvironment, Stdin: nil, Stdout: &stdout, AdditionalGroups: []string{"plugdev", "audio"}, } err = container.Run(&pconfig) ok(t, err) // Wait for process waitProcess(&pconfig, t) stdinW.Close() waitProcess(process, t) outputGroups := string(stdout.Bytes()) // Check that the groups output has the groups that we specified if !strings.Contains(outputGroups, "audio") { t.Fatalf("Listed groups do not contain the audio group as expected: %v", outputGroups) } if !strings.Contains(outputGroups, "plugdev") { t.Fatalf("Listed groups do not contain the plugdev group as expected: %v", outputGroups) } } func TestExecInError(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer func() { stdinW.Close() if _, err := process.Wait(); err != nil { t.Log(err) } }() ok(t, err) for i := 0; i < 42; i++ { var out bytes.Buffer unexistent := &libcontainer.Process{ Cwd: "/", Args: []string{"unexistent"}, Env: standardEnvironment, Stdout: &out, } err = container.Run(unexistent) if err == nil { t.Fatal("Should be an error") } if !strings.Contains(err.Error(), "executable file not found") { t.Fatalf("Should be error about not found executable, got %s", err) } if !bytes.Contains(out.Bytes(), []byte("executable file not found")) { t.Fatalf("executable file not found error not delivered to stdio:\n%s", out.String()) } } } func TestExecInTTY(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer stdinW.Close() ok(t, err) var stdout bytes.Buffer ps := &libcontainer.Process{ Cwd: "/", Args: []string{"ps"}, Env: standardEnvironment, } err = container.Run(ps) ok(t, err) console, err := ps.GetConsole() copy := make(chan struct{}) go func() { io.Copy(&stdout, console) close(copy) }() ok(t, err) select { case <-time.After(5 * time.Second): t.Fatal("Waiting for copy timed out") case <-copy: } waitProcess(ps, t) stdinW.Close() waitProcess(process, t) out := stdout.String() if !strings.Contains(out, "cat") || !strings.Contains(out, "ps") { t.Fatalf("unexpected running process, output %q", out) } if strings.Contains(out, "\r") { t.Fatalf("unexpected carriage-return in output") } } func TestExecInEnvironment(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer stdinW.Close() ok(t, err) buffers := newStdBuffers() process2 := &libcontainer.Process{ Cwd: "/", Args: []string{"env"}, Env: []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "DEBUG=true", "DEBUG=false", "ENV=test", }, Stdin: buffers.Stdin, Stdout: buffers.Stdout, Stderr: buffers.Stderr, } err = container.Run(process2) ok(t, err) waitProcess(process2, t) stdinW.Close() waitProcess(process, t) out := buffers.Stdout.String() // check execin's process environment if !strings.Contains(out, "DEBUG=false") || !strings.Contains(out, "ENV=test") || !strings.Contains(out, "HOME=/root") || !strings.Contains(out, "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") || strings.Contains(out, "DEBUG=true") { t.Fatalf("unexpected running process, output %q", out) } } func TestExecinPassExtraFiles(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() if err != nil { t.Fatal(err) } defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) if err != nil { t.Fatal(err) } defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() if err != nil { t.Fatal(err) } process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer stdinW.Close() if err != nil { t.Fatal(err) } var stdout bytes.Buffer pipeout1, pipein1, err := os.Pipe() pipeout2, pipein2, err := os.Pipe() inprocess := &libcontainer.Process{ Cwd: "/", Args: []string{"sh", "-c", "cd /proc/$$/fd; echo -n *; echo -n 1 >3; echo -n 2 >4"}, Env: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, ExtraFiles: []*os.File{pipein1, pipein2}, Stdin: nil, Stdout: &stdout, } err = container.Run(inprocess) if err != nil { t.Fatal(err) } waitProcess(inprocess, t) stdinW.Close() waitProcess(process, t) out := string(stdout.Bytes()) // fd 5 is the directory handle for /proc/$$/fd if out != "0 1 2 3 4 5" { t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to exec, got '%s'", out) } var buf = []byte{0} _, err = pipeout1.Read(buf) if err != nil { t.Fatal(err) } out1 := string(buf) if out1 != "1" { t.Fatalf("expected first pipe to receive '1', got '%s'", out1) } _, err = pipeout2.Read(buf) if err != nil { t.Fatal(err) } out2 := string(buf) if out2 != "2" { t.Fatalf("expected second pipe to receive '2', got '%s'", out2) } } func TestExecInOomScoreAdj(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) config.OomScoreAdj = 200 container, err := newContainer(config) ok(t, err) defer container.Destroy() stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer stdinW.Close() ok(t, err) buffers := newStdBuffers() ps := &libcontainer.Process{ Cwd: "/", Args: []string{"/bin/sh", "-c", "cat /proc/self/oom_score_adj"}, Env: standardEnvironment, Stdin: buffers.Stdin, Stdout: buffers.Stdout, Stderr: buffers.Stderr, } err = container.Run(ps) ok(t, err) waitProcess(ps, t) stdinW.Close() waitProcess(process, t) out := buffers.Stdout.String() if oomScoreAdj := strings.TrimSpace(out); oomScoreAdj != strconv.Itoa(config.OomScoreAdj) { t.Fatalf("expected oomScoreAdj to be %d, got %s", config.OomScoreAdj, oomScoreAdj) } } func TestExecInUserns(t *testing.T) { if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) { t.Skip("userns is unsupported") } if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) config.UidMappings = []configs.IDMap{{HostID: 0, ContainerID: 0, Size: 1000}} config.GidMappings = []configs.IDMap{{HostID: 0, ContainerID: 0, Size: 1000}} config.Namespaces = append(config.Namespaces, configs.Namespace{Type: configs.NEWUSER}) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Cwd: "/", Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Run(process) stdinR.Close() defer stdinW.Close() ok(t, err)
initPID, err := process.Pid() ok(t, err) initUserns, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/user", initPID)) ok(t, err) buffers := newStdBuffers() process2 := &libcontainer.Process{ Cwd: "/", Args: []string{"readlink", "/proc/self/ns/user"}, Env: []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", }, Stdout: buffers.Stdout, Stderr: os.Stderr, } err = container.Run(process2) ok(t, err) waitProcess(process2, t) stdinW.Close() waitProcess(process, t) if out := strings.TrimSpace(buffers.Stdout.String()); out != initUserns { t.Errorf("execin userns(%s), wanted %s", out, initUserns) } }
opts.rs
mod utils; use clap::{App, Arg, ArgMatches, ArgSettings, ErrorKind}; #[cfg(feature = "suggestions")] static DYM: &str = "error: Found argument '--optio' which wasn't expected, or isn't valid in this context \tDid you mean '--option'? \tIf you tried to supply `--optio` as a value rather than a flag, use `-- --optio` USAGE: clap-test --option <opt>... For more information try --help"; #[cfg(feature = "suggestions")] static DYM_ISSUE_1073: &str = "error: Found argument '--files-without-matches' which wasn't expected, or isn't valid in this context \tDid you mean '--files-without-match'? \tIf you tried to supply `--files-without-matches` as a value rather than a flag, use `-- --files-without-matches` USAGE: ripgrep-616 --files-without-match For more information try --help"; #[test] fn require_equals_fail() { let res = App::new("prog") .arg( Arg::new("cfg") .setting(ArgSettings::RequireEquals) .setting(ArgSettings::TakesValue) .long("config"), ) .try_get_matches_from(vec!["prog", "--config", "file.conf"]); assert!(res.is_err()); assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); } #[test] fn require_equals_min_values_zero() { let res = App::new("prog") .arg( Arg::new("cfg") .setting(ArgSettings::RequireEquals) .min_values(0) .long("config"), ) .arg(Arg::new("cmd")) .try_get_matches_from(vec!["prog", "--config", "cmd"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("cfg")); assert_eq!(m.value_of("cmd"), Some("cmd")); } #[test] fn double_hyphen_as_value() { let res = App::new("prog") .arg( Arg::new("cfg") .setting(ArgSettings::AllowHyphenValues) .long("config"), ) .try_get_matches_from(vec!["prog", "--config", "--"]); assert!(res.is_ok(), "{:?}", res); assert_eq!(res.unwrap().value_of("cfg"), Some("--")); } #[test] fn require_equals_no_empty_values_fail() { let res = App::new("prog") .arg( Arg::new("cfg") .setting(ArgSettings::RequireEquals) .long("config"), ) .arg(Arg::new("some")) .try_get_matches_from(vec!["prog", "--config=", "file.conf"]); assert!(res.is_err()); assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); } #[test] fn require_equals_empty_vals_pass() { let res = App::new("prog") .arg( Arg::new("cfg") .setting(ArgSettings::RequireEquals) .setting(ArgSettings::AllowEmptyValues) .long("config"), ) .try_get_matches_from(vec!["prog", "--config="]); assert!(res.is_ok()); } #[test] fn require_equals_pass() { let res = App::new("prog") .arg( Arg::new("cfg") .setting(ArgSettings::RequireEquals) .long("config"), ) .try_get_matches_from(vec!["prog", "--config=file.conf"]); assert!(res.is_ok()); } #[test] fn stdin_char() { let r = App::new("opts") .arg(Arg::from("-f [flag] 'some flag'")) .try_get_matches_from(vec!["", "-f", "-"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("f")); assert_eq!(m.value_of("f").unwrap(), "-"); } #[test] fn opts_using_short() { let r = App::new("opts") .args(&[ Arg::from("-f [flag] 'some flag'"), Arg::from("-c [color] 'some other flag'"), ]) .try_get_matches_from(vec!["", "-f", "some", "-c", "other"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("f")); assert_eq!(m.value_of("f").unwrap(), "some"); assert!(m.is_present("c")); assert_eq!(m.value_of("c").unwrap(), "other"); } #[test] fn lots_o_vals() { let r = App::new("opts") .arg(Arg::from("-o [opt]... 'some opt'")) .try_get_matches_from(vec![ "", "-o", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.values_of("o").unwrap().count(), 297); // i.e. more than u8 } #[test] fn opts_using_long_space() { let r = App::new("opts") .args(&[ Arg::from("--flag [flag] 'some flag'"), Arg::from("--color [color] 'some other flag'"), ]) .try_get_matches_from(vec!["", "--flag", "some", "--color", "other"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("flag")); assert_eq!(m.value_of("flag").unwrap(), "some"); assert!(m.is_present("color")); assert_eq!(m.value_of("color").unwrap(), "other"); } #[test]
Arg::from("--flag [flag] 'some flag'"), Arg::from("--color [color] 'some other flag'"), ]) .try_get_matches_from(vec!["", "--flag=some", "--color=other"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("flag")); assert_eq!(m.value_of("flag").unwrap(), "some"); assert!(m.is_present("color")); assert_eq!(m.value_of("color").unwrap(), "other"); } #[test] fn opts_using_mixed() { let r = App::new("opts") .args(&[ Arg::from("-f, --flag [flag] 'some flag'"), Arg::from("-c, --color [color] 'some other flag'"), ]) .try_get_matches_from(vec!["", "-f", "some", "--color", "other"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("flag")); assert_eq!(m.value_of("flag").unwrap(), "some"); assert!(m.is_present("color")); assert_eq!(m.value_of("color").unwrap(), "other"); } #[test] fn opts_using_mixed2() { let r = App::new("opts") .args(&[ Arg::from("-f, --flag [flag] 'some flag'"), Arg::from("-c, --color [color] 'some other flag'"), ]) .try_get_matches_from(vec!["", "--flag=some", "-c", "other"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("flag")); assert_eq!(m.value_of("flag").unwrap(), "some"); assert!(m.is_present("color")); assert_eq!(m.value_of("color").unwrap(), "other"); } #[test] fn default_values_user_value() { let r = App::new("df") .arg(Arg::from("-o [opt] 'some opt'").default_value("default")) .try_get_matches_from(vec!["", "-o", "value"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.value_of("o").unwrap(), "value"); } #[test] fn multiple_vals_pos_arg_equals() { let r = App::new("mvae") .arg(Arg::from("-o [opt]... 'some opt'")) .arg(Arg::from("[file] 'some file'")) .try_get_matches_from(vec!["", "-o=1", "some"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.value_of("o").unwrap(), "1"); assert!(m.is_present("file")); assert_eq!(m.value_of("file").unwrap(), "some"); } #[test] fn multiple_vals_pos_arg_delim() { let r = App::new("mvae") .arg(Arg::from("-o [opt]... 'some opt'").setting(ArgSettings::UseValueDelimiter)) .arg(Arg::from("[file] 'some file'")) .try_get_matches_from(vec!["", "-o", "1,2", "some"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.values_of("o").unwrap().collect::<Vec<_>>(), &["1", "2"]); assert!(m.is_present("file")); assert_eq!(m.value_of("file").unwrap(), "some"); } #[test] fn require_delims_no_delim() { let r = App::new("mvae") .arg(Arg::from("-o [opt]... 'some opt'").setting(ArgSettings::RequireDelimiter)) .arg(Arg::from("[file] 'some file'")) .try_get_matches_from(vec!["mvae", "-o", "1", "2", "some"]); assert!(r.is_err()); let err = r.unwrap_err(); assert_eq!(err.kind, ErrorKind::UnknownArgument); } #[test] fn require_delims() { let r = App::new("mvae") .arg(Arg::from("-o [opt]... 'some opt'").setting(ArgSettings::RequireDelimiter)) .arg(Arg::from("[file] 'some file'")) .try_get_matches_from(vec!["", "-o", "1,2", "some"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.values_of("o").unwrap().collect::<Vec<_>>(), &["1", "2"]); assert!(m.is_present("file")); assert_eq!(m.value_of("file").unwrap(), "some"); } #[test] fn leading_hyphen_pass() { let r = App::new("mvae") .arg(Arg::from("-o [opt]... 'some opt'").setting(ArgSettings::AllowHyphenValues)) .try_get_matches_from(vec!["", "-o", "-2", "3"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.values_of("o").unwrap().collect::<Vec<_>>(), &["-2", "3"]); } #[test] fn leading_hyphen_fail() { let r = App::new("mvae") .arg(Arg::from("-o [opt] 'some opt'")) .try_get_matches_from(vec!["", "-o", "-2"]); assert!(r.is_err()); let m = r.unwrap_err(); assert_eq!(m.kind, ErrorKind::UnknownArgument); } #[test] fn leading_hyphen_with_flag_after() { let r = App::new("mvae") .arg(Arg::from("-o [opt]... 'some opt'").setting(ArgSettings::AllowHyphenValues)) .arg("-f 'some flag'") .try_get_matches_from(vec!["", "-o", "-2", "-f"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.values_of("o").unwrap().collect::<Vec<_>>(), &["-2", "-f"]); assert!(!m.is_present("f")); } #[test] fn leading_hyphen_with_flag_before() { let r = App::new("mvae") .arg(Arg::from("-o [opt]... 'some opt'").setting(ArgSettings::AllowHyphenValues)) .arg("-f 'some flag'") .try_get_matches_from(vec!["", "-f", "-o", "-2"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.values_of("o").unwrap().collect::<Vec<_>>(), &["-2"]); assert!(m.is_present("f")); } #[test] fn leading_hyphen_with_only_pos_follows() { let r = App::new("mvae") .arg( Arg::from("-o [opt]... 'some opt'") .number_of_values(1) .setting(ArgSettings::AllowHyphenValues), ) .arg("[arg] 'some arg'") .try_get_matches_from(vec!["", "-o", "-2", "--", "val"]); assert!(r.is_ok(), "{:?}", r); let m = r.unwrap(); assert!(m.is_present("o")); assert_eq!(m.values_of("o").unwrap().collect::<Vec<_>>(), &["-2"]); assert_eq!(m.value_of("arg"), Some("val")); } #[test] #[cfg(feature = "suggestions")] fn did_you_mean() { assert!(utils::compare_output( utils::complex_app(), "clap-test --optio=foo", DYM, true )); } #[test] fn issue_665() { let res = App::new("tester") .arg("-v, --reroll-count=[N] 'Mark the patch series as PATCH vN'") .arg(Arg::from( "--subject-prefix [Subject-Prefix] 'Use [Subject-Prefix] instead of the standard [PATCH] prefix'") ) .try_get_matches_from(vec!["test", "--subject-prefix", "-v", "2"]); assert!(res.is_err()); assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); } #[test] fn issue_1047_min_zero_vals_default_val() { let m = App::new("foo") .arg( Arg::new("del") .short('d') .long("del") .setting(ArgSettings::RequireEquals) .min_values(0) .default_missing_value("default"), ) .get_matches_from(vec!["foo", "-d"]); assert_eq!(m.occurrences_of("del"), 1); assert_eq!(m.value_of("del"), Some("default")); } fn issue_1105_setup(argv: Vec<&'static str>) -> Result<ArgMatches, clap::Error> { App::new("opts") .arg(Arg::from("-o, --option [opt] 'some option'").setting(ArgSettings::AllowEmptyValues)) .arg(Arg::from("--flag 'some flag'")) .try_get_matches_from(argv) } #[test] fn issue_1105_empty_value_long_fail() { let r = issue_1105_setup(vec!["app", "--option", "--flag"]); assert!(r.is_err()); assert_eq!(r.unwrap_err().kind, ErrorKind::EmptyValue); } #[test] fn issue_1105_empty_value_long_explicit() { let r = issue_1105_setup(vec!["app", "--option", ""]); assert!(r.is_ok()); let m = r.unwrap(); assert_eq!(m.value_of("option"), Some("")); } #[test] fn issue_1105_empty_value_long_equals() { let r = issue_1105_setup(vec!["app", "--option="]); assert!(r.is_ok()); let m = r.unwrap(); assert_eq!(m.value_of("option"), Some("")); } #[test] fn issue_1105_empty_value_short_fail() { let r = issue_1105_setup(vec!["app", "-o", "--flag"]); assert!(r.is_err()); assert_eq!(r.unwrap_err().kind, ErrorKind::EmptyValue); } #[test] fn issue_1105_empty_value_short_explicit() { let r = issue_1105_setup(vec!["app", "-o", ""]); assert!(r.is_ok()); let m = r.unwrap(); assert_eq!(m.value_of("option"), Some("")); } #[test] fn issue_1105_empty_value_short_equals() { let r = issue_1105_setup(vec!["app", "-o="]); assert!(r.is_ok()); let m = r.unwrap(); assert_eq!(m.value_of("option"), Some("")); } #[test] fn issue_1105_empty_value_short_explicit_no_space() { let r = issue_1105_setup(vec!["app", "-o", ""]); assert!(r.is_ok()); let m = r.unwrap(); assert_eq!(m.value_of("option"), Some("")); } #[test] #[cfg(feature = "suggestions")] fn issue_1073_suboptimal_flag_suggestion() { let app = App::new("ripgrep-616") .arg(Arg::new("files-with-matches").long("files-with-matches")) .arg(Arg::new("files-without-match").long("files-without-match")); assert!(utils::compare_output( app, "ripgrep-616 --files-without-matches", DYM_ISSUE_1073, true )); } #[test] fn short_non_ascii_no_space() { let matches = App::new("app") .arg("<opt> -磨 <opt>") .get_matches_from(&["test", "-磨VALUE"]); assert_eq!("VALUE", matches.value_of("opt").unwrap()); } #[test] fn short_eq_val_starts_with_eq() { let matches = App::new("app") .arg("<opt> -f <opt>") .get_matches_from(&["test", "-f==value"]); assert_eq!("=value", matches.value_of("opt").unwrap()); } #[test] fn long_eq_val_starts_with_eq() { let matches = App::new("app") .arg("<opt> --foo <opt>") .get_matches_from(&["test", "--foo==value"]); assert_eq!("=value", matches.value_of("opt").unwrap()); } #[test] fn issue_2022_get_flags_misuse() { let app = App::new("test") .help_heading("test") .arg(Arg::new("a").long("a").default_value("32")); let matches = app.get_matches_from(&[""]); assert!(matches.value_of("a").is_some()) }
fn opts_using_long_equals() { let r = App::new("opts") .args(&[
scope-name-conflict.ts
/** * @tsplus type scope-name-conflict/A * @tsplus companion scope-name-conflict/AOps */ export class A { constructor(readonly conflict: string) {} } /** * @tsplus static scope-name-conflict/AOps conflict */ export function conflict(s: string): A { return new A(s) } function test() { A.x; const conflict = "name conflict" A.conflict(conflict) } /** * @tsplus static scope-name-conflict/AOps x */ export const x = new A("thing") conflict('');
export const y = x; export { conflict as __x }
page.go
package teaconfigs // 特殊页面配置 type PageConfig struct { On bool `yaml:"on" json:"on"` // TODO Status []string `yaml:"status" json:"status"` // 响应支持40x, 50x, 3x2 URL string `yaml:"url" json:"url"` // URL NewStatus int `yaml:"newStatus" json:"newStatus"` // 新状态码 statusList []*WildcardStatus hasStatusList bool } // 获取新对象 func NewPageConfig() *PageConfig { return &PageConfig{ On: true, }
te() error { this.statusList = []*WildcardStatus{} for _, s := range this.Status { this.statusList = append(this.statusList, NewWildcardStatus(s)) } this.hasStatusList = len(this.statusList) > 0 return nil } // 检查是否匹配 func (this *PageConfig) Match(status int) bool { if !this.hasStatusList { return false } for _, s := range this.statusList { if s.Match(status) { return true } } return false }
} // 校验 func (this *PageConfig) Valida
dhtmlxgantt.js
/* @license dhtmlxGantt v.7.1.9 Standard This version of dhtmlxGantt is distributed under GPL 2.0 license and can be legally used in GPL projects. To use dhtmlxGantt in non-GPL projects (and get Pro version of the product), please obtain Commercial/Enterprise or Ultimate license on our site https://dhtmlx.com/docs/products/dhtmlxGantt/#licensing or contact us at [email protected] (c) XB Software Ltd. */ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("dhtmlxgantt",[],e):"object"==typeof exports?exports.dhtmlxgantt=e():t.dhtmlxgantt=e()}(window,function(){return function(t){var e={};function n(i){if(e[i])return e[i].exports;var r=e[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/codebase/",n(n.s=252)}([function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var r,a=n(2),o={}.constructor.toString();t.exports={copy:function t(e){var n,r;if(e&&"object"==i(e))switch(!0){case a.isDate(e):r=new Date(e);break;case a.isArray(e):for(r=new Array(e.length),n=0;n<e.length;n++)r[n]=t(e[n]);break;default:for(n in r=function(t){return t.constructor.toString()!==o}(e)?Object.create(e):{},e)Object.prototype.hasOwnProperty.apply(e,[n])&&(r[n]=t(e[n]))}return r||e},defined:function(t){return void 0!==t},mixin:function(t,e,n){for(var i in e)(void 0===t[i]||n)&&(t[i]=e[i]);return t},uid:function(){return r||(r=(new Date).valueOf()),++r},bind:function(t,e){return t.bind?t.bind(e):function(){return t.apply(e,arguments)}},event:function(t,e,n,i){t.addEventListener?t.addEventListener(e,n,void 0!==i&&i):t.attachEvent&&t.attachEvent("on"+e,n)},eventRemove:function(t,e,n,i){t.removeEventListener?t.removeEventListener(e,n,void 0!==i&&i):t.detachEvent&&t.detachEvent("on"+e,n)}}},function(t,e){function n(t){var e=0,n=0,i=0,r=0;if(t.getBoundingClientRect){var a=t.getBoundingClientRect(),o=document.body,s=document.documentElement||document.body.parentNode||document.body,l=window.pageYOffset||s.scrollTop||o.scrollTop,c=window.pageXOffset||s.scrollLeft||o.scrollLeft,u=s.clientTop||o.clientTop||0,d=s.clientLeft||o.clientLeft||0;e=a.top+l-u,n=a.left+c-d,i=document.body.offsetWidth-a.right,r=document.body.offsetHeight-a.bottom}else{for(;t;)e+=parseInt(t.offsetTop,10),n+=parseInt(t.offsetLeft,10),t=t.offsetParent;i=document.body.offsetWidth-t.offsetWidth-n,r=document.body.offsetHeight-t.offsetHeight-e}return{y:Math.round(e),x:Math.round(n),width:t.offsetWidth,height:t.offsetHeight,right:Math.round(i),bottom:Math.round(r)}}function i(t){var e=!1,n=!1;if(window.getComputedStyle){var i=window.getComputedStyle(t,null);e=i.display,n=i.visibility}else t.currentStyle&&(e=t.currentStyle.display,n=t.currentStyle.visibility);return"none"!=e&&"hidden"!=n}function r(t){return!isNaN(t.getAttribute("tabindex"))&&1*t.getAttribute("tabindex")>=0}function a(t){return!{a:!0,area:!0}[t.nodeName.loLowerCase()]||!!t.getAttribute("href")}function o(t){return!{input:!0,select:!0,textarea:!0,button:!0,object:!0}[t.nodeName.toLowerCase()]||!t.hasAttribute("disabled")}function s(t){if(!t)return"";var e=t.className||"";return e.baseVal&&(e=e.baseVal),e.indexOf||(e=""),u(e)}var l;function c(t){var e;return t.tagName?e=t:(e=(t=t||window.event).target||t.srcElement).shadowRoot&&t.composedPath&&(e=t.composedPath()[0]),e}function u(t){return(String.prototype.trim||function(){return this.replace(/^\s+|\s+$/g,"")}).apply(t)}function d(){return document.head.createShadowRoot||document.head.attachShadow}function h(t){if(!t)return document.body;if(!d())return document.body;for(;t.parentNode&&(t=t.parentNode);)if(t instanceof ShadowRoot)return t.host;return document.body}t.exports={getNodePosition:n,getFocusableNodes:function(t){for(var e=t.querySelectorAll(["a[href]","area[href]","input","select","textarea","button","iframe","object","embed","[tabindex]","[contenteditable]"].join(", ")),n=Array.prototype.slice.call(e,0),s=0;s<n.length;s++)n[s].$position=s;for(n.sort(function(t,e){return 0===t.tabIndex&&0!==e.tabIndex?1:0!==t.tabIndex&&0===e.tabIndex?-1:t.tabIndex===e.tabIndex?t.$position-e.$position:t.tabIndex<e.tabIndex?-1:1}),s=0;s<n.length;s++){var l=n[s];(r(l)||o(l)||a(l))&&i(l)||(n.splice(s,1),s--)}return n},getScrollSize:function(){var t=document.createElement("div");t.style.cssText="visibility:hidden;position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;height:110px;min-height:100px;overflow-y:scroll;",document.body.appendChild(t);var e=t.offsetWidth-t.clientWidth;return document.body.removeChild(t),e},getClassName:s,addClassName:function(t,e){e&&-1===t.className.indexOf(e)&&(t.className+=" "+e)},removeClassName:function(t,e){e=e.split(" ");for(var n=0;n<e.length;n++){var i=new RegExp("\\s?\\b"+e[n]+"\\b(?![-_.])","");t.className=t.className.replace(i,"")}},insertNode:function(t,e){l||(l=document.createElement("div")),l.innerHTML=e;var n=l.firstChild;return t.appendChild(n),n},removeNode:function(t){t&&t.parentNode&&t.parentNode.removeChild(t)},getChildNodes:function(t,e){for(var n=t.childNodes,i=n.length,r=[],a=0;a<i;a++){var o=n[a];o.className&&-1!==o.className.indexOf(e)&&r.push(o)}return r},toNode:function(t){return"string"==typeof t?document.getElementById(t)||document.querySelector(t)||document.body:t||document.body},locateClassName:function(t,e,n){var i=c(t),r="";for(void 0===n&&(n=!0);i;){if(r=s(i)){var a=r.indexOf(e);if(a>=0){if(!n)return i;var o=0===a||!u(r.charAt(a-1)),l=a+e.length>=r.length||!u(r.charAt(a+e.length));if(o&&l)return i}}i=i.parentNode}return null},locateAttribute:function(t,e){if(e){for(var n=c(t);n;){if(n.getAttribute&&n.getAttribute(e))return n;n=n.parentNode}return null}},getTargetNode:c,getRelativeEventPosition:function(t,e){var i=document.documentElement,r=n(e);return{x:t.clientX+i.scrollLeft-i.clientLeft-r.x+e.scrollLeft,y:t.clientY+i.scrollTop-i.clientTop-r.y+e.scrollTop}},isChildOf:function(t,e){if(!t||!e)return!1;for(;t&&t!=e;)t=t.parentNode;return t===e},hasClass:function(t,e){return"classList"in t?t.classList.contains(e):new RegExp("\\b"+e+"\\b").test(t.className)},closest:function(t,e){if(t.closest)return t.closest(e);if(t.matches||t.msMatchesSelector||t.webkitMatchesSelector){var n=t;if(!document.documentElement.contains(n))return null;do{if((n.matches||n.msMatchesSelector||n.webkitMatchesSelector).call(n,e))return n;n=n.parentElement||n.parentNode}while(null!==n&&1===n.nodeType);return null}return console.error("Your browser is not supported"),null},getRootNode:h,hasShadowParent:function(t){return!!h(t)},isShadowDomSupported:d,getActiveElement:function(){var t=document.activeElement;return t.shadowRoot&&(t=t.shadowRoot.activeElement),t===document.body&&document.getSelection&&(t=document.getSelection().focusNode||document.body),t}}},function(t,e){function n(t){"@babel/helpers - typeof";return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var i={second:1,minute:60,hour:3600,day:86400,week:604800,month:2592e3,quarter:7776e3,year:31536e3};function r(t){return!(!t||"object"!==n(t))&&!!(t.getFullYear&&t.getMonth&&t.getDate)}function a(t,e){var n=[];if(t.filter)return t.filter(e);for(var i=0;i<t.length;i++)e(t[i],i)&&(n[n.length]=t[i]);return n}function o(t){return 0===t}t.exports={getSecondsInUnit:function(t){return i[t]||i.hour},forEach:function(t,e){if(t.forEach)t.forEach(e);else for(var n=t.slice(),i=0;i<n.length;i++)e(n[i],i)},arrayMap:function(t,e){if(t.map)return t.map(e);for(var n=t.slice(),i=[],r=0;r<n.length;r++)i.push(e(n[r],r));return i},arrayIncludes:function(t,e){if(t.includes)return t.includes(e);for(var n=0;n<t.length;n++)if(t[n]===e)return!0;return!1},arrayFind:function(t,e){if(t.find)return t.find(e);for(var n=0;n<t.length;n++)if(e(t[n],n))return t[n]},arrayFilter:a,arrayDifference:function(t,e){return a(t,function(t,n){return!e(t,n)})},arraySome:function(t,e){if(0===t.length)return!1;for(var n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1},hashToArray:function(t){var e=[];for(var n in t)t.hasOwnProperty(n)&&e.push(t[n]);return e},sortArrayOfHash:function(t,e,n){var i=function(t,e){return t<e};t.sort(function(t,r){return t[e]===r[e]?0:n?i(t[e],r[e]):i(r[e],t[e])})},throttle:function(t,e){var n=!1;return function(){n||(t.apply(null,arguments),n=!0,setTimeout(function(){n=!1},e))}},isArray:function(t){return Array.isArray?Array.isArray(t):t&&void 0!==t.length&&t.pop&&t.push},isDate:r,isValidDate:function(t){return r(t)&&!isNaN(t.getTime())},isStringObject:function(t){return t&&"object"===n(t)&&"function String() { [native code] }"===Function.prototype.toString.call(t.constructor)},isNumberObject:function(t){return t&&"object"===n(t)&&"function Number() { [native code] }"===Function.prototype.toString.call(t.constructor)},isBooleanObject:function(t){return t&&"object"===n(t)&&"function Boolean() { [native code] }"===Function.prototype.toString.call(t.constructor)},delay:function(t,e){var n,i=function i(){i.$cancelTimeout(),i.$pending=!0;var r=Array.prototype.slice.call(arguments);n=setTimeout(function(){t.apply(this,r),i.$pending=!1},e)};return i.$pending=!1,i.$cancelTimeout=function(){clearTimeout(n),i.$pending=!1},i.$execute=function(){var e=Array.prototype.slice.call(arguments);t.apply(this,e),i.$cancelTimeout()},i},objectKeys:function(t){if(Object.keys)return Object.keys(t);var e,n=[];for(e in t)Object.prototype.hasOwnProperty.call(t,e)&&n.push(e);return n},isEventable:function(t){return t.attachEvent&&t.detachEvent},replaceValidZeroId:function(t,e){return o(t)&&!o(e)&&(t="0"),t},checkZeroId:o,findBinary:function(t,e){for(var n,i,r,a=0,o=t.length-1;a<=o;)if(i=+t[n=Math.floor((a+o)/2)],r=+t[n-1],i<e)a=n+1;else{if(!(i>e)){for(;+t[n]==+t[n+1];)n++;return n}if(!isNaN(r)&&r<e)return n-1;o=n-1}return t.length-1}}},function(t,e){t.exports=function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);function i(){this.constructor=t}t.prototype=null===e?Object.create(e):(i.prototype=e.prototype,new i)}},function(t,e){var n=function(){this._silent_mode=!1,this.listeners={}};n.prototype={_silentStart:function(){this._silent_mode=!0},_silentEnd:function(){this._silent_mode=!1}};var i=function(t){var e={},n=0,i=function(){var n=!0;for(var i in e){var r=e[i].apply(t,arguments);n=n&&r}return n};return i.addEvent=function(t,r){if("function"==typeof t){var a;if(r&&r.id?a=r.id:(a=n,n++),r&&r.once){var o=t;t=function(){o(),i.removeEvent(a)}}return e[a]=t,a}return!1},i.removeEvent=function(t){delete e[t]},i.clear=function(){e={}},i};t.exports=function(t){var e=new n;t.attachEvent=function(t,n,r){t="ev_"+t.toLowerCase(),e.listeners[t]||(e.listeners[t]=i(this)),r&&r.thisObject&&(n=n.bind(r.thisObject));var a=t+":"+e.listeners[t].addEvent(n,r);return r&&r.id&&(a=r.id),a},t.attachAll=function(t){this.attachEvent("listen_all",t)},t.callEvent=function(t,n){if(e._silent_mode)return!0;var i="ev_"+t.toLowerCase(),r=e.listeners;return r.ev_listen_all&&r.ev_listen_all.apply(this,[t].concat(n)),!r[i]||r[i].apply(this,n)},t.checkEvent=function(t){return!!e.listeners["ev_"+t.toLowerCase()]},t.detachEvent=function(t){if(t){var n=e.listeners;for(var i in n)n[i].removeEvent(t);var r=t.split(":");if(n=e.listeners,2===r.length){var a=r[0],o=r[1];n[a]&&n[a].removeEvent(o)}}},t.detachAllEvents=function(){for(var t in e.listeners)e.listeners[t].clear()}}},function(t,e){t.exports=function(t,e,n,i,r){var a=e.getItemIndexByTopPosition(r.y)||0,o=e.getItemIndexByTopPosition(r.y_end)||i.count();return{start:Math.max(0,a-1),end:Math.min(i.count(),o+1)}}},function(t,e){function n(){console.log("Method is not implemented.")}function i(){}i.prototype.render=n,i.prototype.set_value=n,i.prototype.get_value=n,i.prototype.focus=n,t.exports=function(t){return i}},function(t,e){t.exports=function(t){var e=function(){};return e.prototype={show:function(t,e,n,i){},hide:function(){},set_value:function(t,e,n,i){this.get_input(i).value=t},get_value:function(t,e,n){return this.get_input(n).value||""},is_changed:function(t,e,n,i){var r=this.get_value(e,n,i);return r&&t&&r.valueOf&&t.valueOf?r.valueOf()!=t.valueOf():r!=t},is_valid:function(t,e,n,i){return!0},save:function(t,e,n){},get_input:function(t){return t.querySelector("input")},focus:function(t){var e=this.get_input(t);e&&(e.focus&&e.focus(),e.select&&e.select())}},e}},function(t,e){var n="undefined"!=typeof window,i={isIE:n&&(navigator.userAgent.indexOf("MSIE")>=0||navigator.userAgent.indexOf("Trident")>=0),isIE6:n&&!XMLHttpRequest&&navigator.userAgent.indexOf("MSIE")>=0,isIE7:n&&navigator.userAgent.indexOf("MSIE 7.0")>=0&&navigator.userAgent.indexOf("Trident")<0,isIE8:n&&navigator.userAgent.indexOf("MSIE 8.0")>=0&&navigator.userAgent.indexOf("Trident")>=0,isOpera:n&&navigator.userAgent.indexOf("Opera")>=0,isChrome:n&&navigator.userAgent.indexOf("Chrome")>=0,isKHTML:n&&(navigator.userAgent.indexOf("Safari")>=0||navigator.userAgent.indexOf("Konqueror")>=0),isFF:n&&navigator.userAgent.indexOf("Firefox")>=0,isIPad:n&&navigator.userAgent.search(/iPad/gi)>=0,isEdge:n&&-1!=navigator.userAgent.indexOf("Edge"),isNode:!n||"undefined"==typeof navigator};t.exports=i},function(t,e,n){var i=n(0),r=n(4),a=n(1),o=function(){"use strict";function t(t,e,n,o){t&&(this.$container=a.toNode(t),this.$parent=t),this.$config=i.mixin(e,{headerHeight:33}),this.$gantt=o,this.$domEvents=o._createDomEventScope(),this.$id=e.id||"c"+i.uid(),this.$name="cell",this.$factory=n,r(this)}return t.prototype.destructor=function(){this.$parent=this.$container=this.$view=null,this.$gantt.$services.getService("mouseEvents").detach("click","gantt_header_arrow",this._headerClickHandler),this.$domEvents.detachAll(),this.callEvent("onDestroy",[]),this.detachAllEvents()},t.prototype.cell=function(t){return null},t.prototype.scrollTo=function(t,e){var n=this.$view;this.$config.html&&(n=this.$view.firstChild),1*t==t&&(n.scrollLeft=t),1*e==e&&(n.scrollTop=e)},t.prototype.clear=function(){this.getNode().innerHTML="",this.getNode().className="gantt_layout_content",this.getNode().style.padding="0"},t.prototype.resize=function(t){if(this.$parent)return this.$parent.resize(t);!1===t&&(this.$preResize=!0);var e=this.$container,n=e.offsetWidth,i=e.offsetHeight,r=this.getSize();e===document.body&&(n=document.body.offsetWidth,i=document.body.offsetHeight),n<r.minWidth&&(n=r.minWidth),n>r.maxWidth&&(n=r.maxWidth),i<r.minHeight&&(i=r.minHeight),i>r.maxHeight&&(i=r.maxHeight),this.setSize(n,i),this.$preResize,this.$preResize=!1},t.prototype.hide=function(){this._hide(!0),this.resize()},t.prototype.show=function(t){this._hide(!1),t&&this.$parent&&this.$parent.show(),this.resize()},t.prototype._hide=function(t){if(!0===t&&this.$view.parentNode)this.$view.parentNode.removeChild(this.$view);else if(!1===t&&!this.$view.parentNode){var e=this.$parent.cellIndex(this.$id);this.$parent.moveView(this,e)}this.$config.hidden=t},t.prototype.$toHTML=function(t,e){void 0===t&&(t=""),e=[e||"",this.$config.css||""].join(" ");var n=this.$config,i="";n.raw?t="string"==typeof n.raw?n.raw:"":(t||(t="<div class='gantt_layout_content' "+(e?" class='"+e+"' ":"")+" >"+(n.html||"")+"</div>"),n.header&&(i="<div class='gantt_layout_header'>"+(n.canCollapse?"<div class='gantt_layout_header_arrow'></div>":"")+"<div class='gantt_layout_header_content'>"+n.header+"</div></div>"));return"<div class='gantt_layout_cell "+e+"' data-cell-id='"+this.$id+"'>"+i+t+"</div>"},t.prototype.$fill=function(t,e){this.$view=t,this.$parent=e,this.init()},t.prototype.getNode=function(){return this.$view.querySelector("gantt_layout_cell")||this.$view},t.prototype.init=function(){var t=this;this._headerClickHandler=function(e){a.locateAttribute(e,"data-cell-id")==t.$id&&t.toggle()},this.$gantt.$services.getService("mouseEvents").delegate("click","gantt_header_arrow",this._headerClickHandler),this.callEvent("onReady",[])},t.prototype.toggle=function(){this.$config.collapsed=!this.$config.collapsed,this.resize()},t.prototype.getSize=function(){var t={height:this.$config.height||0,width:this.$config.width||0,gravity:this.$config.gravity||1,minHeight:this.$config.minHeight||0,minWidth:this.$config.minWidth||0,maxHeight:this.$config.maxHeight||1e11,maxWidth:this.$config.maxWidth||1e11};if(this.$config.collapsed){var e="x"===this.$config.mode;t[e?"width":"height"]=t[e?"maxWidth":"maxHeight"]=this.$config.headerHeight}return t},t.prototype.getContentSize=function(){var t=this.$lastSize.contentX;t!==1*t&&(t=this.$lastSize.width);var e=this.$lastSize.contentY;return e!==1*e&&(e=this.$lastSize.height),{width:t,height:e}},t.prototype._getBorderSizes=function(){var t={top:0,right:0,bottom:0,left:0,horizontal:0,vertical:0};return this._currentBorders&&(this._currentBorders[this._borders.left]&&(t.left=1,t.horizontal++),this._currentBorders[this._borders.right]&&(t.right=1,t.horizontal++),this._currentBorders[this._borders.top]&&(t.top=1,t.vertical++),this._currentBorders[this._borders.bottom]&&(t.bottom=1,t.vertical++)),t},t.prototype.setSize=function(t,e){this.$view.style.width=t+"px",this.$view.style.height=e+"px";var n=this._getBorderSizes(),i=e-n.vertical,r=t-n.horizontal;this.$lastSize={x:t,y:e,contentX:r,contentY:i},this.$config.header?this._sizeHeader():this._sizeContent()},t.prototype._borders={left:"gantt_layout_cell_border_left",right:"gantt_layout_cell_border_right",top:"gantt_layout_cell_border_top",bottom:"gantt_layout_cell_border_bottom"},t.prototype._setBorders=function(t,e){e||(e=this);var n=e.$view;for(var i in this._borders)a.removeClassName(n,this._borders[i]);"string"==typeof t&&(t=[t]);var r={};for(i=0;i<t.length;i++)a.addClassName(n,t[i]),r[t[i]]=!0;e._currentBorders=r},t.prototype._sizeContent=function(){var t=this.$view.childNodes[0];t&&"gantt_layout_content"==t.className&&(t.style.height=this.$lastSize.contentY+"px")},t.prototype._sizeHeader=function(){var t=this.$lastSize;t.contentY-=this.$config.headerHeight;var e=this.$view.childNodes[0],n=this.$view.childNodes[1],i="x"===this.$config.mode;if(this.$config.collapsed)if(n.style.display="none",i){e.className="gantt_layout_header collapsed_x",e.style.width=t.y+"px";var r=Math.floor(t.y/2-t.x/2);e.style.transform="rotate(90deg) translate("+r+"px, "+r+"px)",n.style.display="none"}else e.className="gantt_layout_header collapsed_y";else e.className=i?"gantt_layout_header":"gantt_layout_header vertical",e.style.width="auto",e.style.transform="",n.style.display="",n.style.height=t.contentY+"px";e.style.height=this.$config.headerHeight+"px"},t}();t.exports=o},function(t,e,n){var i=n(8);t.exports=function(t){return i.isNode||!t.$root}},function(t,e){t.exports=function(t,e,n,i){if((i=e?e.config:i)&&i.placeholder_task&&n.exists(t))return n.getItem(t).type===i.types.placeholder;return!1}},function(t,e,n){var i=n(3),r=n(29);t.exports=function(t){var e=n(6)(t);function a(){return e.apply(this,arguments)||this}return i(a,e),a.prototype.render=function(t){var e="<div class='gantt_cal_ltext' style='height:"+((t.height||"23")+"px")+";'>";return e+=r.getHtmlSelect(t.options,[{key:"style",value:"width:100%;"}]),e+="</div>"},a.prototype.set_value=function(t,e,n,i){var r=t.firstChild;!r._dhx_onchange&&i.onchange&&(r.onchange=i.onchange,r._dhx_onchange=!0),void 0===e&&(e=(r.options[0]||{}).value),r.value=e||""},a.prototype.get_value=function(t){return t.firstChild.value},a.prototype.focus=function(e){var n=e.firstChild;t._focus(n,!0)},a}},function(t,e){t.exports=function(t){return t.config.smart_rendering&&t._smart_render}},function(t,e){function n(t){"@babel/helpers - typeof";return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var i;i=function(){return this}();try{i=i||Function("return this")()||(0,eval)("this")}catch(t){"object"===("undefined"==typeof window?"undefined":n(window))&&(i=window)}t.exports=i},function(t,e,n){(function(e){var n;n="undefined"!=typeof window?window:e,t.exports=n}).call(this,n(14))},function(t,e,n){var i=n(0);t.exports={createDropTargetObject:function(t){var e={targetParent:null,targetIndex:0,targetId:null,child:!1,nextSibling:!1,prevSibling:!1};return t&&i.mixin(e,t,!0),e},nextSiblingTarget:function(t,e,n){var i=this.createDropTargetObject();return i.targetId=e,i.nextSibling=!0,i.targetParent=n.getParent(i.targetId),i.targetIndex=n.getBranchIndex(i.targetId),(n.getParent(t)!=i.targetParent||i.targetIndex<n.getBranchIndex(t))&&(i.targetIndex+=1),i},prevSiblingTarget:function(t,e,n){var i=this.createDropTargetObject();return i.targetId=e,i.prevSibling=!0,i.targetParent=n.getParent(i.targetId),i.targetIndex=n.getBranchIndex(i.targetId),n.getParent(t)==i.targetParent&&i.targetIndex>n.getBranchIndex(t)&&(i.targetIndex-=1),i},firstChildTarget:function(t,e,n){var i=this.createDropTargetObject();return i.targetId=e,i.targetParent=i.targetId,i.targetIndex=0,i.child=!0,i},lastChildTarget:function(t,e,n){var i=n.getChildren(e),r=this.createDropTargetObject();return r.targetId=i[i.length-1],r.targetParent=e,r.targetIndex=i.length,r.nextSibling=!0,r}}},function(t,e,n){var i=n(13);t.exports=function(t,e,n,r){var a=e.width[t];if(a<=0)return!1;if(!r.config.smart_rendering||i(r))return!0;var o=e.left[t]-a,s=e.left[t]+a;return o<=n.x_end&&s>=n.x}},function(t,e){t.exports=function(t,e){var n=0,i=t.left.length-1;if(e)for(var r=0;r<t.left.length;r++){var a=t.left[r];if(a<e.x&&(n=r),a>e.x_end){i=r;break}}return{start:n,end:i}}},function(t,e){t.exports=function(t,e,n){return{top:e.getItemTop(t.id),height:e.getItemHeight(t.id),left:0,right:1/0}}},function(t,e){t.exports=function(t){function e(e,a,o){if(!t._isAllowedUnscheduledTask(e)&&t._isTaskInTimelineLimits(e)){var s=a.getItemPosition(e),l=o,c=a.$getTemplates(),u=t.getTaskType(e.type),d=a.getBarHeight(e.id,u==l.types.milestone),h=0;u==l.types.milestone&&(h=(d-s.height)/2);var f=Math.floor((a.getItemHeight(e.id)-d)/2);u==l.types.milestone&&(s.left-=Math.round(d/2),s.width=d);var _=document.createElement("div"),g=Math.round(s.width);a.$config.item_attribute&&(_.setAttribute(a.$config.item_attribute,e.id),_.setAttribute(a.$config.bind+"_id",e.id)),l.show_progress&&u!=l.types.milestone&&function(e,n,i,r,a){var o=1*e.progress||0;i=Math.max(i-2,0);var s=document.createElement("div"),l=Math.round(i*o);l=Math.min(i,l),e.progressColor&&(s.style.backgroundColor=e.progressColor,s.style.opacity=1),s.style.width=l+"px",s.className="gantt_task_progress",s.innerHTML=a.progress_text(e.start_date,e.end_date,e),r.rtl&&(s.style.position="absolute",s.style.right="0px");var c=document.createElement("div");if(c.className="gantt_task_progress_wrapper",c.appendChild(s),n.appendChild(c),t.config.drag_progress&&!t.isReadonly(e)){var u=document.createElement("div"),d=l;r.rtl&&(d=i-l),u.style.left=d+"px",u.className="gantt_task_progress_drag",s.appendChild(u),n.appendChild(u)}}(e,_,g,l,c);var p=function(e,n,i){var r=document.createElement("div");return t.getTaskType(e.type)!=t.config.types.milestone?r.innerHTML=i.task_text(e.start_date,e.end_date,e):t.getTaskType(e.type)==t.config.types.milestone&&n&&(r.style.height=r.style.width=n+"px"),r.className="gantt_task_content",r}(e,g,c);e.textColor&&(p.style.color=e.textColor),_.appendChild(p);var v=function(e,n,i,r){var a=r.$getConfig(),o=[e];n&&o.push(n);var s=t.getState(),l=t.getTask(i);if(t.getTaskType(l.type)==a.types.milestone?o.push("gantt_milestone"):t.getTaskType(l.type)==a.types.project&&o.push("gantt_project"),o.push("gantt_bar_"+t.getTaskType(l.type)),t.isSummaryTask(l)&&o.push("gantt_dependent_task"),t.isSplitTask(l)&&(a.open_split_tasks&&!l.$open||!a.open_split_tasks)&&o.push("gantt_split_parent"),a.select_task&&t.isSelectedTask(i)&&o.push("gantt_selected"),i==s.drag_id&&(o.push("gantt_drag_"+s.drag_mode),s.touch_drag&&o.push("gantt_touch_"+s.drag_mode)),s.link_source_id==i&&o.push("gantt_link_source"),s.link_target_id==i&&o.push("gantt_link_target"),a.highlight_critical_path&&t.isCriticalTask&&t.isCriticalTask(l)&&o.push("gantt_critical_task"),s.link_landing_area&&s.link_target_id&&s.link_source_id&&s.link_target_id!=s.link_source_id&&(s.link_target_id==i||s.link_source_id==i)){var c=s.link_source_id,u=s.link_from_start,d=s.link_to_start,h=t.isLinkAllowed(c,i,u,d),f="";f=h?d?"link_start_allow":"link_finish_allow":d?"link_start_deny":"link_finish_deny",o.push(f)}return o.join(" ")}("gantt_task_line",c.task_class(e.start_date,e.end_date,e),e.id,a);(e.color||e.progressColor||e.textColor)&&(v+=" gantt_task_inline_color"),s.width<20&&(v+=" gantt_thin_task"),_.className=v;var m=["left:"+s.left+"px","top:"+(f+s.top)+"px","height:"+(u==l.types.milestone?s.height:d)+"px","line-height:"+Math.max(d<30?d-2:d,0)+"px","width:"+g+"px"];e.color&&m.push("background-color:"+e.color),e.textColor&&m.push("color:"+e.textColor),_.style.cssText=m.join(";");var y=function(t,e,r,a){var o="gantt_left "+i(!e.rtl,t),s=null;return a&&(s={type:"marginRight",value:a}),n(t,r.leftside_text,o,s)}(e,l,c,h);y&&_.appendChild(y),(y=function(t,e,r,a){var o="gantt_right "+i(!!e.rtl,t),s=null;return a&&(s={type:"marginLeft",value:a}),n(t,r.rightside_text,o,s)}(e,l,c,h))&&_.appendChild(y),t._waiAria.setTaskBarAttr(e,_);var k=t.getState();return t.isReadonly(e)||(l.drag_resize&&!t.isSummaryTask(e)&&u!=l.types.milestone&&r(_,"gantt_task_drag",e,function(t){var e=document.createElement("div");return e.className=t,e},l),l.drag_links&&l.show_links&&r(_,"gantt_link_control",e,function(t){var e=document.createElement("div");e.className=t,e.style.cssText=["height:"+d+"px","line-height:"+d+"px"].join(";");var n=document.createElement("div");n.className="gantt_link_point";var i=!1;return k.link_source_id&&l.touch&&(i=!0),n.style.display=i?"block":"",e.appendChild(n),e},l,h)),_}}function n(t,e,n,i){if(!e)return null;var r=e(t.start_date,t.end_date,t);if(!r)return null;var a=document.createElement("div");return a.className="gantt_side_content "+n,a.innerHTML=r,i&&(a.style[i.type]=Math.abs(i.value)+"px"),a}function i(e,n){var i=function(e){return e?{$source:[t.config.links.start_to_start],$target:[t.config.links.start_to_start,t.config.links.finish_to_start]}:{$source:[t.config.links.finish_to_start,t.config.links.finish_to_finish],$target:[t.config.links.finish_to_finish]}}(e);for(var r in i)for(var a=n[r],o=0;o<a.length;o++)for(var s=t.getLink(a[o]),l=0;l<i[r].length;l++)if(s.type==i[r][l])return"gantt_link_crossing";return""}function r(e,n,i,r,a,o){var s,l=t.getState();+i.start_date>=+l.min_date&&((s=r([n,a.rtl?"task_right":"task_left","task_start_date"].join(" "))).setAttribute("data-bind-property","start_date"),o&&(s.style.marginLeft=o+"px"),e.appendChild(s)),+i.end_date<=+l.max_date&&((s=r([n,a.rtl?"task_left":"task_right","task_end_date"].join(" "))).setAttribute("data-bind-property","end_date"),o&&(s.style.marginRight=o+"px"),e.appendChild(s))}return function(n,i,r){var a=(r=i.$getConfig()).type_renderers[t.getTaskType(n.type)],o=e;return a?a.call(t,n,function(e){return o.call(t,e,i,r)},i):o.call(t,n,i,r)}}},function(t,e){t.exports=function(t,e,n,i,r){if(!t.start_date||!t.end_date)return null;var a=n.getItemTop(t.id),o=n.getItemHeight(t.id);if(a>e.y_end||a+o<e.y)return!1;var s=n.posFromDate(t.start_date),l=n.posFromDate(t.end_date),c=Math.min(s,l)-200,u=Math.max(s,l)+200;return!(c>e.x_end||u<e.x)}},function(t,e,n){var i=n(26),r=n(4),a=n(0),o=n(2),s=n(34),l=n(104),c=function(t,e,n,o){this.$config=a.mixin({},e||{}),this.$scaleHelper=new i(o),this.$gantt=o,this._posFromDateCache={},this._timelineDragScroll=null,a.mixin(this,s(this)),r(this)};c.prototype={init:function(t){t.innerHTML+="<div class='gantt_task' style='width:inherit;height:inherit;'></div>",this.$task=t.childNodes[0],this.$task.innerHTML="<div class='gantt_task_scale'></div><div class='gantt_data_area'></div>",this.$task_scale=this.$task.childNodes[0],this.$task_data=this.$task.childNodes[1],this.$task_data.innerHTML="<div class='gantt_task_bg'></div><div class='gantt_links_area'></div><div class='gantt_bars_area'></div>",this.$task_bg=this.$task_data.childNodes[0],this.$task_links=this.$task_data.childNodes[1],this.$task_bars=this.$task_data.childNodes[2],this._tasks={col_width:0,width:[],full_width:0,trace_x:[],rendered:{}};var e=this.$getConfig(),n=e[this.$config.bind+"_attribute"],i=e[this.$config.bindLinks+"_attribute"];!n&&this.$config.bind&&(n="data-"+this.$config.bind+"-id"),!i&&this.$config.bindLinks&&(i="data-"+this.$config.bindLinks+"-id"),this.$config.item_attribute=n||null,this.$config.link_attribute=i||null;var r=this._createLayerConfig();this.$config.layers||(this.$config.layers=r.tasks),this.$config.linkLayers||(this.$config.linkLayers=r.links),this._attachLayers(this.$gantt),this.callEvent("onReady",[]),this.$gantt.ext.dragTimeline&&(this._timelineDragScroll=this.$gantt.ext.dragTimeline.create(),this._timelineDragScroll.attach(this))},setSize:function(t,e){var n=this.$getConfig();if(1*t===t&&(this.$config.width=t),1*e===e){this.$config.height=e;var i=Math.max(this.$config.height-n.scale_height);this.$task_data.style.height=i+"px"}this.refresh(),this.$task_bg.style.backgroundImage="",n.smart_rendering&&this.$config.rowStore?this.$task_bg.style.height=this.getTotalHeight()+"px":this.$task_bg.style.height="";for(var r=this._tasks,a=this.$task_data.childNodes,o=0,s=a.length;o<s;o++){var l=a[o];l.hasAttribute("data-layer")&&l.style&&(l.style.width=r.full_width+"px")}},isVisible:function(){return this.$parent&&this.$parent.$config?!this.$parent.$config.hidden:this.$task.offsetWidth},getSize:function(){var t=this.$getConfig(),e=this.$config.rowStore?this.getTotalHeight():0,n=this.isVisible()?this._tasks.full_width:0;return{x:this.isVisible()?this.$config.width:0,y:this.isVisible()?this.$config.height:0,contentX:this.isVisible()?n:0,contentY:this.isVisible()?t.scale_height+e:0,scrollHeight:this.isVisible()?e:0,scrollWidth:this.isVisible()?n:0}},scrollTo:function(t,e){if(this.isVisible()){var n=!1;this.$config.scrollTop=this.$config.scrollTop||0,this.$config.scrollLeft=this.$config.scrollLeft||0,1*e===e&&(this.$config.scrollTop=e,this.$task_data.scrollTop=this.$config.scrollTop,n=!0),1*t===t&&(this.$task.scrollLeft=t,this.$config.scrollLeft=this.$task.scrollLeft,this._refreshScales(),n=!0),n&&this.callEvent("onScroll",[this.$config.scrollLeft,this.$config.scrollTop])}},_refreshScales:function(){if(this.isVisible()&&this.$getConfig().smart_scales){var t=this.getViewPort(),e=this._scales;this.$task_scale.innerHTML=this._getScaleChunkHtml(e,t.x,t.x_end)}},getViewPort:function(){var t=this.$config.scrollLeft||0,e=this.$config.scrollTop||0,n=this.$config.height||0,i=this.$config.width||0;return{y:e,y_end:e+n,x:t,x_end:t+i,height:n,width:i}},_createLayerConfig:function(){var t=this,e=function(){return t.isVisible()};return{tasks:[{expose:!0,renderer:this.$gantt.$ui.layers.taskBar(),container:this.$task_bars,filter:[e,function(t,e){return!e.hide_bar}]},{renderer:this.$gantt.$ui.layers.taskSplitBar(),filter:[e],container:this.$task_bars,append:!0},{renderer:this.$gantt.$ui.layers.taskRollupBar(),filter:[e],container:this.$task_bars,append:!0},{renderer:this.$gantt.$ui.layers.taskBg(),container:this.$task_bg,filter:[e]}],links:[{expose:!0,renderer:this.$gantt.$ui.layers.link(),container:this.$task_links,filter:[e]}]}},_attachLayers:function(t){this._taskLayers=[],this._linkLayers=[];var e=this,n=this.$gantt.$services.getService("layers");if(this.$config.bind){this._bindStore();var i=n.getDataRender(this.$config.bind);i||(i=n.createDataRender({name:this.$config.bind,defaultContainer:function(){return e.$task_data}})),i.container=function(){return e.$task_data};for(var r=this.$config.layers,a=0;r&&a<r.length;a++){"string"==typeof(c=r[a])&&(c=this.$gantt.$ui.layers[c]()),("function"==typeof c||c&&c.render&&c.update)&&(c={renderer:c}),c.view=this;var o=i.addLayer(c);this._taskLayers.push(o),c.expose&&(this._taskRenderer=i.getLayer(o))}this._initStaticBackgroundRender()}if(this.$config.bindLinks){e.$config.linkStore=e.$gantt.getDatastore(e.$config.bindLinks);var s=n.getDataRender(this.$config.bindLinks);s||(s=n.createDataRender({name:this.$config.bindLinks,defaultContainer:function(){return e.$task_data}}));var l=this.$config.linkLayers;for(a=0;l&&a<l.length;a++){var c;"string"==typeof c&&(c=this.$gantt.$ui.layers[c]()),(c=l[a]).view=this;var u=s.addLayer(c);this._taskLayers.push(u),l[a].expose&&(this._linkRenderer=s.getLayer(u))}}},_initStaticBackgroundRender:function(){var t=this,e=l.create(),n=t.$config.rowStore;n&&(this._staticBgHandler=n.attachEvent("onStoreUpdated",function(n,i,r){if(null===n&&t.isVisible()){var a=t.$getConfig();if(a.static_background){var o=t.$gantt.getDatastore(t.$config.bind),s=t.$task_bg_static;s||((s=document.createElement("div")).className="gantt_task_bg",t.$task_bg_static=s,t.$task_bg.nextSibling?t.$task_data.insertBefore(s,t.$task_bg.nextSibling):t.$task_data.appendChild(s)),o&&e.render(s,a,t.getScale(),t.getTotalHeight(),t.getItemHeight(i?i.id:null))}else a.static_background&&t.$task_bg_static&&t.$task_bg_static.parentNode&&t.$task_bg_static.parentNode.removeChild(t.$task_bg_static)}}),this.attachEvent("onDestroy",function(){e.destroy()}),this._initStaticBackgroundRender=function(){})},_clearLayers:function(t){var e=this.$gantt.$services.getService("layers"),n=e.getDataRender(this.$config.bind),i=e.getDataRender(this.$config.bindLinks);if(this._taskLayers)for(var r=0;r<this._taskLayers.length;r++)n.removeLayer(this._taskLayers[r]);if(this._linkLayers)for(r=0;r<this._linkLayers.length;r++)i.removeLayer(this._linkLayers[r]);this._linkLayers=[],this._taskLayers=[]},_render_tasks_scales:function(){var t=this.$getConfig(),e="",n=0,i=0,r=this.$gantt.getState();if(this.isVisible()){var a=this.$scaleHelper,o=this._getScales();i=t.scale_height;var s=this.$config.width;"x"!=t.autosize&&"xy"!=t.autosize||(s=Math.max(t.autosize_min_width,0));var l=a.prepareConfigs(o,t.min_column_width,s,i-1,r.min_date,r.max_date,t.rtl),c=this._tasks=l[l.length-1];this._scales=l,this._posFromDateCache={},e=this._getScaleChunkHtml(l,0,this.$config.width),n=c.full_width+"px",i+="px"}this.$task_scale.style.height=i,this.$task_data.style.width=this.$task_scale.style.width=n,this.$task_scale.innerHTML=e},_getScaleChunkHtml:function(t,e,n){for(var i=[],r=this.$gantt.templates.scale_row_class,a=0;a<t.length;a++){var o="gantt_scale_line",s=r(t[a]);s&&(o+=" "+s),i.push('<div class="'+o+'" style="height:'+t[a].height+"px;position:relative;line-height:"+t[a].height+'px">'+this._prepareScaleHtml(t[a],e,n)+"</div>")}return i.join("")},_prepareScaleHtml:function(t,e,n){var i=this.$getConfig(),r=this.$gantt.templates,a=[],s=null,l=null,c=t.format||t.template||t.date;"string"==typeof c&&(c=this.$gantt.date.date_to_str(c));var u=0,d=t.count;!i.smart_scales||isNaN(e)||isNaN(n)||(u=o.findBinary(t.left,e),d=o.findBinary(t.left,n)+1),l=t.css||function(){},!t.css&&i.inherit_scale_class&&(l=r.scale_cell_class);for(var h=u;h<d&&t.trace_x[h];h++){s=new Date(t.trace_x[h]);var f=c.call(this,s),_=t.width[h],g=t.height,p=t.left[h],v="",m="",y="";if(_){v="width:"+_+"px;height:"+g+"px;"+(i.smart_scales?"position:absolute;left:"+p+"px":""),y="gantt_scale_cell"+(h==t.count-1?" gantt_last_cell":""),(m=l.call(this,s))&&(y+=" "+m);var k="<div class='"+y+"'"+this.$gantt._waiAria.getTimelineCellAttr(f)+" style='"+v+"'>"+f+"</div>";a.push(k)}}return a.join("")},dateFromPos:function(t){var e=this._tasks;if(t<0||t>e.full_width||!e.full_width)return null;var n=o.findBinary(this._tasks.left,t),i=this._tasks.left[n],r=e.width[n]||e.col_width,a=0;r&&(a=(t-i)/r,e.rtl&&(a=1-a));var s=0;return a&&(s=this._getColumnDuration(e,e.trace_x[n])),new Date(e.trace_x[n].valueOf()+Math.round(a*s))},posFromDate:function(t){if(!this.isVisible())return 0;if(!t)return 0;var e=String(t.valueOf());if(void 0!==this._posFromDateCache[e])return this._posFromDateCache[e];var n=this.columnIndexByDate(t);this.$gantt.assert(n>=0,"Invalid day index");var i=Math.floor(n),r=n%1,a=this._tasks.left[Math.min(i,this._tasks.width.length-1)];i==this._tasks.width.length&&(a+=this._tasks.width[this._tasks.width.length-1]),r&&(i<this._tasks.width.length?a+=this._tasks.width[i]*(r%1):a+=1);var o=Math.round(a);return this._posFromDateCache[e]=o,Math.round(o)},_getNextVisibleColumn:function(t,e,n){for(var i=+e[t],r=t;n[i];)i=+e[++r];return r},_getPrevVisibleColumn:function(t,e,n){for(var i=+e[t],r=t;n[i];)i=+e[--r];return r},_getClosestVisibleColumn:function(t,e,n){var i=this._getNextVisibleColumn(t,e,n);return e[i]||(i=this._getPrevVisibleColumn(t,e,n)),i},columnIndexByDate:function(t){var e=new Date(t).valueOf(),n=this._tasks.trace_x_ascending,i=this._tasks.ignore_x,r=this.$gantt.getState();if(e<=r.min_date)return this._tasks.rtl?n.length:0;if(e>=r.max_date)return this._tasks.rtl?0:n.length;var a=o.findBinary(n,e),s=this._getClosestVisibleColumn(a,n,i),l=n[s],c=this._tasks.trace_index_transition;if(!l)return c?c[0]:0;var u=(t-n[s])/this._getColumnDuration(this._tasks,n[s]);return c?c[s]+(1-u):s+u},getItemPosition:function(t,e,n){var i,r,a;return this._tasks.rtl?(r=this.posFromDate(e||t.start_date),i=this.posFromDate(n||t.end_date)):(i=this.posFromDate(e||t.start_date),r=this.posFromDate(n||t.end_date)),a=Math.max(r-i,0),{left:i,top:this.getItemTop(t.id),height:this.getBarHeight(t.id),width:a,rowHeight:this.getItemHeight(t.id)}},getBarHeight:function(t,e){var n=this.$getConfig(),i=this.$config.rowStore.getItem(t),r=i.task_height||i.bar_height||n.bar_height||n.task_height,a=this.getItemHeight(t);"full"==r&&(r=a-(n.task_height_offset||5));return r=Math.min(r,a),e&&(r=Math.round(r/Math.sqrt(2))),Math.max(r,0)},getScale:function(){return this._tasks},_getScales:function(){var t=this.$getConfig(),e=this.$scaleHelper,n=[e.primaryScale(t)].concat(e.getSubScales(t));return e.sortScales(n),n},_getColumnDuration:function(t,e){return this.$gantt.date.add(e,t.step,t.unit)-e},_bindStore:function(){if(this.$config.bind){var t=this.$gantt.getDatastore(this.$config.bind);if(this.$config.rowStore=t,t&&!t._timelineCacheAttached){var e=this;t._timelineCacheAttached=t.attachEvent("onBeforeFilter",function(){e._resetTopPositionHeight()})}}},_unbindStore:function(){if(this.$config.bind){var t=this.$gantt.getDatastore(this.$config.bind);t&&t._timelineCacheAttached&&(t.detachEvent(t._timelineCacheAttached),t._timelineCacheAttached=!1)}},refresh:function(){this._bindStore(),this.$config.bindLinks&&(this.$config.linkStore=this.$gantt.getDatastore(this.$config.bindLinks)),this._resetTopPositionHeight(),this._resetHeight(),this._initStaticBackgroundRender(),this._render_tasks_scales()},destructor:function(){var t=this.$gantt;this._clearLayers(t),this._unbindStore(),this.$task=null,this.$task_scale=null,this.$task_data=null,this.$task_bg=null,this.$task_links=null,this.$task_bars=null,this.$gantt=null,this.$config.rowStore&&(this.$config.rowStore.detachEvent(this._staticBgHandler),this.$config.rowStore=null),this.$config.linkStore&&(this.$config.linkStore=null),this._timelineDragScroll&&(this._timelineDragScroll.destructor(),this._timelineDragScroll=null),this.callEvent("onDestroy",[]),this.detachAllEvents()}},t.exports=c},function(t,e){t.exports=function(t,e,n){return{top:e.getItemTop(t.id),height:e.getItemHeight(t.id),left:0,right:1/0}}},function(t,e){t.exports=function(t){var e=[];return{delegate:function(n,i,r,a){e.push([n,i,r,a]),t.$services.getService("mouseEvents").delegate(n,i,r,a)},destructor:function(){for(var n=t.$services.getService("mouseEvents"),i=0;i<e.length;i++){var r=e[i];n.detach(r[0],r[1],r[2],r[3])}e=[]}}}},function(t,e,n){var i=n(1),r=n(0),a=n(4),o=n(183),s=n(34),l=n(181),c=n(180).default,u=function(t,e,n,i){this.$config=r.mixin({},e||{}),this.$gantt=i,this.$parent=t,a(this),this.$state={},r.mixin(this,s(this))};u.prototype={init:function(t){var e=this.$gantt,i=e._waiAria.gridAttrString(),r=e._waiAria.gridDataAttrString(),a=this.$getConfig(),s=a.reorder_grid_columns||!1;void 0!==this.$config.reorder_grid_columns&&(s=this.$config.reorder_grid_columns),t.innerHTML="<div class='gantt_grid' style='height:inherit;width:inherit;' "+i+"></div>",this.$grid=t.childNodes[0],this.$grid.innerHTML="<div class='gantt_grid_scale' "+e._waiAria.gridScaleRowAttrString()+"></div><div class='gantt_grid_data' "+r+"></div>",this.$grid_scale=this.$grid.childNodes[0],this.$grid_data=this.$grid.childNodes[1];var u=a[this.$config.bind+"_attribute"];if(!u&&this.$config.bind&&(u="data-"+this.$config.bind+"-id"),this.$config.item_attribute=u||null,!this.$config.layers){var d=this._createLayerConfig();this.$config.layers=d}var h=o(e,this);h.init(),this._renderHeaderResizers=h.doOnRender,this._mouseDelegates=n(24)(e),l(e,this).init(),this._addLayers(this.$gantt),this._initEvents(),s&&(this._columnDND=new c(e,this),this._columnDND.init()),this.callEvent("onReady",[])},_validateColumnWidth:function(t,e){var n=t[e];if(n&&"*"!=n){var i=this.$gantt,r=1*n;isNaN(r)?i.assert(!1,"Wrong "+e+" value of column "+t.name):t[e]=r}},setSize:function(t,e){this.$config.width=this.$state.width=t,this.$config.height=this.$state.height=e;for(var n,i=this.getGridColumns(),r=0,a=(u=this.$getConfig()).grid_elastic_columns,o=0,s=i.length;o<s;o++)this._validateColumnWidth(i[o],"min_width"),this._validateColumnWidth(i[o],"max_width"),this._validateColumnWidth(i[o],"width"),r+=1*i[o].width;if(!isNaN(r)&&this.$config.scrollable||(r=n=this._setColumnsWidth(t+1)),this.$config.scrollable&&a&&!isNaN(r)){var l=0;i.forEach(function(t){l+=t.min_width||u.min_grid_column_width});var c=Math.max(l,t);r=this._setColumnsWidth(c),n=t}this.$config.scrollable?(this.$grid_scale.style.width=r+"px",this.$grid_data.style.width=r+"px"):(this.$grid_scale.style.width="inherit",this.$grid_data.style.width="inherit"),this.$config.width-=1;var u=this.$getConfig();n!==t&&(void 0!==n?(u.grid_width=n,this.$config.width=n-1):isNaN(r)||(this._setColumnsWidth(r),u.grid_width=r,this.$config.width=r-1));var d=Math.max(this.$state.height-u.scale_height,0);this.$grid_data.style.height=d+"px",this.refresh()},getSize:function(){var t=this.$getConfig(),e=this.$config.rowStore?this.getTotalHeight():0,n=this._getGridWidth();return{x:this.$state.width,y:this.$state.height,contentX:this.isVisible()?n:0,contentY:this.isVisible()?t.scale_height+e:0,scrollHeight:this.isVisible()?e:0,scrollWidth:this.isVisible()?n:0}},_bindStore:function(){if(this.$config.bind){var t=this.$gantt.getDatastore(this.$config.bind);if(this.$config.rowStore=t,t&&!t._gridCacheAttached){var e=this;t._gridCacheAttached=t.attachEvent("onBeforeFilter",function(){e._resetTopPositionHeight()})}}},_unbindStore:function(){if(this.$config.bind){var t=this.$gantt.getDatastore(this.$config.bind);t&&t._gridCacheAttached&&(t.detachEvent(t._gridCacheAttached),t._gridCacheAttached=!1)}},refresh:function(){this._bindStore(),this._resetTopPositionHeight(),this._resetHeight(),this._initSmartRenderingPlaceholder(),this._calculateGridWidth(),this._renderGridHeader()},getViewPort:function(){var t=this.$config.scrollLeft||0,e=this.$config.scrollTop||0,n=this.$config.height||0,i=this.$config.width||0;return{y:e,y_end:e+n,x:t,x_end:t+i,height:n,width:i}},scrollTo:function(t,e){if(this.isVisible()){var n=!1;this.$config.scrollTop=this.$config.scrollTop||0,this.$config.scrollLeft=this.$config.scrollLeft||0,1*t==t&&(this.$config.scrollLeft=this.$state.scrollLeft=this.$grid.scrollLeft=t,n=!0),1*e==e&&(this.$config.scrollTop=this.$state.scrollTop=this.$grid_data.scrollTop=e,n=!0),n&&this.callEvent("onScroll",[this.$config.scrollLeft,this.$config.scrollTop])}},getColumnIndex:function(t,e){for(var n=this.$getConfig().columns,i=0,r=0;r<n.length;r++)if(e&&n[r].hide&&i++,n[r].name==t)return r-i;return null},getColumn:function(t){var e=this.getColumnIndex(t);return null===e?null:this.$getConfig().columns[e]},getGridColumns:function(){return this.$getConfig().columns.slice()},isVisible:function(){return this.$parent&&this.$parent.$config?!this.$parent.$config.hidden:this.$grid.offsetWidth},_createLayerConfig:function(){var t=this.$gantt,e=this;return[{renderer:t.$ui.layers.gridLine(),container:this.$grid_data,filter:[function(){return e.isVisible()}]},{renderer:t.$ui.layers.gridTaskRowResizer(),container:this.$grid_data,append:!0,filter:[function(){return t.config.resize_rows}]}]},_addLayers:function(t){if(this.$config.bind){this._taskLayers=[];var e=this,n=this.$gantt.$services.getService("layers"),i=n.getDataRender(this.$config.bind);i||(i=n.createDataRender({name:this.$config.bind,defaultContainer:function(){return e.$grid_data}}));for(var r=this.$config.layers,a=0;r&&a<r.length;a++){var o=r[a];o.view=this;var s=i.addLayer(o);this._taskLayers.push(s)}this._bindStore(),this._initSmartRenderingPlaceholder()}},_refreshPlaceholderOnStoreUpdate:function(t){var e=this.$getConfig(),n=this.$config.rowStore;if(n&&null===t&&this.isVisible()&&e.smart_rendering){var i;if(this.$config.scrollY){var r=this.$gantt.$ui.getView(this.$config.scrollY);r&&(i=r.getScrollState().scrollSize)}if(i||(i=n?this.getTotalHeight():0),i){this.$rowsPlaceholder&&this.$rowsPlaceholder.parentNode&&this.$rowsPlaceholder.parentNode.removeChild(this.$rowsPlaceholder);var a=this.$rowsPlaceholder=document.createElement("div");a.style.visibility="hidden",a.style.height=i+"px",a.style.width="1px",this.$grid_data.appendChild(a)}}},_initSmartRenderingPlaceholder:function(){var t=this.$config.rowStore;t&&(this._initSmartRenderingPlaceholder=function(){},this._staticBgHandler=t.attachEvent("onStoreUpdated",r.bind(this._refreshPlaceholderOnStoreUpdate,this)))},_initEvents:function(){var t=this.$gantt;this._mouseDelegates.delegate("click","gantt_close",t.bind(function(t,e,n){var r=this.$config.rowStore;if(!r)return!0;var a=i.locateAttribute(t,this.$config.item_attribute);return a&&r.close(a.getAttribute(this.$config.item_attribute)),!1},this),this.$grid),this._mouseDelegates.delegate("click","gantt_open",t.bind(function(t,e,n){var r=this.$config.rowStore;if(!r)return!0;var a=i.locateAttribute(t,this.$config.item_attribute);return a&&r.open(a.getAttribute(this.$config.item_attribute)),!1},this),this.$grid)},_clearLayers:function(t){var e=this.$gantt.$services.getService("layers").getDataRender(this.$config.bind);if(this._taskLayers)for(var n=0;n<this._taskLayers.length;n++)e.removeLayer(this._taskLayers[n]);this._taskLayers=[]},_getColumnWidth:function(t,e,n){var i=t.min_width||e.min_grid_column_width,r=Math.max(n,i||10);return t.max_width&&(r=Math.min(r,t.max_width)),r},_checkGridColumnMinWidthLimits:function(t,e){for(var n=0,i=t.length;n<i;n++){var r=1*t[n].width;!t[n].min_width&&r<e.min_grid_column_width&&(t[n].min_width=r)}},_getGridWidthLimits:function(){for(var t=this.$getConfig(),e=this.getGridColumns(),n=0,i=0,r=0;r<e.length;r++)n+=e[r].min_width?e[r].min_width:t.min_grid_column_width,void 0!==i&&(i=e[r].max_width?i+e[r].max_width:void 0);return this._checkGridColumnMinWidthLimits(e,t),[n,i]},_setColumnsWidth:function(t,e){var n=this.$getConfig(),i=this.getGridColumns(),r=0,a=t;e=window.isNaN(e)?-1:e;for(var o=0,s=i.length;o<s;o++)r+=1*i[o].width;if(window.isNaN(r)){this._calculateGridWidth(),r=0;for(o=0,s=i.length;o<s;o++)r+=1*i[o].width}var l=a-r,c=0;for(o=0;o<e+1;o++)c+=i[o].width;r-=c;for(o=e+1;o<i.length;o++){var u=i[o],d=Math.round(l*(u.width/r));l<0?u.min_width&&u.width+d<u.min_width?d=u.min_width-u.width:!u.min_width&&n.min_grid_column_width&&u.width+d<n.min_grid_column_width&&(d=n.min_grid_column_width-u.width):u.max_width&&u.width+d>u.max_width&&(d=u.max_width-u.width),r-=u.width,u.width+=d,l-=d}for(var h=l>0?1:-1;l>0&&1===h||l<0&&-1===h;){var f=l;for(o=e+1;o<i.length;o++){var _;if((_=i[o].width+h)==this._getColumnWidth(i[o],n,_)&&(l-=h,i[o].width=_),!l)break}if(f==l)break}l&&e>-1&&((_=i[e].width+l)==this._getColumnWidth(i[e],n,_)&&(i[e].width=_));return this._getColsTotalWidth()},_getColsTotalWidth:function(){for(var t=this.getGridColumns(),e=0,n=0;n<t.length;n++){var i=parseFloat(t[n].width);if(window.isNaN(i))return!1;e+=i}return e},_calculateGridWidth:function(){for(var t=this.$getConfig(),e=this.getGridColumns(),n=0,i=[],r=[],a=0;a<e.length;a++){var o=parseFloat(e[a].width);window.isNaN(o)&&(o=t.min_grid_column_width||10,i.push(a)),r[a]=o,n+=o}var s=this._getGridWidth()+1;if(t.autofit||i.length){var l=s-n;if(t.autofit&&!t.grid_elastic_columns)for(a=0;a<r.length;a++){var c=Math.round(l/(r.length-a));r[a]+=c,(u=this._getColumnWidth(e[a],t,r[a]))!=r[a]&&(c=u-r[a],r[a]=u),l-=c}else if(i.length)for(a=0;a<i.length;a++){c=Math.round(l/(i.length-a));var u,d=i[a];r[d]+=c,(u=this._getColumnWidth(e[d],t,r[d]))!=r[d]&&(c=u-r[d],r[d]=u),l-=c}for(a=0;a<r.length;a++)e[a].width=r[a]}else{var h=s!=n;this.$config.width=n-1,t.grid_width=n,h&&this.$parent._setContentSize(this.$config.width,null)}},_renderGridHeader:function(){var t=this.$gantt,e=this.$getConfig(),n=this.$gantt.locale,i=this.$gantt.templates,r=this.getGridColumns();e.rtl&&(r=r.reverse());for(var a=[],o=0,s=n.labels,l=e.scale_height-1,c=0;c<r.length;c++){var u=c==r.length-1,d=r[c];d.name||(d.name=t.uid()+"");var h=1*d.width,f=this._getGridWidth();u&&f>o+h&&(d.width=h=f-o),o+=h;var _=t._sort&&d.name==t._sort.name?"<div class='gantt_sort gantt_"+t._sort.direction+"'></div>":"",g=["gantt_grid_head_cell","gantt_grid_head_"+d.name,u?"gantt_last_cell":"",i.grid_header_class(d.name,d)].join(" "),p="width:"+(h-(u?1:0))+"px;",v=d.label||s["column_"+d.name]||s[d.name];v=v||"";var m="<div class='"+g+"' style='"+p+"' "+t._waiAria.gridScaleCellAttrString(d,v)+" data-column-id='"+d.name+"' column_id='"+d.name+"' data-column-name='"+d.name+"' data-column-index='"+c+"'>"+v+_+"</div>";a.push(m)}this.$grid_scale.style.height=e.scale_height+"px",this.$grid_scale.style.lineHeight=l+"px",this.$grid_scale.innerHTML=a.join(""),this._renderHeaderResizers&&this._renderHeaderResizers()},_getGridWidth:function(){return this.$config.width},destructor:function(){this._clearLayers(this.$gantt),this._mouseDelegates&&(this._mouseDelegates.destructor(),this._mouseDelegates=null),this._unbindStore(),this.$grid=null,this.$grid_scale=null,this.$grid_data=null,this.$gantt=null,this.$config.rowStore&&(this.$config.rowStore.detachEvent(this._staticBgHandler),this.$config.rowStore=null),this.callEvent("onDestroy",[]),this.detachAllEvents()}},t.exports=u},function(t,e,n){var i=n(0);t.exports=function(t){var e=t.date,n=t.$services;return{getSum:function(t,e,n){void 0===n&&(n=t.length-1),void 0===e&&(e=0);for(var i=0,r=e;r<=n;r++)i+=t[r];return i},setSumWidth:function(t,e,n,i){var r=e.width;void 0===i&&(i=r.length-1),void 0===n&&(n=0);var a=i-n+1;if(!(n>r.length-1||a<=0||i>r.length-1)){var o=t-this.getSum(r,n,i);this.adjustSize(o,r,n,i),this.adjustSize(-o,r,i+1),e.full_width=this.getSum(r)}},splitSize:function(t,e){for(var n=[],i=0;i<e;i++)n[i]=0;return this.adjustSize(t,n),n},adjustSize:function(t,e,n,i){n||(n=0),void 0===i&&(i=e.length-1);for(var r=i-n+1,a=this.getSum(e,n,i),o=n;o<=i;o++){var s=Math.floor(t*(a?e[o]/a:1/r));a-=e[o],t-=s,r--,e[o]+=s}e[e.length-1]+=t},sortScales:function(t){function n(t,n){var i=new Date(1970,0,1);return e.add(i,n,t)-i}t.sort(function(t,e){return n(t.unit,t.step)<n(e.unit,e.step)?1:n(t.unit,t.step)>n(e.unit,e.step)?-1:0});for(var i=0;i<t.length;i++)t[i].index=i},_isLegacyMode:function(e){var n=e||t.config;return n.scale_unit||n.date_scale||n.subscales},_prepareScaleObject:function(e){var n=e.format;return n||(n=e.template||e.date||"%d %M"),"string"==typeof n&&(n=t.date.date_to_str(n)),{unit:e.unit||"day",step:e.step||1,format:n,css:e.css}},primaryScale:function(e){var i,r=n.getService("templateLoader"),a=this._isLegacyMode(e),o=e||t.config;if(a)r.initTemplate("date_scale",void 0,void 0,o,t.config.templates),i={unit:t.config.scale_unit,step:t.config.step,template:t.templates.date_scale,date:t.config.date_scale,css:t.templates.scale_cell_class};else{var s=o.scales[0];i={unit:s.unit,step:s.step,template:s.template,format:s.format,date:s.date,css:s.css||t.templates.scale_cell_class}}return this._prepareScaleObject(i)},getSubScales:function(e){var n=this._isLegacyMode(e),i=e||t.config;return(n?i.subscales||[]:i.scales.slice(1)).map(function(t){return this._prepareScaleObject(t)}.bind(this))},prepareConfigs:function(t,e,n,i,r,a,o){for(var s=this.splitSize(i,t.length),l=n,c=[],u=t.length-1;u>=0;u--){var d=u==t.length-1,h=this.initScaleConfig(t[u],r,a);d&&this.processIgnores(h),this.initColSizes(h,e,l,s[u]),this.limitVisibleRange(h),d&&(l=h.full_width),c.unshift(h)}for(u=0;u<c.length-1;u++)this.alineScaleColumns(c[c.length-1],c[u]);for(u=0;u<c.length;u++)o&&this.reverseScale(c[u]),this.setPosSettings(c[u]);return c},reverseScale:function(t){t.width=t.width.reverse(),t.trace_x=t.trace_x.reverse();var e=t.trace_indexes;t.trace_indexes={},t.trace_index_transition={},t.rtl=!0;for(var n=0;n<t.trace_x.length;n++)t.trace_indexes[t.trace_x[n].valueOf()]=n,t.trace_index_transition[e[t.trace_x[n].valueOf()]]=n;return t},setPosSettings:function(t){for(var e=0,n=t.trace_x.length;e<n;e++)t.left.push((t.width[e-1]||0)+(t.left[e-1]||0))},_ignore_time_config:function(n,i){if(t.config.skip_off_time){for(var r=!0,a=n,o=0;o<i.step;o++)o&&(a=e.add(n,o,i.unit)),r=r&&!this.isWorkTime(a,i.unit);return r}return!1},processIgnores:function(t){t.ignore_x={},t.display_count=t.count},initColSizes:function(t,n,i,r){var a=i;t.height=r;var o=void 0===t.display_count?t.count:t.display_count;o||(o=1),t.col_width=Math.floor(a/o),n&&t.col_width<n&&(t.col_width=n,a=t.col_width*o),t.width=[];for(var s=t.ignore_x||{},l=0;l<t.trace_x.length;l++)if(s[t.trace_x[l].valueOf()]||t.display_count==t.count)t.width[l]=0;else{var c=1;"month"==t.unit&&(c=Math.round((e.add(t.trace_x[l],t.step,t.unit)-t.trace_x[l])/864e5)),t.width[l]=c}this.adjustSize(a-this.getSum(t.width),t.width),t.full_width=this.getSum(t.width)},initScaleConfig:function(t,e,n){var r=i.mixin({count:0,col_width:0,full_width:0,height:0,width:[],left:[],trace_x:[],trace_indexes:{},min_date:new Date(e),max_date:new Date(n)},t);return this.eachColumn(t.unit,t.step,e,n,function(t){r.count++,r.trace_x.push(new Date(t)),r.trace_indexes[t.valueOf()]=r.trace_x.length-1}),r.trace_x_ascending=r.trace_x.slice(),r},iterateScales:function(t,e,n,i,r){for(var a=e.trace_x,o=t.trace_x,s=n||0,l=i||o.length-1,c=0,u=1;u<a.length;u++){var d=t.trace_indexes[+a[u]];void 0!==d&&d<=l&&(r&&r.apply(this,[c,u,s,d]),s=d,c=u)}},alineScaleColumns:function(t,e,n,i){this.iterateScales(t,e,n,i,function(n,i,r,a){var o=this.getSum(t.width,r,a-1);this.getSum(e.width,n,i-1)!=o&&this.setSumWidth(o,e,n,i-1)})},eachColumn:function(n,i,r,a,o){var s=new Date(r),l=new Date(a);e[n+"_start"]&&(s=e[n+"_start"](s));var c=new Date(s);for(+c>=+l&&(l=e.add(c,i,n));+c<+l;){o.call(this,new Date(c));var u=c.getTimezoneOffset();c=e.add(c,i,n),c=t._correct_dst_change(c,u,i,n),e[n+"_start"]&&(c=e[n+"_start"](c))}},limitVisibleRange:function(t){var n=t.trace_x,i=t.width.length-1,r=0;if(+n[0]<+t.min_date&&0!=i){var a=Math.floor(t.width[0]*((n[1]-t.min_date)/(n[1]-n[0])));r+=t.width[0]-a,t.width[0]=a,n[0]=new Date(t.min_date)}var o=n.length-1,s=n[o],l=e.add(s,t.step,t.unit);if(+l>+t.max_date&&o>0&&(a=t.width[o]-Math.floor(t.width[o]*((l-t.max_date)/(l-s))),r+=t.width[o]-a,t.width[o]=a),r){for(var c=this.getSum(t.width),u=0,d=0;d<t.width.length;d++){var h=Math.floor(r*(t.width[d]/c));t.width[d]+=h,u+=h}this.adjustSize(r-u,t.width)}}}}},,function(t,e,n){},function(t,e,n){var i=n(2),r={getHtmlSelect:function(t,e,n){var r="",o=this;return t=t||[],i.forEach(t,function(t){var e=[{key:"value",value:t.key}];n==t.key&&(e[e.length]={key:"selected",value:"selected"}),t.attributes&&(e=e.concat(t.attributes)),r+=o.getHtmlOption({innerHTML:t.label},e)}),a("select",{innerHTML:r},e)},getHtmlOption:function(t,e){return a("option",t,e)},getHtmlButton:function(t,e){return a("button",t,e)},getHtmlDiv:function(t,e){return a("div",t,e)},getHtmlLabel:function(t,e){return a("label",t,e)},getHtmlInput:function(t){return"<input"+o(t||[])+">"}};function a(t,e,n){return e=e||[],"<"+t+o(n||[])+">"+(e.innerHTML||"")+"</"+t+">"}function o(t){var e="";return i.forEach(t,function(t){e+=" "+t.key+"='"+t.value+"'"}),e}t.exports=r},function(t,e,n){var i=n(2);t.exports=function(t){var e={};return t.$data.tasksStore.attachEvent("onStoreUpdated",function(){e={}}),function(n,r,a,o){var s=n.id+"_"+r+"_"+a.unit+"_"+a.step;return e[s]?e[s]:e[s]=function(e,n,r,a){var o,s=!1,l={};t.config.process_resource_assignments&&n===t.config.resource_property?(o="task"==e.$role?t.getResourceAssignments(e.$resource_id,e.$task_id):t.getResourceAssignments(e.id),s=!0):o="task"==e.$role?[]:t.getTaskBy(n,e.id);for(var c,u,d,h,f,l=function(e,n,r){for(var a=n.unit,o=n.step,s={},l={},c=0;c<e.length;c++){var u=e[c],d=u;r&&(d=t.getTask(u.task_id));var h=u.start_date||d.start_date,f=u.end_date||d.end_date;r&&(u.start_date&&(h=new Date(Math.max(u.start_date.valueOf(),d.start_date.valueOf()))),u.end_date&&(f=new Date(Math.min(u.end_date.valueOf(),d.end_date.valueOf()))));var _=i.findBinary(n.trace_x,h.valueOf()),g=new Date(n.trace_x[_]||t.date[a+"_start"](new Date(h))),p=t.config.work_time?t.getTaskCalendar(d):t;for(l[p.id]={};g<f;){var v=l[p.id],m=g,y=m.valueOf();if(g=t.date.add(g,o,a),!1!==v[y]){var k=p.isWorkTime({date:m,task:d,unit:a});k?(s[y]||(s[y]={tasks:[],assignments:[]}),s[y].tasks.push(d),r&&s[y].assignments.push(u)):v[y]=!1}}}return s}(o,r,s),_=r.unit,g=r.step,p=[],v=a.$getConfig(),m=0;m<r.trace_x.length;m++)c=new Date(r.trace_x[m]),u=t.date.add(c,g,_),f=l[c.valueOf()]||{},d=f.tasks||[],h=f.assignments||[],d.length||v.resource_render_empty_cells?p.push({start_date:c,end_date:u,tasks:d,assignments:h}):p.push(null);return p}(n,r,a,o)}}},function(t,e,n){var i=n(3),r=n(1),a=function(t){"use strict";function e(e,n,i){var r=t.apply(this,arguments)||this;return e&&(r.$root=!0),r._parseConfig(n),r.$name="layout",r}return i(e,t),e.prototype.destructor=function(){this.$container&&this.$view&&r.removeNode(this.$view);for(var e=0;e<this.$cells.length;e++){this.$cells[e].destructor()}this.$cells=[],t.prototype.destructor.call(this)},e.prototype._resizeScrollbars=function(t,e){var n,i=!1,r=[],a=[];function o(t){t.$parent.show(),i=!0,r.push(t)}function s(t){t.$parent.hide(),i=!0,a.push(t)}for(var l=0;l<e.length;l++)t[(n=e[l]).$config.scroll]?s(n):n.shouldHide()?s(n):n.shouldShow()?o(n):n.isVisible()?r.push(n):a.push(n);var c={};for(l=0;l<r.length;l++)r[l].$config.group&&(c[r[l].$config.group]=!0);for(l=0;l<a.length;l++)if((n=a[l]).$config.group&&c[n.$config.group]){o(n);for(var u=0;u<r.length;u++)if(r[u]==n){this.$gantt.$scrollbarRepaint=!0;break}}return i},e.prototype._syncCellSizes=function(t,e){if(t){var n={};return this._eachChild(function(t){t.$config.group&&"scrollbar"!=t.$name&&"resizer"!=t.$name&&(n[t.$config.group]||(n[t.$config.group]=[]),n[t.$config.group].push(t))}),n[t]&&this._syncGroupSize(n[t],e),n[t]}},e.prototype._syncGroupSize=function(t,e){if(t.length)for(var n=t[0].$parent._xLayout?"width":"height",i=t[0].$parent.getNextSibling(t[0].$id)?1:-1,r=e.value,a=e.isGravity,o=0;o<t.length;o++){var s=t[o].getSize(),l=i>0?t[o].$parent.getNextSibling(t[o].$id):t[o].$parent.getPrevSibling(t[o].$id);"resizer"==l.$name&&(l=i>0?l.$parent.getNextSibling(l.$id):l.$parent.getPrevSibling(l.$id));var c=l.getSize();if(a)t[o].$config.gravity=r;else if(l[n]){var u=s.gravity+c.gravity,d=s[n]+c[n],h=u/d;t[o].$config.gravity=h*r,l.$config[n]=d-r,l.$config.gravity=u-h*r}else t[o].$config[n]=r;var f=this.$gantt.$ui.getView("grid");!f||t[o].$content!==f||f.$config.scrollable||a||(this.$gantt.config.grid_width=r)}},e.prototype.resize=function(e){var n=!1;if(this.$root&&!this._resizeInProgress&&(this.callEvent("onBeforeResize",[]),n=!0,this._resizeInProgress=!0),t.prototype.resize.call(this,!0),t.prototype.resize.call(this,!1),n){var i=[];i=(i=(i=i.concat(this.getCellsByType("viewCell"))).concat(this.getCellsByType("viewLayout"))).concat(this.getCellsByType("hostCell"));for(var r=this.getCellsByType("scroller"),a=0;a<i.length;a++)i[a].$config.hidden||i[a].setContentSize();var o=this._getAutosizeMode(this.$config.autosize),s=this._resizeScrollbars(o,r);if(this.$config.autosize&&(this.autosize(this.$config.autosize),s=!0),s){this.resize();for(a=0;a<i.length;a++)i[a].$config.hidden||i[a].setContentSize()}this.callEvent("onResize",[])}n&&(this._resizeInProgress=!1)},e.prototype._eachChild=function(t,e){if(t(e=e||this),e.$cells)for(var n=0;n<e.$cells.length;n++)this._eachChild(t,e.$cells[n])},e.prototype.isChild=function(t){var e=!1;return this._eachChild(function(n){n!==t&&n.$content!==t||(e=!0)}),e},e.prototype.getCellsByType=function(t){var n=[];if(t===this.$name&&n.push(this),this.$content&&this.$content.$name==t&&n.push(this.$content),this.$cells)for(var i=0;i<this.$cells.length;i++){var r=e.prototype.getCellsByType.call(this.$cells[i],t);r.length&&n.push.apply(n,r)}return n},e.prototype.getNextSibling=function(t){var e=this.cellIndex(t);return e>=0&&this.$cells[e+1]?this.$cells[e+1]:null},e.prototype.getPrevSibling=function(t){var e=this.cellIndex(t);return e>=0&&this.$cells[e-1]?this.$cells[e-1]:null},e.prototype.cell=function(t){for(var e=0;e<this.$cells.length;e++){var n=this.$cells[e];if(n.$id===t)return n;var i=n.cell(t);if(i)return i}},e.prototype.cellIndex=function(t){for(var e=0;e<this.$cells.length;e++)if(this.$cells[e].$id===t)return e;return-1},e.prototype.moveView=function(t,e){if(this.$cells[e]!==t)return window.alert("Not implemented");e+=this.$config.header?1:0;var n=this.$view;e>=n.childNodes.length?n.appendChild(t.$view):n.insertBefore(t.$view,n.childNodes[e])},e.prototype._parseConfig=function(t){this.$cells=[],this._xLayout=!t.rows;for(var e=t.rows||t.cols||t.views,n=0;n<e.length;n++){var i=e[n];i.mode=this._xLayout?"x":"y";var r=this.$factory.initUI(i,this);r?(r.$parent=this,this.$cells.push(r)):(e.splice(n,1),n--)}},e.prototype.getCells=function(){return this.$cells},e.prototype.render=function(){var t=r.insertNode(this.$container,this.$toHTML());this.$fill(t,null),this.callEvent("onReady",[]),this.resize(),this.render=this.resize},e.prototype.$fill=function(t,e){this.$view=t,this.$parent=e;for(var n=r.getChildNodes(t,"gantt_layout_cell"),i=n.length-1;i>=0;i--){var a=this.$cells[i];a.$fill(n[i],this),a.$config.hidden&&a.$view.parentNode.removeChild(a.$view)}},e.prototype.$toHTML=function(){for(var e=this._xLayout?"x":"y",n=[],i=0;i<this.$cells.length;i++)n.push(this.$cells[i].$toHTML());return t.prototype.$toHTML.call(this,n.join(""),(this.$root?"gantt_layout_root ":"")+"gantt_layout gantt_layout_"+e)},e.prototype.getContentSize=function(t){for(var e,n,i,r=0,a=0,o=0;o<this.$cells.length;o++)(n=this.$cells[o]).$config.hidden||(e=n.getContentSize(t),"scrollbar"===n.$config.view&&t[n.$config.scroll]&&(e.height=0,e.width=0),n.$config.resizer&&(this._xLayout?e.height=0:e.width=0),i=n._getBorderSizes(),this._xLayout?(r+=e.width+i.horizontal,a=Math.max(a,e.height+i.vertical)):(r=Math.max(r,e.width+i.horizontal),a+=e.height+i.vertical));return{width:r+=(i=this._getBorderSizes()).horizontal,height:a+=i.vertical}},e.prototype._cleanElSize=function(t){return 1*(t||"").toString().replace("px","")||0},e.prototype._getBoxStyles=function(t){var e=null,n=["width","height","paddingTop","paddingBottom","paddingLeft","paddingRight","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"],i={boxSizing:"border-box"==(e=window.getComputedStyle?window.getComputedStyle(t,null):{width:t.clientWidth,height:t.clientHeight}).boxSizing};e.MozBoxSizing&&(i.boxSizing="border-box"==e.MozBoxSizing);for(var r=0;r<n.length;r++)i[n[r]]=e[n[r]]?this._cleanElSize(e[n[r]]):0;var a={horPaddings:i.paddingLeft+i.paddingRight+i.borderLeftWidth+i.borderRightWidth,vertPaddings:i.paddingTop+i.paddingBottom+i.borderTopWidth+i.borderBottomWidth,borderBox:i.boxSizing,innerWidth:i.width,innerHeight:i.height,outerWidth:i.width,outerHeight:i.height};return a.borderBox?(a.innerWidth-=a.horPaddings,a.innerHeight-=a.vertPaddings):(a.outerWidth+=a.horPaddings,a.outerHeight+=a.vertPaddings),a},e.prototype._getAutosizeMode=function(t){var e={x:!1,y:!1};return"xy"===t?e.x=e.y=!0:"y"===t||!0===t?e.y=!0:"x"===t&&(e.x=!0),e},e.prototype.autosize=function(t){var e=this._getAutosizeMode(t),n=this._getBoxStyles(this.$container),i=this.getContentSize(t),r=this.$container;e.x&&(n.borderBox&&(i.width+=n.horPaddings),r.style.width=i.width+"px"),e.y&&(n.borderBox&&(i.height+=n.vertPaddings),r.style.height=i.height+"px")},e.prototype.getSize=function(){this._sizes=[];for(var e=0,n=0,i=1e11,r=0,a=1e11,o=0,s=0;s<this.$cells.length;s++){var l=this._sizes[s]=this.$cells[s].getSize();this.$cells[s].$config.hidden||(this._xLayout?(!l.width&&l.minWidth?e+=l.minWidth:e+=l.width,i+=l.maxWidth,n+=l.minWidth,r=Math.max(r,l.height),a=Math.min(a,l.maxHeight),o=Math.max(o,l.minHeight)):(!l.height&&l.minHeight?r+=l.minHeight:r+=l.height,a+=l.maxHeight,o+=l.minHeight,e=Math.max(e,l.width),i=Math.min(i,l.maxWidth),n=Math.max(n,l.minWidth)))}var c=t.prototype.getSize.call(this);return c.maxWidth>=1e5&&(c.maxWidth=i),c.maxHeight>=1e5&&(c.maxHeight=a),c.minWidth=c.minWidth!=c.minWidth?0:c.minWidth,c.minHeight=c.minHeight!=c.minHeight?0:c.minHeight,this._xLayout?(c.minWidth+=this.$config.margin*this.$cells.length||0,c.minWidth+=2*this.$config.padding||0,c.minHeight+=2*this.$config.padding||0):(c.minHeight+=this.$config.margin*this.$cells.length||0,c.minHeight+=2*this.$config.padding||0),c},e.prototype._calcFreeSpace=function(t,e,n){var i=n?e.minWidth:e.minHeight,r=e.maxWidth,a=t;return a?(a>r&&(a=r),a<i&&(a=i),this._free-=a):((a=Math.floor(this._free/this._gravity*e.gravity))>r&&(a=r,this._free-=a,this._gravity-=e.gravity),a<i&&(a=i,this._free-=a,this._gravity-=e.gravity)),a},e.prototype._calcSize=function(t,e,n){var i=t,r=n?e.minWidth:e.minHeight,a=n?e.maxWidth:e.maxHeight;return i||(i=Math.floor(this._free/this._gravity*e.gravity)),i>a&&(i=a),i<r&&(i=r),i},e.prototype._configureBorders=function(){this.$root&&this._setBorders([this._borders.left,this._borders.top,this._borders.right,this._borders.bottom],this);for(var t=this._xLayout?this._borders.right:this._borders.bottom,e=this.$cells,n=e.length-1,i=n;i>=0;i--)if(!e[i].$config.hidden){n=i;break}for(i=0;i<e.length;i++)if(!e[i].$config.hidden){var r=i>=n,a="";!r&&e[i+1]&&"scrollbar"==e[i+1].$config.view&&(this._xLayout?r=!0:a="gantt_layout_cell_border_transparent"),this._setBorders(r?[]:[t,a],e[i])}},e.prototype._updateCellVisibility=function(){for(var t=this._visibleCells||{},e=!this._visibleCells,n={},i=null,r=[],a=0;a<this._sizes.length;a++)(i=this.$cells[a]).$config.hide_empty&&r.push(i),!e&&i.$config.hidden&&t[i.$id]?i._hide(!0):i.$config.hidden||t[i.$id]||i._hide(!1),i.$config.hidden||(n[i.$id]=!0);this._visibleCells=n;for(a=0;a<r.length;a++){var o=!0;(i=r[a]).$cells.forEach(function(t){t.$config.hidden||t.$config.resizer||(o=!1)}),i.$config.hidden=o}},e.prototype.setSize=function(e,n){this._configureBorders(),t.prototype.setSize.call(this,e,n),n=this.$lastSize.contentY,e=this.$lastSize.contentX;var i,r,a=this.$config.padding||0;this.$view.style.padding=a+"px",this._gravity=0,this._free=this._xLayout?e:n,this._free-=2*a,this._updateCellVisibility();for(var o=0;o<this._sizes.length;o++)if(!(i=this.$cells[o]).$config.hidden){var s=this.$config.margin||0;"resizer"!=i.$name||s||(s=-1);var l=i.$view,c=this._xLayout?"marginRight":"marginBottom";o!==this.$cells.length-1&&(l.style[c]=s+"px",this._free-=s),r=this._sizes[o],this._xLayout?r.width||(this._gravity+=r.gravity):r.height||(this._gravity+=r.gravity)}for(o=0;o<this._sizes.length;o++)if(!(i=this.$cells[o]).$config.hidden){var u=(r=this._sizes[o]).width,d=r.height;this._xLayout?this._calcFreeSpace(u,r,!0):this._calcFreeSpace(d,r,!1)}for(o=0;o<this.$cells.length;o++)if(!(i=this.$cells[o]).$config.hidden){r=this._sizes[o];var h=void 0,f=void 0;this._xLayout?(h=this._calcSize(r.width,r,!0),f=n-2*a):(h=e-2*a,f=this._calcSize(r.height,r,!1)),i.setSize(h,f)}},e}(n(9));t.exports=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(170),r=n(169),a=n(168);e.LargerUnitsCache=a.LargerUnitsCache,e.createCacheObject=function(){return"undefined"!=typeof Map?new i.WorkUnitsMapCache:new r.WorkUnitsObjectCache}},function(t,e,n){var i=n(0),r=n(2);function a(t,e,n,i,r){return this.date=t,this.unit=e,this.task=n,this.id=i,this.calendar=r,this}function o(t,e,n,i,r,a){return this.date=t,this.dir=e,this.unit=n,this.task=i,this.id=r,this.calendar=a,this}function s(t,e,n,i,r,a,o){return this.start_date=t,this.duration=e,this.unit=n,this.step=i,this.task=r,this.id=a,this.calendar=o,this}function l(t,e,n,i){return this.start_date=t,this.end_date=e,this.task=n,this.calendar=i,this.unit=null,this.step=null,this}t.exports=function(t){return{getWorkHoursArguments:function(){var e=arguments[0];if(e=r.isDate(e)?{date:e}:i.mixin({},e),!r.isValidDate(e.date))throw t.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return e},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var e,n=arguments[0];if(n instanceof a)return n;if((e=n.date?new a(n.date,n.unit,n.task,null,n.calendar):new a(arguments[0],arguments[1],arguments[2],null,arguments[3])).unit=e.unit||t.config.duration_unit,!r.isValidDate(e.date))throw t.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return e},getClosestWorkTimeArguments:function(e){var n,i=arguments[0];if(i instanceof o)return i;if(n=r.isDate(i)?new o(i):new o(i.date,i.dir,i.unit,i.task,null,i.calendar),i.id&&(n.task=i),n.dir=i.dir||"any",n.unit=i.unit||t.config.duration_unit,!r.isValidDate(n.date))throw t.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return n},_getStartEndConfig:function(e){var n,i=l;if(e instanceof i)return e;if(r.isDate(e)?n=new i(arguments[0],arguments[1],arguments[2],arguments[3]):(n=new i(e.start_date,e.end_date,e.task),null!==e.id&&void 0!==e.id&&(n.task=e)),n.unit=n.unit||t.config.duration_unit,n.step=n.step||t.config.duration_step,n.start_date=n.start_date||n.start||n.date,!r.isValidDate(n.start_date))throw t.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!r.isValidDate(n.end_date))throw t.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return n},getDurationArguments:function(t,e,n,i){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,e,n,i){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(e,n,i,a){var o,l=arguments[0];if(l instanceof s)return l;if(o=r.isDate(l)?new s(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):new s(l.start_date,l.duration,l.unit,l.step,l.task,null,l.calendar),null!==l.id&&void 0!==l.id&&(o.task=l,o.unit=null,o.step=null),o.unit=o.unit||t.config.duration_unit,o.step=o.step||t.config.duration_step,!r.isValidDate(o.start_date))throw t.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return o}}}},function(t,e,n){var i=n(182);t.exports=function(t){var e={},n={},r=null,a=-1,o=null,s=i(t);return{_resetTopPositionHeight:function(){e={},n={},s.resetCache()},_resetHeight:function(){var t=this.$config.rowStore,e=this.getCacheStateTotalHeight(t);o?this.shouldClearHeightCache(o,e)&&(o=e,r=null):o=e,a=-1,s.resetCache()},getRowTop:function(t){if(s.canUseSimpleCalculation())return s.getRowTop(t);var e=this.$config.rowStore;if(!e)return 0;if(void 0!==n[t])return n[t];for(var i=e.getIndexRange(),r=0,a=0,o=0;o<i.length;o++)n[o]=r,r+=this.getItemHeight(i[o].id),o<t&&(a=r);return a},getItemTop:function(t){if(this.$config.rowStore){if(void 0!==e[t])return e[t];var n=this.$config.rowStore;if(!n)return 0;var i=n.getIndexById(t);if(-1===i&&n.getParent&&n.exists(t)){var r=n.getParent(t);if(n.exists(r)){var a=n.getItem(r);if(this.$gantt.isSplitTask(a))return this.getItemTop(r)}}return e[t]=this.getRowTop(i),e[t]}return 0},getItemHeight:function(t){if(s.canUseSimpleCalculation())return s.getItemHeight(t);if(!r&&this.$config.rowStore&&this._fillHeightCache(this.$config.rowStore),void 0!==r[t])return r[t];var e=this.$getConfig().row_height;if(this.$config.rowStore){var n=this.$config.rowStore;if(!n)return e;var i=n.getItem(t);return r[t]=i&&i.row_height||e}return e},_fillHeightCache:function(t){if(t){r={};var e=this.$getConfig().row_height;t.eachItem(function(t){return r[t.id]=t&&t.row_height||e})}},getCacheStateTotalHeight:function(t){var e=this.$getConfig().row_height,n={},i=[],r=0;return t&&t.eachItem(function(t){i.push(t),n[t.id]=t.row_height,r+=t.row_height||e}),{globalHeight:e,items:i,count:i.length,sumHeight:r}},shouldClearHeightCache:function(t,e){if(t.count!=e.count)return!0;if(t.globalHeight!=e.globalHeight)return!0;if(t.sumHeight!=e.sumHeight)return!0;for(var n in t.items){var i=e.items[n];if(void 0!==i&&i!=t.items[n])return!0}return!1},getTotalHeight:function(){if(s.canUseSimpleCalculation())return s.getTotalHeight();if(-1!=a)return a;if(this.$config.rowStore){var t=this.$config.rowStore;this._fillHeightCache(t);var e=this.getItemHeight.bind(this),n=0;return t.getVisibleItems().forEach(function(t){n+=e(t.id)}),a=n,n}return 0},getItemIndexByTopPosition:function(t){if(!this.$config.rowStore)return 0;if(s.canUseSimpleCalculation())return s.getItemIndexByTopPosition(t);for(var e=this.$config.rowStore,n=0;n<e.countVisible();n++){var i=this.getRowTop(n),r=this.getRowTop(n+1);if(!r){var a=e.getIdByIndex(n);r=i+this.getItemHeight(a)}if(t>=i&&t<r)return n}}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(){var t=this;this.canParse=function(e){return!isNaN(t.parse(e))},this.format=function(t){return String(t)},this.parse=function(t){return parseInt(t,10)}}return t.create=function(e){return void 0===e&&(e=null),new t},t}();e.default=i},function(t,e){function n(t,e,n){for(var i=0;i<e.length;i++)t.isLinkExists(e[i])&&(n[e[i]]=t.getLink(e[i]))}function i(t,e,i){n(t,e.$source,i),n(t,e.$target,i)}t.exports={getSubtreeLinks:function(t,e){var n={};return t.isTaskExists(e)&&i(t,t.getTask(e),n),t.eachTask(function(e){i(t,e,n)},e),n},getSubtreeTasks:function(t,e){var n={};return t.eachTask(function(t){n[t.id]=t},e),n}}},function(t,e,n){var i=n(26),r=n(26);function a(t){var e=function(t){var e=new r(t).primaryScale(),n=e.unit,a=e.step;if(t.config.scale_offset_minimal){var o=new i(t),s=[o.primaryScale()].concat(o.getSubScales());o.sortScales(s),n=s[s.length-1].unit,a=s[s.length-1].step||1}return{unit:n,step:a}}(t),n=e.unit,a=e.step,o=function(t,e){var n={start_date:null,end_date:null};if(e.config.start_date&&e.config.end_date){n.start_date=e.date[t+"_start"](new Date(e.config.start_date));var i=new Date(e.config.end_date),r=e.date[t+"_start"](new Date(i));i=+i!=+r?e.date.add(r,1,t):r,n.end_date=i}return n}(n,t);o.start_date&&o.end_date||((o=t.getSubtaskDates()).start_date&&o.end_date||(o={start_date:new Date,end_date:new Date}),o.start_date=t.date[n+"_start"](o.start_date),o.start_date=t.calculateEndDate({start_date:t.date[n+"_start"](o.start_date),duration:-1,unit:n,step:a}),o.end_date=t.date[n+"_start"](o.end_date),o.end_date=t.calculateEndDate({start_date:o.end_date,duration:2,unit:n,step:a})),t._min_date=o.start_date,t._max_date=o.end_date}t.exports=function(t){a(t),function(t){if(t.config.fit_tasks){var e=+t._min_date,n=+t._max_date;if(+t._min_date!=e||+t._max_date!=n)return t.render(),t.callEvent("onScaleAdjusted",[]),!0}}(t)}},function(t,e,n){var i=n(39),r=n(0),a=n(2),o=n(40),s=n(11),l=n(2).replaceValidZeroId;o.default&&(o=o.default);var c=function(t){o.apply(this,[t]),this._branches={},this.pull={},this.$initItem=function(e){var n=e;t.initItem&&(n=t.initItem(n));var i=this.getItem(e.id);return i&&i.parent!=n.parent&&this.move(n.id,n.$index||-1,n.parent||this._ganttConfig.root_id),n},this.$parentProperty=t.parentProperty||"parent","function"!=typeof t.rootId?this.$getRootId=function(t){return function(){return t}}(t.rootId||0):this.$getRootId=t.rootId,this.$openInitially=t.openInitially,this.visibleOrder=i.$create(),this.fullOrder=i.$create(),this._searchVisibleOrder={},this._indexRangeCache={},this._eachItemMainRangeCache=null,this._getItemsCache=null,this._skip_refresh=!1,this._ganttConfig=null,t.getConfig&&(this._ganttConfig=t.getConfig());var e={},n={},r={},a={},s=!1;return this._attachDataChange(function(){return this._indexRangeCache={},this._eachItemMainRangeCache=null,this._getItemsCache=null,!0}),this.attachEvent("onPreFilter",function(){this._indexRangeCache={},this._eachItemMainRangeCache=null,e={},n={},r={},a={},s=!1,this.eachItem(function(t){var i=this.getParent(t.id);t.$open&&!1!==r[i]?r[t.id]=!0:r[t.id]=!1,this._isSplitItem(t)&&(s=!0,e[t.id]=!0,n[t.id]=!0),s&&n[i]&&(n[t.id]=!0),r[i]||void 0===r[i]?a[t.id]=!0:a[t.id]=!1})}),this.attachEvent("onFilterItem",function(t,i){var r=!1;if(this._ganttConfig)r=this._ganttConfig.open_split_tasks;var o=a[i.id];return s&&(o&&n[i.id]&&!e[i.id]&&(o=!!r),n[i.id]&&!e[i.id]&&(i.$split_subtask=!0)),i.$expanded_branch=!!a[i.id],!!o}),this.attachEvent("onFilter",function(){e={},n={},r={},a={}}),this};c.prototype=r.mixin({_buildTree:function(t){for(var e=null,n=this.$getRootId(),i=0,a=t.length;i<a;i++)e=t[i],this.setParent(e,l(this.getParent(e),n)||n);for(i=0,a=t.length;i<a;i++)e=t[i],this._add_branch(e),e.$level=this.calculateItemLevel(e),e.$local_index=this.getBranchIndex(e.id),r.defined(e.$open)||(e.$open=r.defined(e.open)?e.open:this.$openInitially());this._updateOrder()},_isSplitItem:function(t){return"split"==t.render&&this.hasChild(t.id)},parse:function(t){this._skip_refresh||this.callEvent("onBeforeParse",[t]);var e=this._parseInner(t);this._buildTree(e),this.filter(),this._skip_refresh||this.callEvent("onParse",[e])},_addItemInner:function(t,e){var n=this.getParent(t);r.defined(n)||(n=this.$getRootId(),this.setParent(t,n));var i=this.getIndexById(n)+Math.min(Math.max(e,0),this.visibleOrder.length);1*i!==i&&(i=void 0),o.prototype._addItemInner.call(this,t,i),this.setParent(t,n),t.hasOwnProperty("$rendered_parent")&&this._move_branch(t,t.$rendered_parent),this._add_branch(t,e)},_changeIdInner:function(t,e){var n=this.getChildren(t),i=this._searchVisibleOrder[t];o.prototype._changeIdInner.call(this,t,e);var r=this.getParent(e);this._replace_branch_child(r,t,e),this._branches[t]&&(this._branches[e]=this._branches[t]);for(var a=0;a<n.length;a++){var s=this.getItem(n[a]);s[this.$parentProperty]=e,s.$rendered_parent=e}this._searchVisibleOrder[e]=i,delete this._branches[t]},_traverseBranches:function(t,e){r.defined(e)||(e=this.$getRootId());var n=this._branches[e];if(n)for(var i=0;i<n.length;i++){var a=n[i];t.call(this,a),this._branches[a]&&this._traverseBranches(t,a)}},_updateOrder:function(t){this.fullOrder=i.$create(),this._traverseBranches(function(t){this.fullOrder.push(t)}),t&&o.prototype._updateOrder.call(this,t)},_removeItemInner:function(t){var e=[];this.eachItem(function(t){e.push(t)},t),e.push(this.getItem(t));for(var n=0;n<e.length;n++)this._move_branch(e[n],this.getParent(e[n]),null),o.prototype._removeItemInner.call(this,e[n].id),this._move_branch(e[n],this.getParent(e[n]),null)},move:function(t,e,n){var i=arguments[3];if(i=l(i,this._ganttConfig.root_id)){if(i===t)return;n=this.getParent(i),e=this.getBranchIndex(i)}if(t!=n){r.defined(n)||(n=this.$getRootId());var a=this.getItem(t),o=this.getParent(a.id),c=this.getChildren(n);if(-1==e&&(e=c.length+1),o==n)if(this.getBranchIndex(t)==e)return;if(!1===this.callEvent("onBeforeItemMove",[t,n,e]))return!1;for(var u=[],d=0;d<c.length;d++)s(c[d],null,this,this._ganttConfig)&&(u.push(c[d]),c.splice(d,1),d--);this._replace_branch_child(o,t);var h=(c=this.getChildren(n))[e];(h=l(h,this._ganttConfig.root_id))?c=c.slice(0,e).concat([t]).concat(c.slice(e)):c.push(t),u.length&&(c=c.concat(u)),this.setParent(a,n),this._branches[n]=c;var f=this.calculateItemLevel(a)-a.$level;a.$level+=f,this.eachItem(function(t){t.$level+=f},a.id,this),this._moveInner(this.getIndexById(t),this.getIndexById(n)+e),this.callEvent("onAfterItemMove",[t,n,e]),this.refresh()}},getBranchIndex:function(t){for(var e=this.getChildren(this.getParent(t)),n=0;n<e.length;n++)if(e[n]==t)return n;return-1},hasChild:function(t){var e=this._branches[t];return e&&e.length},getChildren:function(t){var e=this._branches[t];return e||i.$create()},isChildOf:function(t,e){if(!this.exists(t))return!1;if(e===this.$getRootId())return!0;if(!this.hasChild(e))return!1;var n=this.getItem(t),i=this.getParent(t);if(this.getItem(e).$level>=n.$level)return!1;for(;n&&this.exists(i);){if((n=this.getItem(i))&&n.id==e)return!0;i=this.getParent(n)}return!1},getSiblings:function(t){if(!this.exists(t))return i.$create();var e=this.getParent(t);return this.getChildren(e)},getNextSibling:function(t){for(var e=this.getSiblings(t),n=0,i=e.length;n<i;n++)if(e[n]==t){var r=e[n+1];return 0===r&&n>0&&(r="0"),r||null}return null},getPrevSibling:function(t){for(var e=this.getSiblings(t),n=0,i=e.length;n<i;n++)if(e[n]==t){var r=e[n-1];return 0===r&&n>0&&(r="0"),r||null}return null},getParent:function(t){var e=null;return(e=void 0!==t.id?t:this.getItem(t))?e[this.$parentProperty]:this.$getRootId()},clearAll:function(){this._branches={},o.prototype.clearAll.call(this)},calculateItemLevel:function(t){var e=0;return this.eachParent(function(){e++},t),e},_setParentInner:function(t,e,n){n||(t.hasOwnProperty("$rendered_parent")?this._move_branch(t,t.$rendered_parent,e):this._move_branch(t,t[this.$parentProperty],e))},setParent:function(t,e,n){this._setParentInner(t,e,n),t[this.$parentProperty]=e},_eachItemCached:function(t,e){for(var n=0,i=e.length;n<i;n++)t.call(this,e[n])},_eachItemIterate:function(t,e,n){var i=this.getChildren(e);for(i.length&&(i=i.slice().reverse());i.length;){var r=i.pop(),a=this.getItem(r);if(t.call(this,a),n&&n.push(a),this.hasChild(a.id))for(var o=this.getChildren(a.id),s=o.length-1;s>=0;s--)i.push(o[s])}},eachItem:function(t,e){var n=this.$getRootId();r.defined(e)||(e=n);var i=l(e,n)||n,a=!1,o=!1,s=null;i===n&&(this._eachItemMainRangeCache?(a=!0,s=this._eachItemMainRangeCache):(o=!0,s=this._eachItemMainRangeCache=[])),a?this._eachItemCached(t,s):this._eachItemIterate(t,i,o?s:null)},eachParent:function(t,e){for(var n={},i=e,r=this.getParent(i);this.exists(r);){if(n[r])throw new Error("Invalid tasks tree. Cyclic reference has been detected on task "+r);n[r]=!0,i=this.getItem(r),t.call(this,i),r=this.getParent(i)}},_add_branch:function(t,e,n){var r=void 0===n?this.getParent(t):n;this.hasChild(r)||(this._branches[r]=i.$create());for(var a=this.getChildren(r),o=!1,s=0,l=a.length;s<l;s++)if(a[s]==t.id){o=!0;break}o||(1*e==e?a.splice(e,0,t.id):a.push(t.id),t.$rendered_parent=r)},_move_branch:function(t,e,n){this._eachItemMainRangeCache=null,this._replace_branch_child(e,t.id),this.exists(n)||n==this.$getRootId()?this._add_branch(t,void 0,n):delete this._branches[t.id],t.$level=this.calculateItemLevel(t),this.eachItem(function(t){t.$level=this.calculateItemLevel(t)},t.id)},_replace_branch_child:function(t,e,n){var r=this.getChildren(t);if(r&&void 0!==t){for(var a=i.$create(),o=0;o<r.length;o++)r[o]!=e?a.push(r[o]):n&&a.push(n);this._branches[t]=a}},sort:function(t,e,n){this.exists(n)||(n=this.$getRootId()),t||(t="order");var i="string"==typeof t?function(e,n){return e[t]==n[t]||a.isDate(e[t])&&a.isDate(n[t])&&e[t].valueOf()==n[t].valueOf()?0:e[t]>n[t]?1:-1}:t;if(e){var r=i;i=function(t,e){return r(e,t)}}var o=this.getChildren(n);if(o){for(var s=[],l=o.length-1;l>=0;l--)s[l]=this.getItem(o[l]);s.sort(i);for(l=0;l<s.length;l++)o[l]=s[l].id,this.sort(t,e,o[l])}},filter:function(t){for(var e in this.pull)this.pull[e].$rendered_parent!==this.getParent(this.pull[e])&&this._move_branch(this.pull[e],this.pull[e].$rendered_parent,this.getParent(this.pull[e]));return o.prototype.filter.apply(this,arguments)},open:function(t){this.exists(t)&&(this.getItem(t).$open=!0,this.callEvent("onItemOpen",[t]))},close:function(t){this.exists(t)&&(this.getItem(t).$open=!1,this.callEvent("onItemClose",[t]))},destructor:function(){o.prototype.destructor.call(this),this._branches=null,this._indexRangeCache={},this._eachItemMainRangeCache=null}},o.prototype),t.exports=c},function(t,e,n){var i=n(0),r={$create:function(t){return i.mixin(t||[],this)},$removeAt:function(t,e){t>=0&&this.splice(t,e||1)},$remove:function(t){this.$removeAt(this.$find(t))},$insertAt:function(t,e){if(e||0===e){var n=this.splice(e,this.length-e);this[e]=t,this.push.apply(this,n)}else this.push(t)},$find:function(t){for(var e=0;e<this.length;e++)if(t==this[e])return e;return-1},$each:function(t,e){for(var n=0;n<this.length;n++)t.call(e||this,this[n])},$map:function(t,e){for(var n=0;n<this.length;n++)this[n]=t.call(e||this,this[n]);return this},$filter:function(t,e){for(var n=0;n<this.length;n++)t.call(e||this,this[n])||(this.splice(n,1),n--);return this}};t.exports=r},function(t,e,n){var i=n(39),r=n(0),a=n(4),o=n(11),s=function(t){return this.pull={},this.$initItem=t.initItem,this.visibleOrder=i.$create(),this.fullOrder=i.$create(),this._skip_refresh=!1,this._filterRule=null,this._searchVisibleOrder={},this._indexRangeCache={},this._getItemsCache=null,this.$config=t,a(this),this._attachDataChange(function(){return this._indexRangeCache={},this._getItemsCache=null,!0}),this};s.prototype={_attachDataChange:function(t){this.attachEvent("onClearAll",t),this.attachEvent("onBeforeParse",t),this.attachEvent("onBeforeUpdate",t),this.attachEvent("onBeforeDelete",t),this.attachEvent("onBeforeAdd",t),this.attachEvent("onParse",t),this.attachEvent("onBeforeFilter",t)},_parseInner:function(t){for(var e=null,n=[],i=0,a=t.length;i<a;i++)e=t[i],this.$initItem&&(this.$config.copyOnParse()&&(e=r.copy(e)),e=this.$initItem(e)),this.callEvent("onItemLoading",[e])&&(this.pull.hasOwnProperty(e.id)||this.fullOrder.push(e.id),n.push(e),this.pull[e.id]=e);return n},parse:function(t){this.isSilent()||this.callEvent("onBeforeParse",[t]);var e=this._parseInner(t);this.isSilent()||(this.refresh(),this.callEvent("onParse",[e]))},getItem:function(t){return this.pull[t]},_updateOrder:function(t){t.call(this.visibleOrder),t.call(this.fullOrder)},updateItem:function(t,e){if(r.defined(e)||(e=this.getItem(t)),!this.isSilent()&&!1===this.callEvent("onBeforeUpdate",[e.id,e]))return!1;r.mixin(this.pull[t],e,!0),this.isSilent()||(this.callEvent("onAfterUpdate",[e.id,e]),this.callEvent("onStoreUpdated",[e.id,e,"update"]))},_removeItemInner:function(t){this._updateOrder(function(){this.$remove(t)}),delete this.pull[t]},removeItem:function(t){var e=this.getItem(t);if(!this.isSilent()&&!1===this.callEvent("onBeforeDelete",[e.id,e]))return!1;this.callEvent("onAfterDeleteConfirmed",[e.id,e]),this._removeItemInner(t),this.isSilent()||(this.filter(),this.callEvent("onAfterDelete",[e.id,e]),this.callEvent("onStoreUpdated",[e.id,e,"delete"]))},_addItemInner:function(t,e){if(this.exists(t.id))this.silent(function(){this.updateItem(t.id,t)});else{var n=this.visibleOrder,i=n.length;(!r.defined(e)||e<0)&&(e=i),e>i&&(e=Math.min(n.length,e))}this.pull[t.id]=t,this.isSilent()||this._updateOrder(function(){-1===this.$find(t.id)&&this.$insertAt(t.id,e)}),this.filter()},isVisible:function(t){return this.visibleOrder.$find(t)>-1},getVisibleItems:function(){return this.getIndexRange()},addItem:function(t,e){return r.defined(t.id)||(t.id=r.uid()),this.$initItem&&(t=this.$initItem(t)),!(!this.isSilent()&&!1===this.callEvent("onBeforeAdd",[t.id,t]))&&(this._addItemInner(t,e),this.isSilent()||(this.callEvent("onAfterAdd",[t.id,t]),this.callEvent("onStoreUpdated",[t.id,t,"add"])),t.id)},_changeIdInner:function(t,e){this.pull[t]&&(this.pull[e]=this.pull[t]);var n=this._searchVisibleOrder[t];this.pull[e].id=e,this._updateOrder(function(){this[this.$find(t)]=e}),this._searchVisibleOrder[e]=n,delete this._searchVisibleOrder[t],delete this.pull[t]},changeId:function(t,e){this._changeIdInner(t,e),this.callEvent("onIdChange",[t,e])},exists:function(t){return!!this.pull[t]},_moveInner:function(t,e){var n=this.getIdByIndex(t);this._updateOrder(function(){this.$removeAt(t),this.$insertAt(n,Math.min(this.length,e))})},move:function(t,e){var n=this.getIdByIndex(t),i=this.getItem(n);this._moveInner(t,e),this.isSilent()||this.callEvent("onStoreUpdated",[i.id,i,"move"])},clearAll:function(){this.$destroyed||(this.silent(function(){this.unselect()}),this.pull={},this.visibleOrder=i.$create(),this.fullOrder=i.$create(),this.isSilent()||(this.callEvent("onClearAll",[]),this.refresh()))},silent:function(t,e){var n=!1;this.isSilent()&&(n=!0),this._skip_refresh=!0,t.call(e||this),n||(this._skip_refresh=!1)},isSilent:function(){return!!this._skip_refresh},arraysEqual:function(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0},refresh:function(t,e){var n,i;if(!this.isSilent()&&(t&&(n=this.getItem(t)),i=t?[t,n,"paint"]:[null,null,null],!1!==this.callEvent("onBeforeStoreUpdate",i))){var r=this._quick_refresh&&!this._mark_recompute;if(this._mark_recompute=!1,t){if(!e&&!r){var a=this.visibleOrder;this.filter(),this.arraysEqual(a,this.visibleOrder)||(t=void 0)}}else r||this.filter();i=t?[t,n,"paint"]:[null,null,null],this.callEvent("onStoreUpdated",i)}},count:function(){return this.fullOrder.length},countVisible:function(){return this.visibleOrder.length},sort:function(t){},serialize:function(){},eachItem:function(t){for(var e=0;e<this.fullOrder.length;e++){var n=this.getItem(this.fullOrder[e]);t.call(this,n)}},find:function(t){var e=[];return this.eachItem(function(n){t(n)&&e.push(n)}),e},filter:function(t){this.isSilent()||this.callEvent("onBeforeFilter",[]),this.callEvent("onPreFilter",[]);var e=i.$create(),n=[];this.eachItem(function(t){this.callEvent("onFilterItem",[t.id,t])&&(o(t.id,null,this,this._ganttConfig)?n.push(t.id):e.push(t.id))});for(var r=0;r<n.length;r++)e.push(n[r]);this.visibleOrder=e,this._searchVisibleOrder={};for(r=0;r<this.visibleOrder.length;r++)this._searchVisibleOrder[this.visibleOrder[r]]=r;this.isSilent()||this.callEvent("onFilter",[])},getIndexRange:function(t,e){var n=Math.min(e||1/0,this.countVisible()-1),i=t||0,r=i+"-"+n;if(this._indexRangeCache[r])return this._indexRangeCache[r].slice();for(var a=[],o=i;o<=n;o++)a.push(this.getItem(this.visibleOrder[o]));return this._indexRangeCache[r]=a.slice(),a},getItems:function(){if(this._getItemsCache)return this._getItemsCache.slice();var t=[];for(var e in this.pull)t.push(this.pull[e]);return this._getItemsCache=t.slice(),t},getIdByIndex:function(t){return this.visibleOrder[t]},getIndexById:function(t){var e=this._searchVisibleOrder[t];return void 0===e&&(e=-1),e},_getNullIfUndefined:function(t){return void 0===t?null:t},getFirst:function(){return this._getNullIfUndefined(this.visibleOrder[0])},getLast:function(){return this._getNullIfUndefined(this.visibleOrder[this.visibleOrder.length-1])},getNext:function(t){return this._getNullIfUndefined(this.visibleOrder[this.getIndexById(t)+1])},getPrev:function(t){return this._getNullIfUndefined(this.visibleOrder[this.getIndexById(t)-1])},destructor:function(){this.callEvent("onDestroy",[]),this.detachAllEvents(),this.$destroyed=!0,this.pull=null,this.$initItem=null,this.visibleOrder=null,this.fullOrder=null,this._skip_refresh=null,this._filterRule=null,this._searchVisibleOrder=null,this._indexRangeCache={}}},t.exports=s},function(t,e){var n,i,r=t.exports={};function a(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(t){if(n===setTimeout)return setTimeout(t,0);if((n===a||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:a}catch(t){n=a}try{i="function"==typeof clearTimeout?clearTimeout:o}catch(t){i=o}}();var l,c=[],u=!1,d=-1;function h(){u&&l&&(u=!1,l.length?c=l.concat(c):d=-1,c.length&&f())}function f(){if(!u){var t=s(h);u=!0;for(var e=c.length;e;){for(l=c,c=[];++d<e;)l&&l[d].run();d=-1,e=c.length}l=null,u=!1,function(t){if(i===clearTimeout)return clearTimeout(t);if((i===o||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(t);try{i(t)}catch(e){try{return i.call(null,t)}catch(e){return i.call(this,t)}}}(t)}}function _(t,e){this.fun=t,this.array=e}function g(){}r.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new _(t,e)),1!==c.length||u||s(f)},_.prototype.run=function(){this.fun.apply(null,this.array)},r.title="browser",r.browser=!0,r.env={},r.argv=[],r.version="",r.versions={},r.on=g,r.addListener=g,r.once=g,r.off=g,r.removeListener=g,r.removeAllListeners=g,r.emit=g,r.prependListener=g,r.prependOnceListener=g,r.listeners=function(t){return[]},r.binding=function(t){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(t){throw new Error("process.chdir is not supported")},r.umask=function(){return 0}},function(t,e){t.exports=function(t,e){if(!e)return!0;if(t._on_timeout)return!1;var n=Math.ceil(1e3/e);return n<2||(setTimeout(function(){delete t._on_timeout},n),t._on_timeout=!0,!0)}},function(t,e,n){var i=n(0);t.exports=function t(e,n){e=e||i.event,n=n||i.eventRemove;var r=[],a={attach:function(t,n,i,a){r.push({element:t,event:n,callback:i,capture:a}),e(t,n,i,a)},detach:function(t,e,i,a){n(t,e,i,a);for(var o=0;o<r.length;o++){var s=r[o];s.element===t&&s.event===e&&s.callback===i&&s.capture===a&&(r.splice(o,1),o--)}},detachAll:function(){for(var t=r.slice(),e=0;e<t.length;e++){var n=t[e];a.detach(n.element,n.event,n.callback,n.capture),a.detach(n.element,n.event,n.callback,void 0),a.detach(n.element,n.event,n.callback,!1),a.detach(n.element,n.event,n.callback,!0)}r.splice(0,r.length)},extend:function(){return t(this.event,this.eventRemove)}};return a}},function(t,e){t.exports=function(t){var e=new RegExp("<(?:.|\n)*?>","gm"),n=new RegExp(" +","gm");function i(t){return(t+"").replace(e," ").replace(n," ")}var r=new RegExp("'","gm");function a(t){return(t+"").replace(r,"&#39;")}for(var o in t._waiAria={getAttributeString:function(t){var e=[" "];for(var n in t){var r=a(i(t[n]));e.push(n+"='"+r+"'")}return e.push(" "),e.join(" ")},getTimelineCellAttr:function(e){return t._waiAria.getAttributeString({"aria-label":e})},_taskCommonAttr:function(e,n){e.start_date&&e.end_date&&(n.setAttribute("aria-label",i(t.templates.tooltip_text(e.start_date,e.end_date,e))),e.$dataprocessor_class&&n.setAttribute("aria-busy",!0),n.setAttribute("aria-selected",t.isSelectedTask(e.id)?"true":"false"))},setTaskBarAttr:function(e,n){this._taskCommonAttr(e,n),!t.isReadonly(e)&&t.config.drag_move&&(e.id!=t.getState("tasksDnd").drag_id?n.setAttribute("aria-grabbed",!1):n.setAttribute("aria-grabbed",!0))},taskRowAttr:function(e,n){this._taskCommonAttr(e,n),!t.isReadonly(e)&&t.config.order_branch&&n.setAttribute("aria-grabbed",!1),n.setAttribute("role","row"),n.setAttribute("aria-level",e.$level),t.hasChild(e.id)&&n.setAttribute("aria-expanded",e.$open?"true":"false")},linkAttr:function(e,n){var r=t.config.links,a=e.type==r.finish_to_start||e.type==r.start_to_start,o=e.type==r.start_to_start||e.type==r.start_to_finish,s=t.locale.labels.link+" "+t.templates.drag_link(e.source,o,e.target,a);n.setAttribute("aria-label",i(s)),t.isReadonly(e)&&n.setAttribute("aria-readonly",!0)},gridSeparatorAttr:function(t){t.setAttribute("role","separator")},lightboxHiddenAttr:function(t){t.setAttribute("aria-hidden","true")},lightboxVisibleAttr:function(t){t.setAttribute("aria-hidden","false")},lightboxAttr:function(t){t.setAttribute("role","dialog"),t.setAttribute("aria-hidden","true"),t.firstChild.setAttribute("role","heading")},lightboxButtonAttrString:function(e){return this.getAttributeString({role:"button","aria-label":t.locale.labels[e],tabindex:"0"})},lightboxHeader:function(t,e){t.setAttribute("aria-label",e)},lightboxSelectAttrString:function(e){var n="";switch(e){case"%Y":n=t.locale.labels.years;break;case"%m":n=t.locale.labels.months;break;case"%d":n=t.locale.labels.days;break;case"%H:%i":n=t.locale.labels.hours+t.locale.labels.minutes}return t._waiAria.getAttributeString({"aria-label":n})},lightboxDurationInputAttrString:function(e){return this.getAttributeString({"aria-label":t.locale.labels.column_duration,"aria-valuemin":"0"})},gridAttrString:function(){return[" role='treegrid'",t.config.multiselect?"aria-multiselectable='true'":"aria-multiselectable='false'"," "].join(" ")},gridScaleRowAttrString:function(){return"role='row'"},gridScaleCellAttrString:function(e,n){var i="";if("add"==e.name)i=this.getAttributeString({role:"button","aria-label":t.locale.labels.new_task});else{var r={role:"columnheader","aria-label":n};t._sort&&t._sort.name==e.name&&("asc"==t._sort.direction?r["aria-sort"]="ascending":r["aria-sort"]="descending"),i=this.getAttributeString(r)}return i},gridDataAttrString:function(){return"role='rowgroup'"},gridCellAttrString:function(e,n,i){var r={role:"gridcell","aria-label":n};return e.editor&&!t.isReadonly(i)||(r["aria-readonly"]=!0),this.getAttributeString(r)},gridAddButtonAttrString:function(e){return this.getAttributeString({role:"button","aria-label":t.locale.labels.new_task})},messageButtonAttrString:function(t){return"tabindex='0' role='button' aria-label='"+t+"'"},messageInfoAttr:function(t){t.setAttribute("role","alert")},messageModalAttr:function(t,e){t.setAttribute("role","dialog"),e&&t.setAttribute("aria-labelledby",e)},quickInfoAttr:function(t){t.setAttribute("role","dialog")},quickInfoHeaderAttrString:function(){return" role='heading' "},quickInfoHeader:function(t,e){t.setAttribute("aria-label",e)},quickInfoButtonAttrString:function(e){return t._waiAria.getAttributeString({role:"button","aria-label":e,tabindex:"0"})},tooltipAttr:function(t){t.setAttribute("role","tooltip")},tooltipVisibleAttr:function(t){t.setAttribute("aria-hidden","false")},tooltipHiddenAttr:function(t){t.setAttribute("aria-hidden","true")}},t._waiAria)t._waiAria[o]=function(e){return function(){return t.config.wai_aria_attributes?e.apply(this,arguments):""}}(t._waiAria[o])}},function(t,e){t.exports=function(t){t._extend_to_optional=function(e){var n=e,i={render:n.render,focus:n.focus,set_value:function(e,r,a,o){var s=t._resolve_default_mapping(o);if(!a[s.start_date]||"start_date"==s.start_date&&this._isAllowedUnscheduledTask(a)){i.disable(e,o);var l={};for(var c in s)l[s[c]]=a[c];return n.set_value.call(t,e,r,l,o)}return i.enable(e,o),n.set_value.call(t,e,r,a,o)},get_value:function(e,i,r){return r.disabled?{start_date:null}:n.get_value.call(t,e,i,r)},update_block:function(e,n){if(t.callEvent("onSectionToggle",[t._lightbox_id,n]),e.style.display=n.disabled?"none":"block",n.button){var i=e.previousSibling.querySelector(".gantt_custom_button_label"),r=t.locale.labels,a=n.disabled?r[n.name+"_enable_button"]:r[n.name+"_disable_button"];i.innerHTML=a}t.resizeLightbox()},disable:function(t,e){e.disabled=!0,i.update_block(t,e)},enable:function(t,e){e.disabled=!1,i.update_block(t,e)},button_click:function(e,n,r,a){if(!1!==t.callEvent("onSectionButton",[t._lightbox_id,r])){var o=t._get_typed_lightbox_config()[e];o.disabled?i.enable(a,o):i.disable(a,o)}}};return i},t.form_blocks.duration_optional=t._extend_to_optional(t.form_blocks.duration),t.form_blocks.time_optional=t._extend_to_optional(t.form_blocks.time)}},function(t,e,n){var i=n(3);t.exports=function(t){var e=n(12)(t);function r(){return e.apply(this,arguments)||this}return i(r,e),r.prototype.render=function(n){var i=t.config.types,r=t.locale.labels,a=[],o=n.filter||function(t,e){return!i.placeholder||e!==i.placeholder};for(var s in i)!1==!o(s,i[s])&&a.push({key:i[s],label:r["type_"+s]});n.options=a;var l=n.onchange;return n.onchange=function(){t.changeLightboxType(this.value),this.value===t.config.types.task&&(t._lightbox_new_type="task"),"function"==typeof l&&l.apply(this,arguments)},e.prototype.render.apply(this,arguments)},r}},function(t,e,n){var i=n(3),r=n(29);t.exports=function(t){var e=n(6)(t);function a(){return e.apply(this,arguments)||this}function o(e){return!e||e===t.config.constraint_types.ASAP||e===t.config.constraint_types.ALAP}function s(t,e){for(var n=o(e),i=0;i<t.length;i++)t[i].disabled=n}return i(a,e),a.prototype.render=function(e){var n=(e.height||30)+"px",i="<div class='gantt_cal_ltext gantt_section_"+e.name+"' style='height:"+n+";'>",a=[];for(var o in t.config.constraint_types)a.push({key:t.config.constraint_types[o],label:t.locale.labels[t.config.constraint_types[o]]});return e.options=e.options||a,i+="<span data-constraint-type-select>"+r.getHtmlSelect(e.options,[{key:"data-type",value:"constraint-type"}])+"</span>",i+="<label data-constraint-time-select>"+(t.locale.labels.constraint_date||"Constraint date")+": "+t.form_blocks.getTimePicker.call(this,e)+"</label>",i+="</div>"},a.prototype.set_value=function(e,n,i,r){var a=e.querySelector("[data-constraint-type-select] select"),o=e.querySelectorAll("[data-constraint-time-select] select"),l=r._time_format_order,c=t._resolve_default_mapping(r);a._eventsInitialized||(a.addEventListener("change",function(t){s(o,t.target.value)}),a._eventsInitialized=!0);var u=i[c.constraint_date]||new Date;t.form_blocks._fill_lightbox_select(o,0,u,l,r);var d=i[c.constraint_type]||t.getConstraintType(i);a.value=d,s(o,d)},a.prototype.get_value=function(e,n,i){var r=e.querySelector("[data-constraint-type-select] select"),a=e.querySelectorAll("[data-constraint-time-select] select"),s=r.value,l=null;return o(s)||(l=t.form_blocks.getTimePickerValue(a,i)),{constraint_type:s,constraint_date:l}},a.prototype.focus=function(e){t._focus(e.querySelector("select"))},a}},function(t,e,n){var i=n(3);t.exports=function(t){var e=n(12)(t);function r(){return e.apply(this,arguments)||this}function a(e,n){var i=[],r=[];n&&(i=t.getTaskByTime(),e.allow_root&&i.unshift({id:t.config.root_id,text:e.root_label||""}),i=function(e,n,i){var r=n.filter||function(){return!0};e=e.slice(0);for(var a=0;a<e.length;a++){var o=e[a];(o.id==i||t.isChildOf(o.id,i)||!1===r(o.id,o))&&(e.splice(a,1),a--)}return e}(i,e,n),e.sort&&i.sort(e.sort));for(var a=e.template||t.templates.task_text,o=0;o<i.length;o++){var s=a.apply(t,[i[o].start_date,i[o].end_date,i[o]]);void 0===s&&(s=""),r.push({key:i[o].id,label:s})}return e.options=r,e.map_to=e.map_to||"parent",t.form_blocks.select.render.apply(this,arguments)}return i(r,e),r.prototype.render=function(t){return a(t,!1)},r.prototype.set_value=function(e,n,i,r){0===n&&(n="0");var o=document.createElement("div");o.innerHTML=a(r,i.id);var s=o.removeChild(o.firstChild);return e.onselect=null,e.parentNode.replaceChild(s,e),t.form_blocks.select.set_value.apply(t,[s,n,i,r])},r}},function(t,e,n){var i=n(3),r=n(35).default;t.exports=function(t){var e=n(6)(t);function a(){return e.apply(this,arguments)||this}function o(t){return t.formatter||new r}function s(e,n){var i=e.getElementsByTagName("select"),r=n._time_format_order,a=0,o=0;if(t.defined(r[3])){var s=i[r[3]],l=parseInt(s.value,10);isNaN(l)&&s.hasAttribute("data-value")&&(l=parseInt(s.getAttribute("data-value"),10)),a=Math.floor(l/60),o=l%60}return new Date(i[r[2]].value,i[r[1]].value,i[r[0]].value,a,o)}function l(t,e){var n=t.getElementsByTagName("input")[1];return(n=o(e).parse(n.value))&&!window.isNaN(n)||(n=1),n<0&&(n*=-1),n}return i(a,e),a.prototype.render=function(e){var n="<div class='gantt_time_selects'>"+t.form_blocks.getTimePicker.call(this,e)+"</div>",i=" "+t.locale.labels[t.config.duration_unit+"s"]+" ",r=e.single_date?" style='display:none'":"",a=e.readonly?" disabled='disabled'":"",o=t._waiAria.lightboxDurationInputAttrString(e),s="gantt_duration_value";e.formatter&&(i="",s+=" gantt_duration_value_formatted");var l="<div class='gantt_duration' "+r+"><input type='button' class='gantt_duration_dec' value='−'"+a+"><input type='text' value='5days' class='"+s+"'"+a+" "+o+"><input type='button' class='gantt_duration_inc' value='+'"+a+">"+i+"<span></span></div>";return"<div style='height:"+(e.height||30)+"px;padding-top:0px;font-size:inherit;' class='gantt_section_time'>"+n+" "+l+"</div>"},a.prototype.set_value=function(e,n,i,r){var a,c,u,d,h=e.getElementsByTagName("select"),f=e.getElementsByTagName("input"),_=f[1],g=[f[0],f[2]],p=e.getElementsByTagName("span")[0],v=r._time_format_order;function m(){var n=s.call(t,e,r),a=l.call(t,e,r),o=t.calculateEndDate({start_date:n,duration:a,task:i}),c=t.templates.task_end_date||t.templates.task_date;p.innerHTML=c(o)}function y(t){var e=_.value;e=o(r).parse(e),window.isNaN(e)&&(e=0),(e+=t)<1&&(e=1),_.value=o(r).format(e),m()}g[0].onclick=t.bind(function(){y(-1*t.config.duration_step)},this),g[1].onclick=t.bind(function(){y(1*t.config.duration_step)},this),h[0].onchange=m,h[1].onchange=m,h[2].onchange=m,h[3]&&(h[3].onchange=m),_.onkeydown=t.bind(function(e){var n;return(n=(e=e||window.event).charCode||e.keyCode||e.which)==t.constants.KEY_CODES.DOWN?(y(-1*t.config.duration_step),!1):n==t.constants.KEY_CODES.UP?(y(1*t.config.duration_step),!1):void window.setTimeout(m,1)},this),_.onchange=t.bind(m,this),"string"==typeof(a=t._resolve_default_mapping(r))&&(a={start_date:a}),c=i[a.start_date]||new Date,u=i[a.end_date]||t.calculateEndDate({start_date:c,duration:1,task:i}),d=Math.round(i[a.duration])||t.calculateDuration({start_date:c,end_date:u,task:i}),d=o(r).format(d),t.form_blocks._fill_lightbox_select(h,0,c,v,r),_.value=d,m()},a.prototype.get_value=function(e,n,i){var r=s(e,i),a=l(e,i),o=t.calculateEndDate({start_date:r,duration:a,task:n});return"string"==typeof t._resolve_default_mapping(i)?r:{start_date:r,end_date:o,duration:a}},a.prototype.focus=function(e){t._focus(e.getElementsByTagName("select")[0])},a}},function(t,e,n){var i=n(3);t.exports=function(t){var e=n(6)(t);function r(){return e.apply(this,arguments)||this}return i(r,e),r.prototype.render=function(t){var e="<div class='gantt_cal_ltext' style='height:"+((t.height||"23")+"px")+";'>";if(t.options&&t.options.length)for(var n=0;n<t.options.length;n++)e+="<label><input type='radio' value='"+t.options[n].key+"' name='"+t.name+"'>"+t.options[n].label+"</label>";return e+="</div>"},r.prototype.set_value=function(t,e,n,i){var r;i.options&&i.options.length&&(r=t.querySelector("input[type=radio][value='"+e+"']")||t.querySelector("input[type=radio][value='"+i.default_value+"']"))&&(!t._dhx_onchange&&i.onchange&&(t.onchange=i.onchange,t._dhx_onchange=!0),r.checked=!0)},r.prototype.get_value=function(t,e){var n=t.querySelector("input[type=radio]:checked");return n?n.value:""},r.prototype.focus=function(e){t._focus(e.querySelector("input[type=radio]"))},r}},function(t,e,n){var i=n(2),r=n(3);t.exports=function(t){var e=n(6)(t);function a(){return e.apply(this,arguments)||this}return r(a,e),a.prototype.render=function(t){var e="<div class='gantt_cal_ltext' style='height:"+((t.height||"23")+"px")+";'>";if(t.options&&t.options.length)for(var n=0;n<t.options.length;n++)e+="<label><input type='checkbox' value='"+t.options[n].key+"' name='"+t.name+"'>"+t.options[n].label+"</label>";else t.single_value=!0,e+="<label><input type='checkbox' name='"+t.name+"'></label>";return e+="</div>"},a.prototype.set_value=function(t,e,n,r){var a=Array.prototype.slice.call(t.querySelectorAll("input[type=checkbox]"));(!t._dhx_onchange&&r.onchange&&(t.onchange=r.onchange,t._dhx_onchange=!0),r.single_value)?a[0].checked=!!e:i.forEach(a,function(t){t.checked=!!e&&e.indexOf(t.value)>=0})},a.prototype.get_value=function(t,e,n){return n.single_value?t.querySelector("input[type=checkbox]").checked:i.arrayMap(Array.prototype.slice.call(t.querySelectorAll("input[type=checkbox]:checked")),function(t){return t.value})},a.prototype.focus=function(e){t._focus(e.querySelector("input[type=checkbox]"))},a}},function(t,e,n){var i=n(3);t.exports=function(t){var e=n(6)(t);function r(){return e.apply(this,arguments)||this}return i(r,e),r.prototype.render=function(e){var n=t.form_blocks.getTimePicker.call(this,e),i="<div style='height:"+(e.height||30)+"px;padding-top:0px;font-size:inherit;text-align:center;' class='gantt_section_time'>";return i+=n,e.single_date?(n=t.form_blocks.getTimePicker.call(this,e,!0),i+="<span></span>"):i+="<span style='font-weight:normal; font-size:10pt;'> &nbsp;&ndash;&nbsp; </span>",i+=n,i+="</div>"},r.prototype.set_value=function(e,n,i,r){var a=r,o=e.getElementsByTagName("select"),s=r._time_format_order;if(a.auto_end_date)for(var l=function(){d=new Date(o[s[2]].value,o[s[1]].value,o[s[0]].value,0,0),h=t.calculateEndDate({start_date:d,duration:1,task:i}),t.form_blocks._fill_lightbox_select(o,s.size,h,s,a)},c=0;c<4;c++)o[c].onchange=l;var u=t._resolve_default_mapping(r);"string"==typeof u&&(u={start_date:u});var d=i[u.start_date]||new Date,h=i[u.end_date]||t.calculateEndDate({start_date:d,duration:1,task:i});t.form_blocks._fill_lightbox_select(o,0,d,s,a),t.form_blocks._fill_lightbox_select(o,s.size,h,s,a)},r.prototype.get_value=function(e,n,i){var r,a=e.getElementsByTagName("select"),o=i._time_format_order;return r=t.form_blocks.getTimePickerValue(a,i),"string"==typeof t._resolve_default_mapping(i)?r:{start_date:r,end_date:function(e,n,r){var a=t.form_blocks.getTimePickerValue(e,i,n.size);return a<=r&&(!1!==i.autofix_end||i.single_date)?t.date.add(r,t._get_timepicker_step(),"minute"):a}(a,o,r)}},r.prototype.focus=function(e){t._focus(e.getElementsByTagName("select")[0])},r}},function(t,e,n){var i=n(3);t.exports=function(t){var e=n(6)(t);function r(){return e.apply(this,arguments)||this}return i(r,e),r.prototype.render=function(t){return"<div class='gantt_cal_ltext' style='height:"+((t.height||"130")+"px")+";'><textarea></textarea></div>"},r.prototype.set_value=function(e,n){t.form_blocks.textarea._get_input(e).value=n||""},r.prototype.get_value=function(e){return t.form_blocks.textarea._get_input(e).value},r.prototype.focus=function(e){var n=t.form_blocks.textarea._get_input(e);t._focus(n,!0)},r.prototype._get_input=function(t){return t.querySelector("textarea")},r}},function(t,e,n){var i=n(3);t.exports=function(t){var e=n(6)(t);function r(){return e.apply(this,arguments)||this}return i(r,e),r.prototype.render=function(t){return"<div class='gantt_cal_ltext gantt_cal_template' style='height:"+((t.height||"30")+"px")+";'></div>"},r.prototype.set_value=function(t,e){t.innerHTML=e||""},r.prototype.get_value=function(t){return t.innerHTML||""},r.prototype.focus=function(){},r}},function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}t.exports=function(t){var e=n(1),r=n(2),a=n(54)(t),o=n(53)(t),s=n(52)(t),l=n(12)(t),c=n(51)(t),u=n(50)(t),d=n(49)(t),h=n(48)(t),f=n(12)(t),_=n(47)(t),g=n(46)(t);function p(e,n){var i,r,a="";for(r=0;r<e.length;r++)i=t.config._migrate_buttons[e[r]]?t.config._migrate_buttons[e[r]]:e[r],a+="<div "+t._waiAria.lightboxButtonAttrString(i)+" class='gantt_btn_set gantt_left_btn_set "+i+"_set'"+(n?" style='float:right;'":"")+"><div dhx_button='1' data-dhx-button='1' class='"+i+"'></div><div>"+t.locale.labels[i]+"</div></div>";return a}function v(e,n,i){var r,a,o,s,l,c,u="";switch(i.timeFormat[n]){case"%Y":for(e._time_format_order[2]=n,e._time_format_order.size++,e.year_range&&(isNaN(e.year_range)?e.year_range.push&&(o=e.year_range[0],s=e.year_range[1]):r=e.year_range),r=r||10,a=a||Math.floor(r/2),o=o||i.date.getFullYear()-a,s=s||t.getState().max_date.getFullYear()+a,l=o;l<s;l++)u+="<option value='"+l+"'>"+l+"</option>";break;case"%m":for(e._time_format_order[1]=n,e._time_format_order.size++,l=0;l<12;l++)u+="<option value='"+l+"'>"+t.locale.date.month_full[l]+"</option>";break;case"%d":for(e._time_format_order[0]=n,e._time_format_order.size++,l=1;l<32;l++)u+="<option value='"+l+"'>"+l+"</option>";break;case"%H:%i":for(e._time_format_order[3]=n,e._time_format_order.size++,l=i.first,c=i.date.getDate(),e._time_values=[];l<i.last;)u+="<option value='"+l+"'>"+t.templates.time_picker(i.date)+"</option>",e._time_values.push(l),i.date.setTime(i.date.valueOf()+60*t._get_timepicker_step()*1e3),l=24*(i.date.getDate()!=c?1:0)*60+60*i.date.getHours()+i.date.getMinutes()}return u}t._lightbox_methods={},t._lightbox_template="<div class='gantt_cal_ltitle'><span class='gantt_mark'>&nbsp;</span><span class='gantt_time'></span><span class='gantt_title'></span></div><div class='gantt_cal_larea'></div>",t.$services.getService("state").registerProvider("lightbox",function(){return{lightbox:t._lightbox_id}}),t.showLightbox=function(t){if(this.callEvent("onBeforeLightbox",[t])){var e=this.getTask(t),n=this.getLightbox(this.getTaskType(e.type));this._center_lightbox(n),this.showCover(),this._fill_lightbox(t,n),this._waiAria.lightboxVisibleAttr(n),this.callEvent("onLightbox",[t])}},t._get_timepicker_step=function(){if(this.config.round_dnd_dates){var e;if(function(t){var e=t.$ui.getView("timeline");return!(!e||!e.isVisible())}(this)){var n=t.getScale();e=r.getSecondsInUnit(n.unit)*n.step/60}return(!e||e>=1440)&&(e=this.config.time_step),e}return this.config.time_step},t.getLabel=function(t,e){for(var n=this._get_typed_lightbox_config(),i=0;i<n.length;i++)if(n[i].map_to==t)for(var r=n[i].options,a=0;a<r.length;a++)if(r[a].key==e)return r[a].label;return""},t.updateCollection=function(e,n){n=n.slice(0);var i=t.serverList(e);if(!i)return!1;i.splice(0,i.length),i.push.apply(i,n||[]),t.resetLightbox()},t.getLightboxType=function(){return this.getTaskType(this._lightbox_type)},t.getLightbox=function(e){var n,i,r,a,o,s="";if(void 0===e&&(e=this.getLightboxType()),!this._lightbox||this.getLightboxType()!=this.getTaskType(e)){this._lightbox_type=this.getTaskType(e),n=document.createElement("div"),s="gantt_cal_light",i=this._is_lightbox_timepicker(),(t.config.wide_form||i)&&(s+=" gantt_cal_light_wide"),i&&(t.config.wide_form=!0,s+=" gantt_cal_light_full"),n.className=s,n.style.visibility="hidden",r=this._lightbox_template,r+=p(this.config.buttons_left),r+=p(this.config.buttons_right,!0),n.innerHTML=r,t._waiAria.lightboxAttr(n),t.config.drag_lightbox&&(n.firstChild.onmousedown=t._ready_to_dnd,n.firstChild.onselectstart=function(){return!1},n.firstChild.style.cursor="pointer",t._init_dnd_events()),document.body.insertBefore(n,document.body.firstChild),this._lightbox=n,a=this._get_typed_lightbox_config(e),r=this._render_sections(a);var l=(o=n.querySelector("div.gantt_cal_larea")).style.overflow;o.style.overflow="hidden",o.innerHTML=r,function(e){var n,i,r,a,o,s;for(s=0;s<e.length;s++)n=e[s],r=document.getElementById(n.id),n.id&&r&&(i=r.querySelector("label"),(a=r.nextSibling)&&(o=a.querySelector("input, select, textarea"))&&(o.id=o.id||"input_"+t.uid(),n.inputId=o.id,i.setAttribute("for",n.inputId)))}(a),this.resizeLightbox(),o.style.overflow=l,this._init_lightbox_events(this),n.style.display="none",n.style.visibility="visible"}return this._lightbox},t._render_sections=function(t){for(var e="",n=0;n<t.length;n++){var i=this.form_blocks[t[n].type];if(i){t[n].id="area_"+this.uid();var r=t[n].hidden?" style='display:none'":"",a="";t[n].button&&(a="<div class='gantt_custom_button' data-index='"+n+"'><div class='gantt_custom_button_"+t[n].button+"'></div><div class='gantt_custom_button_label'>"+this.locale.labels["button_"+t[n].button]+"</div></div>"),this.config.wide_form&&(e+="<div class='gantt_wrap_section' "+r+">"),e+="<div id='"+t[n].id+"' class='gantt_cal_lsection'><label>"+a+this.locale.labels["section_"+t[n].name]+"</label></div>"+i.render.call(this,t[n]),e+="</div>"}}return e},t.resizeLightbox=function(){if(this._lightbox){var t=this._lightbox.querySelector(".gantt_cal_larea");t.style.height="0px",t.style.height=t.scrollHeight+"px",this._lightbox.style.height=t.scrollHeight+this.config.lightbox_additional_height+"px",t.style.height=t.scrollHeight+"px"}},t._center_lightbox=function(t){if(t){t.style.display="block";var e=window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop,n=window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft,i=window.innerHeight||document.documentElement.clientHeight;t.style.top=e?Math.round(e+Math.max((i-t.offsetHeight)/2,0))+"px":Math.round(Math.max((i-t.offsetHeight)/2,0)+9)+"px",document.documentElement.scrollWidth>document.body.offsetWidth?t.style.left=Math.round(n+(document.body.offsetWidth-t.offsetWidth)/2)+"px":t.style.left=Math.round((document.body.offsetWidth-t.offsetWidth)/2)+"px"}},t.showCover=function(){this._cover||(this._cover=document.createElement("DIV"),this._cover.className="gantt_cal_cover",document.body.appendChild(this._cover))},t.event(window,"deviceorientation",function(){t.getState().lightbox&&t._center_lightbox(t.getLightbox())}),t._init_lightbox_events=function(){t.lightbox_events={},t.lightbox_events.gantt_save_btn=function(){t._save_lightbox()},t.lightbox_events.gantt_delete_btn=function(){t._lightbox_new_type=null,t.callEvent("onLightboxDelete",[t._lightbox_id])&&(t.isTaskExists(t._lightbox_id)?t.$click.buttons.delete(t._lightbox_id):t.hideLightbox())},t.lightbox_events.gantt_cancel_btn=function(){t._cancel_lightbox()},t.lightbox_events.default=function(n,i){if(i.getAttribute("data-dhx-button"))t.callEvent("onLightboxButton",[i.className,i,n]);else{var r,a,o=e.getClassName(i);if(-1!=o.indexOf("gantt_custom_button"))if(-1!=o.indexOf("gantt_custom_button_"))for(r=i.parentNode.getAttribute("data-index"),a=i;a&&-1==e.getClassName(a).indexOf("gantt_cal_lsection");)a=a.parentNode;else r=i.getAttribute("data-index"),a=i.parentNode,i=i.firstChild;var s=t._get_typed_lightbox_config();r&&(r*=1,t.form_blocks[s[1*r].type].button_click(r,i,a,a.nextSibling))}},this.event(t.getLightbox(),"click",function(n){n=n||window.event;var i=e.getTargetNode(n),r=e.getClassName(i);return r||(i=i.previousSibling,r=e.getClassName(i)),i&&r&&0===r.indexOf("gantt_btn_set")&&(i=i.firstChild,r=e.getClassName(i)),!(!i||!r)&&(t.defined(t.lightbox_events[i.className])?t.lightbox_events[i.className]:t.lightbox_events.default)(n,i)}),t.getLightbox().onkeydown=function(n){var i=n||window.event,r=n.target||n.srcElement,a=e.getClassName(r).indexOf("gantt_btn_set")>-1;switch((n||i).keyCode){case t.constants.KEY_CODES.SPACE:if((n||i).shiftKey)return;a&&r.click&&r.click();break;case t.keys.edit_save:if((n||i).shiftKey)return;a&&r.click?r.click():t._save_lightbox();break;case t.keys.edit_cancel:t._cancel_lightbox()}}},t._cancel_lightbox=function(){var e=this.getLightboxValues();this.callEvent("onLightboxCancel",[this._lightbox_id,e.$new]),t.isTaskExists(e.id)&&e.$new&&this.silent(function(){t.$data.tasksStore.removeItem(e.id),t._update_flags(e.id,null)}),this.refreshData(),this.hideLightbox()},t._save_lightbox=function(){var t=this.getLightboxValues();this.callEvent("onLightboxSave",[this._lightbox_id,t,!!t.$new])&&(t.$new?(delete t.$new,this.addTask(t,t.parent,this.getTaskIndex(t.id))):this.isTaskExists(t.id)&&(this.mixin(this.getTask(t.id),t,!0),this.refreshTask(t.id),this.updateTask(t.id)),this.refreshData(),this.hideLightbox())},t._resolve_default_mapping=function(t){var e=t.map_to;return!{time:!0,time_optional:!0,duration:!0,duration_optional:!0}[t.type]?"constraint"===t.type&&(t.map_to&&"string"!=typeof t.map_to||(e={constraint_type:"constraint_type",constraint_date:"constraint_date"})):"auto"==t.map_to?e={start_date:"start_date",end_date:"end_date",duration:"duration"}:"string"==typeof t.map_to&&(e={start_date:t.map_to}),e},t.getLightboxValues=function(){var e={};t.isTaskExists(this._lightbox_id)&&(e=this.mixin({},this.getTask(this._lightbox_id)));for(var n=this._get_typed_lightbox_config(),r=0;r<n.length;r++){var a=document.getElementById(n[r].id);a=a?a.nextSibling:a;var o=this.form_blocks[n[r].type];if(o){var s=o.get_value.call(this,a,e,n[r]),l=t._resolve_default_mapping(n[r]);if("string"==typeof l&&"auto"!=l)e[l]=s;else if("object"==i(l))for(var c in l)l[c]&&(e[l[c]]=s[c])}}return"task"==t._lightbox_new_type&&(e.type=t.config.types.task,t._lightbox_new_type=null),e},t.hideLightbox=function(){var t=this.getLightbox();t&&(t.style.display="none"),this._waiAria.lightboxHiddenAttr(t),this._lightbox_id=null,this.hideCover(),this.callEvent("onAfterLightbox",[])},t.hideCover=function(){this._cover&&this._cover.parentNode.removeChild(this._cover),this._cover=null},t.resetLightbox=function(){t._lightbox&&!t._custom_lightbox&&t._lightbox.parentNode.removeChild(t._lightbox),t._lightbox=null,t.hideCover()},t._set_lightbox_values=function(e,n){var i=e,r=n.getElementsByTagName("span"),a=[];t.templates.lightbox_header?(a.push(""),a.push(t.templates.lightbox_header(i.start_date,i.end_date,i)),r[1].innerHTML="",r[2].innerHTML=t.templates.lightbox_header(i.start_date,i.end_date,i)):(a.push(this.templates.task_time(i.start_date,i.end_date,i)),a.push(String(this.templates.task_text(i.start_date,i.end_date,i)||"").substr(0,70)),r[1].innerHTML=this.templates.task_time(i.start_date,i.end_date,i),r[2].innerHTML=String(this.templates.task_text(i.start_date,i.end_date,i)||"").substr(0,70)),r[1].innerHTML=a[0],r[2].innerHTML=a[1],t._waiAria.lightboxHeader(n,a.join(" "));for(var o=this._get_typed_lightbox_config(this.getLightboxType()),s=0;s<o.length;s++){var l=o[s];if(this.form_blocks[l.type]){var c=document.getElementById(l.id).nextSibling,u=this.form_blocks[l.type],d=t._resolve_default_mapping(o[s]),h=this.defined(i[d])?i[d]:l.default_value;u.set_value.call(t,c,h,i,l),l.focus&&u.focus.call(t,c)}}t.isTaskExists(e.id)&&(t._lightbox_id=e.id)},t._fill_lightbox=function(t,e){var n=this.getTask(t);this._set_lightbox_values(n,e)},t.getLightboxSection=function(e){for(var n=this._get_typed_lightbox_config(),i=0;i<n.length&&n[i].name!=e;i++);var r=n[i];if(!r)return null;this._lightbox||this.getLightbox();var a=document.getElementById(r.id),o=a.nextSibling,s={section:r,header:a,node:o,getValue:function(e){return t.form_blocks[r.type].get_value.call(t,o,e||{},r)},setValue:function(e,n){return t.form_blocks[r.type].set_value.call(t,o,e,n||{},r)}},l=this._lightbox_methods["get_"+r.type+"_control"];return l?l(s):s},t._lightbox_methods.get_template_control=function(t){return t.control=t.node,t},t._lightbox_methods.get_select_control=function(t){return t.control=t.node.getElementsByTagName("select")[0],t},t._lightbox_methods.get_textarea_control=function(t){return t.control=t.node.getElementsByTagName("textarea")[0],t},t._lightbox_methods.get_time_control=function(t){return t.control=t.node.getElementsByTagName("select"),t},t._init_dnd_events=function(){var e=document.body;this.event(e,"mousemove",t._move_while_dnd),this.event(e,"mouseup",t._finish_dnd),t._init_dnd_events=function(){}},t._move_while_dnd=function(e){if(t._dnd_start_lb){document.gantt_unselectable||(document.body.className+=" gantt_unselectable",document.gantt_unselectable=!0);var n=t.getLightbox(),i=[e.pageX,e.pageY];n.style.top=t._lb_start[1]+i[1]-t._dnd_start_lb[1]+"px",n.style.left=t._lb_start[0]+i[0]-t._dnd_start_lb[0]+"px"}},t._ready_to_dnd=function(e){var n=t.getLightbox();t._lb_start=[parseInt(n.style.left,10),parseInt(n.style.top,10)],t._dnd_start_lb=[e.pageX,e.pageY]},t._finish_dnd=function(){t._lb_start&&(t._lb_start=t._dnd_start_lb=!1,document.body.className=document.body.className.replace(" gantt_unselectable",""),document.gantt_unselectable=!1)},t._focus=function(e,n){if(e&&e.focus)if(t.config.touch);else try{n&&e.select&&e.select(),e.focus()}catch(t){}},t.form_blocks={getTimePicker:function(e,n){var i,a,o,s="",l=this.config,c={first:0,last:1440,date:this.date.date_part(new Date(t._min_date.valueOf())),timeFormat:function(e){var n,i,a;if(e.time_format)return e.time_format;a=["%d","%m","%Y"],n=t.getScale(),i=n?n.unit:t.config.duration_unit,r.getSecondsInUnit(i)<r.getSecondsInUnit("day")&&a.push("%H:%i");return a}(e)};for(e._time_format_order={size:0},t.config.limit_time_select&&(c.first=60*l.first_hour,c.last=60*l.last_hour+1,c.date.setHours(l.first_hour)),i=0;i<c.timeFormat.length;i++)i>0&&(s+=" "),(a=v(e,i,c))&&(o=t._waiAria.lightboxSelectAttrString(c.timeFormat[i]),s+="<select "+(e.readonly?"disabled='disabled'":"")+(n?" style='display:none' ":"")+o+">"+a+"</select>");return s},getTimePickerValue:function(e,n,i){var r,a=n._time_format_order,o=t.defined(a[3]),s=0,l=0,c=i||0;return o&&(r=parseInt(e[a[3]+c].value,10),s=Math.floor(r/60),l=r%60),new Date(e[a[2]+c].value,e[a[1]+c].value,e[a[0]+c].value,s,l)},_fill_lightbox_select:function(e,n,i,r){if(e[n+r[0]].value=i.getDate(),e[n+r[1]].value=i.getMonth(),e[n+r[2]].value=i.getFullYear(),t.defined(r[3])){var a=60*i.getHours()+i.getMinutes();a=Math.round(a/t._get_timepicker_step())*t._get_timepicker_step();var o=e[n+r[3]];o.value=a,o.setAttribute("data-value",a)}},template:new a,textarea:new o,select:new l,time:new s,duration:new d,parent:new h,radio:new u,checkbox:new c,resources:new f,constraint:new _,typeselect:new g},t._is_lightbox_timepicker=function(){for(var t=this._get_typed_lightbox_config(),e=0;e<t.length;e++)if("time"==t[e].name&&"time"==t[e].type)return!0;return!1},t._dhtmlx_confirm=function(e,n,i,r){if(!e)return i();var a={text:e};n&&(a.title=n),r&&(a.ok=r),i&&(a.callback=function(t){t&&i()}),t.confirm(a)},t._get_typed_lightbox_config=function(e){void 0===e&&(e=this.getLightboxType());var n=function(t){for(var e in this.config.types)if(this.config.types[e]==t)return e;return"task"}.call(this,e);return t.config.lightbox[n+"_sections"]?t.config.lightbox[n+"_sections"]:t.config.lightbox.sections},t._silent_redraw_lightbox=function(t){var e=this.getLightboxType();if(this.getState().lightbox){var n=this.getState().lightbox,i=this.getLightboxValues(),r=this.copy(this.getTask(n));this.resetLightbox();var a=this.mixin(r,i,!0),o=this.getLightbox(t||void 0);this._center_lightbox(this.getLightbox()),this._set_lightbox_values(a,o),this.showCover()}else this.resetLightbox(),this.getLightbox(t||void 0);this.callEvent("onLightboxChange",[e,this.getLightboxType()])}}},function(t,e){t.exports=function(t){function e(e){var n=e.$config.scrollX?t.$ui.getView(e.$config.scrollX):null,i=e.$config.scrollY?t.$ui.getView(e.$config.scrollY):null,r={x:null,y:null};n&&(n.getScrollState().visible&&(r.x=n.$view.scrollLeft));i&&(i.getScrollState().visible&&(r.y=i.$view.scrollTop));return r}function n(){var e;return t.$ui.getView("timeline")&&(e=t.$ui.getView("timeline")._tasks_dnd),e}t.config.touch_drag=500,t.config.touch=!0,t.config.touch_feedback=!0,t.config.touch_feedback_duration=1,t._prevent_touch_scroll=!1,t._touch_feedback=function(){t.config.touch_feedback&&navigator.vibrate&&navigator.vibrate(t.config.touch_feedback_duration)},t.attachEvent("onGanttReady",t.bind(function(){if("force"!=this.config.touch&&(this.config.touch=this.config.touch&&(-1!=navigator.userAgent.indexOf("Mobile")||-1!=navigator.userAgent.indexOf("iPad")||-1!=navigator.userAgent.indexOf("Android")||-1!=navigator.userAgent.indexOf("Touch"))||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),this.config.touch){var t=!0;try{document.createEvent("TouchEvent")}catch(e){t=!1}t?this._touch_events(["touchmove","touchstart","touchend"],function(t){return t.touches&&t.touches.length>1?null:t.touches[0]?{target:t.target,pageX:t.touches[0].pageX,pageY:t.touches[0].pageY,clientX:t.touches[0].clientX,clientY:t.touches[0].clientY}:t},function(){return!1}):window.navigator.pointerEnabled?this._touch_events(["pointermove","pointerdown","pointerup"],function(t){return"mouse"==t.pointerType?null:t},function(t){return!t||"mouse"==t.pointerType}):window.navigator.msPointerEnabled&&this._touch_events(["MSPointerMove","MSPointerDown","MSPointerUp"],function(t){return t.pointerType==t.MSPOINTER_TYPE_MOUSE?null:t},function(t){return!t||t.pointerType==t.MSPOINTER_TYPE_MOUSE})}},t));var i=[];t._touch_events=function(r,a,o){for(var s,l=0,c=!1,u=!1,d=null,h=null,f=null,_=[],g=null,p=0;p<i.length;p++)t.eventRemove(i[p][0],i[p][1],i[p][2]);(i=[]).push([t.$container,r[0],function(i){var r=n();if(!o(i)&&c){h&&clearTimeout(h);var f=a(i);if(r&&(r.drag.id||r.drag.start_drag))return r.on_mouse_move(f),i.preventDefault&&i.preventDefault(),i.cancelBubble=!0,!1;if(!t._prevent_touch_scroll){if(f&&d){var _=d.pageX-f.pageX,p=d.pageY-f.pageY;if(!u&&(Math.abs(_)>5||Math.abs(p)>5)&&(u=!0,l=0,s=g?e(g):t.getScrollState()),u){var m,y=s.x+_,k=s.y+p;if(g?(!function(e,n,i){var r=e.$config.scrollX?t.$ui.getView(e.$config.scrollX):null,a=e.$config.scrollY?t.$ui.getView(e.$config.scrollY):null;r&&r.scrollTo(n,null),a&&a.scrollTo(null,i)}(g,y,k),m=e(g)):(t.scrollTo(y,k),m=t.getScrollState()),s.x!=m.x&&p>2*_||s.y!=m.y&&_>2*p)return v(i)}}return v(i)}return!0}}]),i.push([this.$container,"contextmenu",function(t){if(c)return v(t)}]),i.push([this.$container,r[1],function(e){if(document&&document.body&&document.body.classList.add("gantt_touch_active"),!o(e))if(e.touches&&e.touches.length>1)c=!1;else{d=a(e),g=function(e){for(var n=t.$layout.getCellsByType("viewCell"),i=0;i<n.length;i++){var r=n[i].$view.getBoundingClientRect();if(e.clientX>=r.left&&e.clientX<=r.right&&e.clientY<=r.bottom&&e.clientY>=r.top)return n[i]}}(d),t._locate_css(d,"gantt_hor_scroll")||t._locate_css(d,"gantt_ver_scroll")||(c=!0);var i=n();h=setTimeout(function(){var e=t.locate(d);i&&e&&!t._locate_css(d,"gantt_link_control")&&!t._locate_css(d,"gantt_grid_data")&&(i.on_mouse_down(d),i.drag&&i.drag.start_drag&&(!function(e){var n=t._getTaskLayers(),i=t.getTask(e);if(i&&t.isTaskVisible(e)){f=e;for(var r=0;r<n.length;r++)if((i=n[r].rendered[e])&&i.getAttribute(t.config.task_attribute)&&i.getAttribute(t.config.task_attribute)==e){var a=i.cloneNode(!0);_.push(i),n[r].rendered[e]=a,i.style.display="none",a.className+=" gantt_drag_move ",i.parentNode.appendChild(a)}}}(e),i._start_dnd(d),t._touch_drag=!0,t.refreshTask(e),t._touch_feedback())),h=null},t.config.touch_drag)}}]),i.push([this.$container,r[2],function(e){if(document&&document.body&&document.body.classList.remove("gantt_touch_active"),!o(e)){h&&clearTimeout(h),t._touch_drag=!1,c=!1;var i=a(e),r=n();if(r&&r.on_mouse_up(i),f&&t.isTaskExists(f)&&(t.refreshTask(f),_.length&&(_.forEach(function(t){t.parentNode&&t.parentNode.removeChild(t)}),t._touch_feedback())),c=u=!1,_=[],f=null,d&&l){var s=new Date;if(s-l<500)t.$services.getService("mouseEvents").onDoubleClick(d),v(e);else l=s}else l=new Date}}]);for(p=0;p<i.length;p++)t.event(i[p][0],i[p][1],i[p][2]);function v(t){return t&&t.preventDefault&&t.preventDefault(),t.cancelBubble=!0,!1}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(8),r=n(4),a=["ctrlKey","altKey","shiftKey","metaKey"],o=[[{unit:"month",date:"%M",step:1},{unit:"day",date:"%d",step:1}],[{unit:"day",date:"%d %M",step:1}],[{unit:"day",date:"%d %M",step:1},{unit:"hour",date:"%H:00",step:8}],[{unit:"day",date:"%d %M",step:1},{unit:"hour",date:"%H:00",step:1}]],s=function(){function t(t){var e=this;this.zoomIn=function(){var t=e.getCurrentLevel()-1;t<0||e.setLevel(t)},this.zoomOut=function(){var t=e.getCurrentLevel()+1;t>e._levels.length-1||e.setLevel(t)},this.getCurrentLevel=function(){return e._activeLevelIndex},this.getLevels=function(){return e._levels},this.setLevel=function(t){var n=e._getZoomIndexByName(t);-1===n&&e.$gantt.assert(-1!==n,"Invalid zoom level for gantt.ext.zoom.setLevel. "+t+" is not an expected value."),e._setLevel(n,0)},this._getZoomIndexByName=function(t){var n=-1;if("string"==typeof t){if(!isNaN(Number(t))&&e._levels[Number(t)])n=Number(t);else for(var i=0;i<e._levels.length;i++)if(e._levels[i].name===t){n=i;break}}else n=t;return n},this._getVisibleDate=function(){var t=e.$gantt.getScrollState().x,n=e.$gantt.$task.offsetWidth;e._visibleDate=e.$gantt.dateFromPos(t+n/2)},this._setLevel=function(t,n){e._activeLevelIndex=t;var i=e.$gantt,r=i.copy(e._levels[e._activeLevelIndex]),a=i.copy(r);if(delete a.name,i.mixin(i.config,a,!0),!!i.$root){if(n){var o=e.$gantt.dateFromPos(n+e.$gantt.getScrollState().x);e.$gantt.render();var s=e.$gantt.posFromDate(o);e.$gantt.scrollTo(s-n)}else{var l=e.$gantt.$task.offsetWidth;e._visibleDate||e._getVisibleDate();var c=e._visibleDate;e.$gantt.render();s=e.$gantt.posFromDate(c);e.$gantt.scrollTo(s-l/2)}e.callEvent("onAfterZoom",[e._activeLevelIndex,r])}},this._attachWheelEvent=function(t){var n,r=i.isFF?"wheel":"mousewheel";(n="function"==typeof t.element?t.element():t.element)&&e._domEvents.attach(n,r,e.$gantt.bind(function(t){if(this._useKey){if(a.indexOf(this._useKey)<0)return!1;if(!t[this._useKey])return!1}if("function"==typeof this._handler)return this._handler.apply(this,[t]),!0},e),{passive:!1})},this._defaultHandler=function(t){var n=e.$gantt.$task.getBoundingClientRect().x,i=t.clientX-n,r=!1;(e.$gantt.env.isFF?-40*t.deltaY:t.wheelDelta)>0&&(r=!0),t.preventDefault(),t.stopPropagation(),e._setScaleSettings(r,i)},this._setScaleDates=function(){e._initialStartDate&&e._initialEndDate&&(e.$gantt.config.start_date=e._initialStartDate,e.$gantt.config.end_date=e._initialEndDate)},this.$gantt=t,this._domEvents=this.$gantt._createDomEventScope()}return t.prototype.init=function(t){var e=this;this.$gantt.env.isNode||(this._initialStartDate=t.startDate,this._initialEndDate=t.endDate,this._activeLevelIndex=t.activeLevelIndex?t.activeLevelIndex:0,this._levels=this._mapScales(t.levels||o),this._handler=t.handler||this._defaultHandler,this._minColumnWidth=t.minColumnWidth||60,this._maxColumnWidth=t.maxColumnWidth||240,this._widthStep=t.widthStep||3/8*t.minColumnWidth,this._useKey=t.useKey,this._initialized||(r(this),this.$gantt.attachEvent("onGanttScroll",function(){e._getVisibleDate()})),this._domEvents.detachAll(),"wheel"===t.trigger&&(this.$gantt.$root?this._attachWheelEvent(t):this.$gantt.attachEvent("onGanttReady",function(){e._attachWheelEvent(t)})),this._initialized=!0,this.setLevel(this._activeLevelIndex))},t.prototype._mapScales=function(t){return t.map(function(t){return Array.isArray(t)?{scales:t}:t})},t.prototype._setScaleSettings=function(t,e){t?this._stepUp(e):this._stepDown(e)},t.prototype._stepUp=function(t){if(!(this._activeLevelIndex>=this._levels.length-1)){var e=this._activeLevelIndex;if(this._setScaleDates(),this._widthStep){var n=this.$gantt.config.min_column_width+this._widthStep;n>this._maxColumnWidth&&(n=this._minColumnWidth,e++),this.$gantt.config.min_column_width=n}else e++;this._setLevel(e,t)}},t.prototype._stepDown=function(t){if(!(this._activeLevelIndex<1)){var e=this._activeLevelIndex;if(this._setScaleDates(),this._widthStep){var n=this.$gantt.config.min_column_width-this._widthStep;n<this._minColumnWidth&&(n=this._maxColumnWidth,e--),this.$gantt.config.min_column_width=n}else e--;this._setLevel(e,t)}},t}();e.default=s},function(t,e){window.dhtmlx&&(window.dhtmlx.attaches||(window.dhtmlx.attaches={}),window.dhtmlx.attaches.attachGantt=function(t,e,n){var i=document.createElement("DIV");n=n||window.gantt,i.id="gantt_"+n.uid(),i.style.width="100%",i.style.height="100%",i.cmp="grid",document.body.appendChild(i),this.attachObject(i.id),this.dataType="gantt",this.dataObj=n;var r=this.vs[this.av];r.grid=n,n.init(i.id,t,e),i.firstChild.style.border="none",r.gridId=i.id,r.gridObj=i;return this.vs[this._viewRestore()].grid}),void 0!==window.dhtmlXCellObject&&(window.dhtmlXCellObject.prototype.attachGantt=function(t,e,n){n=n||window.gantt;var i=document.createElement("DIV");return i.id="gantt_"+n.uid(),i.style.width="100%",i.style.height="100%",i.cmp="grid",document.body.appendChild(i),this.attachObject(i.id),this.dataType="gantt",this.dataObj=n,n.init(i.id,t,e),i.firstChild.style.border="none",i=null,this.callEvent("_onContentAttach",[]),this.dataObj}),t.exports=null},function(t,e){function n(t){"@babel/helpers - typeof";return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}window.jQuery&&function(t){var e=[];t.fn.dhx_gantt=function(i){if("string"!=typeof(i=i||{})){var r=[];return this.each(function(){if(this&&this.getAttribute)if(this.gantt||window.gantt.$root==this)r.push("object"==n(this.gantt)?this.gantt:window.gantt);else{var t=window.gantt.$container&&window.Gantt?window.Gantt.getGanttInstance():window.gantt;for(var e in i)"data"!=e&&(t.config[e]=i[e]);t.init(this),i.data&&t.parse(i.data),r.push(t)}}),1===r.length?r[0]:r}if(e[i])return e[i].apply(this,[]);t.error("Method "+i+" does not exist on jQuery.dhx_gantt")}}(window.jQuery),t.exports=null},function(t,e,n){var i=n(1),r=n(10);t.exports=function(t){var e=50,n=30,a=10,o=50,s=null,l=!1,c=null,u={started:!1},d={};function h(e){return e&&i.isChildOf(e,t.$root)&&e.offsetHeight}function f(){var e=!!document.querySelector(".gantt_drag_marker"),n=!!document.querySelector(".gantt_drag_marker.gantt_grid_resize_area")||!!document.querySelector(".gantt_drag_marker.gantt_row_grid_resize_area"),i=!!document.querySelector(".gantt_link_direction"),r=t.getState(),a=r.autoscroll;return l=e&&!n&&!i,!(!r.drag_mode&&!e||n)||a}function _(e){if(c&&(clearTimeout(c),c=null),e){var n=t.config.autoscroll_speed;n&&n<10&&(n=10),c=setTimeout(function(){s=setInterval(v,n||o)},t.config.autoscroll_delay||a)}}function g(t){t?(_(!0),u.started||(u.x=d.x,u.y=d.y,u.started=!0)):(s&&(clearInterval(s),s=null),_(!1),u.started=!1)}function p(e){var n=f();if(!s&&!c||n||g(!1),!t.config.autoscroll||!n)return!1;d={x:e.clientX,y:e.clientY},"touchmove"==e.type&&(d.x=e.targetTouches[0].clientX,d.y=e.targetTouches[0].clientY),!s&&n&&g(!0)}function v(){if(!f())return g(!1),!1;var e=h(t.$task)?t.$task:h(t.$grid)?t.$grid:t.$root;if(e){var r=i.getNodePosition(e),a=d.x-r.x,o=d.y-r.y,s=l?0:m(a,r.width,u.x-r.x),c=m(o,r.height,u.y-r.y),_=t.getScrollState(),p=_.y,v=_.inner_height,y=_.height,k=_.x,b=_.inner_width,w=_.width;c&&!v?c=0:c<0&&!p?c=0:c>0&&p+v>=y+2&&(c=0),s&&!b?s=0:s<0&&!k?s=0:s>0&&k+b>=w&&(s=0);var x=t.config.autoscroll_step;x&&x<2&&(x=2),s*=x||n,c*=x||n,(s||c)&&function(e,n){var i=t.getScrollState(),r=null,a=null;e&&(r=i.x+e,r=Math.min(i.width,r),r=Math.max(0,r));n&&(a=i.y+n,a=Math.min(i.height,a),a=Math.max(0,a));t.scrollTo(r,a)}(s,c)}}function m(t,n,i){return t-e<0&&t<i?-1:t>n-e&&t>i?1:0}t.attachEvent("onGanttReady",function(){if(!r(t)){var e=i.getRootNode(t.$root)||document.body;t.eventRemove(e,"mousemove",p),t.event(e,"mousemove",p),t.eventRemove(e,"touchmove",p),t.event(e,"touchmove",p),t.eventRemove(e,"pointermove",p),t.event(e,"pointermove",p)}}),t.attachEvent("onDestroy",function(){g(!1)})}},function(t,e,n){t.exports=function(t){t.ext||(t.ext={});for(var e=[n(60),n(59),n(58)],i=0;i<e.length;i++)e[i]&&e[i](t);var r=n(57).default;t.ext.zoom=new r(t)}},function(t,e){t.exports=function(t){t.skins.contrast_white={config:{grid_width:360,row_height:35,scale_height:35,link_line_width:2,link_arrow_size:6,lightbox_additional_height:75},_second_column_width:100,_third_column_width:80}}},function(t,e){t.exports=function(t){t.skins.contrast_black={config:{grid_width:360,row_height:35,scale_height:35,link_line_width:2,link_arrow_size:6,lightbox_additional_height:75},_second_column_width:100,_third_column_width:80}}},function(t,e){t.exports=function(t){t.skins.material={config:{grid_width:411,row_height:34,task_height_offset:6,scale_height:36,link_line_width:2,link_arrow_size:6,lightbox_additional_height:80},_second_column_width:110,_third_column_width:75,_redefine_lightbox_buttons:{buttons_left:["dhx_delete_btn"],buttons_right:["dhx_save_btn","dhx_cancel_btn"]}},t.attachEvent("onAfterTaskDrag",function(e){var n=t.getTaskNode(e);n&&(n.className+=" gantt_drag_animation",setTimeout(function(){var t=n.className.indexOf(" gantt_drag_animation");t>-1&&(n.className=n.className.slice(0,t))},200))})}},function(t,e){t.exports=function(t){t.skins.broadway={config:{grid_width:360,row_height:35,scale_height:35,link_line_width:1,link_arrow_size:7,lightbox_additional_height:86},_second_column_width:90,_third_column_width:80,_lightbox_template:"<div class='gantt_cal_ltitle'><span class='gantt_mark'>&nbsp;</span><span class='gantt_time'></span><span class='gantt_title'></span><div class='gantt_cancel_btn'></div></div><div class='gantt_cal_larea'></div>",_config_buttons_left:{},_config_buttons_right:{gantt_delete_btn:"icon_delete",gantt_save_btn:"icon_save"}}}},function(t,e){t.exports=function(t){t.skins.terrace={config:{grid_width:360,row_height:35,scale_height:35,link_line_width:2,link_arrow_size:6,lightbox_additional_height:75},_second_column_width:90,_third_column_width:70}}},function(t,e){t.exports=function(t){t.skins.meadow={config:{grid_width:350,row_height:27,scale_height:30,link_line_width:2,link_arrow_size:6,lightbox_additional_height:72},_second_column_width:95,_third_column_width:80}}},function(t,e){t.exports=function(t){t.skins.skyblue={config:{grid_width:350,row_height:27,scale_height:27,link_line_width:1,link_arrow_size:8,lightbox_additional_height:75},_second_column_width:95,_third_column_width:80}}},function(t,e){function n(t,e){var n=e.skin;if(!n||t)for(var i=document.getElementsByTagName("link"),r=0;r<i.length;r++){var a=i[r].href.match("dhtmlxgantt_([a-z_]+).css");if(a&&(e.skins[a[1]]||!n)){n=a[1];break}}e.skin=n||"terrace";var o=e.skins[e.skin]||e.skins.terrace;!function(t,e,n){for(var i in e)(void 0===t[i]||n)&&(t[i]=e[i])}(e.config,o.config,t);var s=e.getGridColumns();s[1]&&!e.defined(s[1].width)&&(s[1].width=o._second_column_width),s[2]&&!e.defined(s[2].width)&&(s[2].width=o._third_column_width);for(r=0;r<s.length;r++){var l=s[r];"add"==l.name&&(l.width||(l.width=44),e.defined(l.min_width)&&e.defined(l.max_width)||(l.min_width=l.min_width||l.width,l.max_width=l.max_width||l.width),l.min_width&&(l.min_width=+l.min_width),l.max_width&&(l.max_width=+l.max_width),l.width&&(l.width=+l.width,l.width=l.min_width&&l.min_width>l.width?l.min_width:l.width,l.width=l.max_width&&l.max_width<l.width?l.max_width:l.width))}o.config.task_height&&(e.config.task_height=o.config.task_height||"full"),o.config.bar_height&&(e.config.bar_height=o.config.bar_height||"full"),o._lightbox_template&&(e._lightbox_template=o._lightbox_template),o._redefine_lightbox_buttons&&(e.config.buttons_right=o._redefine_lightbox_buttons.buttons_right,e.config.buttons_left=o._redefine_lightbox_buttons.buttons_left),e.resetLightbox()}t.exports=function(t){t.resetSkin||(t.resetSkin=function(){this.skin="",n(!0,this)},t.skins={},t.attachEvent("onGanttLayoutReady",function(){n(!1,this)}))}},function(t,e){t.exports=function(){function t(t){return t.$ui.getView("timeline")}function e(t){return t.$ui.getView("grid")}function n(t){return t.$ui.getView("scrollVer")}function i(t){return t.$ui.getView("scrollHor")}var r="DEFAULT_VALUE";function a(t,e,n,i){var a=t(this);return a&&a.isVisible()?a[e].apply(a,n):i?i():r}return{getColumnIndex:function(t){var n=a.call(this,e,"getColumnIndex",[t]);return n===r?0:n},dateFromPos:function(e){var n=a.call(this,t,"dateFromPos",Array.prototype.slice.call(arguments));return n===r?this.getState().min_date:n},posFromDate:function(e){var n=a.call(this,t,"posFromDate",[e]);return n===r?0:n},getRowTop:function(n){var i=this,o=a.call(i,t,"getRowTop",[n],function(){return a.call(i,e,"getRowTop",[n])});return o===r?0:o},getTaskTop:function(n){var i=this,o=a.call(i,t,"getItemTop",[n],function(){return a.call(i,e,"getItemTop",[n])});return o===r?0:o},getTaskPosition:function(e,n,i){var o=a.call(this,t,"getItemPosition",[e,n,i]);return o===r?{left:0,top:this.getTaskTop(e.id),height:this.getTaskBarHeight(e.id),width:0}:o},getTaskBarHeight:function(n,i){var o=this,s=a.call(o,t,"getBarHeight",[n,i],function(){return a.call(o,e,"getItemHeight",[n])});return s===r?0:s},getTaskHeight:function(n){var i=this,o=a.call(i,t,"getItemHeight",[n],function(){return a.call(i,e,"getItemHeight",[n])});return o===r?0:o},columnIndexByDate:function(e){var n=a.call(this,t,"columnIndexByDate",[e]);return n===r?0:n},roundTaskDates:function(){a.call(this,t,"roundTaskDates",[])},getScale:function(){var e=a.call(this,t,"getScale",[]);return e===r?null:e},getTaskNode:function(e){var n=t(this);if(n&&n.isVisible()){var i=n._taskRenderer.rendered[e];if(!i){var r=n.$config.item_attribute;i=n.$task_bars.querySelector("["+r+"='"+e+"']")}return i||null}return null},getLinkNode:function(e){var n=t(this);return n.isVisible()?n._linkRenderer.rendered[e]:null},scrollTo:function(t,e){var r=n(this),a=i(this),o={position:0},s={position:0};r&&(s=r.getScrollState()),a&&(o=a.getScrollState());var l=a&&1*t==t,c=r&&1*e==e;if(l&&c)for(var u=r._getLinkedViews(),d=a._getLinkedViews(),h=[],f=0;f<u.length;f++)for(var _=0;_<d.length;_++)u[f].$config.id&&d[_].$config.id&&u[f].$config.id===d[_].$config.id&&h.push(u[f].$config.id);l&&(h&&h.forEach(function(t){this.$ui.getView(t).$config.$skipSmartRenderOnScroll=!0}.bind(this)),a.scroll(t),h&&h.forEach(function(t){this.$ui.getView(t).$config.$skipSmartRenderOnScroll=!1}.bind(this))),c&&r.scroll(e);var g={position:0},p={position:0};r&&(g=r.getScrollState()),a&&(p=a.getScrollState()),this.callEvent("onGanttScroll",[o.position,s.position,p.position,g.position])},showDate:function(t){var e=this.posFromDate(t),n=Math.max(e-this.config.task_scroll_offset,0);this.scrollTo(n)},showTask:function(t){var e=this.getTaskPosition(this.getTask(t)),n=e.left;this.config.rtl&&(n=e.left+e.width);var i,r=Math.max(n-this.config.task_scroll_offset,0),a=this._scroll_state().y;i=a?e.top-(a-this.getTaskBarHeight(t))/2:e.top,this.scrollTo(r,i)},_scroll_state:function(){var t={x:!1,y:!1,x_pos:0,y_pos:0,scroll_size:this.config.scroll_size+1,x_inner:0,y_inner:0},e=n(this),r=i(this);if(r){var a=r.getScrollState();a.visible&&(t.x=a.size,t.x_inner=a.scrollSize),t.x_pos=a.position||0}if(e){var o=e.getScrollState();o.visible&&(t.y=o.size,t.y_inner=o.scrollSize),t.y_pos=o.position||0}return t},getScrollState:function(){var t=this._scroll_state();return{x:t.x_pos,y:t.y_pos,inner_width:t.x,inner_height:t.y,width:t.x_inner,height:t.y_inner}}}}},function(t,e){t.exports=function(t){delete t.addTaskLayer,delete t.addLinkLayer}},function(t,e,n){var i=n(1),r=function(t){return{getVerticalScrollbar:function(){return t.$ui.getView("scrollVer")},getHorizontalScrollbar:function(){return t.$ui.getView("scrollHor")},_legacyGridResizerClass:function(t){for(var e=t.getCellsByType("resizer"),n=0;n<e.length;n++){var i=e[n],r=!1,a=i.$parent.getPrevSibling(i.$id);if(a&&a.$config&&"grid"===a.$config.id)r=!0;else{var o=i.$parent.getNextSibling(i.$id);o&&o.$config&&"grid"===o.$config.id&&(r=!0)}r&&(i.$config.css=(i.$config.css?i.$config.css+" ":"")+"gantt_grid_resize_wrap")}},onCreated:function(e){var n=!0;this._legacyGridResizerClass(e),e.attachEvent("onBeforeResize",function(){var r=t.$ui.getView("timeline");r&&(r.$config.hidden=r.$parent.$config.hidden=!t.config.show_chart);var a=t.$ui.getView("grid");if(a){var o=a._getColsTotalWidth(),s=!t.config.show_grid||!t.config.grid_width||0===o;if(n&&!s&&!1!==o&&(t.config.grid_width=o),a.$config.hidden=a.$parent.$config.hidden=s,!a.$config.hidden){var l=a._getGridWidthLimits();if(l[0]&&t.config.grid_width<l[0]&&(t.config.grid_width=l[0]),l[1]&&t.config.grid_width>l[1]&&(t.config.grid_width=l[1]),r&&t.config.show_chart){if(a.$config.width=t.config.grid_width-1,!a.$config.scrollable&&a.$config.scrollY&&t.$root.offsetWidth){var c=a.$gantt.$layout.$container.offsetWidth,u=t.$ui.getView(a.$config.scrollY).$config.width,d=c-(a.$config.width+u);d<0&&(a.$config.width+=d,t.config.grid_width+=d)}if(n)a.$parent.$config.width=t.config.grid_width,a.$parent.$config.group&&t.$layout._syncCellSizes(a.$parent.$config.group,{value:a.$parent.$config.width,isGravity:!1});else if(r&&!i.isChildOf(r.$task,e.$view)){if(!a.$config.original_grid_width){var h=t.skins[t.skin];h&&h.config&&h.config.grid_width?a.$config.original_grid_width=h.config.grid_width:a.$config.original_grid_width=0}t.config.grid_width=a.$config.original_grid_width,a.$parent.$config.width=t.config.grid_width}else a.$parent._setContentSize(a.$config.width,null),t.$layout._syncCellSizes(a.$parent.$config.group,{value:t.config.grid_width,isGravity:!1})}else r&&i.isChildOf(r.$task,e.$view)&&(a.$config.original_grid_width=t.config.grid_width),n||(a.$parent.$config.width=0)}n=!1}}),this._initScrollStateEvents(e)},_initScrollStateEvents:function(e){t._getVerticalScrollbar=this.getVerticalScrollbar,t._getHorizontalScrollbar=this.getHorizontalScrollbar;var n=this.getVerticalScrollbar(),i=this.getHorizontalScrollbar();n&&n.attachEvent("onScroll",function(e,n,i){var r=t.getScrollState();t.callEvent("onGanttScroll",[r.x,e,r.x,n])}),i&&i.attachEvent("onScroll",function(e,n,i){var r=t.getScrollState();t.callEvent("onGanttScroll",[e,r.y,n,r.y]);var a=t.$ui.getView("grid");a&&a.$grid_data&&!a.$config.scrollable&&(a.$grid_data.style.left=a.$grid.scrollLeft+"px",a.$grid_data.scrollLeft=a.$grid.scrollLeft)}),e.attachEvent("onResize",function(){n&&!t.$scroll_ver&&(t.$scroll_ver=n.$scroll_ver),i&&!t.$scroll_hor&&(t.$scroll_hor=i.$scroll_hor)})},_findGridResizer:function(t,e){for(var n,i=t.getCellsByType("resizer"),r=!0,a=0;a<i.length;a++){var o=i[a];o._getSiblings();var s=o._behind,l=o._front;if(s&&s.$content===e||s.isChild&&s.isChild(e)){n=o,r=!0;break}if(l&&l.$content===e||l.isChild&&l.isChild(e)){n=o,r=!1;break}}return{resizer:n,gridFirst:r}},onInitialized:function(e){var n=t.$ui.getView("grid"),i=this._findGridResizer(e,n);if(i.resizer){var r,a=i.gridFirst,o=i.resizer;if("x"!==o.$config.mode)return;o.attachEvent("onResizeStart",function(e,n){var i=t.$ui.getView("grid"),o=i?i.$parent:null;if(o){var s=i._getGridWidthLimits();i.$config.scrollable||(o.$config.minWidth=s[0]),o.$config.maxWidth=s[1]}return r=a?e:n,t.callEvent("onGridResizeStart",[r])}),o.attachEvent("onResize",function(e,n){var i=a?e:n;return t.callEvent("onGridResize",[r,i])}),o.attachEvent("onResizeEnd",function(e,n,i,r){var o=a?e:n,s=a?i:r,l=t.$ui.getView("grid"),c=l?l.$parent:null;c&&(c.$config.minWidth=void 0);var u=t.callEvent("onGridResizeEnd",[o,s]);return u&&0!==s&&(t.config.grid_width=s),u})}},onDestroyed:function(t){}}};t.exports=r},function(t,e,n){var i=n(1),r=function(t,e){var n,r,a,o,s,l=10,c=18;function u(){return{link_source_id:o,link_target_id:r,link_from_start:s,link_to_start:a,link_landing_area:n}}var d=e.$services,h=d.getService("state"),f=d.getService("dnd");h.registerProvider("linksDnD",u);var _=new f(t.$task_bars,{sensitivity:0,updates_per_second:60,mousemoveContainer:e.$root,selector:".gantt_link_point",preventDefault:!0});function g(n,i,r,a,o){var s=function(n,i,r){var a=i(n),o={x:a.left,y:a.top,width:a.width,height:a.height};r.rtl?(o.xEnd=o.x,o.x=o.xEnd+o.width):o.xEnd=o.x+o.width;if(o.yEnd=o.y+o.height,e.getTaskType(n.type)==e.config.types.milestone){var s=function(e){var n=t.getBarHeight(e,!0);return Math.round(Math.sqrt(2*n*n))-2}(n.id);o.x+=(r.rtl?1:-1)*(s/2),o.xEnd+=(r.rtl?-1:1)*(s/2),o.width=a.xEnd-a.x}return o}(n,function(t){return e.getTaskPosition(t)},a),l={x:s.x,y:s.y};i||(l.x=s.xEnd),l.y+=e.getTaskHeight(n.id)/2;var c=function(t){return e.getTaskType(t.type)==e.config.types.milestone}(n)&&o?2:0;return r=r||0,a.rtl&&(r*=-1),l.x+=(i?-1:1)*r-c,l}function p(t,n){var i=_.getPosition(t),r=function(t){var e=0,n=0;return t&&(e=t.offsetWidth||0,n=t.offsetHeight||0),{width:e,height:n}}(n),a=function(){var t=e.$root;return{right:t.offsetWidth,bottom:t.offsetHeight}}(),o=e.config.tooltip_offset_x||l,s=e.config.tooltip_offset_y||l,u=e.config.scroll_size||c,d={y:i.y+s,x:i.x+o,bottom:i.y+r.height+s+u,right:i.x+r.width+o+u};return d.bottom>a.bottom&&(d.y=a.bottom-r.height-s),d.right>a.right&&(d.x=a.right-r.width-o),d}function v(t){var n=u(),i=["gantt_link_tooltip"];n.link_source_id&&n.link_target_id&&(e.isLinkAllowed(n.link_source_id,n.link_target_id,n.link_from_start,n.link_to_start)?i.push("gantt_allowed_link"):i.push("gantt_invalid_link"));var r=e.templates.drag_link_class(n.link_source_id,n.link_from_start,n.link_target_id,n.link_to_start);r&&i.push(r);var a="<div class='"+r+"'>"+e.templates.drag_link(n.link_source_id,n.link_from_start,n.link_target_id,n.link_to_start)+"</div>";t.innerHTML=a}function m(){o=s=r=null,a=!0}function y(n,i,r,a){var o=function(){_._direction&&_._direction.parentNode||(_._direction=document.createElement("div"),t.$task_links.appendChild(_._direction));return _._direction}(),s=u(),l=["gantt_link_direction"];e.templates.link_direction_class&&l.push(e.templates.link_direction_class(s.link_source_id,s.link_from_start,s.link_target_id,s.link_to_start));var c=Math.sqrt(Math.pow(r-n,2)+Math.pow(a-i,2));if(c=Math.max(0,c-3)){o.className=l.join(" ");var d=(a-i)/(r-n),h=Math.atan(d);2==k(n,r,i,a)?h+=Math.PI:3==k(n,r,i,a)&&(h-=Math.PI);var f=Math.sin(h),g=Math.cos(h),p=Math.round(i),v=Math.round(n),m=["-webkit-transform: rotate("+h+"rad)","-moz-transform: rotate("+h+"rad)","-ms-transform: rotate("+h+"rad)","-o-transform: rotate("+h+"rad)","transform: rotate("+h+"rad)","width:"+Math.round(c)+"px"];if(-1!=window.navigator.userAgent.indexOf("MSIE 8.0")){m.push('-ms-filter: "'+function(t,e){return"progid:DXImageTransform.Microsoft.Matrix(M11 = "+e+",M12 = -"+t+",M21 = "+t+",M22 = "+e+",SizingMethod = 'auto expand')"}(f,g)+'"');var y=Math.abs(Math.round(n-r)),b=Math.abs(Math.round(a-i));switch(k(n,r,i,a)){case 1:p-=b;break;case 2:v-=y,p-=b;break;case 3:v-=y}}m.push("top:"+p+"px"),m.push("left:"+v+"px"),o.style.cssText=m.join(";")}}function k(t,e,n,i){return e>=t?i<=n?1:4:i<=n?2:3}_.attachEvent("onBeforeDragStart",e.bind(function(n,r){var a=r.target||r.srcElement;if(m(),e.getState("tasksDnd").drag_id)return!1;if(i.locateClassName(a,"gantt_link_point")){i.locateClassName(a,"task_start_date")&&(s=!0);var l=e.locate(r);o=l;var c=e.getTask(l);if(e.isReadonly(c))return m(),!1;return this._dir_start=g(c,!!s,0,t.$getConfig(),!0),!0}return!1},this)),_.attachEvent("onAfterDragStart",e.bind(function(t,n){e.config.touch&&e.refreshData(),v(_.config.marker)},this)),_.attachEvent("onDragMove",e.bind(function(o,s){var l=_.config,c=p(s,l.marker);!function(t,e){t.style.left=e.x+"px",t.style.top=e.y+"px"}(l.marker,c);var u=!!i.locateClassName(s,"gantt_link_control"),d=r,h=n,f=a,m=e.locate(s),k=!0,b=i.getTargetNode(s);if(i.isChildOf(b,e.$root)||(u=!1,m=null),u&&(k=!i.locateClassName(s,"task_end_date"),u=!!m),r=m,n=u,a=k,u){var w=e.getTask(m),x=t.$getConfig(),$=i.locateClassName(s,"gantt_link_control"),S=0;$&&(S=Math.floor($.offsetWidth/2)),this._dir_end=g(w,!!a,S,x)}else this._dir_end=i.getRelativeEventPosition(s,t.$task_data),e.env.isEdge&&(this._dir_end.y+=window.scrollY);var T=!(h==u&&d==m&&f==k);return T&&(d&&e.refreshTask(d,!1),m&&e.refreshTask(m,!1)),T&&v(l.marker),y(this._dir_start.x,this._dir_start.y,this._dir_end.x,this._dir_end.y),!0},this)),_.attachEvent("onDragEnd",e.bind(function(){var t=u();if(t.link_source_id&&t.link_target_id&&t.link_source_id!=t.link_target_id){var n=e._get_link_type(t.link_from_start,t.link_to_start),i={source:t.link_source_id,target:t.link_target_id,type:n};i.type&&e.isLinkAllowed(i)&&e.callEvent("onLinkCreated",[i])&&e.addLink(i)}m(),e.config.touch?e.refreshData():(t.link_source_id&&e.refreshTask(t.link_source_id,!1),t.link_target_id&&e.refreshTask(t.link_target_id,!1)),_._direction&&(_._direction.parentNode&&_._direction.parentNode.removeChild(_._direction),_._direction=null)},this)),e.attachEvent("onGanttRender",e.bind(function(){_._direction&&y(this._dir_start.x,this._dir_start.y,this._dir_end.x,this._dir_end.y)},this))};t.exports={createLinkDND:function(){return{init:r}}}},function(t,e,n){var i=n(1),r=n(0),a=n(42),o=n(2);t.exports={createTaskDND:function(){var t;return{extend:function(e){e.roundTaskDates=function(e){t.round_task_dates(e)}},init:function(e,n){return t=function(t,e){var n=e.$services;return{drag:null,dragMultiple:{},_events:{before_start:{},before_finish:{},after_finish:{}},_handlers:{},init:function(){this._domEvents=e._createDomEventScope(),this.clear_drag_state();var t=e.config.drag_mode;this.set_actions(),n.getService("state").registerProvider("tasksDnd",r.bind(function(){return{drag_id:this.drag?this.drag.id:void 0,drag_mode:this.drag?this.drag.mode:void 0,drag_from_start:this.drag?this.drag.left:void 0}},this));var i={before_start:"onBeforeTaskDrag",before_finish:"onBeforeTaskChanged",after_finish:"onAfterTaskDrag"};for(var a in this._events)for(var o in t)this._events[a][o]=i[a];this._handlers[t.move]=this._move,this._handlers[t.resize]=this._resize,this._handlers[t.progress]=this._resize_progress},set_actions:function(){var n=t.$task_data;this._domEvents.attach(n,"mousemove",e.bind(function(t){this.on_mouse_move(t)},this)),this._domEvents.attach(n,"mousedown",e.bind(function(t){this.on_mouse_down(t)},this)),this._domEvents.attach(document.body,"mouseup",e.bind(function(t){this.on_mouse_up(t)},this))},clear_drag_state:function(){this.drag={id:null,mode:null,pos:null,start_x:null,start_y:null,obj:null,left:null},this.dragMultiple={}},_resize:function(n,i,r){var a=t.$getConfig(),o=this._drag_task_coords(n,r);r.left?(n.start_date=e.dateFromPos(o.start+i),n.start_date||(n.start_date=new Date(e.getState().min_date))):(n.end_date=e.dateFromPos(o.end+i),n.end_date||(n.end_date=new Date(e.getState().max_date)));var s=this._calculateMinDuration(a.min_duration,a.duration_unit);n.end_date-n.start_date<a.min_duration&&(r.left?n.start_date=e.calculateEndDate(n.end_date,-s,a.duration_unit,n):n.end_date=e.calculateEndDate(n.start_date,s,a.duration_unit,n)),e._init_task_timing(n)},_calculateMinDuration:function(t,e){return Math.ceil(t/{minute:6e4,hour:36e5,day:864e5,week:6048e5,month:24192e5,year:31356e6}[e])},_resize_progress:function(e,n,i){var r=this._drag_task_coords(e,i),a=t.$getConfig().rtl?r.start-i.pos.x:i.pos.x-r.start,o=Math.max(0,a);e.progress=Math.min(1,o/Math.abs(r.end-r.start))},_find_max_shift:function(t,n){var i;for(var r in t){var a=t[r],o=e.getTask(a.id),s=this._drag_task_coords(o,a),l=e.posFromDate(new Date(e.getState().min_date)),c=e.posFromDate(new Date(e.getState().max_date));if(s.end+n>c){var u=c-s.end;(u<i||void 0===i)&&(i=u)}else if(s.start+n<l){var d=l-s.start;(d>i||void 0===i)&&(i=d)}}return i},_move:function(t,n,i,r){var a=this._drag_task_coords(t,i),o=null,s=null;r?(o=new Date(+i.obj.start_date+r),s=new Date(+i.obj.end_date+r)):(o=e.dateFromPos(a.start+n),s=e.dateFromPos(a.end+n)),o?s?(t.start_date=o,t.end_date=s):(t.end_date=new Date(e.getState().max_date),t.start_date=e.dateFromPos(e.posFromDate(t.end_date)-(a.end-a.start))):(t.start_date=new Date(e.getState().min_date),t.end_date=e.dateFromPos(e.posFromDate(t.start_date)+(a.end-a.start)))},_drag_task_coords:function(t,n){return{start:n.obj_s_x=n.obj_s_x||e.posFromDate(t.start_date),end:n.obj_e_x=n.obj_e_x||e.posFromDate(t.end_date)}},_mouse_position_change:function(t,e){var n=t.x-e.x,i=t.y-e.y;return Math.sqrt(n*n+i*i)},_is_number:function(t){return!isNaN(parseFloat(t))&&isFinite(t)},on_mouse_move:function(t){if(this.drag.start_drag){var n=i.getRelativeEventPosition(t,e.$task_data),r=this.drag.start_drag.start_x,o=this.drag.start_drag.start_y;(Date.now()-this.drag.timestamp>50||this._is_number(r)&&this._is_number(o)&&this._mouse_position_change({x:r,y:o},n)>20)&&this._start_dnd(t)}if(this.drag.mode){if(!a(this,40))return;this._update_on_move(t)}},_update_item_on_move:function(t,n,i,r,a,o){var s=e.getTask(n),l=e.mixin({},s),c=e.mixin({},s);this._handlers[i].apply(this,[c,t,r,o]),e.mixin(s,c,!0),e.callEvent("onTaskDrag",[s.id,i,c,l,a]),e.mixin(s,c,!0),e.refreshTask(n)},_update_on_move:function(n){var a=this.drag,o=t.$getConfig();if(a.mode){var s=i.getRelativeEventPosition(n,t.$task_data);if(a.pos&&a.pos.x==s.x)return;a.pos=s;var l=e.dateFromPos(s.x);if(!l||isNaN(l.getTime()))return;var c=s.x-a.start_x,u=e.getTask(a.id);if(this._handlers[a.mode]){if(a.mode===o.drag_mode.move){var d={};this._isMultiselect()&&e.getSelectedTasks().indexOf(a.id)>=0&&(d=this.dragMultiple);var h=!1;if(e.isSummaryTask(u)&&e.config.drag_project){var f={};f[a.id]=r.copy(a),h=!0,d=r.mixin(f,this.dragMultiple)}var _=this._find_max_shift(d,c);for(var g in void 0!==_&&(c=_),this._update_item_on_move(c,a.id,a.mode,a,n),d){var p=d[g];if(h&&p.id!=a.id&&(e._bulk_dnd=!0),void 0===_&&(h||Object.keys(d).length>1))var v=l-e.dateFromPos(a.start_x);this._update_item_on_move(c,p.id,p.mode,p,n,v)}e._bulk_dnd=!1}else this._update_item_on_move(c,a.id,a.mode,a,n);e._update_parents(a.id)}}},on_mouse_down:function(n,r){if(2!=n.button||void 0===n.button){var a=t.$getConfig(),o=e.locate(n),s=null;if(e.isTaskExists(o)&&(s=e.getTask(o)),!e.isReadonly(s)&&!this.drag.mode){this.clear_drag_state(),r=r||n.target||n.srcElement;var l=i.getClassName(r),c=this._get_drag_mode(l,r);if(!l||!c)return r.parentNode?this.on_mouse_down(n,r.parentNode):void 0;if(c)if(c.mode&&c.mode!=a.drag_mode.ignore&&a["drag_"+c.mode]){if(o=e.locate(r),s=e.copy(e.getTask(o)||{}),e.isReadonly(s))return this.clear_drag_state(),!1;if(e.isSummaryTask(s)&&!a.drag_project&&c.mode!=a.drag_mode.progress)return void this.clear_drag_state();c.id=o;var u=i.getRelativeEventPosition(n,e.$task_data);c.start_x=u.x,c.start_y=u.y,c.obj=s,this.drag.start_drag=c,this.drag.timestamp=Date.now()}else this.clear_drag_state();else if(e.checkEvent("onMouseDown")&&e.callEvent("onMouseDown",[l.split(" ")[0]])&&r.parentNode)return this.on_mouse_down(n,r.parentNode)}}},_fix_dnd_scale_time:function(n,i){var r=t.$getConfig(),a=e.getScale().unit,o=e.getScale().step;function s(n){if(e.config.correct_work_time){var i=t.$getConfig();e.isWorkTime(n.start_date,void 0,n)||(n.start_date=e.calculateEndDate({start_date:n.start_date,duration:-1,unit:i.duration_unit,task:n}))}}r.round_dnd_dates||(a="minute",o=r.time_step),i.mode==r.drag_mode.resize?i.left?(n.start_date=e.roundDate({date:n.start_date,unit:a,step:o}),s(n)):(n.end_date=e.roundDate({date:n.end_date,unit:a,step:o}),function(n){if(e.config.correct_work_time){var i=t.$getConfig();e.isWorkTime(new Date(n.end_date-1),void 0,n)||(n.end_date=e.calculateEndDate({start_date:n.end_date,duration:1,unit:i.duration_unit,task:n}))}}(n)):i.mode==r.drag_mode.move&&(n.start_date=e.roundDate({date:n.start_date,unit:a,step:o}),s(n),n.end_date=e.calculateEndDate(n))},_fix_working_times:function(n,i){var r=t.$getConfig();(i=i||{mode:r.drag_mode.move}).mode==r.drag_mode.resize?i.left?n.start_date=e.getClosestWorkTime({date:n.start_date,dir:"future",task:n}):n.end_date=e.getClosestWorkTime({date:n.end_date,dir:"past",task:n}):i.mode==r.drag_mode.move&&e.correctTaskWorkTime(n)},_finalize_mouse_up:function(t,n,i,r){var a=e.getTask(t);if(n.work_time&&n.correct_work_time&&this._fix_working_times(a,i),this._fix_dnd_scale_time(a,i),this._fireEvent("before_finish",i.mode,[t,i.mode,e.copy(i.obj),r])){var o=t;e._init_task_timing(a),this.clear_drag_state(),e.updateTask(a.id),this._fireEvent("after_finish",i.mode,[o,i.mode,r])}else this.clear_drag_state(),t==i.id&&(i.obj._dhx_changed=!1,e.mixin(a,i.obj,!0)),e.refreshTask(a.id)},on_mouse_up:function(n){var i=this.drag;if(i.mode&&i.id){var r=t.$getConfig(),a=e.getTask(i.id),o=this.dragMultiple,s=!1,l=0;i.mode===r.drag_mode.move&&(e.isSummaryTask(a)&&r.drag_project||this._isMultiselect())&&(s=!0,l=Object.keys(o).length);var c=function(){if(s)for(var t in o)this._finalize_mouse_up(o[t].id,r,o[t],n);this._finalize_mouse_up(i.id,r,i,n)};s&&l>10?e.batchUpdate(function(){c.call(this)}.bind(this)):c.call(this)}this.clear_drag_state()},_get_drag_mode:function(e,n){var i=t.$getConfig().drag_mode,r={mode:null,left:null};switch((e||"").split(" ")[0]){case"gantt_task_line":case"gantt_task_content":r.mode=i.move;break;case"gantt_task_drag":r.mode=i.resize;var a=n.getAttribute("data-bind-property");r.left="start_date"==a;break;case"gantt_task_progress_drag":r.mode=i.progress;break;case"gantt_link_control":case"gantt_link_point":r.mode=i.ignore;break;default:r=null}return r},_start_dnd:function(n){var i=this.drag=this.drag.start_drag;delete i.start_drag;var r=t.$getConfig(),a=i.id;if(r["drag_"+i.mode]&&e.callEvent("onBeforeDrag",[a,i.mode,n])&&this._fireEvent("before_start",i.mode,[a,i.mode,n])){delete i.start_drag;var s=e.getTask(a);if(e.isReadonly(s))return void this.clear_drag_state();if(this._isMultiselect()){var l=e.getSelectedTasks();l.indexOf(i.id)>=0&&o.forEach(l,e.bind(function(t){var n=e.getTask(t);e.isSummaryTask(n)&&e.config.drag_project&&i.mode==r.drag_mode.move&&this._addSubtasksToDragMultiple(n.id),this.dragMultiple[t]=e.mixin({id:n.id,obj:e.copy(n)},this.drag)},this))}e.isSummaryTask(s)&&e.config.drag_project&&i.mode==r.drag_mode.move&&this._addSubtasksToDragMultiple(s.id),e.callEvent("onTaskDragStart",[])}else this.clear_drag_state()},_fireEvent:function(t,n,i){e.assert(this._events[t],"Invalid stage:{"+t+"}");var r=this._events[t][n];return e.assert(r,"Unknown after drop mode:{"+n+"}"),e.assert(i,"Invalid event arguments"),!e.checkEvent(r)||e.callEvent(r,i)},round_task_dates:function(e){var n=this.drag,i=t.$getConfig();n||(n={mode:i.drag_mode.move}),this._fix_dnd_scale_time(e,n)},destructor:function(){this._domEvents.detachAll()},_isMultiselect:function(){return e.config.drag_multiple&&!!(e.getSelectedTasks&&e.getSelectedTasks().length>0)},_addSubtasksToDragMultiple:function(t){e.eachTask(function(t){this.dragMultiple[t.id]=e.mixin({id:t.id,obj:e.copy(t)},this.drag)},t,this)}}}(e,n),e._tasks_dnd=t,t.init(n)},destructor:function(){t&&(t.destructor(),t=null)}}}}},function(t,e,n){var i=n(0),r=n(74),a=n(73),o=n(1),s=function(t){var e=t.$services;return{onCreated:function(e){var o=e.$config;o.bind=i.defined(o.bind)?o.bind:"task",o.bindLinks=i.defined(o.bindLinks)?o.bindLinks:"link",e._linksDnD=a.createLinkDND(),e._tasksDnD=r.createTaskDND(),e._tasksDnD.extend(e),this._mouseDelegates=n(24)(t)},onInitialized:function(e){this._attachDomEvents(t),this._attachStateProvider(t,e),e._tasksDnD.init(e,t),e._linksDnD.init(e,t),"timeline"==e.$config.id&&this.extendDom(e)},onDestroyed:function(e){this._clearDomEvents(t),this._clearStateProvider(t),e._tasksDnD&&e._tasksDnD.destructor()},extendDom:function(e){t.$task=e.$task,t.$task_scale=e.$task_scale,t.$task_data=e.$task_data,t.$task_bg=e.$task_bg,t.$task_links=e.$task_links,t.$task_bars=e.$task_bars},_clearDomEvents:function(){this._mouseDelegates.destructor(),this._mouseDelegates=null},_attachDomEvents:function(t){function e(e,n){if(e&&this.callEvent("onLinkDblClick",[e,n])){var i=this.getLink(e);if(this.isReadonly(i))return;var r=this.locale.labels.link+" "+this.templates.link_description(this.getLink(e))+" "+this.locale.labels.confirm_link_deleting;window.setTimeout(function(){t._dhtmlx_confirm(r,"",function(){t.deleteLink(e)})},this.config.touch?300:1)}}this._mouseDelegates.delegate("click","gantt_task_link",t.bind(function(t,e){var n=this.locate(t,this.config.link_attribute);n&&this.callEvent("onLinkClick",[n,t])},t),this.$task),this._mouseDelegates.delegate("click","gantt_scale_cell",t.bind(function(e,n){var i=o.getRelativeEventPosition(e,t.$task_data),r=t.dateFromPos(i.x),a=Math.floor(t.columnIndexByDate(r)),s=t.getScale().trace_x[a];t.callEvent("onScaleClick",[e,s])},t),this.$task),this._mouseDelegates.delegate("doubleclick","gantt_task_link",t.bind(function(n,i,r){i=this.locate(n,t.config.link_attribute),e.call(this,i,n)},t),this.$task),this._mouseDelegates.delegate("doubleclick","gantt_link_point",t.bind(function(t,n,i){n=this.locate(t);var r=this.getTask(n),a=null;return i.parentNode&&o.getClassName(i.parentNode)&&(a=o.getClassName(i.parentNode).indexOf("_left")>-1?r.$target[0]:r.$source[0]),a&&e.call(this,a,t),!1},t),this.$task)},_attachStateProvider:function(t,n){var i=n;e.getService("state").registerProvider("tasksTimeline",function(){return{scale_unit:i._tasks?i._tasks.unit:void 0,scale_step:i._tasks?i._tasks.step:void 0}})},_clearStateProvider:function(){e.getService("state").unregisterProvider("tasksTimeline")}}};t.exports=s},function(t,e,n){var i=n(1);function r(t,e){var n=i.getNodePosition(e.$grid_data);return t.x+=n.x-e.$grid.scrollLeft,t.y+=n.y-e.$grid_data.scrollTop,t}t.exports={removeLineHighlight:function(t){t.markerLine&&t.markerLine.parentNode&&t.markerLine.parentNode.removeChild(t.markerLine),t.markerLine=null},highlightPosition:function(t,e,n){var a=function(t,e){var n=i.getNodePosition(e.$grid_data),r=i.getRelativeEventPosition(t,e.$grid_data),a=n.x,o=r.y-10,s=e.getItemHeight(t.targetId);o<n.y&&(o=n.y);var l=e.getTotalHeight();return o>n.y+l-s&&(o=n.y+l-s),n.x=a,n.y=o,n}(t,n);e.marker.style.left=a.x+9+"px",e.marker.style.top=a.y+"px";var o=e.markerLine;o||((o=document.createElement("div")).className="gantt_drag_marker gantt_grid_dnd_marker",o.innerHTML="<div class='gantt_grid_dnd_marker_line'></div>",o.style.pointerEvents="none"),t.child?function(t,e,n){var i=t.targetParent,a=r({x:0,y:n.getItemTop(i)},n),o=n.$grid_data.getBoundingClientRect().bottom;e.innerHTML="<div class='gantt_grid_dnd_marker_folder'></div>",e.style.width=n.$grid_data.offsetWidth+"px",e.style.top=a.y+"px",e.style.left=a.x+"px",e.style.height=n.getItemHeight(i)+"px",a.y>o&&(e.style.top=o+"px")}(t,o,n):function(t,e,n){var i=function(t,e){var n=e.$config.rowStore,i={x:0,y:0},a=e.$grid_data.querySelector(".gantt_tree_indent"),o=15,s=0;if(a&&(o=a.offsetWidth),t.targetId!==n.$getRootId()){var l=e.getItemTop(t.targetId),c=e.getItemHeight(t.targetId);if(s=n.exists(t.targetId)?n.calculateItemLevel(n.getItem(t.targetId)):0,t.prevSibling)i.y=l;else if(t.nextSibling){var u=0;n.eachItem(function(t){-1!==n.getIndexById(t.id)&&u++},t.targetId),i.y=l+c+u*c}else i.y=l+c,s+=1}return i.x=40+s*o,i.width=Math.max(e.$grid_data.offsetWidth-i.x,0),r(i,e)}(t,n),a=n.$grid_data.getBoundingClientRect().bottom;e.innerHTML="<div class='gantt_grid_dnd_marker_line'></div>",e.style.left=i.x+"px",e.style.height="4px";var o=i.y-2;e.style.top=o+"px",e.style.width=i.width+"px",o>a&&(e.style.top=a+"px")}(t,o,n),e.markerLine||(document.body.appendChild(o),e.markerLine=o)}}},function(t,e,n){var i=n(16);t.exports=function(t,e,n,r,a){var o;if(e!==a.$getRootId())o=n<.25?i.prevSiblingTarget(t,e,a):!(n>.6)||a.hasChild(e)&&a.getItem(e).$open?i.firstChildTarget(t,e,a):i.nextSiblingTarget(t,e,a);else{var s=a.$getRootId();o=a.hasChild(s)&&r>=0?i.lastChildTarget(t,s,a):i.firstChildTarget(t,s,a)}return o}},function(t,e,n){var i=n(16);function r(t,e,n,r,a){for(var o=e;r.exists(o);){var s=r.calculateItemLevel(r.getItem(o));if((s===n||s===n-1)&&r.getBranchIndex(o)>-1)break;o=a?r.getPrev(o):r.getNext(o)}return r.exists(o)?r.calculateItemLevel(r.getItem(o))===n?a?i.nextSiblingTarget(t,o,r):i.prevSiblingTarget(t,o,r):i.firstChildTarget(t,o,r):null}function a(t,e,n,i){return r(t,e,n,i,!0)}function o(t,e,n,i){return r(t,e,n,i,!1)}t.exports=function(t,e,n,r,s,l){var c;if(e!==s.$getRootId()){var u=s.getItem(e),d=s.calculateItemLevel(u);if(d===l){var h=s.getPrevSibling(e);n<.5&&!h?c=i.prevSiblingTarget(t,e,s):(n<.5&&(e=h),c=i.nextSiblingTarget(t,e,s))}else if(d>l)s.eachParent(function(t){s.calculateItemLevel(t)===l&&(e=t.id)},u),c=a(t,e,l,s);else{var f=a(t,e,l,s),_=o(t,e,l,s);c=n<.5?f:_}}else{var g=s.$getRootId(),p=s.getChildren(g);c=i.createDropTargetObject(),c=p.length&&r>=0?a(t,function(t){for(var e=t.getNext();t.exists(e);){var n=t.getNext(e);if(!t.exists(n))return e;e=n}return null}(s),l,s):o(t,g,l,s)}return c}},function(t,e,n){var i=n(1),r=n(16),a=n(78),o=n(77),s=n(76),l=n(11);t.exports={init:function(t,e){var n=t.$services.getService("dnd");if(e.$config.bind&&t.getDatastore(e.$config.bind)){var c=new n(e.$grid_data,{updates_per_second:60});t.defined(e.$getConfig().dnd_sensitivity)&&(c.config.sensitivity=e.$getConfig().dnd_sensitivity),c.attachEvent("onBeforeDragStart",t.bind(function(n,r){var a=u(r);if(!a)return!1;if(t.hideQuickInfo&&t._hideQuickInfo(),i.closest(r.target,".gantt_grid_editor_placeholder"))return!1;var o=a.getAttribute(e.$config.item_attribute),s=e.$config.rowStore.getItem(o);return!t.isReadonly(s)&&!d(o)&&(c.config.initial_open_state=s.$open,!!t.callEvent("onRowDragStart",[o,r.target||r.srcElement,r])&&void 0)},t)),c.attachEvent("onAfterDragStart",t.bind(function(t,n){var i=u(n);c.config.marker.innerHTML=i.outerHTML;var a=c.config.marker.firstChild;a&&(c.config.marker.style.opacity=.4,a.style.position="static",a.style.pointerEvents="none"),c.config.id=i.getAttribute(e.$config.item_attribute);var o=e.$config.rowStore,s=o.getItem(c.config.id);c.config.level=o.calculateItemLevel(s),c.config.drop_target=r.createDropTargetObject({targetParent:o.getParent(s.id),targetIndex:o.getBranchIndex(s.id),targetId:s.id,nextSibling:!0}),s.$open=!1,s.$transparent=!0,this.refreshData()},t)),c.attachEvent("onDragMove",t.bind(function(n,i){var a=h(i);return a&&!1!==t.callEvent("onBeforeRowDragMove",[c.config.id,a.targetParent,a.targetIndex])||(a=r.createDropTargetObject(c.config.drop_target)),s.highlightPosition(a,c.config,e),c.config.drop_target=a,this.callEvent("onRowDragMove",[c.config.id,a.targetParent,a.targetIndex]),!0},t)),c.attachEvent("onDragEnd",t.bind(function(){var n=e.$config.rowStore,i=n.getItem(c.config.id);s.removeLineHighlight(c.config),i.$transparent=!1,i.$open=c.config.initial_open_state;var r=c.config.drop_target;!1===this.callEvent("onBeforeRowDragEnd",[c.config.id,r.targetParent,r.targetIndex])?i.$drop_target=null:(n.move(c.config.id,r.targetIndex,r.targetParent),t.render(),this.callEvent("onRowDragEnd",[c.config.id,r.targetParent,r.targetIndex])),n.refresh(i.id)},t))}function u(
){return i.locateAttribute(t,e.$config.item_attribute)}function d(n){return l(n,t,t.getDatastore(e.$config.bind))}function h(n){var r,s=function(n){var r=i.getRelativeEventPosition(n,e.$grid_data).y,a=e.$config.rowStore;r=r||0;var o=e.$state.scrollTop||0,s=t.$grid_data.getBoundingClientRect().height+o,l=o,c=e.getItemIndexByTopPosition(e.$state.scrollTop);if(a.exists(c)||(c=a.countVisible()-1),c<0)return a.$getRootId();var u=a.getIdByIndex(c),h=e.$state.scrollTop/e.getItemHeight(u),f=h-Math.floor(h);f>.1&&f<.9&&(s-=e.getItemHeight(u)*f,l+=e.getItemHeight(u)*(1-f)),r>=s?r=s:r<=l&&(r=l);var _=e.getItemIndexByTopPosition(r);if(_>a.countVisible()-1||_<0)return a.$getRootId();var g=a.getIdByIndex(_);return d(g)?a.getPrevSibling(g):a.getIdByIndex(_)}(n),l=null,u=e.$config.rowStore,h=!e.$getConfig().order_branch_free,f=i.getRelativeEventPosition(n,e.$grid_data).y;return s!==u.$getRootId()&&(l=(f-e.getItemTop(s))/e.getItemHeight(s)),h?(r=a(c.config.id,s,l,f,u,c.config.level))&&r.targetParent&&d(r.targetParent)&&(s=u.getPrevSibling(r.targetParent),r=a(c.config.id,s,l,f,u,c.config.level)):r=o(c.config.id,s,l,f,u),r}}}},function(t,e,n){var i=n(1),r=n(11);t.exports={init:function(t,e){var n=t.$services.getService("dnd");if(e.$config.bind&&t.getDatastore(e.$config.bind)){var a=new n(e.$grid_data,{updates_per_second:60});t.defined(e.$getConfig().dnd_sensitivity)&&(a.config.sensitivity=e.$getConfig().dnd_sensitivity),a.attachEvent("onBeforeDragStart",t.bind(function(n,r){var c=o(r);if(!c)return!1;if(t.hideQuickInfo&&t._hideQuickInfo(),i.closest(r.target,".gantt_grid_editor_placeholder"))return!1;var u=c.getAttribute(e.$config.item_attribute);if(l(u))return!1;var d=s().getItem(u);return!t.isReadonly(d)&&(a.config.initial_open_state=d.$open,!!t.callEvent("onRowDragStart",[u,r.target||r.srcElement,r])&&void 0)},t)),a.attachEvent("onAfterDragStart",t.bind(function(t,n){var i=o(n);a.config.marker.innerHTML=i.outerHTML;var r=a.config.marker.firstChild;r&&(r.style.position="static"),a.config.id=i.getAttribute(e.$config.item_attribute);var l=s(),c=l.getItem(a.config.id);a.config.index=l.getBranchIndex(a.config.id),a.config.parent=c.parent,c.$open=!1,c.$transparent=!0,this.refreshData()},t)),a.lastTaskOfLevel=function(t){for(var e=null,n=s().getItems(),i=0,r=n.length;i<r;i++)n[i].$level==t&&(e=n[i]);return e?e.id:null},a._getGridPos=t.bind(function(t){var n=i.getNodePosition(e.$grid_data),r=n.x,o=t.pos.y-10,s=e.getItemHeight(a.config.id);o<n.y&&(o=n.y);var l=e.getTotalHeight();return o>n.y+l-s&&(o=n.y+l-s),n.x=r,n.y=o,n},t),a._getTargetY=t.bind(function(n){var r=i.getNodePosition(e.$grid_data),a=e.$state.scrollTop||0,o=t.$grid_data.getBoundingClientRect().height+a,s=n.pageY-r.y+a;return s>o?s=o:s<a&&(s=a),s},t),a._getTaskByY=t.bind(function(t,n){var i=s();t=t||0;var r=e.getItemIndexByTopPosition(t);return(r=n<r?r-1:r)>i.countVisible()-1?null:i.getIdByIndex(r)},t),a.attachEvent("onDragMove",t.bind(function(n,i){var r=t.$grid_data.getBoundingClientRect().height+(e.$state.scrollTop||0),o=a.config,c=a._getGridPos(i),u=e.$getConfig(),d=s();c.y<r?o.marker.style.top=c.y+"px":o.marker.style.top=r+"px",o.marker.style.left=c.x+10+"px";var h=d.getItem(a.config.id),f=a._getTargetY(i),_=a._getTaskByY(f,d.getIndexById(h.id));function g(t,e){return!d.isChildOf(p.id,e.id)&&(t.$level==e.$level||u.order_branch_free)}if(d.exists(_)||(_=a.lastTaskOfLevel(u.order_branch_free?h.$level:0))==a.config.id&&(_=null),d.exists(_)){var p=d.getItem(_),v=e.getItemTop(p.id),m=e.getItemHeight(p.id);if(v+m/2<f){var y=d.getIndexById(p.id),k=d.getNext(p.id),b=d.getItem(k);if(l(k)){var w=d.getPrev(b.id);b=d.getItem(w)}if(b){if(b.id==h.id)return u.order_branch_free&&d.isChildOf(h.id,p.id)&&1==d.getChildren(p.id).length?void d.move(h.id,d.getBranchIndex(p.id)+1,d.getParent(p.id)):void 0;p=b}else if(k=d.getIdByIndex(y),b=d.getItem(k),l(k)&&(w=d.getPrev(b.id),b=d.getItem(w)),g(b,h)&&b.id!=h.id)return void d.move(h.id,-1,d.getParent(b.id))}else if(u.order_branch_free&&p.id!=h.id&&g(p,h)&&!l(p.id)){if(!d.hasChild(p.id))return p.$open=!0,void d.move(h.id,-1,p.id);if(d.getIndexById(p.id)||m/3<f)return}y=d.getIndexById(p.id),w=d.getIdByIndex(y-1);for(var x=d.getItem(w),$=1;(!x||x.id==p.id)&&y-$>=0;)w=d.getIdByIndex(y-$),x=d.getItem(w),$++;if(h.id==p.id||l(p.id))return;g(p,h)&&h.id!=p.id?d.move(h.id,0,0,p.id):p.$level!=h.$level-1||d.getChildren(p.id).length?x&&g(x,h)&&h.id!=x.id&&d.move(h.id,-1,d.getParent(x.id)):d.move(h.id,0,p.id)}return!0},t)),a.attachEvent("onDragEnd",t.bind(function(){var e=s(),n=e.getItem(a.config.id);n.$transparent=!1,n.$open=a.config.initial_open_state,!1===this.callEvent("onBeforeRowDragEnd",[a.config.id,a.config.parent,a.config.index])?(e.move(a.config.id,a.config.index,a.config.parent),n.$drop_target=null):this.callEvent("onRowDragEnd",[a.config.id,n.$drop_target]),t.render(),this.refreshData()},t))}function o(t){return i.locateAttribute(t,e.$config.item_attribute)}function s(){return t.getDatastore(e.$config.bind)}function l(e){return r(e,t,s())}}}},function(t,e,n){var i=n(0),r=n(80),a=n(79),o=function(t){return{onCreated:function(e){e.$config=i.mixin(e.$config,{bind:"task"}),"grid"==e.$config.id&&(this.extendGantt(e),t.ext.inlineEditors=t.ext._inlineEditors.createEditors(e),t.ext.inlineEditors.init()),this._mouseDelegates=n(24)(t)},onInitialized:function(e){var n=e.$getConfig();n.order_branch&&("marker"==n.order_branch?a.init(e.$gantt,e):r.init(e.$gantt,e)),this.initEvents(e,t),"grid"==e.$config.id&&this.extendDom(e)},onDestroyed:function(e){"grid"==e.$config.id&&t.ext.inlineEditors.destructor(),this.clearEvents(e,t)},initEvents:function(t,e){this._mouseDelegates.delegate("click","gantt_row",e.bind(function(n,i,r){var a=t.$getConfig();if(null!==i){var o=this.getTask(i);a.scroll_on_click&&!e._is_icon_open_click(n)&&this.showDate(o.start_date),e.callEvent("onTaskRowClick",[i,r])}},e),t.$grid),this._mouseDelegates.delegate("click","gantt_grid_head_cell",e.bind(function(n,i,r){var a=r.getAttribute("data-column-id");if(e.callEvent("onGridHeaderClick",[a,n])){var o=t.$getConfig();if("add"!=a){if(o.sort&&a){for(var s,l=a,c=0;c<o.columns.length;c++)if(o.columns[c].name==a){s=o.columns[c];break}if(s&&void 0!==s.sort&&!0!==s.sort&&!(l=s.sort))return;var u=this._sort&&this._sort.direction&&this._sort.name==a?this._sort.direction:"desc";u="desc"==u?"asc":"desc",this._sort={name:a,direction:u},this.sort(l,"desc"==u)}}else e.$services.getService("mouseEvents").callHandler("click","gantt_add",t.$grid,[n,o.root_id])}},e),t.$grid),this._mouseDelegates.delegate("click","gantt_add",e.bind(function(n,i,r){if(!t.$getConfig().readonly)return this.createTask({},i||e.config.root_id),!1},e),t.$grid)},clearEvents:function(t,e){this._mouseDelegates.destructor(),this._mouseDelegates=null},extendDom:function(e){t.$grid=e.$grid,t.$grid_scale=e.$grid_scale,t.$grid_data=e.$grid_data},extendGantt:function(e){t.getGridColumns=t.bind(e.getGridColumns,e),e.attachEvent("onColumnResizeStart",function(){return t.callEvent("onColumnResizeStart",arguments)}),e.attachEvent("onColumnResize",function(){return t.callEvent("onColumnResize",arguments)}),e.attachEvent("onColumnResizeEnd",function(){return t.callEvent("onColumnResizeEnd",arguments)}),e.attachEvent("onColumnResizeComplete",function(e,n){t.config.grid_width=n}),e.attachEvent("onBeforeRowResize",function(){return t.callEvent("onBeforeRowResize",arguments)}),e.attachEvent("onRowResize",function(){return t.callEvent("onRowResize",arguments)}),e.attachEvent("onBeforeRowResizeEnd",function(){return t.callEvent("onBeforeRowResizeEnd",arguments)}),e.attachEvent("onAfterRowResize",function(){return t.callEvent("onAfterRowResize",arguments)})}}};t.exports=o},function(t,e,n){var i=n(23),r=n(5);t.exports=function(t){return{render:function(e,n,i){var r=n.$getConfig(),a=document.createElement("div");return a.className="gantt_task_grid_row_resize_wrap",a.style.top=n.getItemTop(e.id)+n.getItemHeight(e.id)+"px",a.innerHTML="<div class='gantt_task_grid_row_resize'></div>",a.setAttribute(r.task_grid_row_resizer_attribute,e.id),t._waiAria.gridSeparatorAttr(a),a},update:null,getRectangle:i,getVisibleRange:r}}},function(t,e,n){var i=n(19),r=n(5),a=n(18),o=n(17),s=n(30);function l(t,e,n,i){var r=100*(1-(1*t||0)),a=i.posFromDate(e),o=i.posFromDate(n),s=document.createElement("div");return s.className="gantt_histogram_hor_bar",s.style.top=r+"%",s.style.left=a+"px",s.style.width=o-a+1+"px",s}function c(t,e,n){if(t===e)return null;var i=1-Math.max(t,e),r=Math.abs(t-e),a=document.createElement("div");return a.className="gantt_histogram_vert_bar",a.style.top=100*i+"%",a.style.height=100*r+"%",a.style.left=n+"px",a}t.exports=function(t){var e=s(t),n={},u={},d={};function h(t,e){var i=n[t];i&&i[e]&&i[e].parentNode&&i[e].parentNode.removeChild(i[e])}function f(e,n,i,r,o,s,u){var h=d[e.id];h&&h.parentNode&&h.parentNode.removeChild(h);var f=function(e,n,i,r){for(var o=n.getScale(),s=document.createElement("div"),u=a(o,r),d=u.start;d<=u.end;d++){var h=o.trace_x[d],f=o.trace_x[d+1]||t.date.add(h,o.step,o.unit),_=o.trace_x[d].valueOf(),g=Math.min(e[_]/i,1)||0;if(g<0)return null;var p=Math.min(e[f.valueOf()]/i,1)||0,v=l(g,h,f,n);v&&s.appendChild(v);var m=c(g,p,n.posFromDate(f));m&&s.appendChild(m)}return s}(i,o,s,u);return f&&n&&(f.setAttribute("data-resource-id",e.id),f.setAttribute(o.$config.item_attribute,e.id),f.style.position="absolute",f.style.top=n.top+1+"px",f.style.height=o.getItemHeight(e.id)-1+"px",f.style.left=0),f}function _(t,e,n,i,r,a,o){var s=r.histogram_cell_class(a.start_date,a.end_date,t,a.tasks,a.assignments),l=r.histogram_cell_label(a.start_date,a.end_date,t,a.tasks,a.assignments),c=r.histogram_cell_allocated(a.start_date,a.end_date,t,a.tasks,a.assignments),u=o.getItemHeight(t.id)-1;if(s||l){var d=document.createElement("div");return d.className=["gantt_histogram_cell",s].join(" "),d.setAttribute(o.$config.item_attribute,t.id),d.style.cssText=["left:"+e.left+"px","width:"+e.width+"px","height:"+u+"px","line-height:"+u+"px","top:"+(e.top+1)+"px"].join(";"),l&&(l="<div class='gantt_histogram_label'>"+l+"</div>"),c&&(l="<div class='gantt_histogram_fill' style='height:"+100*Math.min(c/n||0,1)+"%;'></div>"+l),l&&(d.innerHTML=l),d}return null}return{render:function(i,r,s,l){var c=r.$getTemplates(),h=r.getScale(),g=e(i,s.resource_property,h,r),p=[],v={},m=i.capacity||r.$config.capacity||24;n[i.id]={},u[i.id]=null,d[i.id]=null;for(var y=!!l,k=a(h,l),b=k.start;b<=k.end;b++){var w=g[b];if(w&&(!y||o(b,h,l,t))){var x=c.histogram_cell_capacity(w.start_date,w.end_date,i,w.tasks,w.assignments);v[w.start_date.valueOf()]=x||0;var $=r.getItemPosition(i,w.start_date,w.end_date),S=_(i,$,m,0,c,w,r);S&&(p.push(S),n[i.id][b]=S)}}var T=null;if(p.length){T=document.createElement("div");for(var C=0;C<p.length;C++)T.appendChild(p[C]);var E=f(i,$,v,0,r,m,l);E&&(T.appendChild(E),d[i.id]=E),u[i.id]=T}return T},update:function(i,r,s,l,c){var u=s.$getTemplates(),g=s.getScale(),p=e(i,l.resource_property,g,s),v=i.capacity||s.$config.capacity||24,m={},y=!!c,k=a(g,c),b={};if(n&&n[i.id])for(var w in n[i.id])b[w]=w;for(var x=k.start;x<=k.end;x++){var $=p[x];if(b[x]=!1,$){var S=u.histogram_cell_capacity($.start_date,$.end_date,i,$.tasks,$.assignments);m[$.start_date.valueOf()]=S||0;var T=s.getItemPosition(i,$.start_date,$.end_date);if(!y||o(x,g,c,t)){var C=n[i.id];if(C&&C[x])C&&C[x]&&!C[x].parentNode&&r.appendChild(C[x]);else{var E=_(i,T,v,0,u,$,s);E&&(r.appendChild(E),n[i.id][x]=E)}}else h(i.id,x)}}for(var w in b)!1!==b[w]&&h(i.id,w);var D=f(i,T,m,0,s,v,c);D&&(r.appendChild(D),d[i.id]=D)},getRectangle:i,getVisibleRange:r}}},function(t,e,n){var i=n(19),r=n(5),a=n(18),o=n(17),s=n(30);t.exports=function(t){var e=s(t),n={};function l(t,e,n,i,r){var a=n.resource_cell_class(e.start_date,e.end_date,t,e.tasks,e.assignments),o=n.resource_cell_value(e.start_date,e.end_date,t,e.tasks,e.assignments),s=r.getItemHeight(t.id)-1;if(a||o){var l=r.getItemPosition(t,e.start_date,e.end_date),c=document.createElement("div");return c.setAttribute(r.$config.item_attribute,t.id),c.className=["gantt_resource_marker",a].join(" "),c.style.cssText=["left:"+l.left+"px","width:"+l.width+"px","height:"+s+"px","line-height:"+s+"px","top:"+l.top+"px"].join(";"),o&&(c.innerHTML=o),c}return null}function c(t,e){n[t]&&n[t][e]&&n[t][e].parentNode&&n[t][e].parentNode.removeChild(n[t][e])}return{render:function(i,r,s,c){var u=r.$getTemplates(),d=r.getScale(),h=e(i,s.resource_property,r.getScale(),r),f=!!c,_=[];n[i.id]={};for(var g=a(d,c),p=g.start;p<=g.end;p++){var v=h[p];if(v&&(!f||o(p,d,c,t))){var m=l(i,v,u,0,r);m&&(_.push(m),n[i.id][p]=m)}}var y=null;if(_.length){y=document.createElement("div");for(var k=0;k<_.length;k++)y.appendChild(_[k])}return y},update:function(i,r,s,u,d){var h=s.$getTemplates(),f=s.getScale(),_=e(i,u.resource_property,s.getScale(),s),g=a(f,d),p={};if(n&&n[i.id])for(var v in n[i.id])p[v]=v;for(var m=g.start;m<=g.end;m++){var y=_[m];if(p[m]=!1,y)if(o(m,f,d,t))if(n[i.id]&&n[i.id][m])n[i.id]&&n[i.id][m]&&!n[i.id][m].parentNode&&r.appendChild(n[i.id][m]);else{var k=l(i,y,h,0,s);k&&(r.appendChild(k),n[i.id][m]=k)}else c(i.id,m)}for(var v in p)!1!==p[v]&&c(i.id,v)},getRectangle:i,getVisibleRange:r}}},function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var r=n(2),a=n(23),o=n(5);t.exports=function(t){return{render:function(e,n,i,a){for(var o=n.getGridColumns(),s=n.$getTemplates(),l=n.$config.rowStore,c=[],u=0;u<o.length;u++){var d,h,f,_=u==o.length-1,g=o[u];"add"==g.name?(h="<div "+(b=t._waiAria.gridAddButtonAttrString(g))+" class='gantt_add'></div>",f=""):(h=g.template?g.template(e):e[g.name],r.isDate(h)&&(h=s.date_grid(h,e,g.name)),null!==h&&void 0!==h||(h=""),f=h,h="<div class='gantt_tree_content'>"+h+"</div>");var p="gantt_cell"+(_?" gantt_last_cell":""),v=[];if(g.tree){p+=" gantt_cell_tree";for(var m=0;m<e.$level;m++)v.push(s.grid_indent(e));!l.hasChild(e.id)||t.isSplitTask(e)&&!t.config.open_split_tasks?(v.push(s.grid_blank(e)),v.push(s.grid_file(e))):(v.push(s.grid_open(e)),v.push(s.grid_folder(e)))}var y="width:"+(g.width-(_?1:0))+"px;";if(this.defined(g.align)){var k={right:"flex-end",left:"flex-start",center:"center"}[g.align];y+="text-align:"+g.align+";justify-content:"+k+";"}var b=t._waiAria.gridCellAttrString(g,f,e);v.push(h),d="<div class='"+p+"' data-column-index='"+u+"' data-column-name='"+g.name+"' style='"+y+"' "+b+">"+v.join("")+"</div>",c.push(d)}if(p=t.getGlobalTaskIndex(e.id)%2==0?"":" odd",p+=e.$transparent?" gantt_transparent":"",p+=e.$dataprocessor_class?" "+e.$dataprocessor_class:"",s.grid_row_class){var w=s.grid_row_class.call(t,e.start_date,e.end_date,e);w&&(p+=" "+w)}l.isSelected(e.id)&&(p+=" gantt_selected");var x=document.createElement("div");x.className="gantt_row"+p+" gantt_row_"+t.getTaskType(e.type);var $=n.getItemHeight(e.id);return x.style.height=$+"px",x.style.lineHeight=$+"px",i.smart_rendering&&(x.style.position="absolute",x.style.left="0px",x.style.top=n.getItemTop(e.id)+"px"),n.$config.item_attribute&&(x.setAttribute(n.$config.item_attribute,e.id),x.setAttribute(n.$config.bind+"_id",e.id)),t._waiAria.taskRowAttr(e,x),x.innerHTML=c.join(""),x},update:null,getRectangle:a,getVisibleRange:o,onrender:function(e,n,r){for(var a=r.getGridColumns(),o=0;o<a.length;o++){var s=a[o];if(s.onrender){var l=n.querySelector("[data-column-name="+s.name+"]");if(l){var c=s.onrender(e,l);if(c&&"string"==typeof c)l.innerHTML=c;else if(c&&"object"===i(c)&&t.config.external_render){var u=t.config.external_render;u.isElement(c)&&u.renderElement(c,l)}}}}}}}},function(t,e){t.exports=function(t,e,n,i,r){var a=n.$gantt.getTask(t.source),o=n.$gantt.getTask(t.target),s=n.getItemTop(a.id),l=n.getItemHeight(a.id),c=n.getItemTop(o.id),u=n.getItemHeight(o.id);if(e.y>s+l&&e.y>c+u)return!1;if(e.y_end<c&&e.y_end<s)return!1;var d=n.posFromDate(a.start_date),h=n.posFromDate(a.end_date),f=n.posFromDate(o.start_date),_=n.posFromDate(o.end_date);if(d>h){var g=h;h=d,d=g}if(f>_){g=_;_=f,f=g}return d+=-100,h+=100,f+=-100,_+=100,!(e.x>h&&e.x>_)&&!(e.x_end<d&&e.x_end<f)}},function(t,e,n){var i=n(86);t.exports=function(t){var e={current_pos:null,dirs:{left:"left",right:"right",up:"up",down:"down"},path:[],clear:function(){this.current_pos=null,this.path=[]},point:function(e){this.current_pos=t.copy(e)},get_lines:function(t){this.clear(),this.point(t[0]);for(var e=1;e<t.length;e++)this.line_to(t[e]);return this.get_path()},line_to:function(e){var n=t.copy(e),i=this.current_pos,r=this._get_line(i,n);this.path.push(r),this.current_pos=n},get_path:function(){return this.path},get_wrapper_sizes:function(t,e,n){var i,r=e.$getConfig().link_wrapper_width,a=t.y-r/2;switch(t.direction){case this.dirs.left:i={top:a,height:r,lineHeight:r,left:t.x-t.size-r/2,width:t.size+r};break;case this.dirs.right:i={top:a,lineHeight:r,height:r,left:t.x-r/2,width:t.size+r};break;case this.dirs.up:i={top:a-t.size,lineHeight:t.size+r,height:t.size+r,left:t.x-r/2,width:r};break;case this.dirs.down:i={top:a,lineHeight:t.size+r,height:t.size+r,left:t.x-r/2,width:r}}return i},get_line_sizes:function(t,e){var n,i=e.$getConfig(),r=i.link_line_width,a=i.link_wrapper_width,o=t.size+r;switch(t.direction){case this.dirs.left:case this.dirs.right:n={height:r,width:o,marginTop:(a-r)/2,marginLeft:(a-r)/2};break;case this.dirs.up:case this.dirs.down:n={height:o,width:r,marginTop:(a-r)/2,marginLeft:(a-r)/2}}return n},render_line:function(t,e,n,i){var r=this.get_wrapper_sizes(t,n,i),a=document.createElement("div");a.style.cssText=["top:"+r.top+"px","left:"+r.left+"px","height:"+r.height+"px","width:"+r.width+"px"].join(";"),a.className="gantt_line_wrapper";var o=this.get_line_sizes(t,n),s=document.createElement("div");return s.style.cssText=["height:"+o.height+"px","width:"+o.width+"px","margin-top:"+o.marginTop+"px","margin-left:"+o.marginLeft+"px"].join(";"),s.className="gantt_link_line_"+t.direction,a.appendChild(s),a},_get_line:function(t,e){var n=this.get_direction(t,e),i={x:t.x,y:t.y,direction:this.get_direction(t,e)};return n==this.dirs.left||n==this.dirs.right?i.size=Math.abs(t.x-e.x):i.size=Math.abs(t.y-e.y),i},get_direction:function(t,e){return e.x<t.x?this.dirs.left:e.x>t.x?this.dirs.right:e.y>t.y?this.dirs.down:this.dirs.up}},n={path:[],clear:function(){this.path=[]},current:function(){return this.path[this.path.length-1]},point:function(e){return e?(this.path.push(t.copy(e)),e):this.current()},point_to:function(n,i,r){r=r?{x:r.x,y:r.y}:t.copy(this.point());var a=e.dirs;switch(n){case a.left:r.x-=i;break;case a.right:r.x+=i;break;case a.up:r.y-=i;break;case a.down:r.y+=i}return this.point(r)},get_points:function(n,i,r,a){var o=this.get_endpoint(n,i,r,a),s=t.config,l=o.e_y-o.y,c=o.e_x-o.x,u=e.dirs,d=i.getItemHeight(n.source);this.clear(),this.point({x:o.x,y:o.y});var h=2*s.link_arrow_size,f=this.get_line_type(n,i.$getConfig()),_=o.e_x>o.x;if(f.from_start&&f.to_start)this.point_to(u.left,h),_?(this.point_to(u.down,l),this.point_to(u.right,c)):(this.point_to(u.right,c),this.point_to(u.down,l)),this.point_to(u.right,h);else if(!f.from_start&&f.to_start)if(_=o.e_x>o.x+2*h,this.point_to(u.right,h),_)c-=h,this.point_to(u.down,l),this.point_to(u.right,c);else{c-=2*h;var g=l>0?1:-1;this.point_to(u.down,g*(d/2)),this.point_to(u.right,c),this.point_to(u.down,g*(Math.abs(l)-d/2)),this.point_to(u.right,h)}else f.from_start||f.to_start?f.from_start&&!f.to_start&&(_=o.e_x>o.x-2*h,this.point_to(u.left,h),_?(c+=2*h,g=l>0?1:-1,this.point_to(u.down,g*(d/2)),this.point_to(u.right,c),this.point_to(u.down,g*(Math.abs(l)-d/2)),this.point_to(u.left,h)):(c+=h,this.point_to(u.down,l),this.point_to(u.right,c))):(this.point_to(u.right,h),_?(this.point_to(u.right,c),this.point_to(u.down,l)):(this.point_to(u.down,l),this.point_to(u.right,c)),this.point_to(u.left,h));return this.path},get_line_type:function(e,n){var i=n.links,r=!1,a=!1;return e.type==i.start_to_start?r=a=!0:e.type==i.finish_to_finish?r=a=!1:e.type==i.finish_to_start?(r=!1,a=!0):e.type==i.start_to_finish?(r=!0,a=!1):t.assert(!1,"Invalid link type"),n.rtl&&(r=!r,a=!a),{from_start:r,to_start:a}},get_endpoint:function(t,e,n,i){var a=e.$getConfig(),o=this.get_line_type(t,a),s=o.from_start,l=o.to_start,c=r(n,e,a),u=r(i,e,a);return{x:s?c.left:c.left+c.width,e_x:l?u.left:u.left+u.width,y:c.top+c.rowHeight/2-1,e_y:u.top+u.rowHeight/2-1}}};function r(e,n,i){var r=n.getItemPosition(e);if(t.getTaskType(e.type)==i.types.milestone){var a=n.getBarHeight(e.id,!0),o=Math.sqrt(2*a*a);r.left-=o/2,r.width=o}return r}return{render:function(i,r,a){var o=t.getTask(i.source);if(!o.hide_bar){var s=t.getTask(i.target);if(!s.hide_bar){var l=n.get_endpoint(i,r,o,s),c=l.e_y-l.y;if(!(l.e_x-l.x||c))return null;var u=n.get_points(i,r,o,s),d=e.get_lines(u,r),h=document.createElement("div"),f="gantt_task_link";i.color&&(f+=" gantt_link_inline_color");var _=t.templates.link_class?t.templates.link_class(i):"";_&&(f+=" "+_),a.highlight_critical_path&&t.isCriticalLink&&t.isCriticalLink(i)&&(f+=" gantt_critical_link"),h.className=f,r.$config.link_attribute&&(h.setAttribute(r.$config.link_attribute,i.id),h.setAttribute("link_id",i.id));for(var g=0;g<d.length;g++){g==d.length-1&&(d[g].size-=a.link_arrow_size);var p=e.render_line(d[g],d[g+1],r,i.source);i.color&&(p.firstChild.style.backgroundColor=i.color),h.appendChild(p)}var v=d[d.length-1].direction,m=function(t,n,i,r){var a=i.$getConfig(),o=document.createElement("div"),s=t.y,l=t.x,c=a.link_arrow_size,u="gantt_link_arrow gantt_link_arrow_"+n;switch(n){case e.dirs.right:s-=c/2,l-=c;break;case e.dirs.left:s-=c/2;break;case e.dirs.up:l-=c;break;case e.dirs.down:s+=2*c,l-=c}return o.style.cssText=["top:"+s+"px","left:"+l+"px"].join(";"),o.className=u,o}(u[u.length-1],v,r,i.source);return i.color&&(m.style.borderColor=i.color),h.appendChild(m),t._waiAria.linkAttr(i,h),h}}},update:null,isInViewPort:i}}},function(t,e,n){var i=n(19),r=n(13),a=n(5),o=n(18),s=n(17);t.exports=function(t){var e={},n={};function l(t,n){return!(!e[t.id][n]||!e[t.id][n].parentNode)}function c(t,n){e[t]&&e[t][n]&&e[t][n].parentNode&&e[t][n].parentNode.removeChild(e[t][n])}function u(t){var e,n=t.$getTemplates();return void 0!==n.task_cell_class?(e=n.task_cell_class,(console.warn||console.log)("gantt.templates.task_cell_class template is deprecated and will be removed soon. Please use gantt.templates.timeline_cell_class instead.")):e=n.timeline_cell_class,e}function d(i,r,a,o,l,c,u){var d=i.width[r],h="";if(s(r,i,o,t)){var f=c(a,i.trace_x[r]);if(u.static_background&&(!u.static_background_cells||!f))return null;if(e[a.id][r])return n[a.id][r]=r,e[a.id][r];var _=document.createElement("div");return _.style.width=d+"px",h="gantt_task_cell"+(r==l-1?" gantt_last_cell":""),f&&(h+=" "+f),_.className=h,_.style.position="absolute",_.style.left=i.left[r]+"px",e[a.id][r]=_,n[a.id][r]=r,_}return null}return{render:function(i,a,s,l){var c=a.$getTemplates(),h=a.getScale(),f=h.count;if(s.static_background&&!s.static_background_cells)return null;var _,g=document.createElement("div"),p=u(a);if(_=l&&s.smart_rendering&&!r(t)?o(h,l.x):{start:0,end:f-1},s.show_task_cells){e[i.id]={},n[i.id]={};for(var v=_.start;v<=_.end;v++){var m=d(h,v,i,l,f,p,s);m&&g.appendChild(m)}}var y=t.getGlobalTaskIndex(i.id)%2!=0,k=c.task_row_class(i.start_date,i.end_date,i),b="gantt_task_row"+(y?" odd":"")+(k?" "+k:"");return a.$config.rowStore.isSelected(i.id)&&(b+=" gantt_selected"),g.className=b,s.smart_rendering?(g.style.position="absolute",g.style.top=a.getItemTop(i.id)+"px",g.style.width="100%"):g.style.position="relative",g.style.height=a.getItemHeight(i.id)+"px",a.$config.item_attribute&&(g.setAttribute(a.$config.item_attribute,i.id),g.setAttribute(a.$config.bind+"_id",i.id)),g},update:function(t,i,r,a,s){var h=r.getScale(),f=h.count,_=u(r);if(a.show_task_cells){e[t.id]||(e[t.id]={}),n[t.id]||(n[t.id]={});var g=o(h,s);for(var p in n[t.id]){var v=n[t.id][p];(Number(v)<g.start||Number(v)>g.end)&&c(t.id,v)}n[t.id]={};for(var m=g.start;m<=g.end;m++){var y=d(h,m,t,s,f,_,a);!y&&l(t,m)?c(t.id,m):y&&!y.parentNode&&i.appendChild(y)}}},getRectangle:i,getVisibleRange:a}}},function(t,e,n){var i=n(20),r=n(21),a=n(5);t.exports=function(t){var e=i(t);return{render:function(n,i){if(n.$rollup&&n.$rollup.length){var r=document.createElement("div"),a=t.getTaskPosition(n);return n.$rollup.forEach(function(o){var s=t.getTask(o),l=e(s,i);if(l){var c=i.getBarHeight(n.id,s.type==t.config.types.milestone),u=Math.floor((i.getItemHeight(n.id)-c)/2);l.style.top=a.top+u+"px",l.classList.add("gantt_rollup_child"),r.appendChild(l)}}),r}return!1},update:null,isInViewPort:r,getVisibleRange:a}}},function(t,e,n){var i=n(21);t.exports=function(t,e,n,r,a){if(!a.isSplitTask(t))return!1;var o=a.getSubtaskDates(t.id);return i({id:t.id,start_date:o.start_date,end_date:o.end_date,parent:t.parent},e,n,a)}},function(t,e,n){var i=n(20),r=n(90),a=n(5);t.exports=function(t){var e=i(t);return{render:function(n,i){if(t.isSplitTask(n)&&(t.config.open_split_tasks&&!n.$open||!t.config.open_split_tasks)){var r=document.createElement("div"),a=t.getTaskPosition(n);return t.hasChild(n.id)&&t.eachTask(function(o){var s=t.isSummaryTask(o);if(s&&t.resetProjectDates(o),!o.hide_bar){var l=e(o,i);if(l){var c=i.getBarHeight(n.id,o.type==t.config.types.milestone),u=Math.floor((i.getItemHeight(n.id)-c)/2);l.style.top=a.top+u+"px",l.classList.add("gantt_split_child"),s&&l.classList.add("gantt_split_subproject"),r.appendChild(l)}}},n.id),r}return!1},update:null,isInViewPort:r,getVisibleRange:a}}},function(t,e,n){var i=n(21),r=n(5),a=n(20);t.exports=function(t){return{render:a(t),update:null,isInViewPort:i,getVisibleRange:r}}},function(t,e){t.exports=function(t){return function(n,i,r){"keepDates"==r?function(e,n){"duration"==n?e.end_date=t.calculateEndDate(e):"end_date"!=n&&"start_date"!=n||(e.duration=t.calculateDuration(e))}(n,i):"keepDuration"==r?function(n,i){"end_date"==i?n.start_date=e(n):"start_date"!=i&&"duration"!=i||(n.end_date=t.calculateEndDate(n))}(n,i):function(n,i){t.config.schedule_from_end?"end_date"==i||"duration"==i?n.start_date=e(n):"start_date"==i&&(n.duration=t.calculateDuration(n)):"start_date"==i||"duration"==i?n.end_date=t.calculateEndDate(n):"end_date"==i&&(n.duration=t.calculateDuration(n))}(n,i)};function e(e){return t.calculateEndDate({start_date:e.end_date,duration:-e.duration,task:e})}}},function(t,e,n){t.exports=function(t){var e=n(7)(t),i=n(0);function r(){return e.apply(this,arguments)||this}function a(e){return e.formatter||t.ext.formatters.durationFormatter()}return n(3)(r,e),i.mixin(r.prototype,{show:function(t,e,n,i){var r="<div><input type='text' name='"+e.name+"'></div>";i.innerHTML=r},set_value:function(t,e,n,i){this.get_input(i).value=a(n.editor).format(t)},get_value:function(t,e,n){return a(e.editor).parse(this.get_input(n).value||"")}},!0),r}},function(t,e,n){t.exports=function(t){var e=n(7)(t),i=n(0);function r(){return e.apply(this,arguments)||this}function a(e){return e.formatter||t.ext.formatters.linkFormatter()}function o(t,e){for(var n=(t||"").split(e.delimiter||","),i=0;i<n.length;i++){var r=n[i].trim();r?n[i]=r:(n.splice(i,1),i--)}return n.sort(),n}function s(t,e,n){for(var i=t.$target,r=[],o=0;o<i.length;o++){var s=n.getLink(i[o]);r.push(a(e).format(s))}return r.join((e.delimiter||",")+" ")}function l(t){return t.source+"_"+t.target+"_"+t.type+"_"+(t.lag||0)}function c(e,n,i){var r=function(e,n,i){var r=[];return n.forEach(function(n){var o=a(i).parse(n);o&&(o.target=e,o.id="predecessor_generated",t.isLinkAllowed(o)&&(o.id=void 0,r.push(o)))}),r}(e.id,n,i),o={};e.$target.forEach(function(e){var n=t.getLink(e);o[l(n)]=n.id});var s=[];r.forEach(function(t){var e=l(t);o[e]?delete o[e]:s.push(t)});var c=[];for(var u in o)c.push(o[u]);return{add:s,remove:c}}return n(3)(r,e),i.mixin(r.prototype,{show:function(t,e,n,i){var r="<div><input type='text' name='"+e.name+"'></div>";i.innerHTML=r},hide:function(){},set_value:function(e,n,i,r){this.get_input(r).value=s(e,i.editor,t)},get_value:function(t,e,n){return o(this.get_input(n).value||"",e.editor)},save:function(e,n,i){var r=c(t.getTask(e),this.get_value(e,n,i),n.editor);(r.add.length||r.remove.length)&&t.batchUpdate(function(){r.add.forEach(function(e){t.addLink(e)}),r.remove.forEach(function(e){t.deleteLink(e)}),t.autoSchedule&&t.autoSchedule()})},is_changed:function(e,n,i,r){var a=this.get_value(n,i,r),l=o(s(e,i.editor,t),i.editor);return a.join()!==l.join()}},!0),r}},function(t,e,n){t.exports=function(t){var e=n(7)(t),i=n(0),r="%Y-%m-%d",a=null,o=null;function s(){return e.apply(this,arguments)||this}return n(3)(s,e),i.mixin(s.prototype,{show:function(e,n,i,s){a||(a=t.date.date_to_str(r)),o||(o=t.date.str_to_date(r));var l=null,c=null;l="function"==typeof i.min?i.min(e,n):i.min,c="function"==typeof i.max?i.max(e,n):i.max;var u="<div style='width:140px'><input type='date' "+(l?" min='"+a(l)+"' ":"")+(c?" max='"+a(c)+"' ":"")+" name='"+n.name+"'></div>";s.innerHTML=u},set_value:function(t,e,n,i){t&&t.getFullYear?this.get_input(i).value=a(t):this.get_input(i).value=t},is_valid:function(t,e,n,i){return!(!t||isNaN(t.getTime()))},get_value:function(t,e,n){var i;try{i=o(this.get_input(n).value||"")}catch(t){i=null}return i}},!0),s}},function(t,e,n){t.exports=function(t){var e=n(7)(t),i=n(0);function r(){return e.apply(this,arguments)||this}return n(3)(r,e),i.mixin(r.prototype,{show:function(t,e,n,i){for(var r="<div><select name='"+e.name+"'>",a=[],o=n.options||[],s=0;s<o.length;s++)a.push("<option value='"+n.options[s].key+"'>"+o[s].label+"</option>");r+=a.join("")+"</select></div>",i.innerHTML=r},get_input:function(t){return t.querySelector("select")}},!0),r}},function(t,e,n){t.exports=function(t){var e=n(7)(t),i=n(0);function r(){return e.apply(this,arguments)||this}return n(3)(r,e),i.mixin(r.prototype,{show:function(t,e,n,i){var r="<div><input type='number' min='"+(n.min||0)+"' max='"+(n.max||100)+"' name='"+e.name+"'></div>";i.innerHTML=r},get_value:function(t,e,n){return this.get_input(n).value||""},is_valid:function(t,e,n,i){return!isNaN(parseInt(t,10))}},!0),r}},function(t,e,n){t.exports=function(t){var e=n(7)(t),i=n(0);function r(){return e.apply(this,arguments)||this}return n(3)(r,e),i.mixin(r.prototype,{show:function(t,e,n,i){var r="<div><input type='text' name='"+e.name+"'></div>";i.innerHTML=r}},!0),r}},function(t,e){t.exports={init:function(t,e){var n=t,i=e.$gantt,r=null,a=i.ext.keyboardNavigation;a.attachEvent("onBeforeFocus",function(e){var i=t.locateCell(e);if(clearTimeout(r),i){var a=i.columnName,o=i.id,s=n.getState();if(n.isVisible()&&s.id==o&&s.columnName===a)return!1}return!0}),a.attachEvent("onFocus",function(e){var i=t.locateCell(e),a=t.getState();return clearTimeout(r),!i||i.id==a.id&&i.columnName==a.columnName||n.isVisible()&&n.save(),!0}),t.attachEvent("onHide",function(){clearTimeout(r)}),a.attachEvent("onBlur",function(){return r=setTimeout(function(){n.save()}),!0}),i.attachEvent("onTaskDblClick",function(e,n){var i=t.getState(),r=t.locateCell(n.target);return!r||!t.isVisible()||r.columnName!=i.columnName}),i.attachEvent("onTaskClick",function(e,n){if(i._is_icon_open_click(n))return!0;var r=t.getState(),a=t.locateCell(n.target);return!a||!t.getEditorConfig(a.columnName)||(t.isVisible()&&r.id==a.id&&r.columnName==a.columnName||t.startEdit(a.id,a.columnName),!1)}),i.attachEvent("onEmptyClick",function(){return n.save(),!0}),a.attachEvent("onKeyDown",function(e,r){var o=t.locateCell(r.target),s=!!o&&t.getEditorConfig(o.columnName),l=t.getState(),c=i.constants.KEY_CODES,u=r.keyCode,d=!1;switch(u){case c.ENTER:t.isVisible()?(t.save(),r.preventDefault(),d=!0):s&&!(r.ctrlKey||r.metaKey||r.shiftKey)&&(n.startEdit(o.id,o.columnName),r.preventDefault(),d=!0);break;case c.ESC:t.isVisible()&&(t.hide(),r.preventDefault(),d=!0);break;case c.UP:case c.DOWN:break;case c.LEFT:case c.RIGHT:(s&&t.isVisible()||"date"===l.editorType)&&(d=!0);break;case c.SPACE:t.isVisible()&&(d=!0),s&&!t.isVisible()&&(n.startEdit(o.id,o.columnName),r.preventDefault(),d=!0);break;case c.DELETE:s&&!t.isVisible()?(n.startEdit(o.id,o.columnName),d=!0):s&&t.isVisible()&&(d=!0);break;case c.TAB:if(t.isVisible()){r.shiftKey?t.editPrevCell(!0):t.editNextCell(!0);var h=t.getState();h.id&&a.focus({type:"taskCell",id:h.id,column:h.columnName}),r.preventDefault(),d=!0}break;default:if(t.isVisible())d=!0;else if(u>=48&&u<=57||u>95&&u<112||u>=64&&u<=91||u>185&&u<193||u>218&&u<223){var f=e.modifiers,_=f.alt||f.ctrl||f.meta||f.shift;f.alt||_&&a.getCommandHandler(e,"taskCell")||s&&!t.isVisible()&&(n.startEdit(o.id,o.columnName),d=!0)}}return!d})},onShow:function(t,e,n){},onHide:function(t,e,n){n.$gantt.focus()},destroy:function(){}}},function(t,e){t.exports={init:function(t,e){var n=e.$gantt;n.attachEvent("onTaskClick",function(e,i){if(n._is_icon_open_click(i))return!0;var r=t.getState(),a=t.locateCell(i.target);return!a||!t.getEditorConfig(a.columnName)||(t.isVisible()&&r.id==a.id&&r.columnName==a.columnName||t.startEdit(a.id,a.columnName),!1)}),n.attachEvent("onEmptyClick",function(){return t.isVisible()&&t.isChanged()?t.save():t.hide(),!0}),n.attachEvent("onTaskDblClick",function(e,n){var i=t.getState(),r=t.locateCell(n.target);return!r||!t.isVisible()||r.columnName!=i.columnName})},onShow:function(t,e,n){var i=n.$gantt;i.ext&&i.ext.keyboardNavigation&&i.ext.keyboardNavigation.attachEvent("onKeyDown",function(e,n){var r=i.constants.KEY_CODES,a=!1;switch(n.keyCode){case r.SPACE:t.isVisible()&&(a=!0)}return!a});e.onkeydown=function(e){e=e||window.event;var n=i.constants.KEY_CODES;if(!(e.defaultPrevented||e.shiftKey&&e.keyCode!=n.TAB)){var r=!0;switch(e.keyCode){case i.keys.edit_save:t.save();break;case i.keys.edit_cancel:t.hide();break;case n.UP:case n.DOWN:t.isVisible()&&(t.hide(),r=!1);break;case n.TAB:e.shiftKey?t.editPrevCell(!0):t.editNextCell(!0);break;default:r=!1}r&&e.preventDefault()}}},onHide:function(){},destroy:function(){}}},function(t,e,n){var i=n(101),r=n(100);t.exports=function(t){var e=null;return{setMapping:function(t){e=t},getMapping:function(){return e||(t.config.keyboard_navigation_cells&&t.ext.keyboardNavigation?r:i)}}}},function(t,e,n){var i=n(102),r=n(99),a=n(98),o=n(97),s=n(96),l=n(95),c=n(94),u=n(0),d=n(1),h=n(4),f=n(93);function _(t){t.config.editor_types={text:new(r(t)),number:new(a(t)),select:new(o(t)),date:new(s(t)),predecessor:new(l(t)),duration:new(c(t))}}t.exports=function(t){var e=i(t),n={};h(n);var r={init:_,createEditors:function(i){function r(t,e){var n=i.$getConfig(),r=function(t,e){for(var n=i.$getConfig(),r=i.getItemTop(t),a=i.getItemHeight(t),o=i.getGridColumns(),s=0,l=0,c=0,u=0;u<o.length;u++){if(o[u].name==e){c=o[u].width;break}n.rtl?l+=o[u].width:s+=o[u].width}return n.rtl?{top:r,right:l,height:a,width:c}:{top:r,left:s,height:a,width:c}}(t,e),a=document.createElement("div");a.className="gantt_grid_editor_placeholder",a.setAttribute(i.$config.item_attribute,t),a.setAttribute(i.$config.bind+"_id",t),a.setAttribute("data-column-name",e);var o=function(t,e){for(var n=t.getGridColumns(),i=0;i<n.length;i++)if(n[i].name==e)return i;return 0}(i,e);return a.setAttribute("data-column-index",o),n.rtl?a.style.cssText=["top:"+r.top+"px","right:"+r.right+"px","width:"+r.width+"px","height:"+r.height+"px"].join(";"):a.style.cssText=["top:"+r.top+"px","left:"+r.left+"px","width:"+r.width+"px","height:"+r.height+"px"].join(";"),a}var a=f(t),o=[],s=[],l=null,c={_itemId:null,_columnName:null,_editor:null,_editorType:null,_placeholder:null,locateCell:function(t){if(!d.isChildOf(t,i.$grid))return null;var e=d.locateAttribute(t,i.$config.item_attribute),n=d.locateAttribute(t,"data-column-name");if(e&&n){var r=n.getAttribute("data-column-name");return{id:e.getAttribute(i.$config.item_attribute),columnName:r}}return null},getEditorConfig:function(t){return i.getColumn(t).editor},init:function(){var n=e.getMapping();n.init&&n.init(this,i),l=i.$gantt.getDatastore(i.$config.bind);var r=this;o.push(l.attachEvent("onIdChange",function(t,e){r._itemId==t&&(r._itemId=e)})),o.push(l.attachEvent("onStoreUpdated",function(){i.$gantt.getState("batchUpdate").batch_update||r.isVisible()&&!l.isVisible(r._itemId)&&r.hide()})),s.push(t.attachEvent("onDataRender",function(){r._editor&&r._placeholder&&!d.isChildOf(r._placeholder,t.$root)&&i.$grid_data.appendChild(r._placeholder)})),this.init=function(){}},getState:function(){return{editor:this._editor,editorType:this._editorType,placeholder:this._placeholder,id:this._itemId,columnName:this._columnName}},startEdit:function(e,n){if(this.isVisible()&&this.save(),l.exists(e)){var i={id:e,columnName:n};t.isReadonly(l.getItem(e))?this.callEvent("onEditPrevent",[i]):!1!==this.callEvent("onBeforeEditStart",[i])?(this.show(i.id,i.columnName),this.setValue(),this.callEvent("onEditStart",[i])):this.callEvent("onEditPrevent",[i])}},isVisible:function(){return!(!this._editor||!d.isChildOf(this._placeholder,t.$root))},show:function(t,n){this.isVisible()&&this.save();var a={id:t,columnName:n},o=i.getColumn(a.columnName),s=this.getEditorConfig(o.name);if(s){var l=i.$getConfig().editor_types[s.type],c=r(a.id,a.columnName);i.$grid_data.appendChild(c),l.show(a.id,o,s,c),this._editor=l,this._placeholder=c,this._itemId=a.id,this._columnName=a.columnName,this._editorType=s.type;var u=e.getMapping();u.onShow&&u.onShow(this,c,i)}},setValue:function(){var t=this.getState(),e=t.id,n=t.columnName,r=i.getColumn(n),a=l.getItem(e),o=this.getEditorConfig(n);if(o){var s=a[o.map_to];"auto"==o.map_to&&(s=l.getItem(e)),this._editor.set_value(s,e,r,this._placeholder),this.focus()}},focus:function(){this._editor.focus(this._placeholder)},getValue:function(){var t=i.getColumn(this._columnName);return this._editor.get_value(this._itemId,t,this._placeholder)},_getItemValue:function(){var e=this.getEditorConfig(this._columnName);if(e){var n=t.getTask(this._itemId)[e.map_to];return"auto"==e.map_to&&(n=l.getItem(this._itemId)),n}},isChanged:function(){var t=i.getColumn(this._columnName),e=this._getItemValue();return this._editor.is_changed(e,this._itemId,t,this._placeholder)},hide:function(){if(this._itemId){var t=this._itemId,n=this._columnName,r=e.getMapping();r.onHide&&r.onHide(this,this._placeholder,i),this._itemId=null,this._columnName=null,this._editorType=null,this._placeholder&&(this._editor&&this._editor.hide&&this._editor.hide(this._placeholder),this._editor=null,this._placeholder.parentNode&&this._placeholder.parentNode.removeChild(this._placeholder),this._placeholder=null,this.callEvent("onEditEnd",[{id:t,columnName:n}]))}},save:function(){if(this.isVisible()&&l.exists(this._itemId)&&this.isChanged()){var e=this._itemId,n=this._columnName;if(l.exists(e)){var r=l.getItem(e),o=this.getEditorConfig(n),s={id:e,columnName:n,newValue:this.getValue(),oldValue:this._getItemValue()};if(!1!==this.callEvent("onBeforeSave",[s])&&(!this._editor.is_valid||this._editor.is_valid(s.newValue,s.id,s.columnName,this._placeholder))){var c=o.map_to,u=s.newValue;"auto"!=c?(r[c]=u,a(r,c,t.config.inline_editors_date_processing),l.updateItem(e)):this._editor.save(e,i.getColumn(n),this._placeholder),this.callEvent("onSave",[s])}this.hide()}}else this.hide()},_findEditableCell:function(t,e){var n=t,r=i.getGridColumns()[n],a=r?r.name:null;if(a){for(;a&&!this.getEditorConfig(a);)a=this._findEditableCell(t+e,e);return a}return null},getNextCell:function(t){return this._findEditableCell(i.getColumnIndex(this._columnName,!0)+t,t)},getFirstCell:function(){return this._findEditableCell(0,1)},getLastCell:function(){return this._findEditableCell(i.getGridColumns().length-1,-1)},editNextCell:function(t){var e=this.getNextCell(1);if(e){var n=this.getNextCell(1);n&&this.getEditorConfig(n)&&this.startEdit(this._itemId,n)}else if(t&&this.moveRow(1)){var i=this.moveRow(1);(e=this.getFirstCell())&&this.getEditorConfig(e)&&this.startEdit(i,e)}},editPrevCell:function(t){var e=this.getNextCell(-1);if(e){var n=this.getNextCell(-1);n&&this.getEditorConfig(n)&&this.startEdit(this._itemId,n)}else if(t&&this.moveRow(-1)){var i=this.moveRow(-1);(e=this.getLastCell())&&this.getEditorConfig(e)&&this.startEdit(i,e)}},moveRow:function(e){for(var n=e>0?t.getNext:t.getPrev,i=(n=t.bind(n,t))(this._itemId);t.isTaskExists(i)&&t.isReadonly(t.getTask(i));)i=n(i);return i},editNextRow:function(e){var n=this.getState().id;if(t.isTaskExists(n)){var i=null;i=e?this.moveRow(1):t.getNext(n),t.isTaskExists(i)&&this.startEdit(i,this._columnName)}},editPrevRow:function(e){var n=this.getState().id;if(t.isTaskExists(n)){var i=null;i=e?this.moveRow(-1):t.getPrev(n),t.isTaskExists(i)&&this.startEdit(i,this._columnName)}},destructor:function(){o.forEach(function(t){l.detachEvent(t)}),s.forEach(function(e){t.detachEvent(e)}),o=[],s=[],l=null,this.hide(),this.detachAllEvents()}};return u.mixin(c,e),u.mixin(c,n),c}};return u.mixin(r,e),u.mixin(r,n),r}},function(t,e){t.exports={create:function(){return{render:function(){},destroy:function(){}}}}},function(t,e,n){var i=n(3),r=n(1),a=n(0),o=n(8),s=function(t){"use strict";var e=["altKey","shiftKey","metaKey"];function n(e,n,i,r){var o=t.apply(this,arguments)||this;this.$config=a.mixin(n,{scroll:"x"}),o._scrollHorizontalHandler=a.bind(o._scrollHorizontalHandler,o),o._scrollVerticalHandler=a.bind(o._scrollVerticalHandler,o),o._outerScrollVerticalHandler=a.bind(o._outerScrollVerticalHandler,o),o._outerScrollHorizontalHandler=a.bind(o._outerScrollHorizontalHandler,o),o._mouseWheelHandler=a.bind(o._mouseWheelHandler,o),this.$config.hidden=!0;var s=r.config.scroll_size;return r.env.isIE&&(s+=1),this._isHorizontal()?(o.$config.height=s,o.$parent.$config.height=s):(o.$config.width=s,o.$parent.$config.width=s),this.$config.scrollPosition=0,o.$name="scroller",o}return i(n,t),n.prototype.init=function(t){t.innerHTML=this.$toHTML(),this.$view=t.firstChild,this.$view||this.init(),this._isVertical()?this._initVertical():this._initHorizontal(),this._initMouseWheel(),this._initLinkedViews()},n.prototype.$toHTML=function(){return"<div class='gantt_layout_cell "+(this._isHorizontal()?"gantt_hor_scroll":"gantt_ver_scroll")+"'><div style='"+(this._isHorizontal()?"width:2000px":"height:2000px")+"'></div></div>"},n.prototype._getRootParent=function(){for(var t=this.$parent;t&&t.$parent;)t=t.$parent;if(t)return t},n.prototype._eachView=function(){var t=[];return function t(e,n){if(n.push(e),e.$cells)for(var i=0;i<e.$cells.length;i++)t(e.$cells[i],n)}(this._getRootParent(),t),t},n.prototype._getLinkedViews=function(){for(var t=this._eachView(),e=[],n=0;n<t.length;n++)t[n].$config&&(this._isVertical()&&t[n].$config.scrollY==this.$id||this._isHorizontal()&&t[n].$config.scrollX==this.$id)&&e.push(t[n]);return e},n.prototype._initHorizontal=function(){this.$scroll_hor=this.$view,this.$domEvents.attach(this.$view,"scroll",this._scrollHorizontalHandler)},n.prototype._initLinkedViews=function(){for(var t=this._getLinkedViews(),e=this._isVertical()?"gantt_layout_outer_scroll gantt_layout_outer_scroll_vertical":"gantt_layout_outer_scroll gantt_layout_outer_scroll_horizontal",n=0;n<t.length;n++)r.addClassName(t[n].$view||t[n].getNode(),e)},n.prototype._initVertical=function(){this.$scroll_ver=this.$view,this.$domEvents.attach(this.$view,"scroll",this._scrollVerticalHandler)},n.prototype._updateLinkedViews=function(){},n.prototype._initMouseWheel=function(){o.isFF?this.$domEvents.attach(this._getRootParent().$view,"wheel",this._mouseWheelHandler,{passive:!1}):this.$domEvents.attach(this._getRootParent().$view,"mousewheel",this._mouseWheelHandler,{passive:!1})},n.prototype.scrollHorizontally=function(t){if(!this._scrolling){this._scrolling=!0,this.$scroll_hor.scrollLeft=t,this.$config.codeScrollLeft=t,t=this.$scroll_hor.scrollLeft;for(var e=this._getLinkedViews(),n=0;n<e.length;n++)e[n].scrollTo&&e[n].scrollTo(t,void 0);var i=this.$config.scrollPosition;this.$config.scrollPosition=t,this.callEvent("onScroll",[i,t,this.$config.scroll]),this._scrolling=!1}},n.prototype.scrollVertically=function(t){if(!this._scrolling){this._scrolling=!0,this.$scroll_ver.scrollTop=t,t=this.$scroll_ver.scrollTop;for(var e=this._getLinkedViews(),n=0;n<e.length;n++)e[n].scrollTo&&e[n].scrollTo(void 0,t);var i=this.$config.scrollPosition;this.$config.scrollPosition=t,this.callEvent("onScroll",[i,t,this.$config.scroll]),this._scrolling=!1}},n.prototype._isVertical=function(){return"y"==this.$config.scroll},n.prototype._isHorizontal=function(){return"x"==this.$config.scroll},n.prototype._scrollHorizontalHandler=function(t){if(!this._isVertical()&&!this._scrolling){if(new Date-(this._wheel_time||0)<100)return!0;var e=this.$scroll_hor.scrollLeft;this.scrollHorizontally(e),this._oldLeft=this.$scroll_hor.scrollLeft}},n.prototype._outerScrollHorizontalHandler=function(t){this._isVertical()},n.prototype.show=function(){this.$parent.show()},n.prototype.hide=function(){this.$parent.hide()},n.prototype._getScrollSize=function(){for(var t,e=0,n=0,i=this._isHorizontal(),r=this._getLinkedViews(),a=i?"scrollWidth":"scrollHeight",o=i?"contentX":"contentY",s=i?"x":"y",l=this._getScrollOffset(),c=0;c<r.length;c++)if((t=r[c])&&t.$content&&t.$content.getSize&&!t.$config.hidden){var u,d=t.$content.getSize();if(u=d.hasOwnProperty(a)?d[a]:d[o],l)d[o]>d[s]&&d[o]>e&&u>d[s]-l+2&&(e=u+(i?0:2),n=d[s]);else{var h=Math.max(d[o]-u,0);(u+=h)>Math.max(d[s]-h,0)&&u>e&&(e=u,n=d[s])}}return{outerScroll:n,innerScroll:e}},n.prototype.scroll=function(t){this._isHorizontal()?this.scrollHorizontally(t):this.scrollVertically(t)},n.prototype.getScrollState=function(){return{visible:this.isVisible(),direction:this.$config.scroll,size:this.$config.outerSize,scrollSize:this.$config.scrollSize||0,position:this.$config.scrollPosition||0}},n.prototype.setSize=function(e,n){t.prototype.setSize.apply(this,arguments);var i=this._getScrollSize(),r=(this._isVertical()?n:e)-this._getScrollOffset()+(this._isHorizontal()?1:0);i.innerScroll&&r>i.outerScroll&&(i.innerScroll+=r-i.outerScroll),this.$config.scrollSize=i.innerScroll,this.$config.width=e,this.$config.height=n,this._setScrollSize(i.innerScroll)},n.prototype.isVisible=function(){return!(!this.$parent||!this.$parent.$view.parentNode)},n.prototype.shouldShow=function(){var t=this._getScrollSize();return!(!t.innerScroll&&this.$parent&&this.$parent.$view.parentNode)&&!(!t.innerScroll||this.$parent&&this.$parent.$view.parentNode)},n.prototype.shouldHide=function(){return!(this._getScrollSize().innerScroll||!this.$parent||!this.$parent.$view.parentNode)},n.prototype.toggleVisibility=function(){this.shouldHide()?this.hide():this.shouldShow()&&this.show()},n.prototype._getScaleOffset=function(t){var e=0;return!t||"timeline"!=t.$config.view&&"grid"!=t.$config.view||(e=t.$content.$getConfig().scale_height),e},n.prototype._getScrollOffset=function(){var t=0;if(this._isVertical()){var e=this.$parent.$parent;t=Math.max(this._getScaleOffset(e.getPrevSibling(this.$parent.$id)),this._getScaleOffset(e.getNextSibling(this.$parent.$id)))}else for(var n=this._getLinkedViews(),i=0;i<n.length;i++){var r=n[i].$parent.$cells,a=r[r.length-1];if(a&&"scrollbar"==a.$config.view&&!1===a.$config.hidden){t=a.$config.width;break}}return t||0},n.prototype._setScrollSize=function(t){var e=this._isHorizontal()?"width":"height",n=this._isHorizontal()?this.$scroll_hor:this.$scroll_ver,i=this._getScrollOffset(),a=n.firstChild;i?this._isVertical()?(this.$config.outerSize=this.$config.height-i+3,n.style.height=this.$config.outerSize+"px",n.style.top=i-1+"px",r.addClassName(n,this.$parent._borders.top),r.addClassName(n.parentNode,"gantt_task_vscroll")):(this.$config.outerSize=this.$config.width-i+1,n.style.width=this.$config.outerSize+"px"):(n.style.top="auto",r.removeClassName(n,this.$parent._borders.top),r.removeClassName(n.parentNode,"gantt_task_vscroll"),this.$config.outerSize=this.$config.height),a.style[e]=t+"px"},n.prototype._scrollVerticalHandler=function(t){if(!this._scrollHorizontalHandler()&&!this._scrolling){var e=this.$scroll_ver.scrollTop;e!=this._oldTop&&(this.scrollVertically(e),this._oldTop=this.$scroll_ver.scrollTop)}},n.prototype._outerScrollVerticalHandler=function(t){this._scrollHorizontalHandler()},n.prototype._checkWheelTarget=function(t){for(var e=this._getLinkedViews().concat(this),n=0;n<e.length;n++){var i=e[n].$view;if(r.isChildOf(t,i))return!0}return!1},n.prototype._mouseWheelHandler=function(t){var n=t.target||t.srcElement;if(this._checkWheelTarget(n)){this._wheel_time=new Date;var i={},r={x:1,y:1},a=this.$gantt.config.wheel_scroll_sensitivity;"number"==typeof a&&a?r={x:a,y:a}:"[object Object]"=={}.toString.apply(a)&&(r={x:a.x,y:a.y});var s=o.isFF,l=s?t.deltaX:t.wheelDeltaX,c=s?t.deltaY:t.wheelDelta,u=-20;s&&(u=0!==t.deltaMode?-40:-10);var d=s?l*u*r.x:2*l*r.x,h=s?c*u*r.y:c*r.y,f=this.$gantt.config.horizontal_scroll_key;if(!1!==f&&e.indexOf(f)>=0&&(!t[f]||t.deltaX||t.wheelDeltaX||(d=2*h,h=0)),d&&Math.abs(d)>Math.abs(h)){if(this._isVertical())return;if(i.x)return!0;if(!this.$scroll_hor||!this.$scroll_hor.offsetWidth)return!0;var _=d/-40,g=this._oldLeft,p=g+30*_;if(this.scrollHorizontally(p),this.$scroll_hor.scrollLeft=p,g==this.$scroll_hor.scrollLeft)return!0;this._oldLeft=this.$scroll_hor.scrollLeft}else{if(this._isHorizontal())return;if(i.y)return!0;if(!this.$scroll_ver||!this.$scroll_ver.offsetHeight)return!0;_=h/-40;void 0===h&&(_=t.detail);var v=this._oldTop,m=this.$scroll_ver.scrollTop+30*_;if(this.scrollVertically(m),this.$scroll_ver.scrollTop=m,v==this.$scroll_ver.scrollTop)return!0;this._oldTop=this.$scroll_ver.scrollTop}return t.preventDefault&&t.preventDefault(),t.cancelBubble=!0,!1}},n}(n(9));t.exports=s},function(t,e){t.exports=null},function(t,e,n){var i=n(3),r=n(0),a=function(t){"use strict";function e(e,n,i){var a=t.apply(this,arguments)||this;if(n.view){n.id&&(this.$id=r.uid());var o=r.copy(n);if(delete o.config,delete o.templates,this.$content=this.$factory.createView(n.view,this,o,this),!this.$content)return!1}return a.$name="viewCell",a}return i(e,t),e.prototype.destructor=function(){this.clear(),t.prototype.destructor.call(this)},e.prototype.clear=function(){if(this.$initialized=!1,this.$content){var e=this.$content.unload||this.$content.destructor;e&&e.call(this.$content)}t.prototype.clear.call(this)},e.prototype.scrollTo=function(e,n){this.$content&&this.$content.scrollTo?this.$content.scrollTo(e,n):t.prototype.scrollTo.call(this,e,n)},e.prototype._setContentSize=function(t,e){var n=this._getBorderSizes();if("number"==typeof t){var i=t+n.horizontal;this.$config.width=i}if("number"==typeof e){var r=e+n.vertical;this.$config.height=r}},e.prototype.setSize=function(e,n){if(t.prototype.setSize.call(this,e,n),!this.$preResize&&this.$content&&!this.$initialized){this.$initialized=!0;var i=this.$view.childNodes[0],r=this.$view.childNodes[1];r||(r=i),this.$content.init(r)}},e.prototype.setContentSize=function(){!this.$preResize&&this.$content&&this.$initialized&&this.$content.setSize(this.$lastSize.contentX,this.$lastSize.contentY)},e.prototype.getContentSize=function(){var e=t.prototype.getContentSize.call(this);if(this.$content&&this.$initialized){var n=this.$content.getSize();e.width=void 0===n.contentX?n.width:n.contentX,e.height=void 0===n.contentY?n.height:n.contentY}var i=this._getBorderSizes();return e.width+=i.horizontal,e.height+=i.vertical,e},e}(n(9));t.exports=a},function(t,e,n){var i=n(3),r=n(31),a=n(9),o=function(t){"use strict";function e(e,n,i){for(var r=t.apply(this,arguments)||this,a=0;a<r.$cells.length;a++)r.$cells[a].$config.hidden=0!==a;return r.$cell=r.$cells[0],r.$name="viewLayout",r}return i(e,t),e.prototype.cell=function(e){var n=t.prototype.cell.call(this,e);return n.$view||this.$fill(null,this),n},e.prototype.moveView=function(t){var e=this.$view;this.$cell&&(this.$cell.$config.hidden=!0,e.removeChild(this.$cell.$view)),this.$cell=t,e.appendChild(t.$view)},e.prototype.setSize=function(t,e){a.prototype.setSize.call(this,t,e)},e.prototype.setContentSize=function(){var t=this.$lastSize;this.$cell.setSize(t.contentX,t.contentY)},e.prototype.getSize=function(){var e=t.prototype.getSize.call(this);if(this.$cell){var n=this.$cell.getSize();if(this.$config.byMaxSize)for(var i=0;i<this.$cells.length;i++){var r=this.$cells[i].getSize();for(var a in n)n[a]=Math.max(n[a],r[a])}for(var o in e)e[o]=e[o]||n[o];e.gravity=Math.max(e.gravity,n.gravity)}return e},e}(r);t.exports=o},function(t,e){t.exports=function(t,e){return!!e&&(!(e.left>t.x_end||e.left+e.width<t.x)&&!(e.top>t.y_end||e.top+e.height<t.y))}},function(t,e,n){var i=n(109),r=n(13),a=n(23),o=n(5);t.exports=function(t){var e={},n={};function s(e){var n=null;return"string"==typeof e.view?n=t.$ui.getView(e.view):e.view&&(n=e.view),n}function l(l,c,u){if(n[l])return n[l];c.renderer||t.assert(!1,"Invalid renderer call");var d=null,h=null,f=null,_=null,g=null;"function"==typeof c.renderer?(d=c.renderer,f=a):(d=c.renderer.render,h=c.renderer.update,_=c.renderer.onrender,c.renderer.isInViewPort?g=c.renderer.isInViewPort:f=c.renderer.getRectangle,f||null===f||(f=a));var p=c.filter;return u&&u.setAttribute(t.config.layer_attribute,!0),n[l]={render_item:function(e,n,a,o,l){if(n=n||u,!p||p(e)){var h=o||s(c),v=l||(h?h.$getConfig():null),m=a;!m&&v&&v.smart_rendering&&(m=h.getViewPort());var y=null;!r(t)&&(f||g)&&m?(g?g(e,m,h,v,t):i(m,f(e,h,v,t)))&&(y=d.call(t,e,h,v,m)):y=d.call(t,e,h,v,m),this.append(e,y,n);var k=11==n.nodeType;_&&!k&&y&&_.call(t,e,y,h)}else this.remove_item(e.id)},clear:function(t){this.rendered=e[l]={},c.append||this.clear_container(t)},clear_container:function(t){(t=t||u)&&(t.innerHTML="")},get_visible_range:function(e){var n,i,r=s(c),a=r?r.$getConfig():null;return a&&a.smart_rendering&&(n=r.getViewPort()),r&&n&&("function"==typeof c.renderer?i=o(t,r,a,e,n):c.renderer&&c.renderer.getVisibleRange&&(i=c.renderer.getVisibleRange(t,r,a,e,n))),i||(i={start:0,end:e.count()}),i},render_items:function(e,n){n=n||u;var i=document.createDocumentFragment();this.clear(n);var r=null,a=s(c),o=a?a.$getConfig():null;o&&o.smart_rendering&&(r=a.getViewPort());for(var l=0,d=e.length;l<d;l++)this.render_item(e[l],i,r,a,o);n.appendChild(i,n);var h={};e.forEach(function(t){h[t.id]=t});var f={};if(_){var g={};for(var l in this.rendered)f[l]||(g[l]=this.rendered[l],_.call(t,h[l],this.rendered[l],a))}},update_items:function(e,n){var a=s(c),o=a?a.$getConfig():null;if(a&&a.$getConfig().smart_rendering&&!r(t)&&this.rendered&&(f||g)){n=n||u;var l=document.createDocumentFragment(),d=null;a&&(d=a.getViewPort());var p={};e.forEach(function(t){p[t.id]=t});var v={},m={};for(var y in this.rendered)m[y]=!0,v[y]=!0;for(var k={},b=(y=0,e.length);y<b;y++){var w=e[y],x=this.rendered[w.id];m[w.id]=!1,x&&x.parentNode?(g?g(w,d,a,o,t):i(d,f(w,a,o,t)))?(h&&h.call(t,w,x,a,o,d),this.restore(w,l)):m[w.id]=!0:(k[e[y].id]=!0,this.render_item(e[y],l,d,a,o))}for(var y in m)m[y]&&this.hide(y);if(l.childNodes.length&&n.appendChild(l,n),_){var $={};for(var y in this.rendered)v[y]&&!k[y]||($[y]=this.rendered[y],_.call(t,p[y],this.rendered[y],a))}}},append:function(t,e,n){this.rendered&&(e?(this.rendered[t.id]&&this.rendered[t.id].parentNode?this.replace_item(t.id,e):n.appendChild(e),this.rendered[t.id]=e):this.rendered[t.id]&&this.remove_item(t.id))},replace_item:function(t,e){var n=this.rendered[t];n&&n.parentNode&&n.parentNode.replaceChild(e,n),this.rendered[t]=e},remove_item:function(t){this.hide(t),delete this.rendered[t]},hide:function(t){var e=this.rendered[t];e&&e.parentNode&&e.parentNode.removeChild(e)},restore:function(t,e){var n=this.rendered[t.id];n?n.parentNode||this.append(t,n,e||u):this.render_item(t,e||u)},change_id:function(t,e){this.rendered[e]=this.rendered[t],delete this.rendered[t]},rendered:e[l],node:u,destructor:function(){this.clear(),delete n[l],delete e[l]}},n[l]}return{getRenderer:l,clearRenderers:function(){for(var t in n)l(t).destructor()}}}},function(t,e,n){var i=n(110),r=n(0),a=n(1),o=n(13);function s(t){return t instanceof Array||(t=Array.prototype.slice.call(arguments,0)),function(e){for(var n=!0,i=0,r=t.length;i<r;i++){var a=t[i];a&&(n=n&&!1!==a(e.id,e))}return n}}t.exports=function(t){var e=i(t);return{createGroup:function(n,i,l,c){var u={tempCollection:[],renderers:{},container:n,filters:[],getLayers:function(){this._add();var t=[];for(var e in this.renderers)t.push(this.renderers[e]);return t},getLayer:function(t){return this.renderers[t]},_add:function(n){n&&(n.id=n.id||r.uid(),this.tempCollection.push(n));for(var o=this.container(),s=this.tempCollection,l=0;l<s.length;l++)if(n=s[l],this.container()||n&&n.container&&a.isChildOf(n.container,document.body)){var u=n.container,d=n.id,h=n.topmost;if(!u.parentNode)if(h)o.appendChild(u);else{var f=i?i():o.firstChild;f&&f.parentNode==o?o.insertBefore(u,f):o.appendChild(u)}this.renderers[d]=e.getRenderer(d,n,u),c&&c(n,t),this.tempCollection.splice(l,1),l--}},addLayer:function(e){if(e){"function"==typeof e&&(e={renderer:e}),void 0===e.filter?e.filter=s(l||[]):e.filter instanceof Array&&(e.filter.push(l),e.filter=s(e.filter)),e.container||(e.container=document.createElement("div"));var n=this;e.requestUpdate=function(){t.config.smart_rendering&&!o(t)&&n.renderers[e.id]&&n.onUpdateRequest(n.renderers[e.id])}}return this._add(e),e?e.id:void 0},onUpdateRequest:function(t){},eachLayer:function(t){for(var e in this.renderers)t(this.renderers[e])},removeLayer:function(t){this.renderers[t]&&(this.renderers[t].destructor(),delete this.renderers[t])},clear:function(){for(var t in this.renderers)this.renderers[t].destructor();this.renderers={}}};return t.attachEvent("onDestroy",function(){u.clear(),u=null}),u}}}},function(t,e,n){var i=n(111);function r(t,e){if(t.view){var n=t.view;"string"==typeof n&&(n=e.$ui.getView(n)),n&&n.attachEvent&&n.attachEvent("onScroll",function(){e.$services.getService("state").getState("batchUpdate").batch_update||n.$config.$skipSmartRenderOnScroll||t.requestUpdate&&t.requestUpdate()})}}t.exports=function(t){var e=i(t);return{getDataRender:function(e){return t.$services.getService("layer:"+e)||null},createDataRender:function(n){var i=n.name,a=n.defaultContainer,o=n.defaultContainerSibling,s=e.createGroup(a,o,function(t,e){if(!s.filters)return!0;for(var n=0;n<s.filters.length;n++)if(!1===s.filters[n](t,e))return!1},r);return t.$services.setService("layer:"+i,function(){return s}),t.attachEvent("onGanttReady",function(){s.addLayer()}),s},init:function(){var e=this.createDataRender({name:"task",defaultContainer:function(){return t.$task_data?t.$task_data:t.$ui.getView("timeline")?t.$ui.getView("timeline").$task_data:void 0},defaultContainerSibling:function(){return t.$task_links?t.$task_links:t.$ui.getView("timeline")?t.$ui.getView("timeline").$task_links:void 0},filter:function(t){}},t),n=this.createDataRender({name:"link",defaultContainer:function(){return t.$task_data?t.$task_data:t.$ui.getView("timeline")?t.$ui.getView("timeline").$task_data:void 0}},t);return{addTaskLayer:function(t){return"function"==typeof t&&(t={renderer:t}),t.view="timeline",e.addLayer(t)},_getTaskLayers:function(){return e.getLayers()},removeTaskLayer:function(t){e.removeLayer(t)},_clearTaskLayers:function(){e.clear()},addLinkLayer:function(t){return"function"==typeof t&&(t={renderer:{render:t}}),t.view="timeline",n.addLayer(t)},_getLinkLayers:function(){return n.getLayers()},removeLinkLayer:function(t){n.removeLayer(t)},_clearLinkLayers:function(){n.clear()}}}}}},function(t,e,n){var i=function(t){return function(e){var n={click:{},doubleclick:{},contextMenu:{}};function i(t,e,i,r){n[t][e]||(n[t][e]=[]),n[t][e].push({handler:i,root:r})}function r(t){t=t||window.event;var i=e.locate(t),r=o(t,n.click),a=!0;if(null!==i?a=!e.checkEvent("onTaskClick")||e.callEvent("onTaskClick",[i,t]):e.callEvent("onEmptyClick",[t]),a){if(!s(r,t,i))return;switch(t.target.nodeName){case"SELECT":case"INPUT":return}i&&e.getTask(i)&&!e._multiselect&&e.config.select_task&&e.selectTask(i)}}function a(t){var n=(t=t||window.event).target||t.srcElement,i=e.locate(n),r=e.locate(n,e.config.link_attribute),a=!e.checkEvent("onContextMenu")||e.callEvent("onContextMenu",[i,r,t]);return a||(t.preventDefault?t.preventDefault():t.returnValue=!1),a}function o(e,n){for(var i=e.target||e.srcElement,r=[];i;){var a=t.getClassName(i);if(a){a=a.split(" ");for(var o=0;o<a.length;o++)if(a[o]&&n[a[o]])for(var s=n[a[o]],l=0;l<s.length;l++)s[l].root&&!t.isChildOf(i,s[l].root)||r.push(s[l].handler)}i=i.parentNode}return r}function s(t,n,i){for(var r=!0,a=0;a<t.length;a++){var o=t[a].call(e,n,i,n.target||n.srcElement);r=r&&!(void 0!==o&&!0!==o)}return r}function l(t){t=t||window.event;var i=e.locate(t),r=o(t,n.doubleclick),a=!e.checkEvent("onTaskDblClick")||null===i||e.callEvent("onTaskDblClick",[i,t]);if(a){if(!s(r,t,i))return;null!==i&&e.getTask(i)&&a&&e.config.details_on_dblclick&&!e.isReadonly(i)&&e.showLightbox(i)}}function c(t){if(e.checkEvent("onMouseMove")){var n=e.locate(t);e._last_move_event=t,e.callEvent("onMouseMove",[n,t])}}var u=e._createDomEventScope();function d(t){u.detachAll(),t&&(u.attach(t,"click",r),u.attach(t,"dblclick",l),u.attach(t,"mousemove",c),u.attach(t,"contextmenu",a))}return{reset:d,global:function(t,e,n){i(t,e,n,null)},delegate:i,detach:function(t,e,i,r){if(n[t]&&n[t][e]){for(var a=n[t],o=a[e],s=0;s<o.length;s++)o[s].root==r&&(o.splice(s,1),s--);o.length||delete a[e]}},callHandler:function(t,e,i,r){var a=n[t][e];if(a)for(var o=0;o<a.length;o++)(i||a[o].root)&&a[o].root!==i||a[o].handler.apply(this,r)},onDoubleClick:l,onMouseMove:c,onContextMenu:a,onClick:r,destructor:function(){d(),n=null,u=null}}}}(n(1));t.exports={init:i}},function(t,e,n){var i=n(0);function r(t,e){var n=this.$config[t];return n?(n.$extendedConfig||(n.$extendedConfig=!0,Object.setPrototypeOf(n,e)),n):e}t.exports=function(t,e){i.mixin(t,function(t){var e,n;return{$getConfig:function(){return e||(e=t?t.$getConfig():this.$gantt.config),this.$config.config?r.call(this,"config",e):e},$getTemplates:function(){return n||(n=t?t.$getTemplates():this.$gantt.templates),this.$config.templates?r.call(this,"templates",n):n}}}(e))}},function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var r=n(0),a=n(114);t.exports={createFactory:function(t){var e={};var n={};function o(o,s,l,c){var u=e[o];if(!u||!u.create)return!1;"resizer"!=o||l.mode||(c.$config.cols?l.mode="x":l.mode="y"),"viewcell"!=o||"scrollbar"!=l.view||l.scroll||(c.$config.cols?l.scroll="y":l.scroll="x"),(l=r.copy(l)).id||n[l.view]||(l.id=l.view),l.id&&!l.css&&(l.css=l.id+"_cell");var d=new u.create(s,l,this,t);return u.configure&&u.configure(d),a(d,c),d.$id||(d.$id=l.id||t.uid()),d.$parent||"object"!=i(s)||(d.$parent=s),d.$config||(d.$config=l),n[d.$id]&&(d.$id=t.uid()),n[d.$id]=d,d}return{initUI:function(t,e){var n="cell";return t.view?n="viewcell":t.resizer?n="resizer":t.rows||t.cols?n="layout":t.views&&(n="multiview"),o.call(this,n,null,t,e)},reset:function(){n={}},registerView:function(t,n,i){e[t]={create:n,configure:i}},createView:o,getView:function(t){return n[t]}}}}},function(t,e,n){var i=n(115),r=n(113),a=n(112),o=n(9),s=n(31),l=n(108),c=n(107),u=n(106),d=n(105),h=n(22),f=n(25),_=n(25),g=n(22),p=n(22),v=n(103),m=n(92),y=n(91),k=n(89),b=n(88),w=n(87),x=n(85),$=n(84),S=n(83),T=n(82),C=n(81),E=n(75),D=n(72);t.exports={init:function(t){function e(e,n){var i=n(t);i.onCreated&&i.onCreated(e),e.attachEvent("onReady",function(){i.onInitialized&&i.onInitialized(e)}),e.attachEvent("onDestroy",function(){i.onDestroyed&&i.onDestroyed(e)})}var n=i.createFactory(t);n.registerView("cell",o),n.registerView("resizer",u),n.registerView("scrollbar",d),n.registerView("layout",s,function(t){"main"===(t.$config?t.$config.id:null)&&e(t,D)}),n.registerView("viewcell",c),n.registerView("multiview",l),n.registerView("timeline",h,function(t){"timeline"!==(t.$config?t.$config.id:null)&&"task"!=t.$config.bind||e(t,E)}),n.registerView("grid",f,function(t){"grid"!==(t.$config?t.$config.id:null)&&"task"!=t.$config.bind||e(t,C)}),n.registerView("resourceGrid",_),n.registerView("resourceTimeline",g),n.registerView("resourceHistogram",p);var A=a(t),M=v(t);return t.ext.inlineEditors=M,t.ext._inlineEditors=M,M.init(t),{factory:n,mouseEvents:r.init(t),layersApi:A.init(),render:{gridLine:function(){return x(t)},taskBg:function(){return b(t)},taskBar:function(){return m(t)},taskRollupBar:function(){return k(t)},taskSplitBar:function(){return y(t)},link:function(){return w(t)},resourceRow:function(){return $(t)},resourceHistogram:function(){return S(t)},gridTaskRowResizer:function(){return T(t)}},layersService:{getDataRender:function(e){return A.getDataRender(e,t)},createDataRender:function(e){return A.createDataRender(e,t)}}}}}},function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var r=n(0),a=n(1);t.exports=function(t){var e="data-dhxbox",n=null;function o(t,e){var i=t.callback;y.hide(t.box),n=t.box=null,i&&i(e)}function s(t){if(n){var e=t.which||t.keyCode,i=!1;if(k.keyboard){if(13==e||32==e){var r=t.target||t.srcElement;a.getClassName(r).indexOf("gantt_popup_button")>-1&&r.click?r.click():(o(n,!0),i=!0)}27==e&&(o(n,!1),i=!0)}return i?(t.preventDefault&&t.preventDefault(),!(t.cancelBubble=!0)):void 0}}var l=a.getRootNode(t.$root)||document;function c(t){c.cover||(c.cover=document.createElement("div"),c.cover.onkeydown=s,c.cover.className="dhx_modal_cover",document.body.appendChild(c.cover)),c.cover.style.display=t?"inline-block":"none"}function u(e,n,i){var r=t._waiAria.messageButtonAttrString(e),a=n.toLowerCase().replace(/ /g,"_");return"<div "+r+" class='gantt_popup_button dhtmlx_popup_button "+("gantt_"+a+"_button dhtmlx_"+a+"_button")+"' data-result='"+i+"' result='"+i+"' ><div>"+e+"</div></div>"}function d(e){k.area||(k.area=document.createElement("div"),k.area.className="gantt_message_area dhtmlx_message_area",k.area.style[k.position]="5px",document.body.appendChild(k.area)),k.hide(e.id);var n=document.createElement("div");return n.innerHTML="<div>"+e.text+"</div>",n.className="gantt-info dhtmlx-info gantt-"+e.type+" dhtmlx-"+e.type,n.onclick=function(){k.hide(e.id),e=null},t._waiAria.messageInfoAttr(n),"bottom"==k.position&&k.area.firstChild?k.area.insertBefore(n,k.area.firstChild):k.area.appendChild(n),e.expire>0&&(k.timers[e.id]=window.setTimeout(function(){k&&k.hide(e.id)},e.expire)),k.pull[e.id]=n,n=null,e.id}function h(){for(var t=[].slice.apply(arguments,[0]),e=0;e<t.length;e++)if(t[e])return t[e]}function f(l,d,f){var _=l.tagName?l:function(s,l,c){var d=document.createElement("div"),f=r.uid();t._waiAria.messageModalAttr(d,f),d.className=" gantt_modal_box dhtmlx_modal_box gantt-"+s.type+" dhtmlx-"+s.type,d.setAttribute(e,1);var _="";if(s.width&&(d.style.width=s.width),s.height&&(d.style.height=s.height),s.title&&(_+='<div class="gantt_popup_title dhtmlx_popup_title">'+s.title+"</div>"),_+='<div class="gantt_popup_text dhtmlx_popup_text" id="'+f+'"><span>'+(s.content?"":s.text)+'</span></div><div class="gantt_popup_controls dhtmlx_popup_controls">',l&&(_+=u(h(s.ok,t.locale.labels.message_ok,"OK"),"ok",!0)),c&&(_+=u(h(s.cancel,t.locale.labels.message_cancel,"Cancel"),"cancel",!1)),s.buttons)for(var g=0;g<s.buttons.length;g++){var p=s.buttons[g];"object"==i(p)?_+=u(p.label,p.css||"gantt_"+p.label.toLowerCase()+"_button dhtmlx_"+p.label.toLowerCase()+"_button",p.value||g):_+=u(p,p,g)}if(_+="</div>",d.innerHTML=_,s.content){var v=s.content;"string"==typeof v&&(v=document.getElementById(v)),"none"==v.style.display&&(v.style.display=""),d.childNodes[s.title?1:0].appendChild(v)}return d.onclick=function(t){var e=t.target||t.srcElement;if(e.className||(e=e.parentNode),a.closest(e,".gantt_popup_button")){var n=e.getAttribute("data-result");o(s,n="true"==n||"false"!=n&&n)}},s.box=d,(l||c)&&(n=s),d}(l,d,f);l.hidden||c(!0),document.body.appendChild(_);var g=Math.abs(Math.floor(((window.innerWidth||document.documentElement.offsetWidth)-_.offsetWidth)/2)),p=Math.abs(Math.floor(((window.innerHeight||document.documentElement.offsetHeight)-_.offsetHeight)/2));return"top"==l.position?_.style.top="-3px":_.style.top=p+"px",_.style.left=g+"px",_.onkeydown=s,y.focus(_),l.hidden&&y.hide(_),t.callEvent("onMessagePopup",[_]),_}function _(t){return f(t,!0,!1)}function g(t){return f(t,!0,!0)}function p(t){return f(t)}function v(t,e,n){return"object"!=i(t)&&("function"==typeof e&&(n=e,e=""),t={text:t,type:e,callback:n}),t}function m(t,e,n,a){return"object"!=i(t)&&(t={text:t,type:e,expire:n,id:a}),t.id=t.id||r.uid(),t.expire=t.expire||k.expire,t}t.event(l,"keydown",s,!0);var y=function(){var t=v.apply(this,arguments);return t.type=t.type||"alert",p(t)};y.hide=function(n){for(;n&&n.getAttribute&&!n.getAttribute(e);)n=n.parentNode;n&&(n.parentNode.removeChild(n),c(!1),t.callEvent("onAfterMessagePopup",[n]))},y.focus=function(t){setTimeout(function(){var e=a.getFocusableNodes(t);e.length&&e[0].focus&&e[0].focus()},1)};var k=function(t,e,n,i){switch((t=m.apply(this,arguments)).type=t.type||"info",t.type.split("-")[0]){case"alert":return _(t);case"confirm":return g(t);case"modalbox":return p(t);default:return d(t)}};k.seed=(new Date).valueOf(),k.uid=r.uid,k.expire=4e3,k.keyboard=!0,k.position="top",k.pull={},k.timers={},k.hideAll=function(){for(var t in k.pull)k.hide(t)},k.hide=function(t){var e=k.pull[t];e&&e.parentNode&&(window.setTimeout(function(){e.parentNode.removeChild(e),e=null},2e3),e.className+=" hidden",k.timers[t]&&window.clearTimeout(k.timers[t]),delete k.pull[t])};var b=[];return t.attachEvent("onMessagePopup",function(t){b.push(t)}),t.attachEvent("onAfterMessagePopup",function(t){for(var e=0;e<b.length;e++)b[e]===t&&(b.splice(e,1),e--)}),t.attachEvent("onDestroy",function(){c.cover&&c.cover.parentNode&&c.cover.parentNode.removeChild(c.cover);for(var t=0;t<b.length;t++)b[t].parentNode&&b[t].parentNode.removeChild(b[t]);b=null,k.area&&k.area.parentNode&&k.area.parentNode.removeChild(k.area),k=null}),{alert:function(){var t=v.apply(this,arguments);return t.type=t.type||"confirm",_(t)},confirm:function(){var t=v.apply(this,arguments);return t.type=t.type||"alert",g(t)},message:k,modalbox:y}}},function(t,e,n){t.exports=function(t){var e=n(0),i=n(8),r=n(10);if(!i.isNode){var a=n(1),o=n(2);t.utils={arrayFind:o.arrayFind,dom:a};var s=n(43)();t.event=s.attach,t.eventRemove=s.detach,t._eventRemoveAll=s.detachAll,t._createDomEventScope=s.extend,e.mixin(t,n(117)(t));var l=n(116).init(t);t.$ui=l.factory,t.$ui.layers=l.render,t.$mouseEvents=l.mouseEvents,t.$services.setService("mouseEvents",function(){return t.$mouseEvents}),t.mixin(t,l.layersApi),n(71)(t),t.$services.setService("layers",function(){return l.layersService});var c=n(70);t.mixin(t,c()),n(69)(t),n(68)(t),n(67)(t),n(66)(t),n(65)(t),n(64)(t),n(63)(t),n(62)(t),n(61)(t),n(56)(t),n(55)(t),n(45)(t),n(44)(t),t.locate=function(t){var e=a.getTargetNode(t);if(a.closest(e,".gantt_task_row"))return null;var n=arguments[1]||this.config.task_attribute,i=a.locateAttribute(e,n);return i?i.getAttribute(n):null},t._locate_css=function(t,e,n){return a.locateClassName(t,e,n)},t._locateHTML=function(t,e){return a.locateAttribute(t,e||this.config.task_attribute)}}t.attachEvent("onParse",function(){r(t)||t.attachEvent("onGanttRender",function(){if(t.config.initial_scroll){var e=t.getTaskByIndex(0),n=e?e.id:t.config.root_id;t.isTaskExists(n)&&t.showTask(n)}},{once:!0})}),t.attachEvent("onBeforeGanttReady",function(){this.config.scroll_size||(this.config.scroll_size=a.getScrollSize()||1),r(t)||(this._eventRemoveAll(),this.$mouseEvents.reset(),this.resetLightbox())}),t.attachEvent("onGanttReady",function(){!r(t)&&t.config.rtl&&t.$layout.getCellsByType("viewCell").forEach(function(e){var n=e.$config.scrollX;if(n){var i=t.$ui.getView(n);i&&i.scrollTo(i.$config.scrollSize,0)}})})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Січень","Лютий","Березень","Квітень","Травень","Червень","Липень","Серпень","Вересень","Жовтень","Листопад","Грудень"],month_short:["Січ","Лют","Бер","Кві","Тра","Чер","Лип","Сер","Вер","Жов","Лис","Гру"],day_full:["Неділя","Понеділок","Вівторок","Середа","Четвер","П'ятниця","Субота"],day_short:["Нед","Пон","Вів","Сер","Чет","Птн","Суб"]},labels:{new_task:"Нове завдання",icon_save:"Зберегти",icon_cancel:"Відміна",icon_details:"Деталі",icon_edit:"Редагувати",icon_delete:"Вилучити",confirm_closing:"",confirm_deleting:"Подія вилучиться назавжди. Ви впевнені?",section_description:"Опис",section_time:"Часовий проміжок",section_type:"Тип",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Відміна",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"],month_short:["Oca","Şub","Mar","Nis","May","Haz","Tem","Ağu","Eyl","Eki","Kas","Ara"],day_full:["Pazar","Pazartesi","Salı","Çarşamba","Perşembe","Cuma","Cumartesi"],day_short:["Paz","Pzt","Sal","Çar","Per","Cum","Cmt"]},labels:{new_task:"Yeni görev",icon_save:"Kaydet",icon_cancel:"İptal",icon_details:"Detaylar",icon_edit:"Düzenle",icon_delete:"Sil",confirm_closing:"",confirm_deleting:"Görev silinecek, emin misiniz?",section_description:"Açıklama",section_time:"Zaman Aralığı",section_type:"Tip",column_wbs:"WBS",column_text:"Görev Adı",column_start_date:"Başlangıç",column_duration:"Süre",column_add:"",link:"Bağlantı",confirm_link_deleting:"silinecek",link_start:" (başlangıç)",link_end:" (bitiş)",type_task:"Görev",type_project:"Proje",type_milestone:"Kilometretaşı",minutes:"Dakika",hours:"Saat",days:"Gün",weeks:"Hafta",months:"Ay",years:"Yıl",message_ok:"OK",message_cancel:"Ýptal",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],month_short:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"],day_full:["Söndag","Måndag","Tisdag","Onsdag","Torsdag","Fredag","Lördag"],day_short:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"]},labels:{new_task:"Ny uppgift",icon_save:"Spara",icon_cancel:"Avbryt",icon_details:"Detajer",icon_edit:"Ändra",icon_delete:"Ta bort",confirm_closing:"",confirm_deleting:"Är du säker på att du vill ta bort händelsen permanent?",section_description:"Beskrivning",section_time:"Tid",section_type:"Typ",column_wbs:"WBS",column_text:"Uppgiftsnamn",column_start_date:"Starttid",column_duration:"Varaktighet",column_add:"",link:"Länk",confirm_link_deleting:"kommer tas bort",link_start:" (start)",link_end:" (slut)",type_task:"Uppgift",type_project:"Projekt",type_milestone:"Milstolpe",minutes:"Minuter",hours:"Timmar",days:"Dagar",weeks:"Veckor",months:"Månader",years:"År",message_ok:"OK",message_cancel:"Avbryt",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Január","Február","Marec","Apríl","Máj","Jún","Júl","August","September","Október","November","December"],month_short:["Jan","Feb","Mar","Apr","Máj","Jún","Júl","Aug","Sept","Okt","Nov","Dec"],day_full:["Nedeľa","Pondelok","Utorok","Streda","Štvrtok","Piatok","Sobota"],day_short:["Ne","Po","Ut","St","Št","Pi","So"]},labels:{new_task:"Nová úloha",icon_save:"Uložiť",icon_cancel:"Späť",icon_details:"Detail",icon_edit:"Edituj",icon_delete:"Zmazať",confirm_closing:"Vaše zmeny nebudú uložené. Skutočne?",confirm_deleting:"Udalosť bude natrvalo vymazaná. Skutočne?",section_description:"Poznámky",section_time:"Doba platnosti",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Späť",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Januar","Februar","Marec","April","Maj","Junij","Julij","Avgust","September","Oktober","November","December"],month_short:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"],day_full:["Nedelja","Ponedeljek","Torek","Sreda","Četrtek","Petek","Sobota"],day_short:["Ned","Pon","Tor","Sre","Čet","Pet","Sob"]},labels:{new_task:"Nova naloga",icon_save:"Shrani",icon_cancel:"Prekliči",icon_details:"Podrobnosti",icon_edit:"Uredi",icon_delete:"Izbriši",confirm_closing:"",confirm_deleting:"Dogodek bo izbrisan. Želite nadaljevati?",section_description:"Opis",section_time:"Časovni okvir",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Prekliči",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Январь","Февраль","Март","Апрель","Maй","Июнь","Июль","Август","Сентябрь","Oктябрь","Ноябрь","Декабрь"],month_short:["Янв","Фев","Maр","Aпр","Maй","Июн","Июл","Aвг","Сен","Окт","Ноя","Дек"],day_full:["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"],day_short:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]},labels:{new_task:"Новое задание",icon_save:"Сохранить",icon_cancel:"Отменить",icon_details:"Детали",icon_edit:"Изменить",icon_delete:"Удалить",confirm_closing:"",confirm_deleting:"Событие будет удалено безвозвратно, продолжить?",section_description:"Описание",section_time:"Период времени",section_type:"Тип",column_wbs:"ИСР",column_text:"Задача",column_start_date:"Начало",column_duration:"Длительность",column_add:"",link:"Связь",confirm_link_deleting:"будет удалена",link_start:" (начало)",link_end:" (конец)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Минута",hours:"Час",days:"День",weeks:"Неделя",months:"Месяц",years:"Год",message_ok:"OK",message_cancel:"Отменить",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"начните вводить слово для фильтрации",resources_filter_label:"спрятать не установленные"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Ianuarie","Februarie","Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","November","December"],month_short:["Ian","Feb","Mar","Apr","Mai","Iun","Iul","Aug","Sep","Oct","Nov","Dec"],day_full:["Duminica","Luni","Marti","Miercuri","Joi","Vineri","Sambata"],day_short:["Du","Lu","Ma","Mi","Jo","Vi","Sa"]},labels:{new_task:"Sarcina noua",icon_save:"Salveaza",icon_cancel:"Anuleaza",icon_details:"Detalii",icon_edit:"Editeaza",icon_delete:"Sterge",confirm_closing:"Schimbarile nu vor fi salvate, esti sigur?",confirm_deleting:"Evenimentul va fi sters permanent, esti sigur?",section_description:"Descriere",section_time:"Interval",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Anuleaza",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],month_short:["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],day_full:["Domingo","Segunda","Terça","Quarta","Quinta","Sexta","Sábado"],day_short:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"]},labels:{new_task:"Nova tarefa",icon_save:"Salvar",icon_cancel:"Cancelar",icon_details:"Detalhes",icon_edit:"Editar",icon_delete:"Excluir",confirm_closing:"",confirm_deleting:"As tarefas serão excluidas permanentemente, confirme?",section_description:"Descrição",section_time:"Período",section_type:"Tipo",column_wbs:"EAP",column_text:"Nome tarefa",column_start_date:"Data início",column_duration:"Duração",column_add:"",link:"Link",confirm_link_deleting:"Será excluído!",link_start:" (início)",link_end:" (fim)",type_task:"Task",type_project:"Projeto",type_milestone:"Marco",minutes:"Minutos",hours:"Horas",days:"Dias",weeks:"Semanas",months:"Meses",years:"Anos",message_ok:"OK",message_cancel:"Cancelar",section_constraint:"Restrição",constraint_type:"Tipo Restrição",constraint_date:"Data restrição",asap:"Mais breve possível",alap:"Mais tarde possível",snet:"Não começar antes de",snlt:"Não começar depois de",fnet:"Não terminar antes de",fnlt:"Não terminar depois de",mso:"Precisa começar em",mfo:"Precisa terminar em",resources_filter_placeholder:"Tipo de filtros",resources_filter_label:"Ocultar vazios"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień"],month_short:["Sty","Lut","Mar","Kwi","Maj","Cze","Lip","Sie","Wrz","Paź","Lis","Gru"],day_full:["Niedziela","Poniedziałek","Wtorek","Środa","Czwartek","Piątek","Sobota"],day_short:["Nie","Pon","Wto","Śro","Czw","Pią","Sob"]},labels:{new_task:"Nowe zadanie",icon_save:"Zapisz",icon_cancel:"Anuluj",icon_details:"Szczegóły",icon_edit:"Edytuj",icon_delete:"Usuń",confirm_closing:"",confirm_deleting:"Zdarzenie zostanie usunięte na zawsze, kontynuować?",section_description:"Opis",section_time:"Okres czasu",section_type:"Typ",column_wbs:"WBS",column_text:"Nazwa zadania",column_start_date:"Początek",column_duration:"Czas trwania",column_add:"",link:"Link",confirm_link_deleting:"zostanie usunięty",link_start:" (początek)",link_end:" (koniec)",type_task:"Zadanie",type_project:"Projekt",type_milestone:"Milestone",minutes:"Minuty",hours:"Godziny",days:"Dni",weeks:"Tydzień",months:"Miesiące",years:"Lata",message_ok:"OK",message_cancel:"Anuluj",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Januar","Februar","Mars","April","Mai","Juni","Juli","August","September","Oktober","November","Desember"],month_short:["Jan","Feb","Mar","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Des"],day_full:["Søndag","Mandag","Tirsdag","Onsdag","Torsdag","Fredag","Lørdag"],day_short:["Søn","Man","Tir","Ons","Tor","Fre","Lør"]},labels:{new_task:"Ny oppgave",icon_save:"Lagre",icon_cancel:"Avbryt",icon_details:"Detaljer",icon_edit:"Endre",icon_delete:"Slett",confirm_closing:"Endringer blir ikke lagret, er du sikker?",confirm_deleting:"Oppføringen vil bli slettet, er du sikker?",section_description:"Beskrivelse",section_time:"Tidsperiode",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Avbryt",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Januari","Februari","Maart","April","Mei","Juni","Juli","Augustus","September","Oktober","November","December"],month_short:["Jan","Feb","mrt","Apr","Mei","Jun","Jul","Aug","Sep","Okt","Nov","Dec"],day_full:["Zondag","Maandag","Dinsdag","Woensdag","Donderdag","Vrijdag","Zaterdag"],day_short:["Zo","Ma","Di","Wo","Do","Vr","Za"]},labels:{new_task:"Nieuwe taak",icon_save:"Opslaan",icon_cancel:"Annuleren",icon_details:"Details",icon_edit:"Bewerken",icon_delete:"Verwijderen",confirm_closing:"",confirm_deleting:"Item zal permanent worden verwijderd, doorgaan?",section_description:"Beschrijving",section_time:"Tijd periode",section_type:"Type",column_wbs:"WBS",column_text:"Taak omschrijving",column_start_date:"Startdatum",column_duration:"Duur",column_add:"",link:"Koppeling",confirm_link_deleting:"zal worden verwijderd",link_start:" (start)",link_end:" (eind)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"minuten",hours:"uren",days:"dagen",weeks:"weken",months:"maanden",years:"jaren",message_ok:"OK",message_cancel:"Annuleren",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Januar","Februar","Mars","April","Mai","Juni","Juli","August","September","Oktober","November","Desember"],month_short:["Jan","Feb","Mar","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Des"],day_full:["Søndag","Mandag","Tirsdag","Onsdag","Torsdag","Fredag","Lørdag"],day_short:["Søn","Mon","Tir","Ons","Tor","Fre","Lør"]},labels:{new_task:"Ny oppgave",icon_save:"Lagre",icon_cancel:"Avbryt",icon_details:"Detaljer",icon_edit:"Rediger",icon_delete:"Slett",confirm_closing:"",confirm_deleting:"Hendelsen vil bli slettet permanent. Er du sikker?",section_description:"Beskrivelse",section_time:"Tidsperiode",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Avbryt",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){return function(t){var e=this;for(var n in this.addLocale=function(t,n){e._locales[t]=n},this.getLocale=function(t){return e._locales[t]},this._locales={},t)this._locales[n]=t[n]}}();e.default=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],month_short:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],day_full:["일요일","월요일","화요일","수요일","목요일","금요일","토요일"],day_short:["일","월","화","수","목","금","토"]},labels:{new_task:"이름없는 작업",icon_save:"저장",icon_cancel:"취소",icon_details:"세부 사항",icon_edit:"수정",icon_delete:"삭제",confirm_closing:"",confirm_deleting:"작업을 삭제하시겠습니까?",section_description:"설명",section_time:"기간",section_type:"Type",column_wbs:"WBS",column_text:"작업명",column_start_date:"시작일",column_duration:"기간",column_add:"",link:"전제",confirm_link_deleting:"삭제 하시겠습니까?",link_start:" (start)",link_end:" (end)",type_task:"작업",type_project:"프로젝트",type_milestone:"마일스톤",minutes:"분",hours:"시간",days:"일",weeks:"주",months:"달",years:"년",message_ok:"OK",message_cancel:"취소",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],month_short:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],day_full:["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"],day_short:["日","月","火","水","木","金","土"]},labels:{new_task:"新しい仕事",icon_save:"保存",icon_cancel:"キャンセル",icon_details:"詳細",icon_edit:"編集",icon_delete:"削除",confirm_closing:"",confirm_deleting:"イベント完全に削除されます、宜しいですか?",section_description:"デスクリプション",section_time:"期間",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"キャンセル",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],month_short:["Gen","Feb","Mar","Apr","Mag","Giu","Lug","Ago","Set","Ott","Nov","Dic"],day_full:["Domenica","Lunedì","Martedì","Mercoledì","Giovedì","Venerdì","Sabato"],day_short:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"]},labels:{new_task:"Nuovo compito",icon_save:"Salva",icon_cancel:"Chiudi",icon_details:"Dettagli",icon_edit:"Modifica",icon_delete:"Elimina",confirm_closing:"",confirm_deleting:"Sei sicuro di confermare l'eliminazione?",section_description:"Descrizione",section_time:"Periodo di tempo",section_type:"Tipo",column_wbs:"WBS",column_text:"Nome Attività",column_start_date:"Inizio",column_duration:"Durata",column_add:"",link:"Link",confirm_link_deleting:"sarà eliminato",link_start:" (inizio)",link_end:" (fine)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minuti",hours:"Ore",days:"Giorni",weeks:"Settimane",months:"Mesi",years:"Anni",message_ok:"OK",message_cancel:"Chiudi",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"],month_short:["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Ags","Sep","Okt","Nov","Des"],day_full:["Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu"],day_short:["Ming","Sen","Sel","Rab","Kam","Jum","Sab"]},labels:{new_task:"Tugas baru",icon_save:"Simpan",icon_cancel:"Batal",icon_details:"Detail",icon_edit:"Edit",icon_delete:"Hapus",confirm_closing:"",confirm_deleting:"Acara akan dihapus",section_description:"Keterangan",section_time:"Periode",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Batal",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Január","Február","Március","Április","Május","Június","Július","Augusztus","Szeptember","Október","November","December"],month_short:["Jan","Feb","Már","Ápr","Máj","Jún","Júl","Aug","Sep","Okt","Nov","Dec"],day_full:["Vasárnap","Hétfõ","Kedd","Szerda","Csütörtök","Péntek","szombat"],day_short:["Va","Hé","Ke","Sze","Csü","Pé","Szo"]},labels:{new_task:"Új feladat",icon_save:"Mentés",icon_cancel:"Mégse",icon_details:"Részletek",icon_edit:"Szerkesztés",icon_delete:"Törlés",confirm_closing:"",confirm_deleting:"Az esemény törölve lesz, biztosan folytatja?",section_description:"Leírás",section_time:"Idõszak",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Mégse",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Siječanj","Veljača","Ožujak","Travanj","Svibanj","Lipanj","Srpanj","Kolovoz","Rujan","Listopad","Studeni","Prosinac"],month_short:["Sij","Velj","Ožu","Tra","Svi","Lip","Srp","Kol","Ruj","Lis","Stu","Pro"],day_full:["Nedjelja","Ponedjeljak","Utorak","Srijeda","Četvrtak","Petak","Subota"],day_short:["Ned","Pon","Uto","Sri","Čet","Pet","Sub"]},labels:{new_task:"Novi Zadatak",icon_save:"Spremi",icon_cancel:"Odustani",icon_details:"Detalji",icon_edit:"Izmjeni",icon_delete:"Obriši",confirm_closing:"",confirm_deleting:"Zadatak će biti trajno izbrisan, jeste li sigurni?",section_description:"Opis",section_time:"Vremenski Period",section_type:"Tip",column_wbs:"WBS",column_text:"Naziv Zadatka",column_start_date:"Početno Vrijeme",column_duration:"Trajanje",column_add:"",link:"Poveznica",confirm_link_deleting:"će biti izbrisan",link_start:" (početak)",link_end:" (kraj)",type_task:"Zadatak",type_project:"Projekt",type_milestone:"Milestone",minutes:"Minute",hours:"Sati",days:"Dani",weeks:"Tjedni",months:"Mjeseci",years:"Godine",message_ok:"OK",message_cancel:"Odustani",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],month_short:["ינו","פבר","מרץ","אפר","מאי","יונ","יול","אוג","ספט","אוק","נוב","דצמ"],day_full:["ראשון","שני","שלישי","רביעי","חמישי","שישי","שבת"],day_short:["א","ב","ג","ד","ה","ו","ש"]},labels:{new_task:"משימה חדש",icon_save:"שמור",icon_cancel:"בטל",icon_details:"פרטים",icon_edit:"ערוך",icon_delete:"מחק",confirm_closing:"",confirm_deleting:"ארוע ימחק סופית.להמשיך?",section_description:"הסבר",section_time:"תקופה",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"בטל",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"],month_short:["Jan","Fév","Mar","Avr","Mai","Juin","Juil","Aoû","Sep","Oct","Nov","Déc"],day_full:["Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"],day_short:["Dim","Lun","Mar","Mer","Jeu","Ven","Sam"]},labels:{new_task:"Nouvelle tâche",icon_save:"Enregistrer",icon_cancel:"Annuler",icon_details:"Détails",icon_edit:"Modifier",icon_delete:"Effacer",confirm_closing:"",confirm_deleting:"L'événement sera effacé sans appel, êtes-vous sûr ?",section_description:"Description",section_time:"Période",section_type:"Type",column_wbs:"OTP",column_text:"Nom de la tâche",column_start_date:"Date initiale",column_duration:"Durée",column_add:"",link:"Le lien",confirm_link_deleting:"sera supprimé",link_start:"(début)",link_end:"(fin)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Heures",days:"Jours",weeks:"Semaines",months:"Mois",years:"Années",message_ok:"OK",message_cancel:"Annuler",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Tammikuu","Helmikuu","Maaliskuu","Huhtikuu","Toukokuu","Kes&auml;kuu","Hein&auml;kuu","Elokuu","Syyskuu","Lokakuu","Marraskuu","Joulukuu"],month_short:["Tam","Hel","Maa","Huh","Tou","Kes","Hei","Elo","Syy","Lok","Mar","Jou"],day_full:["Sunnuntai","Maanantai","Tiistai","Keskiviikko","Torstai","Perjantai","Lauantai"],day_short:["Su","Ma","Ti","Ke","To","Pe","La"]},labels:{new_task:"Uusi tehtävä",icon_save:"Tallenna",icon_cancel:"Peru",icon_details:"Tiedot",icon_edit:"Muokkaa",icon_delete:"Poista",confirm_closing:"",confirm_deleting:"Haluatko varmasti poistaa tapahtuman?",section_description:"Kuvaus",section_time:"Aikajakso",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Peru",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["ژانویه","فوریه","مارس","آوریل","مه","ژوئن","ژوئیه","اوت","سپتامبر","اکتبر","نوامبر","دسامبر"],month_short:["1","2","3","4","5","6","7","8","9","10","11","12"],day_full:["يکشنبه","دوشنبه","سه‌شنبه","چهارشنبه","پنجشنبه","جمعه","شنبه"],day_short:["ی","د","س","چ","پ","ج","ش"]},labels:{new_task:"وظیفه جدید",icon_save:"ذخیره",icon_cancel:"لغو",icon_details:"جزییات",icon_edit:"ویرایش",icon_delete:"حذف",confirm_closing:"تغییرات شما ازدست خواهد رفت، آیا مطمئن هستید؟",confirm_deleting:"این مورد برای همیشه حذف خواهد شد، آیا مطمئن هستید؟",section_description:"توضیحات",section_time:"مدت زمان",section_type:"نوع",column_wbs:"WBS",column_text:"عنوان",column_start_date:"زمان شروع",column_duration:"مدت",column_add:"",link:"ارتباط",confirm_link_deleting:"حذف خواهد شد",link_start:" (آغاز)",link_end:" (پایان)",type_task:"وظیفه",type_project:"پروژه",type_milestone:"نگارش",minutes:"دقایق",hours:"ساعات",days:"روزها",weeks:"هفته",months:"ماه‌ها",years:"سال‌ها",message_ok:"تایید",message_cancel:"لغو",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],month_short:["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"],day_full:["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"],day_short:["Dom","Lun","Mar","Mié","Jue","Vie","Sáb"]},labels:{new_task:"Nueva tarea",icon_save:"Guardar",icon_cancel:"Cancelar",icon_details:"Detalles",icon_edit:"Editar",icon_delete:"Eliminar",confirm_closing:"",confirm_deleting:"El evento se borrará definitivamente, ¿continuar?",section_description:"Descripción",section_time:"Período",section_type:"Tipo",column_wbs:"EDT",column_text:"Tarea",column_start_date:"Inicio",column_duration:"Duración",column_add:"",link:"Enlace",confirm_link_deleting:"será borrada",link_start:" (inicio)",link_end:" (fin)",type_task:"Tarea",type_project:"Proyecto",type_milestone:"Hito",minutes:"Minutos",hours:"Horas",days:"Días",weeks:"Semanas",months:"Meses",years:"Años",message_ok:"OK",message_cancel:"Cancelar",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["January","February","March","April","May","June","July","August","September","October","November","December"],month_short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],day_full:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],day_short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},labels:{new_task:"New task",icon_save:"Save",icon_cancel:"Cancel",icon_details:"Details",icon_edit:"Edit",icon_delete:"Delete",confirm_closing:"",confirm_deleting:"Task will be deleted permanently, are you sure?",section_description:"Description",section_time:"Time period",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Cancel",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Ιανουάριος","Φεβρουάριος","Μάρτιος","Απρίλιος","Μάϊος","Ιούνιος","Ιούλιος","Αύγουστος","Σεπτέμβριος","Οκτώβριος","Νοέμβριος","Δεκέμβριος"],month_short:["ΙΑΝ","ΦΕΒ","ΜΑΡ","ΑΠΡ","ΜΑΙ","ΙΟΥΝ","ΙΟΥΛ","ΑΥΓ","ΣΕΠ","ΟΚΤ","ΝΟΕ","ΔΕΚ"],day_full:["Κυριακή","Δευτέρα","Τρίτη","Τετάρτη","Πέμπτη","Παρασκευή","Κυριακή"],day_short:["ΚΥ","ΔΕ","ΤΡ","ΤΕ","ΠΕ","ΠΑ","ΣΑ"]},labels:{new_task:"Νέα εργασία",icon_save:"Αποθήκευση",icon_cancel:"Άκυρο",icon_details:"Λεπτομέρειες",icon_edit:"Επεξεργασία",icon_delete:"Διαγραφή",confirm_closing:"",confirm_deleting:"Το έργο θα διαγραφεί οριστικά. Θέλετε να συνεχίσετε;",section_description:"Περιγραφή",section_time:"Χρονική περίοδος",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Άκυρο",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:[" Januar"," Februar"," März "," April"," Mai"," Juni"," Juli"," August"," September "," Oktober"," November "," Dezember"],month_short:["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],day_full:["Sonntag","Montag","Dienstag"," Mittwoch"," Donnerstag","Freitag","Samstag"],day_short:["So","Mo","Di","Mi","Do","Fr","Sa"]},labels:{new_task:"Neue Aufgabe",icon_save:"Speichern",icon_cancel:"Abbrechen",icon_details:"Details",icon_edit:"Ändern",icon_delete:"Löschen",confirm_closing:"",confirm_deleting:"Der Eintrag wird gelöscht",section_description:"Beschreibung",section_time:"Zeitspanne",section_type:"Type",column_wbs:"PSP",column_text:"Task-Namen",column_start_date:"Startzeit",column_duration:"Dauer",column_add:"",link:"Link",confirm_link_deleting:"werden gelöscht",link_start:"(starten)",link_end:"(ende)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minuten",hours:"Stunden",days:"Tage",weeks:"Wochen",months:"Monate",years:"Jahre",message_ok:"OK",message_cancel:"Abbrechen",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Januar","Februar","Marts","April","Maj","Juni","Juli","August","September","Oktober","November","December"],month_short:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"],day_full:["Søndag","Mandag","Tirsdag","Onsdag","Torsdag","Fredag","Lørdag"],day_short:["Søn","Man","Tir","Ons","Tor","Fre","Lør"]},labels:{new_task:"Ny opgave",icon_save:"Gem",icon_cancel:"Fortryd",icon_details:"Detaljer",icon_edit:"Tilret",icon_delete:"Slet",confirm_closing:"Dine rettelser vil gå tabt.. Er dy sikker?",confirm_deleting:"Bigivenheden vil blive slettet permanent. Er du sikker?",section_description:"Beskrivelse",section_time:"Tidsperiode",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Fortryd",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Leden","Únor","Březen","Duben","Květen","Červen","Červenec","Srpen","Září","Říjen","Listopad","Prosinec"],month_short:["Led","Ún","Bře","Dub","Kvě","Čer","Čec","Srp","Září","Říj","List","Pro"],day_full:["Neděle","Pondělí","Úterý","Středa","Čtvrtek","Pátek","Sobota"],day_short:["Ne","Po","Út","St","Čt","Pá","So"]},labels:{new_task:"Nová práce",icon_save:"Uložit",icon_cancel:"Zpět",icon_details:"Detail",icon_edit:"Edituj",icon_delete:"Smazat",confirm_closing:"",confirm_deleting:"Událost bude trvale smazána, opravdu?",section_description:"Poznámky",section_time:"Doba platnosti",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Zpět",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],month_short:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],day_full:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],day_short:["日","一","二","三","四","五","六"]},labels:{new_task:"新任務",icon_save:"保存",icon_cancel:"关闭",icon_details:"详细",icon_edit:"编辑",icon_delete:"删除",confirm_closing:"请确认是否撤销修改!",confirm_deleting:"是否删除日程?",section_description:"描述",section_time:"时间范围",section_type:"类型",column_wbs:"工作分解结构",column_text:"任务名",column_start_date:"开始时间",column_duration:"持续时间",column_add:"",link:"关联",confirm_link_deleting:"将被删除",link_start:" (开始)",link_end:" (结束)",type_task:"任务",type_project:"项目",type_milestone:"里程碑",minutes:"分钟",hours:"小时",days:"天",weeks:"周",months:"月",years:"年",message_ok:"OK",message_cancel:"关闭",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Gener","Febrer","Març","Abril","Maig","Juny","Juliol","Agost","Setembre","Octubre","Novembre","Desembre"],month_short:["Gen","Feb","Mar","Abr","Mai","Jun","Jul","Ago","Set","Oct","Nov","Des"],day_full:["Diumenge","Dilluns","Dimarts","Dimecres","Dijous","Divendres","Dissabte"],day_short:["Dg","Dl","Dm","Dc","Dj","Dv","Ds"]},labels:{new_task:"Nova tasca",icon_save:"Guardar",icon_cancel:"Cancel·lar",icon_details:"Detalls",icon_edit:"Editar",icon_delete:"Esborrar",confirm_closing:"",confirm_deleting:"L'esdeveniment s'esborrarà definitivament, continuar ?",section_description:"Descripció",section_time:"Periode de temps",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Cancel·lar",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["Студзень","Люты","Сакавік","Красавік","Maй","Чэрвень","Ліпень","Жнівень","Верасень","Кастрычнік","Лістапад","Снежань"],month_short:["Студз","Лют","Сак","Крас","Maй","Чэр","Ліп","Жнів","Вер","Каст","Ліст","Снеж"],day_full:["Нядзеля","Панядзелак","Аўторак","Серада","Чацвер","Пятніца","Субота"],day_short:["Нд","Пн","Аўт","Ср","Чцв","Пт","Сб"]},labels:{new_task:"Новае заданне",icon_save:"Захаваць",icon_cancel:"Адмяніць",icon_details:"Дэталі",icon_edit:"Змяніць",icon_delete:"Выдаліць",confirm_closing:"",confirm_deleting:"Падзея будзе выдалена незваротна, працягнуць?",section_description:"Апісанне",section_time:"Перыяд часу",section_type:"Тып",column_wbs:"ІСР",column_text:"Задача",column_start_date:"Пачатак",column_duration:"Працяг",column_add:"",link:"Сувязь",confirm_link_deleting:"будзе выдалена",link_start:"(пачатак)",link_end:"(канец)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Хвiлiна",hours:"Гадзiна",days:"Дзень",weeks:"Тыдзень",months:"Месяц",years:"Год",message_ok:"OK",message_cancel:"Адмяніць",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.default={date:{month_full:["كانون الثاني","شباط","آذار","نيسان","أيار","حزيران","تموز","آب","أيلول","تشرين الأول","تشرين الثاني","كانون الأول"],month_short:["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر"],day_full:["الأحد","الأثنين","ألثلاثاء","الأربعاء","ألحميس","ألجمعة","السبت"],day_short:["احد","اثنين","ثلاثاء","اربعاء","خميس","جمعة","سبت"]},labels:{new_task:"مهمة جديد",icon_save:"اخزن",icon_cancel:"الغاء",icon_details:"تفاصيل",icon_edit:"تحرير",icon_delete:"حذف",confirm_closing:"التغييرات سوف تضيع, هل انت متأكد؟",confirm_deleting:"الحدث سيتم حذفها نهائيا ، هل أنت متأكد؟",section_description:"الوصف",section_time:"الفترة الزمنية",section_type:"Type",column_wbs:"WBS",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"الغاء",section_constraint:"Constraint",constraint_type:"Constraint type",constraint_date:"Constraint date",asap:"As Soon As Possible",alap:"As Late As Possible",snet:"Start No Earlier Than",snlt:"Start No Later Than",fnet:"Finish No Earlier Than",fnlt:"Finish No Later Than",mso:"Must Start On",mfo:"Must Finish On",resources_filter_placeholder:"type to filter",resources_filter_label:"hide empty"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(151),r=n(150),a=n(149),o=n(148),s=n(147),l=n(146),c=n(145),u=n(144),d=n(143),h=n(142),f=n(141),_=n(140),g=n(139),p=n(138),v=n(137),m=n(136),y=n(135),k=n(134),b=n(133),w=n(132),x=n(131),$=n(130),S=n(129),T=n(128),C=n(127),E=n(126),D=n(125),A=n(124),M=n(123),I=n(122),N=n(121),P=n(120),L=n(119);e.default=function(){return new x.default({en:d.default,ar:i.default,be:r.default,ca:a.default,cn:o.default,cs:s.default,da:l.default,de:c.default,el:u.default,es:h.default,fa:f.default,fi:_.default,fr:g.default,he:p.default,hr:v.default,hu:m.default,id:y.default,it:k.default,jp:b.default,kr:w.default,nb:$.default,nl:S.default,no:T.default,pl:C.default,pt:E.default,ro:D.default,ru:A.default,si:M.default,sk:I.default,sv:N.default,tr:P.default,ua:L.default})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(){}},function(t,e){t.exports=function(t){t.destructor=function(){for(var t in this.clearAll(),this.callEvent("onDestroy",[]),this.$root&&delete this.$root.gantt,this._eventRemoveAll&&this._eventRemoveAll(),this.$layout&&this.$layout.destructor(),this.resetLightbox&&this.resetLightbox(),this._dp&&this._dp.destructor&&this._dp.destructor(),this.$services.destructor(),this.detachAllEvents(),this)0===t.indexOf("$")&&delete this[t];this.$destroyed=!0}}},function(t,e){t.exports=function(t){return function(e,n){e||t.config.show_errors&&!1!==t.callEvent("onError",[n])&&(t.message?t.message({type:"error",text:n,expire:-1}):console.log(n))}}},function(t,e){function n(t,e){var n,i=t.config.container_resize_timeout||20;if("timeout"==t.config.container_resize_method)s();else try{t.event(e,"resize",function(){t.$scrollbarRepaint?t.$scrollbarRepaint=null:r()})}catch(t){s()}function r(){clearTimeout(n),n=setTimeout(function(){t.$destroyed||t.render()},i)}var a=t.$root.offsetHeight,o=t.$root.offsetWidth;function s(){t.$root.offsetHeight==a&&t.$root.offsetWidth==o||r(),a=t.$root.offsetHeight,o=t.$root.offsetWidth,setTimeout(s,i)}}t.exports=function(t){"static"==window.getComputedStyle(t.$root).getPropertyValue("position")&&(t.$root.style.position="relative");var e=document.createElement("iframe");e.className="gantt_container_resize_watcher",e.tabIndex=-1,t.config.wai_aria_attributes&&(e.setAttribute("role","none"),e.setAttribute("aria-hidden",!0)),(!!window.Sfdc||!!window.$A||window.Aura)&&(t.config.container_resize_method="timeout"),t.$root.appendChild(e),e.contentWindow?n(t,e.contentWindow):(t.$root.removeChild(e),n(t,window))}},function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var r=n(1),a=n(2),o=n(10),s=n(156);t.exports=function(t){var e=n(37);t.assert=n(155)(t);var l="Invalid value of the first argument of `gantt.init`. Supported values: HTMLElement, String (element id).This error means that either invalid object is passed into `gantt.init` or that the element with the specified ID doesn't exist on the page when `gantt.init` is called.";function c(e){if(!e||"string"==typeof e&&document.getElementById(e))return!0;if(function(t){try{t.cloneNode(!1)}catch(t){return!1}return!0}(e))return!0;throw t.assert(!1,l),new Error(l)}t.init=function(e,n,i){t.env.isNode?e=null:c(e),n&&i&&(this.config.start_date=this._min_date=new Date(n),this.config.end_date=this._max_date=new Date(i)),this.date.init(),this.init=function(e){t.env.isNode?e=null:c(e),this.$container&&this.$container.parentNode&&(this.$container.parentNode.removeChild(this.$container),this.$container=null),this.$layout&&this.$layout.clear(),this._reinit(e)},this._reinit(e)},t._quickRefresh=function(t){for(var e=this._getDatastores.call(this),n=0;n<e.length;n++)e[n]._quick_refresh=!0;t();for(n=0;n<e.length;n++)e[n]._quick_refresh=!1};var u=function(){this._clearTaskLayers&&this._clearTaskLayers(),this._clearLinkLayers&&this._clearLinkLayers(),this.$layout&&(this.$layout.destructor(),this.$layout=null,this.$ui.reset())}.bind(t),d=function(){o(t)||(this.$root.innerHTML="",this.$root.gantt=this,e(this),this.config.layout.id="main",this.$layout=this.$ui.createView("layout",this.$root,this.config.layout),this.$layout.attachEvent("onBeforeResize",function(){for(var e=t.$services.getService("datastores"),n=0;n<e.length;n++)t.getDatastore(e[n]).filter(),t.getDatastore(e[n]).callEvent("onBeforeRefreshAll",[])}),this.$layout.attachEvent("onResize",function(){t._quickRefresh(function(){t.refreshData()})}),this.callEvent("onGanttLayoutReady",[]),this.$layout.render(),this.$container=this.$layout.$container.firstChild,s(this))}.bind(t);t.resetLayout=function(){u(),d(),this.render()},t._reinit=function(t){this.callEvent("onBeforeGanttReady",[]),this._update_flags(),this.$services.getService("templateLoader").initTemplates(this),u(),this.$root=null,t&&(this.$root=r.toNode(t),d(),this.$mouseEvents.reset(this.$root)),this.callEvent("onTemplatesReady",[]),this.callEvent("onGanttReady",[]),this.render()},t.$click={buttons:{edit:function(e){t.isReadonly(t.getTask(e))||t.showLightbox(e)},delete:function(e){var n=t.getTask(e);if(!t.isReadonly(n)){var i=t.locale.labels.confirm_deleting,r=t.locale.labels.confirm_deleting_title;t._dhtmlx_confirm(i,r,function(){t.isTaskExists(e)?(n.$new?(t.silent(function(){t.deleteTask(e,!0)}),t.refreshData()):t.deleteTask(e),t.hideLightbox()):t.hideLightbox()})}}}},t.render=function(){var n;if(this.callEvent("onBeforeGanttRender",[]),!o(t)){!this.config.sort&&this._sort&&(this._sort=void 0),this.$root&&(this.config.rtl?(this.$root.classList.add("gantt_rtl"),this.$root.firstChild.classList.add("gantt_rtl")):(this.$root.classList.remove("gantt_rtl"),this.$root.firstChild.classList.remove("gantt_rtl")));var i=this.getScrollState(),r=i?i.x:0;if(this._getHorizontalScrollbar())r=this._getHorizontalScrollbar().$config.codeScrollLeft||r||0;n=null,r&&(n=t.dateFromPos(r+this.config.task_scroll_offset))}if(e(this),o(t))t.refreshData();else{this.$layout.$config.autosize=this.config.autosize;var a=this.config.preserve_scroll;if(this.config.preserve_scroll=!1,this.$layout.resize(),this.config.preserve_scroll=a,this.config.preserve_scroll&&i&&r){var s=t.getScrollState();if(+n!=+t.dateFromPos(s.x)||s.y!=i.y){r=null;var l=null;if(n)r=Math.max(t.posFromDate(n)-t.config.task_scroll_offset,0);i.y&&(l=i.y),t.scrollTo(r,l)}}}this.callEvent("onGanttRender",[])},t.setSizes=t.render,t.getTaskRowNode=function(t){for(var e=this.$grid_data.childNodes,n=this.config.task_attribute,i=0;i<e.length;i++){if(e[i].getAttribute)if(e[i].getAttribute(n)==t)return e[i]}return null},t.changeLightboxType=function(e){if(this.getLightboxType()==e)return!0;t._silent_redraw_lightbox(e)},t._get_link_type=function(e,n){var i=null;return e&&n?i=t.config.links.start_to_start:!e&&n?i=t.config.links.finish_to_start:e||n?e&&!n&&(i=t.config.links.start_to_finish):i=t.config.links.finish_to_finish,i},t.isLinkAllowed=function(t,e,n,r){var a=null;if(!(a="object"==i(t)?t:{source:t,target:e,type:this._get_link_type(n,r)}))return!1;if(!(a.source&&a.target&&a.type))return!1;if(a.source==a.target)return!1;var o=!0;return this.checkEvent("onLinkValidation")&&(o=this.callEvent("onLinkValidation",[a])),o},t._correct_dst_change=function(e,n,i,r){var o=a.getSecondsInUnit(r)*i;if(o>3600&&o<86400){var s=e.getTimezoneOffset()-n;s&&(e=t.date.add(e,s,"minute"))}return e},t.isSplitTask=function(e){return t.assert(e&&e instanceof Object,"Invalid argument <b>task</b>="+e+" of gantt.isSplitTask. Task object was expected"),this.$data.tasksStore._isSplitItem(e)},t._is_icon_open_click=function(t){if(!t)return!1;var e=t.target||t.srcElement;if(!e||!e.className)return!1;var n=r.getClassName(e);return-1!==n.indexOf("gantt_tree_icon")&&(-1!==n.indexOf("gantt_close")||-1!==n.indexOf("gantt_open"))}}},function(t,e){t.exports=function(t){function e(){return t._cached_functions.update_if_changed(t),t._cached_functions.active||t._cached_functions.activate(),!0}t._cached_functions={cache:{},mode:!1,critical_path_mode:!1,wrap_methods:function(t,e){if(e._prefetch_originals)for(var n in e._prefetch_originals)e[n]=e._prefetch_originals[n];e._prefetch_originals={};for(n=0;n<t.length;n++)this.prefetch(t[n],e)},prefetch:function(t,e){var n=e[t];if(n){var i=this;e._prefetch_originals[t]=n,e[t]=function(){for(var e=new Array(arguments.length),r=0,a=arguments.length;r<a;r++)e[r]=arguments[r];if(i.active){var o=i.get_arguments_hash(Array.prototype.slice.call(e));i.cache[t]||(i.cache[t]={});var s=i.cache[t];if(i.has_cached_value(s,o))return i.get_cached_value(s,o);var l=n.apply(this,e);return i.cache_value(s,o,l),l}return n.apply(this,e)}}return n},cache_value:function(t,e,n){this.is_date(n)&&(n=new Date(n)),t[e]=n},has_cached_value:function(t,e){return t.hasOwnProperty(e)},get_cached_value:function(t,e){var n=t[e];return this.is_date(n)&&(n=new Date(n)),n},is_date:function(t){return t&&t.getUTCDate},get_arguments_hash:function(t){for(var e=[],n=0;n<t.length;n++)e.push(this.stringify_argument(t[n]));return"("+e.join(";")+")"},stringify_argument:function(t){return(t.id?t.id:this.is_date(t)?t.valueOf():t)+""},activate:function(){this.clear(),this.active=!0},deactivate:function(){this.clear(),this.active=!1},clear:function(){this.cache={}},setup:function(t){var e=[],n=["_isProjectEnd","_getProjectEnd","_getSlack"];"auto"==this.mode?t.config.highlight_critical_path&&(e=n):!0===this.mode&&(e=n),this.wrap_methods(e,t)},update_if_changed:function(t){(this.critical_path_mode!=t.config.highlight_critical_path||this.mode!==t.config.optimize_render)&&(this.critical_path_mode=t.config.highlight_critical_path,this.mode=t.config.optimize_render,this.setup(t))}},t.attachEvent("onBeforeGanttRender",e),t.attachEvent("onBeforeDataRender",e),t.attachEvent("onBeforeSmartRender",function(){e()}),t.attachEvent("onBeforeParse",e),t.attachEvent("onDataRender",function(){t._cached_functions.deactivate()});var n=null;t.attachEvent("onSmartRender",function(){n&&clearTimeout(n),n=setTimeout(function(){t._cached_functions.deactivate()},1e3)}),t.attachEvent("onBeforeGanttReady",function(){return t._cached_functions.update_if_changed(t),!0})}},function(t,e){function n(t){"@babel/helpers - typeof";return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}t.exports=function(t){t.getTaskType=function(e){var i=e;for(var r in e&&"object"==n(e)&&(i=e.type),this.config.types)if(this.config.types[r]==i)return i;return t.config.types.task}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(){}},function(t,e,n){var i=n(2);t.exports=function(t){t.isUnscheduledTask=function(e){return t.assert(e&&e instanceof Object,"Invalid argument <b>task</b>="+e+" of gantt.isUnscheduledTask. Task object was expected"),!!e.unscheduled||!e.start_date},t._isAllowedUnscheduledTask=function(e){return!(!e.unscheduled||!t.config.show_unscheduled)},t._isTaskInTimelineLimits=function(t){var e=t.start_date?t.start_date.valueOf():null,n=t.end_date?t.end_date.valueOf():null;return!!(e&&n&&e<=this._max_date.valueOf()&&n>=this._min_date.valueOf())},t.isTaskVisible=function(t){if(!this.isTaskExists(t))return!1;var e=this.getTask(t);return!(!this._isAllowedUnscheduledTask(e)&&!this._isTaskInTimelineLimits(e))&&!!(this.getGlobalTaskIndex(t)>=0)},t._getProjectEnd=function(){if(t.config.project_end)return t.config.project_end;var e=t.getTaskByTime();return(e=e.sort(function(t,e){return+t.end_date>+e.end_date?1:-1})).length?e[e.length-1].end_date:null},t._getProjectStart=function(){if(t.config.project_start)return t.config.project_start;if(t.config.start_date)return t.config.start_date;if(t.getState().min_date)return t.getState().min_date;var e=t.getTaskByTime();return(e=e.sort(function(t,e){return+t.start_date>+e.start_date?1:-1})).length?e[0].start_date:null};var e=function(e,n){var i=!(!n||n==t.config.root_id)&&t.getTask(n),r=null;if(i)r=t.config.schedule_from_end?t.calculateEndDate({start_date:i.end_date,duration:-t.config.duration_step,task:e}):i.start_date;else if(t.config.schedule_from_end)r=t.calculateEndDate({start_date:t._getProjectEnd(),duration:-t.config.duration_step,task:e});else{var a=t.getTaskByIndex(0);r=a?a.start_date?a.start_date:a.end_date?t.calculateEndDate({start_date:a.end_date,duration:-t.config.duration_step,task:e}):null:t.config.start_date||t.getState().min_date}return t.assert(r,"Invalid dates"),new Date(r)};t._set_default_task_timing=function(n){n.start_date=n.start_date||e(n,t.getParent(n)),n.duration=n.duration||t.config.duration_step,n.end_date=n.end_date||t.calculateEndDate(n)},t.createTask=function(n,i,r){(n=n||{},t.defined(n.id)||(n.id=t.uid()),n.start_date||(n.start_date=e(n,i)),void 0===n.text&&(n.text=t.locale.labels.new_task),void 0===n.duration&&(n.duration=1),this.isTaskExists(i))&&(this.setParent(n,i,!0),this.getTask(i).$open=!0);if(!this.callEvent("onTaskCreated",[n]))return null;if(this.config.details_on_create){if(t.isTaskExists(n.id))t.getTask(n.id).$index!=n.$index&&(n.start_date&&"string"==typeof n.start_date&&(n.start_date=this.date.parseDate(n.start_date,"parse_date")),n.end_date&&"string"==typeof n.end_date&&(n.end_date=this.date.parseDate(n.end_date,"parse_date")),this.$data.tasksStore.updateItem(n.id,n));else n.$new=!0,this.silent(function(){t.$data.tasksStore.addItem(n,r)});this.selectTask(n.id),this.refreshData(),this.showLightbox(n.id)}else this.addTask(n,i,r)&&(this.showTask(n.id),this.selectTask(n.id));return n.id},t._update_flags=function(e,n){var i=t.$data.tasksStore;void 0===e?(this._lightbox_id=null,i.silent(function(){i.unselect()}),this._tasks_dnd&&this._tasks_dnd.drag&&(this._tasks_dnd.drag.id=null)):(this._lightbox_id==e&&(this._lightbox_id=n),i.getSelectedId()==e&&i.silent(function(){i.unselect(e),i.select(n)}),this._tasks_dnd&&this._tasks_dnd.drag&&this._tasks_dnd.drag.id==e&&(this._tasks_dnd.drag.id=n))};var n=function(e,n){var i=t.getTaskType(e.type),r={type:i,$no_start:!1,$no_end:!1};return n||i!=e.$rendered_type?(i==t.config.types.project?r.$no_end=r.$no_start=!0:i!=t.config.types.milestone&&(r.$no_end=!(e.end_date||e.duration),r.$no_start=!e.start_date,t._isAllowedUnscheduledTask(e)&&(r.$no_end=r.$no_start=!1)),r):(r.$no_start=e.$no_start,r.$no_end=e.$no_end,r)};function r(e){e.$effective_calendar=t.getTaskCalendar(e).id,e.start_date=t.getClosestWorkTime({dir:"future",date:e.start_date,unit:t.config.duration_unit,task:e}),e.end_date=t.calculateEndDate(e)}function a(e){var n=null,i=null,r=void 0!==e?e:t.config.root_id,a=[];return t.eachTask(function(e){t.getTaskType(e.type)==t.config.types.project||t.isUnscheduledTask(e)||(e.rollup&&a.push(e.id),e.start_date&&!e.$no_start&&(!n||n>e.start_date.valueOf())&&(n=e.start_date.valueOf()),e.end_date&&!e.$no_end&&(!i||i<e.end_date.valueOf())&&(i=e.end_date.valueOf()))},r),{start_date:n?new Date(n):null,end_date:i?new Date(i):null,rollup:a}}t._init_task_timing=function(t){var e=n(t,!0),i=t.$rendered_type!=e.type,a=e.type;i&&(t.$no_start=e.$no_start,t.$no_end=e.$no_end,t.$rendered_type=e.type),i&&a!=this.config.types.milestone&&a==this.config.types.project&&(this._set_default_task_timing(t),t.$calculate_duration=!1),a==this.config.types.milestone&&(t.end_date=t.start_date),t.start_date&&t.end_date&&!1!==t.$calculate_duration&&(t.duration=this.calculateDuration(t)),t.$calculate_duration||(t.$calculate_duration=!0),t.end_date||(t.end_date=t.start_date),t.duration=t.duration||0,0===this.config.min_duration&&0===t.duration&&(t.$no_end=!1);var o=this.getTaskCalendar(t);t.$effective_calendar&&t.$effective_calendar!==o.id&&(r(t),this.config.inherit_calendar&&this.isSummaryTask(t)&&this.eachTask(function(t){r(t)},t.id)),t.$effective_calendar=o.id},t.isSummaryTask=function(e){t.assert(e&&e instanceof Object,"Invalid argument <b>task</b>="+e+" of gantt.isSummaryTask. Task object was expected");var i=n(e);return!(!i.$no_end&&!i.$no_start)},t.resetProjectDates=function(t){var i=n(t);if(i.$no_end||i.$no_start){var r=a(t.id);(function(t,n,i,r){n.$no_start&&(t.start_date=i?new Date(i):e(t,this.getParent(t)));n.$no_end&&(t.end_date=r?new Date(r):this.calculateEndDate({start_date:t.start_date,duration:this.config.duration_step,task:t}));(n.$no_start||n.$no_end)&&this._init_task_timing(t)}).call(this,t,i,r.start_date,r.end_date),t.$rollup=r.rollup}},t.getSubtaskDuration=function(e){var n=0,i=void 0!==e?e:t.config.root_id;return this.eachTask(function(e){this.getTaskType(e.type)==t.config.types.project||this.isUnscheduledTask(e)||(n+=e.duration)},i),n},t.getSubtaskDates=function(t){var e=a(t);return{start_date:e.start_date,end_date:e.end_date}},t._update_parents=function(e,i,r){if(e){var a=this.getTask(e);a.rollup&&(r=!0);var o=this.getParent(a),s=n(a),l=!0;if(r||a.start_date&&a.end_date&&(s.$no_start||s.$no_end)){var c=a.start_date.valueOf(),u=a.end_date.valueOf();t.resetProjectDates(a),r||c!=a.start_date.valueOf()||u!=a.end_date.valueOf()||(l=!1),l&&!i&&this.refreshTask(a.id,!0)}l&&o&&this.isTaskExists(o)&&this._update_parents(o,i,r)}},t.roundDate=function(e){var n=t.getScale();i.isDate(e)&&(e={date:e,unit:n?n.unit:t.config.duration_unit,step:n?n.step:t.config.duration_step});var r,a,o,s=e.date,l=e.step,c=e.unit;if(!n)return s;if(c==n.unit&&l==n.step&&+s>=+n.min_date&&+s<=+n.max_date)o=Math.floor(t.columnIndexByDate(s)),n.trace_x[o]||(o-=1,n.rtl&&(o=0)),a=new Date(n.trace_x[o]),r=t.date.add(a,l,c);else{for(o=Math.floor(t.columnIndexByDate(s)),r=t.date[c+"_start"](new Date(n.min_date)),n.trace_x[o]&&(r=t.date[c+"_start"](n.trace_x[o]));+r<+s;){var u=(r=t.date[c+"_start"](t.date.add(r,l,c))).getTimezoneOffset();r=t._correct_dst_change(r,u,r,c),t.date[c+"_start"]&&(r=t.date[c+"_start"](r))}a=t.date.add(r,-1*l,c)}return e.dir&&"future"==e.dir?r:e.dir&&"past"==e.dir?a:Math.abs(s-a)<Math.abs(r-s)?a:r},t.correctTaskWorkTime=function(e){t.config.work_time&&t.config.correct_work_time&&(this.isWorkTime(e.start_date,void 0,e)?this.isWorkTime(new Date(+e.end_date-1),void 0,e)||(e.end_date=this.calculateEndDate(e)):(e.start_date=this.getClosestWorkTime({date:e.start_date,dir:"future",task:e}),e.end_date=this.calculateEndDate(e)))},t.attachEvent("onBeforeTaskUpdate",function(e,n){return t._init_task_timing(n),!0}),t.attachEvent("onBeforeTaskAdd",function(e,n){return t._init_task_timing(n),!0}),t.attachEvent("onAfterTaskMove",function(e,n,i){return t._init_task_timing(t.getTask(e)),!0})}},function(t,e,n){var i=n(0);t.exports={create:function(t,e){return{getWorkHours:function(t){return e.getWorkHours(t)},setWorkTime:function(t){return e.setWorkTime(t)},unsetWorkTime:function(t){e.unsetWorkTime(t)},isWorkTime:function(t,n,i){return e.isWorkTime(t,n,i)},getClosestWorkTime:function(t){return e.getClosestWorkTime(t)},calculateDuration:function(t,n,i){return e.calculateDuration(t,n,i)},_hasDuration:function(t,n,i){return e.hasDuration(t,n,i)},calculateEndDate:function(t,n,i,r){return e.calculateEndDate(t,n,i,r)},mergeCalendars:i.bind(t.mergeCalendars,t),createCalendar:i.bind(t.createCalendar,t),addCalendar:i.bind(t.addCalendar,t),getCalendar:i.bind(t.getCalendar,t),getCalendars:i.bind(t.getCalendars,t),getResourceCalendar:i.bind(t.getResourceCalendar,t),getTaskCalendar:i.bind(t.getTaskCalendar,t),deleteCalendar:i.bind(t.deleteCalendar,t)}}}},function(t,e){function n(t,e){this.argumentsHelper=e,this.$gantt=t}n.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){return this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments).date},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,i=t.unit,r=t.step;return this._calculateDuration(e,n,i,r)},_calculateDuration:function(t,e,n,i){var r=this.$gantt.date,a={week:6048e5,day:864e5,hour:36e5,minute:6e4},o=0;if(a[n])o=Math.round((e-t)/(i*a[n]));else{for(var s=new Date(t),l=new Date(e);s.valueOf()<l.valueOf();)o+=1,s=r.add(s,i,n);s.valueOf()!=e.valueOf()&&(o+=(l-s)/(r.add(s,i,n)-s))}return Math.round(o)},hasDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date;return!!t.unit&&(e=new Date(e),n=new Date(n),e.valueOf()<n.valueOf())},hasWorkTime:function(){return!0},equals:function(t){return t instanceof n},calculateEndDate:function(){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.duration,i=t.unit,r=t.step;return this.$gantt.date.add(e,r*n,i)}},t.exports=n},function(t,e,n){var i=n(33),r=n(163);function a(t){this.$gantt=t.$gantt,this.argumentsHelper=i(this.$gantt),this.calendarManager=t,this.$disabledCalendar=new r(this.$gantt,this.argumentsHelper)}a.prototype={_getCalendar:function(t){var e;if(this.$gantt.config.work_time){var n=this.calendarManager;t.task?e=n.getTaskCalendar(t.task):t.id?e=n.getTaskCalendar(t):t.calendar&&(e=t.calendar),e||(e=n.getTaskCalendar())}else e=this.$disabledCalendar;return e},getWorkHours:function(t){return t=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments),this._getCalendar(t).getWorkHours(t.date)},setWorkTime:function(t,e){return t=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),e||(e=this.calendarManager.getCalendar()),e.setWorkTime(t)},unsetWorkTime:function(t,e){return t=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),e||(e=this.calendarManager.getCalendar()),e.unsetWorkTime(t)},isWorkTime:function(t,e,n,i){var r=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getCalendar(r).isWorkTime(r)},getClosestWorkTime:function(t){return t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments),this._getCalendar(t).getClosestWorkTime(t)},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);return this._getCalendar(t).calculateDuration(t)},hasDuration:function(){var t=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments);return this._getCalendar(t).hasDuration(t)},calculateEndDate:function(t){t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments);return this._getCalendar(t).calculateEndDate(t)}},t.exports=a},function(t,e){t.exports=function(){var t={};return{getCalendarIdFromMultipleResources:function(e,n){var i=function(t){return t.map(function(t){return t&&t.resource_id?t.resource_id:t}).sort().join("-")}(e);if(e.length){if(1===e.length)return n.getResourceCalendar(i).id;if(t[i])return t[i].id;var r=function(t,e){return e.mergeCalendars(t.map(function(t){var n=t&&t.resource_id?t.resource_id:t;return e.getResourceCalendar(n)}))}(e,n);return t[i]=r,n.addCalendar(r)}return null}}}},function(t,e){function n(t){"@babel/helpers - typeof";return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}t.exports={isLegacyResourceCalendarFormat:function(t){if(!t)return!1;for(var e in t)if(t[e]&&"object"===n(t[e]))return!0;return!1},getResourceProperty:function(t){var e=t.resource_calendars,n=t.resource_property;if(this.isLegacyResourceCalendarFormat(e))for(var i in t){n=i;break}return n},getCalendarIdFromLegacyConfig:function(t,e){if(e)for(var n in e){var i=e[n];if(t[n]){var r=i[t[n]];if(r)return r}}return null}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(){this.clear()}return t.prototype._getCacheObject=function(t,e,n){var i=this._cache;i[e]||(i[e]=[]);var r=i[e];r||(r=i[e]={});var a=r[n];a||(a=r[n]={});var o=t.getFullYear(),s=a[o];return s||(s=a[o]={durations:{},endDates:{}}),s},t.prototype._endDateCacheKey=function(t,e){return String(t)+"-"+String(e)},t.prototype._durationCacheKey=function(t,e){return String(t)+"-"+String(e)},t.prototype.getEndDate=function(t,e,n,i,r){var a,o=this._getCacheObject(t,n,i),s=t.valueOf(),l=this._endDateCacheKey(s,e);if(void 0===o.endDates[l]){var c=r(),u=c.valueOf();o.endDates[l]=u,o.durations[this._durationCacheKey(s,u)]=e,a=c}else a=new Date(o.endDates[l]);return a},t.prototype.getDuration=function(t,e,n,i,r){var a,o=this._getCacheObject(t,n,i),s=t.valueOf(),l=e.valueOf(),c=this._durationCacheKey(s,l);if(void 0===o.durations[c]){var u=r();o.durations[c]=u.valueOf(),a=u}else a=o.durations[c];return a},t.prototype.clear=function(){this._cache={}},t}();e.DateDurationCache=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){return function(t){var e=this;this.getMinutesPerWeek=function(t){var n=t.valueOf();if(e._weekCache.has(n))return e._weekCache.get(n);for(var i=e._calendar,r=e._calendar.$gantt,a=0,o=r.date.week_start(new Date(t)),s=0;s<7;s++)a+=60*i.getHoursPerDay(o),o=r.date.add(o,1,"day");return e._weekCache.set(n,a),a},this.getMinutesPerMonth=function(t){var n=t.valueOf();if(e._monthCache.has(n))return e._monthCache.get(n);for(var i=e._calendar,r=e._calendar.$gantt,a=0,o=r.date.week_start(new Date(t)),s=r.date.add(o,1,"month").valueOf();o.valueOf()<s;)a+=60*i.getHoursPerDay(o),o=r.date.add(o,1,"day");return e._monthCache.set(n,a),a},this.clear=function(){e._weekCache=new Map,e._monthCache=new Map},this.clear(),this._calendar=t}}();e.LargerUnitsCache=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(){this.clear()}return t.prototype.getItem=function(t,e,n){var i=this._cache;if(i&&i[t]){var r=i[t];if(void 0===r)return-1;var a=r[n.getFullYear()];if(a&&void 0!==a[e])return a[e]}return-1},t.prototype.setItem=function(t,e,n,i){if(t&&e){var r=this._cache;if(r){r[t]||(r[t]=[]);var a=r[t],o=i.getFullYear(),s=a[o];s||(s=a[o]={}),s[e]=n}}},t.prototype.clear=function(){this._cache={}},t}();e.WorkUnitsObjectCache=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(){this.clear()}return t.prototype.getItem=function(t,e,n){if(this._cache.has(t)){var i=this._cache.get(t)[n.getFullYear()];if(i&&i.has(e))return i.get(e)}return-1},t.prototype.setItem=function(t,e,n,i){if(t&&e){var r,a=this._cache,o=i.getFullYear();a.has(t)?r=a.get(t):(r=[],a.set(t,r));var s=r[o];s||(s=r[o]=new Map),s.set(e,n)}},t.prototype.clear=function(){this._cache=new Map},t}();e.WorkUnitsMapCache=i},function(t,e,n){var i=n(32).createCacheObject,r=n(32).LargerUnitsCache,a=n(0),o=n(167).DateDurationCache;function s(t,e){this.argumentsHelper=e,this.$gantt=t,this._workingUnitsCache=i(),this._largeUnitsCache=new r(this),this._dateDurationCache=new o,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}s.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(t){for(var e=0,n=this.units.length;e<n;e++)if(this.units[e]==t)return e},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(t){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var e=null;if(t.day||0===t.day)e=t.day;else if(t.date){var n=String(t.date.valueOf());this._cached_timestamps[n]?e=this._cached_timestamps[n]:(e=Date.UTC(t.date.getFullYear(),t.date.getMonth(),t.date.getDate()),this._cached_timestamps[n]=e,this._cached_timestamps_count++)}return e},_checkIfWorkingUnit:function(t,e){return!this["_is_work_"+e]||this["_is_work_"+e](t)},_is_work_day:function(t){var e=this._getWorkHours(t);return!!Array.isArray(e)&&e.length>0},_is_work_hour:function(t){for(var e=this._getWorkHours(t),n=t.getHours(),i=0;i<e.length;i++)if(n>=e[i].startHour&&n<e[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(t,e){var n=t.getHours();return t.getHours()||t.getMinutes()||!e||(n=24),60*n*60+60*t.getMinutes()},_is_work_minute:function(t){for(var e=this._getWorkHours(t),n=this._getTimeOfDayStamp(t),i=0;i<e.length;i++)if(n>=e[i].start&&n<e[i].end)return!0;return!1},_nextDate:function(t,e,n){return this.$gantt.date.add(t,n,e)},_getWorkUnitsBetweenGeneric:function(t,e,n,i){var r=this.$gantt.date,a=new Date(t),o=new Date(e);i=i||1;var s,l,c=0,u=null,d=!1;(s=r[n+"_start"](new Date(a))).valueOf()!=a.valueOf()&&(d=!0);var h=!1;(l=r[n+"_start"](new Date(e))).valueOf()!=e.valueOf()&&(h=!0);for(var f=!1;a.valueOf()<o.valueOf();){if(f=(u=this._nextDate(a,n,i)).valueOf()>o.valueOf(),this._isWorkTime(a,n))(d||h&&f)&&(s=r[n+"_start"](new Date(a)),l=r.add(s,i,n)),d?(d=!1,u=this._nextDate(s,n,i),c+=(l.valueOf()-a.valueOf())/(l.valueOf()-s.valueOf())):h&&f?(h=!1,c+=(o.valueOf()-a.valueOf())/(l.valueOf()-s.valueOf())):c++;else{var _=this._getUnitOrder(n),g=this.units[_-1];g&&!this._isWorkTime(a,g)&&(u=this._getClosestWorkTimeFuture(a,g))}a=u}return c},_getMinutesPerHour:function(t){var e=this._getTimeOfDayStamp(t),n=this._getTimeOfDayStamp(this._nextDate(t,"hour",1));0===n&&(n=86400);for(var i=this._getWorkHours(t),r=0;r<i.length;r++){var a=i[r];if(e>=a.start&&n<=a.end)return 60;if(e<a.end&&n>a.start)return(Math.min(n,a.end)-Math.max(e,a.start))/60}return 0},_getMinutesPerDay:function(t){var e=0;return this._getWorkHours(t).forEach(function(t){e+=t.durationMinutes}),e},getHoursPerDay:function(t){var e=0;return this._getWorkHours(t).forEach(function(t){e+=t.durationHours}),e},_getWorkUnitsForRange:function(t,e,n,i){var r,o=0,s=new Date(t),l=new Date(e);for(r="minute"==n?a.bind(this._getMinutesPerDay,this):a.bind(this.getHoursPerDay,this);s.valueOf()<l.valueOf();)if(l-s>27648e5&&0===s.getDate()){var c=this._largeUnitsCache.getMinutesPerMonth(s);"hour"==n&&(c/=60),o+=c,s=this.$gantt.date.add(s,1,"month")}else{if(l-s>13824e5){var u=this.$gantt.date.week_start(new Date(s));if(s.valueOf()===u.valueOf()){c=this._largeUnitsCache.getMinutesPerWeek(s);"hour"==n&&(c/=60),o+=c,s=this.$gantt.date.add(s,7,"day");continue}}o+=r(s),s=this._nextDate(s,"day",1)}return o/i},_getMinutesBetweenSingleDay:function(t,e){for(var n=this._getIntervalTimestamp(t,e),i=this._getWorkHours(t),r=0,a=0;a<i.length;a++){var o=i[a];if(n.end>=o.start&&n.start<=o.end){var s=Math.max(o.start,n.start),l=Math.min(o.end,n.end);r+=(l-s)/60,n.start=l}}return Math.floor(r)},_getMinutesBetween:function(t,e,n,i){var r=new Date(t),a=new Date(e);i=i||1;var o=new Date(r),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(r)),1,"day");if(a.valueOf()<=s.valueOf())return this._getMinutesBetweenSingleDay(t,e);var l=this.$gantt.date.day_start(new Date(a)),c=a,u=this._getMinutesBetweenSingleDay(o,s),d=this._getMinutesBetweenSingleDay(l,c);return u+this._getWorkUnitsForRange(s,l,n,i)+d},_getHoursBetween:function(t,e,n,i){var r=new Date(t),a=new Date(e);i=i||1;var o=new Date(r),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(r)),1,"day");if(a.valueOf()<=s.valueOf())return Math.round(this._getMinutesBetweenSingleDay(t,e)/60);var l=this.$gantt.date.day_start(new Date(a)),c=a,u=this._getMinutesBetweenSingleDay(o,s,n,i)/60,d=this._getMinutesBetweenSingleDay(l,c,n,i)/60,h=u+this._getWorkUnitsForRange(s,l,n,i)+d;return Math.round(h)},getConfig:function(){return this._worktime},_setConfig:function(t){this._worktime=t,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var t=this.getConfig();for(var e in t.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},t.parsed.hours=this._parseHours(t.hours),t.dates)t.parsed.dates[e]=this._parseHours(t.dates[e]);if(t.customWeeks){var n=null,i=null;for(var e in t.customWeeks){var r=t.customWeeks[e];if(r.from&&r.to){var a=r.from,o=r.to;(!n||n>a.valueOf())&&(n=a.valueOf()),(!i||i<o.valueOf())&&(i=o.valueOf()),t.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:o.valueOf(),toReadable:new Date(o),name:e}),t.parsed.haveCustomWeeks=!0;var s=t.parsed.customWeeks[e]={from:r.from,to:r.to,hours:this._parseHours(r.hours),dates:{}};for(var l in r.dates)s.dates[l]=this._parseHours(r.dates[l])}}t.parsed.customWeeksRangeStart=n,t.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(t){var e=JSON.stringify(this.getConfig());return t(),!!this.hasWorkTime()||(this._setConfig(JSON.parse(e)),this._clearCaches(),!1)},_arraysEqual:function(t,e){if(t===e)return!0;if(!t||!e)return!1;if(t.length!=e.length)return!1;for(var n=0;n<t.length;++n)if(t[n]!==e[n])return!1;return!0},_compareSettings:function(t,e){if(!this._arraysEqual(t.hours,e.hours))return!1;var n=Object.keys(t.dates),i=Object.keys(e.dates);if(n.sort(),i.sort(),!this._arraysEqual(n,i))return!1;for(var r=0;r<n.length;r++){var a=n[r],o=t.dates[a],s=t.dates[a];if(o!==s&&!(Array.isArray(o)&&Array.isArray(s)&&this._arraysEqual(o,s)))return!1}return!0},equals:function(t){if(!(t instanceof s))return!1;var e=this.getConfig(),n=t.getConfig();if(!this._compareSettings(e,n))return!1;if(e.parsed.haveCustomWeeks&&n.parsed.haveCustomWeeks){if(e.parsed.customWeeksBoundaries.length!=n.parsed.customWeeksBoundaries.length)return!1;for(var i in e.parsed.customWeeks){var r=e.parsed.customWeeks[i],a=n.parsed.customWeeks[i];if(!a)return!1;if(!this._compareSettings(r,a))return!1}}else if(e.parse.haveCustomWeeks!==n.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var t=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(t.date,!1)},_getWorkHours:function(t,e){var n=this.getConfig();if(!1!==e&&(n=n.parsed),!t)return n.hours;var i=this._timestamp({date:t});if(n.haveCustomWeeks&&n.customWeeksRangeStart<=i&&n.customWeeksRangeEnd>i)for(var r=0;r<n.customWeeksBoundaries.length;r++)if(n.customWeeksBoundaries[r].from<=i&&n.customWeeksBoundaries[r].to>i){n=n.customWeeks[n.customWeeksBoundaries[r].name];break}var a=!0;return void 0!==n.dates[i]?a=n.dates[i]:void 0!==n.dates[t.getDay()]&&(a=n.dates[t.getDay()]),!0===a?n.hours:a||[]},_getIntervalTimestamp:function(t,e){var n={start:0,end:0};n.start=60*t.getHours()*60+60*t.getMinutes()+t.getSeconds();var i=e.getHours();return!i&&!e.getMinutes()&&!e.getSeconds()&&t.valueOf()<e.valueOf()&&(i=24),n.end=60*i*60+60*e.getMinutes()+e.getSeconds(),n},_parseHours:function(t){if(Array.isArray(t)){var e=[];t.forEach(function(t){"number"==typeof t?e.push(60*t*60):"string"==typeof t&&t.split("-").map(function(t){return t.trim()}).forEach(function(t){var n=t.split(":").map(function(t){return t.trim()}),i=parseInt(60*n[0]*60);n[1]&&(i+=parseInt(60*n[1])),n[2]&&(i+=parseInt(n[2])),e.push(i)})});for(var n=[],i=0;i<e.length;i+=2){var r=e[i],a=e[i+1],o=a-r;n.push({start:r,end:a,startHour:Math.floor(r/3600),startMinute:Math.floor(r/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:o,durationMinutes:o/60,durationHours:o/3600})}return n}return t},setWorkTime:function(t){return this._tryChangeCalendarSettings(a.bind(function(){var e=void 0===t.hours||t.hours,n=this._timestamp(t),i=this.getConfig();if(null!==n?i.dates[n]=e:t.customWeeks||(i.hours=e),t.customWeeks)for(var r in i.customWeeks||(i.customWeeks={}),t.customWeeks)i.customWeeks[r]=t.customWeeks[r];this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(t){return this._tryChangeCalendarSettings(a.bind(function(){if(t){var e=this._timestamp(t);null!==e&&delete this.getConfig().dates[e]}else this.reset_calendar();this._clearCaches()},this))},_isWorkTime:function(t,e){var n=-1,i=null;return i=String(t.valueOf()),-1==(n=this._workingUnitsCache.getItem(e,i,t))&&(n=this._checkIfWorkingUnit(t,e),this._workingUnitsCache.setItem(e,i,n,t)),n},isWorkTime:function(){var t=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(t.date,t.unit)},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!t.unit)return!1;var e=this;return this._dateDurationCache.getDuration(t.start_date,t.end_date,t.unit,t.step,function(){return e._calculateDuration(t.start_date,t.end_date,t.unit,t.step)})},_calculateDuration:function(t,e,n,i){var r=0,a=1;if(t.valueOf()>e.valueOf()){var o=e;e=t,t=o,a=-1}return r="hour"==n&&1==i?this._getHoursBetween(t,e,n,i):"minute"==n&&1==i?this._getMinutesBetween(t,e,n,i):this._getWorkUnitsBetweenGeneric(t,e,n,i),a*Math.round(r)},hasDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,i=t.unit,r=t.step;if(!i)return!1;var a=new Date(e),o=new Date(n);for(r=r||1;a.valueOf()<o.valueOf();){if(this._isWorkTime(a,i))return!0;a=this._nextDate(a,i,r)}return!1},calculateEndDate:function(){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.duration,i=t.unit,r=t.step;if(!i)return!1;var a=t.duration>=0?1:-1;n=Math.abs(1*n);var o=this;return this._dateDurationCache.getEndDate(e,n,i,r*a,function(){return o._calculateEndDate(e,n,i,r*a)})},_calculateEndDate:function(t,e,n,i){return!!n&&(1==i&&"minute"==n?this._calculateMinuteEndDate(t,e,i):-1==i&&"minute"==n?this._subtractMinuteDate(t,e,i):1==i&&"hour"==n?this._calculateHourEndDate(t,e,i):this._addInterval(t,e,n,i,null).end)},_addInterval:function(t,e,n,i,r){for(var a=0,o=t,s=new Date(o.valueOf()-1),l=o.getTimezoneOffset()-s.getTimezoneOffset();a<e&&(!r||!r(o));){var c=this._nextDate(o,n,i);l<0&&i>0&&(c.setTime(c.getTime()+6e4*l),l=!1);var u=c.getTimezoneOffset()-o.getTimezoneOffset();u<0&&i>0&&"day"!=n&&c.setTime(c.getTime()+6e4*u);var d=new Date(c.valueOf()+1);i>0&&(d=new Date(c.valueOf()-1)),this._isWorkTime(d,n)&&a++,o=c}return{end:o,start:t,added:a}},_addHoursUntilDayEnd:function(t,e){for(var n=this.$gantt.date.add(this.$gantt.date.day_start(new Date(t)),1,"day"),i=0,r=e,a=this._getIntervalTimestamp(t,n),o=this._getWorkHours(t),s=0;s<o.length&&i<e;s++){var l=o[s];if(a.end>=l.start&&a.start<=l.end){var c=Math.max(l.start,a.start),u=Math.min(l.end,a.end),d=(u-c)/3600;d>r&&(d=r,u=c+60*r*60);var h=Math.round((u-c)/3600);i+=h,r-=h,a.start=u}}var f=n;return i===e&&(f=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,a.start)),{added:i,end:f}},_calculateHourEndDate:function(t,e,n){var i=new Date(t),r=0;n=n||1,e=Math.abs(1*e);var a=this._addHoursUntilDayEnd(i,e);if(r=a.added,i=a.end,c=e-r){for(var o=i;r<e;){var s=this._nextDate(o,"day",n);s.setHours(0),s.setMinutes(0),s.setSeconds(0);var l=0;if(r+(l=n>0?this.getHoursPerDay(new Date(s.valueOf()-1)):this.getHoursPerDay(new Date(s.valueOf()+1)))>=e)break;r+=l,o=s}i=o}if(r<e){var c=e-r;i=(a=this._addHoursUntilDayEnd(i,c)).end}return i},_addMinutesUntilHourEnd:function(t,e){if(0===t.getMinutes())return{added:0,end:new Date(t)};for(var n=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(t)),1,"hour"),i=0,r=e,a=this._getIntervalTimestamp(t,n),o=this._getWorkHours(t),s=0;s<o.length&&i<e;s++){var l=o[s];if(a.end>=l.start&&a.start<=l.end){var c=Math.max(l.start,a.start),u=Math.min(l.end,a.end),d=(u-c)/60;d>r&&(d=r,u=c+60*r);var h=Math.round((u-c)/60);r-=h,i+=h,a.start=u}}var f=n;return i===e&&(f=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,a.start)),{added:i,end:f}},_subtractMinutesUntilHourStart:function(t,e){for(var n=this.$gantt.date.hour_start(new Date(t)),i=0,r=e,a=60*n.getHours()*60+60*n.getMinutes()+n.getSeconds(),o=60*t.getHours()*60+60*t.getMinutes()+t.getSeconds(),s=this._getWorkHours(t),l=s.length-1;l>=0&&i<e;l--){var c=s[l];if(o>c.start&&a<=c.end){var u=Math.min(o,c.end),d=Math.max(a,c.start),h=(u-d)/60;h>r&&(h=r,d=u-60*r);var f=Math.abs(Math.round((u-d)/60));r-=f,i+=f,o=d}}var _=n;return i===e&&(_=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,o)),{added:i,end:_}},_subtractMinuteDate:function(t,e,n){var i=new Date(t),r=0;n=n||-1,e=Math.abs(1*e),e=Math.round(e);var a=this._subtractMinutesUntilHourStart(i,e);r+=a.added,i=a.end;for(var o=0,s=[],l=0;r<e;){var c=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===c.valueOf()&&(c=this.$gantt.date.add(c,-1,"day"),u=!0);var d=new Date(c.getFullYear(),c.getMonth(),c.getDate(),23,59,59,999).valueOf();d!==o&&(s=this._getWorkHours(c),l=this._getMinutesPerDay(c),o=d);var h=e-r,f=this._getTimeOfDayStamp(i,u);if(s.length&&l)if(s[s.length-1].end<=f&&h>l)r+=l,i=this.$gantt.date.add(i,-1,"day");else{for(var _=!1,g=null,p=s.length-1;p>=0;p--)if(s[p].start<f-1&&s[p].end>=f-1){_=!0,g=s[p];break}if(_)if(f===g.end&&h>=g.durationMinutes)r+=g.durationMinutes,i=this.$gantt.date.add(i,-g.durationMinutes,"minute");else if(h<=f/60-g.startMinute)r+=h,i=this.$gantt.date.add(i,-h,"minute");else{var v=this._getMinutesPerHour(i);v<=h?(r+=v,i=this._nextDate(i,"hour",n)):(r+=(a=this._subtractMinutesUntilHourStart(i,h)).added,i=a.end)}else if(0===i.getHours()&&0===i.getMinutes()&&0===i.getSeconds()){if((m=this._getClosestWorkTimePast(i,"hour")).valueOf()===i.valueOf()){var m=this.$gantt.date.add(i,-1,"day"),y=this._getWorkHours(m);if(y.length){var k=y[y.length-1];m.setSeconds(k.durationSeconds)}}i=m}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}else i=this.$gantt.date.add(i,-1,"day")}if(r<e){var b=e-r;r+=(a=this._subtractMinutesUntilHourStart(i,b)).added,i=a.end}return i},_calculateMinuteEndDate:function(t,e,n){var i=new Date(t),r=0;n=n||1,e=Math.abs(1*e),e=Math.round(e);var a=this._addMinutesUntilHourEnd(i,e);r+=a.added,i=a.end;for(var o=0,s=[],l=0;r<e;){var c=this.$gantt.date.day_start(new Date(i)).valueOf();c!==o&&(s=this._getWorkHours(i),l=this._getMinutesPerDay(i),o=c);var u=e-r,d=this._getTimeOfDayStamp(i);if(s.length&&l)if(s[0].start>=d&&u>=l){if(r+=l,u==l){i=new Date(i.getFullYear(),i.getMonth(),i.getDate(),0,0,s[s.length-1].end);break}i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i)}else{for(var h=!1,f=null,_=0;_<s.length;_++)if(s[_].start<=d&&s[_].end>d){h=!0,f=s[_];break}if(h)if(d===f.start&&u>=f.durationMinutes)r+=f.durationMinutes,i=this.$gantt.date.add(i,f.durationMinutes,"minute");else if(u<=f.endMinute-d/60)r+=u,i=this.$gantt.date.add(i,u,"minute");else{var g=this._getMinutesPerHour(i);g<=u?(r+=g,i=this._nextDate(i,"hour",n)):(r+=(a=this._addMinutesUntilHourEnd(i,u)).added,i=a.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}else i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day")}if(r<e){var p=e-r;r+=(a=this._addMinutesUntilHourEnd(i,p)).added,i=a.end}return i},getClosestWorkTime:function(){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(t.date,t.unit,t.dir)},_getClosestWorkTime:function(t,e,n){var i=new Date(t);if(this._isWorkTime(i,e))return i;if(i=this.$gantt.date[e+"_start"](i),"any"!=n&&n)i="past"==n?this._getClosestWorkTimePast(i,e):this._getClosestWorkTimeFuture(i,e);else{var r=this._getClosestWorkTimeFuture(i,e),a=this._getClosestWorkTimePast(i,e);i=Math.abs(r-t)<=Math.abs(t-a)?r:a}return i},_getClosestWorkTimeFuture:function(t,e){return this._getClosestWorkTimeGeneric(t,e,1)},_getClosestWorkTimePast:function(t,e){var n=this._getClosestWorkTimeGeneric(t,e,-1);return this.$gantt.date.add(n,1,e)},_findClosestTimeInDay:function(t,e,n){var i=new Date(t),r=null,a=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",e<0?"past":"future"),e<0&&(i=new Date(i.valueOf()-1),a=!0),n=this._getWorkHours(i));var o=this._getTimeOfDayStamp(i);if(a&&(o=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),e>0){for(var s=0;s<n.length;s++)if(n[s].start>=o){r=new Date(i.getFullYear(),i.getMonth(),i.getDate(),0,0,n[s].start);break}}else for(s=n.length-1;s>=0;s--){if(n[s].end<=o){r=new Date(i.getFullYear(),i.getMonth(),i.getDate(),0,0,n[s].end);break}if(n[s].end>o&&n[s].start<=o){r=new Date(i.getFullYear(),i.getMonth(),i.getDate(),0,0,o);break}}return r},_getClosestWorkMinute:function(t,e,n){var i=new Date(t),r=this._getWorkHours(i),a=this._findClosestTimeInDay(i,n,r);return a||(i=this.calculateEndDate(i,n,"day"),n>0?i=this.$gantt.date.day_start(i):(i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),r=this._getWorkHours(i),a=this._findClosestTimeInDay(i,n,r)),n<0&&(a=this.$gantt.date.add(a,-1,e)),a},_getClosestWorkTimeGeneric:function(t,e,n){if("hour"===e||"minute"===e)return this._getClosestWorkMinute(t,e,n);for(var i=this._getUnitOrder(e),r=this.units[i-1],a=t,o=0;!this._isWorkTime(a,e)&&(!r||this._isWorkTime(a,r)||(a=n>0?this._getClosestWorkTimeFuture(a,r):this._getClosestWorkTimePast(a,r),!this._isWorkTime(a,e)));){if(++o>3e3)return this.$gantt.assert(!1,"Invalid working time check"),!1;var s=a.getTimezoneOffset();a=this.$gantt.date.add(a,n,e),a=this.$gantt._correct_dst_change(a,s,n,e),this.$gantt.date[e+"_start"]&&(a=this.$gantt.date[e+"_start"](a))}return a},hasWorkTime:function(){var t=this.getConfig(),e=t.dates,n=[];for(var i in t.dates)Number(i)>6&&n.push(Number(i));var r=this._checkWorkHours(t.hours),a=!1;return[0,1,2,3,4,5,6].forEach(function(t){if(!a){var n=e[t];!0===n?a=r:Array.isArray(n)&&(a=this._checkWorkHours(n))}}.bind(this)),a},_checkWorkHours:function(t){if(0===t.length)return!1;for(var e=!1,n=0;n<t.length;n+=2)t[n]!==t[n+1]&&(e=!0);return e}},t.exports=s},function(t,e,n){var i=n(0);function r(){}r.prototype={_getIntervals:function(t){for(var e=[],n=0;n<t.length;n+=2)e.push({start:t[n],end:t[n+1]});return e},_toHoursArray:function(t){var e=[];function n(t){var e=Math.floor(t/3600),n=t-60*e*60;return e+":"+function(t){var e=String(t);return e.length<2&&(e="0"+e),e}(Math.floor(n/60))}for(var i=0;i<t.length;i++)e.push(n(t[i].start)+"-"+n(t[i].end));return e},_intersectHourRanges:function(t,e){var n=[],i=t.length>e.length?t:e,r=t===i?e:t;i=i.slice(),r=r.slice();n=[];for(var a=0;a<i.length;a++)for(var o=i[a],s=0;s<r.length;s++){var l=r[s];l.start<o.end&&l.end>o.start&&(n.push({start:Math.max(o.start,l.start),end:Math.min(o.end,l.end)}),o.end>l.end&&(r.splice(s,1),s--,a--))}return n},_mergeAdjacentIntervals:function(t){var e=t.slice();e.sort(function(t,e){return t.start-e.start});for(var n=e[0],i=1;i<e.length;i++){var r=e[i];r.start<=n.end?(r.end>n.end&&(n.end=r.end),e.splice(i,1),i--):n=r}return e},_mergeHoursConfig:function(t,e){return this._mergeAdjacentIntervals(this._intersectHourRanges(t,e))},merge:function(t,e){var n=i.copy(t.getConfig().parsed),r=i.copy(e.getConfig().parsed),a={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,r.hours)),dates:{},customWeeks:{}};for(var o in n.dates){var s=n.dates[o],l=r.dates[o];if(s&&l)if(Array.isArray(s)||Array.isArray(l)){var c=Array.isArray(s)?s:n.hours,u=Array.isArray(l)?l:r.hours;a.dates[o]=this._toHoursArray(this._mergeHoursConfig(c,u))}else a.dates[o]=!0;else a.dates[o]=!1}if(n.customWeeks)for(var o in n.customWeeks)a.customWeeks[o]=n.customWeeks[o];if(r.customWeeks)for(var o in r.customWeeks)a.customWeeks[o]=r.customWeeks[o];return a}},t.exports=r},function(t,e,n){var i=n(0),r=n(33),a=n(172),o=n(171),s=n(166),l=n(165)();function c(t){this.$gantt=t,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=s.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}.bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",function(){this.createDefaultCalendars()}.bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",function(){this.createDefaultCalendars()}.bind(this))}c.prototype={_calendars:{},_convertWorkTimeSettings:function(t){var e=t.days;if(e&&!t.dates){t.dates=t.dates||{};for(var n=0;n<e.length;n++)t.dates[n]=e[n],e[n]instanceof Array||(t.dates[n]=!!e[n])}return delete t.days,t},mergeCalendars:function(){var t=[],e=arguments;if(Array.isArray(e[0]))t=e[0].slice();else for(var n=0;n<arguments.length;n++)t.push(arguments[n]);var i,r=new a;return t.forEach(function(t){i=i?this._createCalendarFromConfig(r.merge(i,t)):t}.bind(this)),this.createCalendar(i)},_createCalendarFromConfig:function(t){var e=new o(this.$gantt,r(this.$gantt));e.id=String(i.uid());var n=this._convertWorkTimeSettings(t);if(n.customWeeks)for(var a in n.customWeeks)n.customWeeks[a]=this._convertWorkTimeSettings(n.customWeeks[a]);return e._setConfig(n),e},createCalendar:function(t){var e;t||(t={}),e=t.getConfig?i.copy(t.getConfig()):t.worktime?i.copy(t.worktime):i.copy(t);var n=i.copy(this.defaults.fulltime.worktime);return i.mixin(e,n),this._createCalendarFromConfig(e)},getCalendar:function(t){t=t||"global";var e=this._calendars[t];return e||(this.createDefaultCalendars(),e=this._calendars[t]),e},getCalendars:function(){var t=[];for(var e in this._calendars)t.push(this.getCalendar(e));return t},_getOwnCalendar:function(t){var e=this.$gantt.config;if(t[e.calendar_property])return this.getCalendar(t[e.calendar_property]);if(e.resource_calendars){var n;if(n=!1===this._legacyConfig?e.resource_property:s.getResourceProperty(e),Array.isArray(t[n]))e.dynamic_resource_calendars&&(i=l.getCalendarIdFromMultipleResources(t[n],this));else if(void 0===this._legacyConfig&&(this._legacyConfig=s.isLegacyResourceCalendarFormat(e.resource_calendars)),this._legacyConfig)var i=s.getCalendarIdFromLegacyConfig(t,e.resource_calendars);else if(n&&t[n]&&e.resource_calendars[t[n]])var r=this.getResourceCalendar(t[n]);if(i&&(r=this.getCalendar(i)),r)return r}return null},getResourceCalendar:function(t){if(null===t||void 0===t)return this.getCalendar();var e=null;e="number"==typeof t||"string"==typeof t?t:t.id||t.key;var n=this.$gantt.config,i=n.resource_calendars,r=null;if(i){if(void 0===this._legacyConfig&&(this._legacyConfig=s.isLegacyResourceCalendarFormat(n.resource_calendars)),this._legacyConfig){for(var a in i)if(i[a][e]){r=i[a][e];break}}else r=i[e];if(r)return this.getCalendar(r)}return this.getCalendar()},getTaskCalendar:function(t){var e,n=this.$gantt;if(null===t||void 0===t)return this.getCalendar();if(!(e="number"!=typeof t&&"string"!=typeof t||!n.isTaskExists(t)?t:n.getTask(t)))return this.getCalendar();var i=this._getOwnCalendar(e),r=!!n.getState().group_mode;if(!i&&n.config.inherit_calendar&&n.isTaskExists(e.parent)){for(var a=e;n.isTaskExists(a.parent)&&(a=n.getTask(a.parent),!n.isSummaryTask(a)||!(i=this._getOwnCalendar(a))););r&&!i&&t.$effective_calendar&&(i=this.getCalendar(t.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(t){if(!this.isCalendar(t)){var e=t.id;(t=this.createCalendar(t)).id=e}if(t._tryChangeCalendarSettings(function(){})){var n=this.$gantt.config;return t.id=t.id||i.uid(),this._calendars[t.id]=t,n.worktimes||(n.worktimes={}),n.worktimes[t.id]=t.getConfig(),t.id}return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},t]),null},deleteCalendar:function(t){var e=this.$gantt.config;return!!t&&(!!this._calendars[t]&&(delete this._calendars[t],e.worktimes&&e.worktimes[t]&&delete e.worktimes[t],!0))},restoreConfigCalendars:function(t){for(var e in t)if(!this._calendars[e]){var n=t[e],i=this.createCalendar(n);i.id=e,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var t=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(t.worktimes)},isCalendar:function(t){return[t.isWorkTime,t.setWorkTime,t.getWorkHours,t.unsetWorkTime,t.getClosestWorkTime,t.calculateDuration,t.hasDuration,t.calculateEndDate].every(function(t){return t instanceof Function})}},t.exports=c},function(t,e,n){var i=n(173),r=n(164),a=n(162),o=n(0);t.exports=function(t){var e=new i(t),n=new r(e),s=a.create(e,n);o.mixin(t,s)}},function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var r=n(2);t.exports=function(t){function e(e){throw t.assert(!1,"Can't parse data: incorrect value of gantt.parse or gantt.load method. Actual argument value: "+JSON.stringify(e)),new Error("Invalid argument for gantt.parse or gantt.load. An object or a JSON string of format https://docs.dhtmlx.com/gantt/desktop__supported_data_formats.html#json is expected. Actual argument value: "+JSON.stringify(e))}t.load=function(e,n,i){this._load_url=e,this.assert(arguments.length,"Invalid load arguments");var r="json",a=null;return arguments.length>=3?(r=n,a=i):"string"==typeof arguments[1]?r=arguments[1]:"function"==typeof arguments[1]&&(a=arguments[1]),this._load_type=r,this.callEvent("onLoadStart",[e,r]),this.ajax.get(e,t.bind(function(t){this.on_load(t,r),this.callEvent("onLoadEnd",[e,r]),"function"==typeof a&&a.call(this)},this))},t.parse=function(t,e){this.on_load({xmlDoc:{responseText:t}},e)},t.serialize=function(t){return this[t=t||"json"].serialize()},t.on_load=function(e,n){if(e.xmlDoc&&404===e.xmlDoc.status)this.assert(!1,"Failed to load the data from <a href='"+e.xmlDoc.responseURL+"' target='_blank'>"+e.xmlDoc.responseURL+"</a>, server returns 404");else if(!t.$destroyed){this.callEvent("onBeforeParse",[]),n||(n="json"),this.assert(this[n],"Invalid data type:'"+n+"'");var i=e.xmlDoc.responseText,r=this[n].parse(i,e);this._process_loading(r)}},t._process_loading=function(t){t.collections&&this._load_collections(t.collections),this.$data.tasksStore.parse(t.data||t.tasks);var e=t.links||(t.collections?t.collections.links:[]);this.$data.linksStore.parse(e),this.callEvent("onParse",[]),this.render()},t._load_collections=function(t){var e=!1;for(var n in t)if(t.hasOwnProperty(n)){e=!0;var i=t[n],r=this.serverList[n];if(!r)continue;r.splice(0,r.length);for(var a=0;a<i.length;a++){var o=i[a],s=this.copy(o);for(var l in s.key=s.value,o)if(o.hasOwnProperty(l)){if("value"==l||"label"==l)continue;s[l]=o[l]}r.push(s)}}e&&this.callEvent("onOptionsLoad",[])},t.attachEvent("onBeforeTaskDisplay",function(t,e){return!e.$ignore}),t.json={parse:function(n){if(n||e(n),"string"==typeof n)if(void 0!=("undefined"==typeof JSON?"undefined":i(JSON)))try{n=JSON.parse(n)}catch(t){e(n)}else t.assert(!1,"JSON is not supported");return n.data||n.tasks||e(n),n.dhx_security&&(t.security_key=n.dhx_security),n},serializeTask:function(t){return this._copyObject(t)},serializeLink:function(t){return this._copyLink(t)},_copyLink:function(t){var e={};for(var n in t)e[n]=t[n];return e},_copyObject:function(e){var n={};for(var i in e)"$"!=i.charAt(0)&&(n[i]=e[i],r.isDate(n[i])&&(n[i]=t.defined(t.templates.xml_format)?t.templates.xml_format(n[i]):t.templates.format_date(n[i])));return n},serialize:function(){var e=[],n=[];t.eachTask(function(n){t.resetProjectDates(n),e.push(this.serializeTask(n))},t.config.root_id,this);for(var i=t.getLinks(),r=0;r<i.length;r++)n.push(this.serializeLink(i[r]));return{data:e,links:n}}},t.xml={_xmlNodeToJSON:function(t,e){for(var n={},i=0;i<t.attributes.length;i++)n[t.attributes[i].name]=t.attributes[i].value;if(!e){for(i=0;i<t.childNodes.length;i++){var r=t.childNodes[i];1==r.nodeType&&(n[r.tagName]=r.firstChild?r.firstChild.nodeValue:"")}n.text||(n.text=t.firstChild?t.firstChild.nodeValue:"")}return n},_getCollections:function(e){for(var n={},i=t.ajax.xpath("//coll_options",e),r=0;r<i.length;r++)for(var a=n[i[r].getAttribute("for")]=[],o=t.ajax.xpath(".//item",i[r]),s=0;s<o.length;s++){for(var l=o[s].attributes,c={key:o[s].getAttribute("value"),label:o[s].getAttribute("label")},u=0;u<l.length;u++){var d=l[u];"value"!=d.nodeName&&"label"!=d.nodeName&&(c[d.nodeName]=d.nodeValue)}a.push(c)}return n},_getXML:function(e,n,i){i=i||"data",n.getXMLTopNode||(n=t.ajax.parse(n));var r=t.ajax.xmltop(i,n.xmlDoc);r&&r.tagName==i||function(e){throw t.assert(!1,"Can't parse data: incorrect value of gantt.parse or gantt.load method. Actual argument value: "+JSON.stringify(e)),new Error("Invalid argument for gantt.parse or gantt.load. An XML of format https://docs.dhtmlx.com/gantt/desktop__supported_data_formats.html#xmldhtmlxgantt20 is expected. Actual argument value: "+JSON.stringify(e))}(e);var a=r.getAttribute("dhx_security");return a&&(t.security_key=a),r},parse:function(e,n){n=this._getXML(e,n);for(var i={},r=i.data=[],a=t.ajax.xpath("//task",n),o=0;o<a.length;o++)r[o]=this._xmlNodeToJSON(a[o]);return i.collections=this._getCollections(n),i},_copyLink:function(t){return"<item id='"+t.id+"' source='"+t.source+"' target='"+t.target+"' type='"+t.type+"' />"},_copyObject:function(t){return"<task id='"+t.id+"' parent='"+(t.parent||"")+"' start_date='"+t.start_date+"' duration='"+t.duration+"' open='"+!!t.open+"' progress='"+t.progress+"' end_date='"+t.end_date+"'><![CDATA["+t.text+"]]></task>"},serialize:function(){for(var e=[],n=[],i=t.json.serialize(),r=0,a=i.data.length;r<a;r++)e.push(this._copyObject(i.data[r]));for(r=0,a=i.links.length;r<a;r++)n.push(this._copyLink(i.links[r]));return"<data>"+e.join("")+"<coll_options for='links'>"+n.join("")+"</coll_options></data>"}},t.oldxml={parse:function(e,n){n=t.xml._getXML(e,n,"projects");for(var i={collections:{links:[]}},r=i.data=[],a=t.ajax.xpath("//task",n),o=0;o<a.length;o++){r[o]=t.xml._xmlNodeToJSON(a[o]);var s=a[o].parentNode;"project"==s.tagName?r[o].parent="project-"+s.getAttribute("id"):r[o].parent=s.parentNode.getAttribute("id")}a=t.ajax.xpath("//project",n);for(o=0;o<a.length;o++){(l=t.xml._xmlNodeToJSON(a[o],!0)).id="project-"+l.id,r.push(l)}for(o=0;o<r.length;o++){var l;(l=r[o]).start_date=l.startdate||l.est,l.end_date=l.enddate,l.text=l.name,l.duration=l.duration/8,l.open=1,l.duration||l.end_date||(l.duration=1),l.predecessortasks&&i.collections.links.push({target:l.id,source:l.predecessortasks,type:t.config.links.finish_to_start})}return i},serialize:function(){t.message("Serialization to 'old XML' is not implemented")}},t.serverList=function(t,e){return e?this.serverList[t]=e.slice(0):this.serverList[t]||(this.serverList[t]=[]),this.serverList[t]}}},function(t,e){t.exports=function(t){t.isReadonly=function(e){return"number"!=typeof e&&"string"!=typeof e||!t.isTaskExists(e)||(e=t.getTask(e)),(!e||!e[this.config.editable_property])&&(e&&e[this.config.readonly_property]||this.config.readonly)}}},function(t,e){t.exports=function(t){t.getGridColumn=function(e){for(var n=t.config.columns,i=0;i<n.length;i++)if(n[i].name==e)return n[i];return null},t.getGridColumns=function(){return t.config.columns.slice()}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t){this._scrollOrder=0;var e=t.gantt,n=t.grid,i=t.dnd,r=t.getCurrentX;this.$gantt=e,this.$grid=n,this._dnd=i,this.getCurrentX=r,this._scrollView=this.$gantt.$ui.getView(this.$grid.$config.scrollX),this.attachEvents()}return t.prototype.attachEvents=function(){var t=this;this.isScrollable()&&(this._dnd.attachEvent("onDragMove",function(e,n){var i=t.$grid.$grid.getBoundingClientRect(),r=i.right,a=i.left,o=t.getCurrentX(n.clientX);return o>=r-20&&(t.autoscrollRight(),t.autoscrollStart()),o<=a+20&&(t.autoscrollLeft(),t.autoscrollStart()),o<r-20&&o>a+20&&t.autoscrollStop(),!0}),this._dnd.attachEvent("onDragEnd",function(){t.autoscrollStop()}))},t.prototype.autoscrollStart=function(){var t=this;if(0!==this._scrollOrder){var e=10*this._scrollOrder,n=this._scrollView.getScrollState();this._scrollView.scrollTo(n.position+e),setTimeout(function(){t.autoscrollStart()},50)}},t.prototype.autoscrollRight=function(){this._scrollOrder=1},t.prototype.autoscrollLeft=function(){this._scrollOrder=-1},t.prototype.autoscrollStop=function(){this._scrollOrder=0},t.prototype.getCorrection=function(){return this.isScrollable()?this._scrollView.getScrollState().position:0},t.prototype.isScrollable=function(){return!!this.$grid.$config.scrollable},t}();e.default=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),r=n(178),a=function(){function t(t,e){var n=this;this._targetMarker=null,this.calculateCurrentPosition=function(t){var e=n.$grid.$grid.getBoundingClientRect(),i=e.right,r=e.left,a=t;return a>i&&(a=i),a<r&&(a=r),a},this.$gantt=t,this.$grid=e}return t.prototype.init=function(){var t=this.$gantt.$services.getService("dnd");this._dnd=new t(this.$grid.$grid_scale,{updates_per_second:60}),this._scrollableGrid=new r.default({gantt:this.$gantt,grid:this.$grid,dnd:this._dnd,getCurrentX:this.calculateCurrentPosition}),this.attachEvents()},t.prototype.attachEvents=function(){var t=this;this._dnd.attachEvent("onBeforeDragStart",function(e,n){if(t._draggedCell=t.$gantt.utils.dom.closest(n.target,".gantt_grid_head_cell"),t._draggedCell){var i,r,a=t.$grid.$getConfig().columns,o=t._draggedCell.getAttribute("data-column-id");return a.map(function(t,e){t.name===o&&(i=t,r=e)}),!1===t.$grid.callEvent("onBeforeColumnDragStart",[{draggedColumn:i,draggedIndex:r}])?!1:!(!t._draggedCell||!i)&&(t._gridConfig=t.$grid.$getConfig(),t._originAutoscroll=t.$gantt.config.autoscroll,t.$gantt.config.autoscroll=!1,!0)}}),this._dnd.attachEvent("onAfterDragStart",function(e,n){t._draggedCell&&(t._dnd.config.column=t._draggedCell.getAttribute("data-column-id"),t._dnd.config.marker.innerHTML=t._draggedCell.outerHTML,t._dnd.config.marker.classList.add("gantt_column_drag_marker"),t._dnd.config.marker.style.height=t._gridConfig.scale_height+"px",t._dnd.config.marker.style.lineHeight=t._gridConfig.scale_height+"px",t._draggedCell.classList.add("gantt_grid_head_cell_dragged"))}),this._dnd.attachEvent("onDragMove",function(e,n){if(t._draggedCell){t._dragX=n.clientX;var i=t.calculateCurrentPosition(n.clientX),r=t.findColumnsIndexes(),a=r.targetIndex,o=r.draggedIndex,s=t.$grid.$getConfig().columns,l=s[o],c=s[a];return!1===t.$grid.callEvent("onColumnDragMove",[{draggedColumn:l,targetColumn:c,draggedIndex:o,targetIndex:a}])?(t.cleanTargetMarker(),!1):(t.setMarkerPosition(i),t.drawTargetMarker(r),!0)}}),this._dnd.attachEvent("onDragEnd",function(){t._draggedCell&&(t.$gantt.config.autoscroll=t._originAutoscroll,t._draggedCell.classList.remove("gantt_grid_head_cell_dragged"),t.cleanTargetMarker(),t.reorderColumns())})},t.prototype.reorderColumns=function(){var t=this.findColumnsIndexes(),e=t.targetIndex,n=t.draggedIndex,i=this.$grid.$getConfig().columns,r=i[n],a=i[e];!1!==this.$grid.callEvent("onBeforeColumnReorder",[{draggedColumn:r,targetColumn:a,draggedIndex:n,targetIndex:e}])&&e!==n&&(i.splice(n,1),i.splice(e,0,r),this.$gantt.render(),this.$grid.callEvent("onAfterColumnReorder",[{draggedColumn:r,targetColumn:a,draggedIndex:n,targetIndex:e}]))},t.prototype.findColumnsIndexes=function(){var t,e,n,i,r,a=this._dnd.config.column,o=this.$grid.$getConfig().columns,s={startX:0,endX:0},l=0,c=o.length-1,u=function(t,e){return t<=e},d=function(t){return++t};this.$gantt.config.rtl&&(l=o.length-1,c=0,u=function(t,e){return t>=e},d=function(t){return--t});for(var h=this._dragX-this.$grid.$grid.getBoundingClientRect().left+this._scrollableGrid.getCorrection(),f=l;u(f,c)&&(void 0===t||void 0===e);f=d(f))o[f].hide||(s.startX=s.endX,s.endX+=o[f].width,h>=s.startX&&(h<=s.endX||!u(d(f),c))&&(t=f,n=s.startX,i=s.endX,r=(h-s.startX)/(s.endX-s.startX)),a===o[f].name&&(e=f));return{targetIndex:t,draggedIndex:e,xBefore:n,xAfter:i,columnRelativePos:r}},t.prototype.setMarkerPosition=function(t,e){void 0===e&&(e=10);var n=this._dnd.config.marker,i=this._dnd._obj.getBoundingClientRect();n.style.top=i.y+e+"px",n.style.left=t+"px"},t.prototype.drawTargetMarker=function(t){var e,n=t.targetIndex,r=t.draggedIndex,a=t.xBefore,o=t.xAfter,s=t.columnRelativePos;this._targetMarker||(this._targetMarker=document.createElement("div"),i.addClassName(this._targetMarker,"gantt_grid_target_marker"),this._targetMarker.style.display="none",this._targetMarker.style.height=this._gridConfig.scale_height+"px"),this._targetMarker.parentNode||this.$grid.$grid_scale.appendChild(this._targetMarker),e=n>r?o:n<r?a:s>.5?o:a,this._targetMarker.style.left=e+"px",this._targetMarker.style.display="block"},t.prototype.cleanTargetMarker=function(){this._targetMarker&&this._targetMarker.parentNode&&this.$grid.$grid_scale.removeChild(this._targetMarker),this._targetMarker=null},t}();e.ColumnsGridDnd=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(179);e.default=i.ColumnsGridDnd},function(t,e,n){var i=n(1);t.exports=function(t,e){var n={row_before_start:t.bind(function(t,n,r){var a=e.$getConfig(),o=e.$config.rowStore;if(!i.locateAttribute(r,a.task_grid_row_resizer_attribute))return!1;var s=this.locate(r,a.task_grid_row_resizer_attribute),l=o.getItem(s);return!1!==e.callEvent("onBeforeRowResize",[l])&&void 0},t),row_after_start:t.bind(function(t,n,i){var r=e.$getConfig(),a=this.locate(i,r.task_grid_row_resizer_attribute);t.config.marker.innerHTML="",t.config.marker.className+=" gantt_row_grid_resize_area",t.config.marker.style.width=e.$grid.offsetWidth+"px",t.config.drag_id=a},t),row_drag_move:t.bind(function(t,n,r){var a=e.$config.rowStore,o=e.$getConfig(),s=t.config,l=parseInt(s.drag_id,10),c=e.getItemHeight(l),u=e.getItemTop(l),d=i.getNodePosition(e.$grid_data),h=parseInt(s.marker.style.top,10),f=u+d.y,_=0,g=o.min_task_grid_row_height;return(_=h-f)<g&&(_=g),s.marker.style.left=d.x+"px",s.marker.style.top=f-1+"px",s.marker.style.height=Math.abs(_)+1+"px",s.marker_height=_,e.callEvent("onRowResize",[l,a.getItem(l),_+c]),!0},t),row_drag_end:t.bind(function(n,i,r){var a=e.$config.rowStore,o=n.config,s=parseInt(o.drag_id,10),l=a.getItem(s),c=e.getItemHeight(s),u=o.marker_height;!1!==e.callEvent("onBeforeRowResizeEnd",[s,l,u])&&l.row_height!=u&&(l.row_height=u,t.updateTask(s),e.callEvent("onAfterRowResize",[s,l,c,u]),this.render())},t)};return{init:function(){var i=t.$services.getService("dnd"),r=e.$getConfig(),a=new i(e.$grid_data,{updates_per_second:60});t.defined(r.dnd_sensitivity)&&(a.config.sensitivity=r.dnd_sensitivity),a.attachEvent("onBeforeDragStart",function(t,e){return n.row_before_start(a,t,e)}),a.attachEvent("onAfterDragStart",function(t,e){return n.row_after_start(a,t,e)}),a.attachEvent("onDragMove",function(t,e){return n.row_drag_move(a,t,e)}),a.attachEvent("onDragEnd",function(t,e){return n.row_drag_end(a,t,e)})}}}},function(t,e){t.exports=function(t){var e=-1,n=-1;return{resetCache:function(){e=-1,n=-1},_getRowHeight:function(){return-1===e&&(e=t.$getConfig().row_height),e},_refreshState:function(){this.resetCache(),n=!0;var e=t.$config.rowStore;if(e)for(var i=this._getRowHeight(),r=0;r<e.fullOrder.length;r++){var a=e.getItem(e.fullOrder[r]);if(a&&a.row_height&&a.row_height!==i){n=!1;break}}},canUseSimpleCalculation:function(){return-1===n&&this._refreshState(),n},getRowTop:function(e){return t.$config.rowStore?e*this._getRowHeight():0},getItemHeight:function(t){return this._getRowHeight()},getTotalHeight:function(){return t.$config.rowStore?t.$config.rowStore.countVisible()*this._getRowHeight():0},getItemIndexByTopPosition:function(e){return t.$config.rowStore?Math.floor(e/this._getRowHeight()):0}}}},function(t,e){t.exports=function(t,e){return{init:function(){},doOnRender:function(){}}}},function(t,e,n){var i=n(25);t.exports=function(t){n(177)(t),i.prototype.getGridColumns=function(){for(var t=this.$getConfig().columns,e=[],n=0;n<t.length;n++)t[n].hide||e.push(t[n]);return e}}},function(t,e,n){t.exports=function(t){var e=n(38),i={};t.attachEvent("onClearAll",function(){i={}});var r=e.prototype.hasChild;t.$data.tasksStore.hasChild=function(e){return t.config.branch_loading?!!r.call(this,e)||!!this.exists(e)&&this.getItem(e)[t.config.branch_loading_property]:r.call(this,e)},t.attachEvent("onTaskOpened",function(e){if(t.config.branch_loading&&t._load_url&&function(e){return!(!t.config.branch_loading||!t._load_url||i[e]||t.getChildren(e).length||!t.hasChild(e))}(e)){var n=t._load_url,r=(n=n.replace(/(\?|&)?parent_id=.+&?/,"")).indexOf("?")>=0?"&":"?",a=t.getScrollState().y||0,o={taskId:e,url:n+r+"parent_id="+encodeURIComponent(e)};if(!1===t.callEvent("onBeforeBranchLoading",[o]))return;t.load(o.url,this._load_type,function(){a&&t.scrollTo(null,a),t.callEvent("onAfterBranchLoading",[o])}),i[e]=!0}})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t){var e=this;this.format=function(t){return e._getWBSCode(t.source)},this.canParse=function(t){return e._linkReg.test(t)},this.parse=function(t){if(!e.canParse(t))return null;var n=e._linkReg.exec(t)[0].trim();return{id:void 0,source:e._findSource(n)||null,target:null,type:e._gantt.config.links.finish_to_start,lag:0}},this._getWBSCode=function(t){var n=e._gantt.getTask(t);return e._gantt.getWBSCode(n)},this._findSource=function(t){var n=new RegExp("^[0-9.]+","i");if(n.exec(t)){var i=n.exec(t)[0],r=e._gantt.getTaskByWBSCode(i);if(r)return r.id}return null},this._linkReg=/^[0-9\.]+/,this._gantt=t}return t.create=function(e,n){return void 0===e&&(e=null),new t(n)},t}();e.default=i},function(t,e,n){var i=n(35).default,r=n(186).default;t.exports=function(t){t.ext.formatters={durationFormatter:function(e){return e||(e={}),e.store||(e.store=t.config.duration_unit),e.enter||(e.enter=t.config.duration_unit),i.create(e,t)},linkFormatter:function(e){return r.create(e,t)}}}},function(t,e){t.exports=function(t){function e(e){return function(){return!t.config.auto_types||t.getTaskType(t.config.types.project)!=t.config.types.project||e.apply(this,arguments)}}function n(e,n){var i=t.getTask(e),r=a(i);!1!==r&&t.getTaskType(i)!==r&&(n.$needsUpdate=!0,n[i.id]={task:i,type:r})}function i(e){if(!t.getState().group_mode){var i=function(e,i){return n(e,i=i||{}),t.eachParent(function(t){n(t.id,i)},e),i}(e);i.$needsUpdate&&t.batchUpdate(function(){!function(e){for(var n in e)if(e[n]&&e[n].task){var i=e[n].task;i.type=e[n].type,t.updateTask(i.id)}}(i)})}}var r;function a(e){var n=t.config.types,i=t.hasChild(e.id),r=t.getTaskType(e.type);return i&&r===n.task?n.project:!i&&r===n.project&&n.task}var o,s,l=!0;function c(e){e!=t.config.root_id&&t.isTaskExists(e)&&i(e)}t.attachEvent("onParse",e(function(){l=!1,t.getState().group_mode||(t.batchUpdate(function(){t.eachTask(function(e){var n=a(e);!1!==n&&function(e,n){t.getState().group_mode||(e.type=n,t.updateTask(e.id))}(e,n)})}),l=!0)})),t.attachEvent("onAfterTaskAdd",e(function(t){l&&i(t)})),t.attachEvent("onAfterTaskUpdate",e(function(t){l&&i(t)})),t.attachEvent("onBeforeTaskDelete",e(function(e,n){return r=t.getParent(e),!0})),t.attachEvent("onAfterTaskDelete",e(function(t,e){c(r)})),t.attachEvent("onRowDragStart",e(function(e,n,i){return o=t.getParent(e),!0})),t.attachEvent("onRowDragEnd",e(function(t,e){c(o),i(t)})),t.attachEvent("onBeforeTaskMove",e(function(e,n,i){return s=t.getParent(e),!0})),t.attachEvent("onAfterTaskMove",e(function(t,e,n){document.querySelector(".gantt_drag_marker")||(c(s),i(t))}))}},function(t,e){t.exports=function(t){function e(e){return function(){return!t.config.placeholder_task||e.apply(this,arguments)}}function n(){var e=t.getTaskBy("type",t.config.types.placeholder);if(!e.length||!t.isTaskExists(e[0].id)){var n={unscheduled:!0,type:t.config.types.placeholder,duration:0,text:t.locale.labels.new_task};if(!1===t.callEvent("onTaskCreated",[n]))return;t.addTask(n)}}function i(e){var n=t.getTask(e);n.type==t.config.types.placeholder&&(n.start_date&&n.end_date&&n.unscheduled&&(n.unscheduled=!1),t.batchUpdate(function(){var e=t.copy(n);t.silent(function(){t.deleteTask(n.id)}),delete e["!nativeeditor_status"],e.type=t.config.types.task,e.id=t.uid(),t.addTask(e)}))}t.config.types.placeholder="placeholder",t.attachEvent("onDataProcessorReady",e(function(n){n&&!n._silencedPlaceholder&&(n._silencedPlaceholder=!0,n.attachEvent("onBeforeUpdate",e(function(e,i,r){return r.type!=t.config.types.placeholder||(n.setUpdated(e,!1),!1)})))}));var r=!1;function a(e){if(t.config.types.placeholder&&t.isTaskExists(e)&&t.getTask(e).type==t.config.types.placeholder)return!0;return!1}function o(t){return!(!a(t.source)&&!a(t.target))}t.attachEvent("onGanttReady",function(){r||(r=!0,t.attachEvent("onAfterTaskUpdate",e(i)),t.attachEvent("onAfterTaskAdd",e(function(e,i){i.type!=t.config.types.placeholder&&(t.getTaskBy("type",t.config.types.placeholder).forEach(function(e){t.silent(function(){t.isTaskExists(e.id)&&t.deleteTask(e.id)})}),n())})),t.attachEvent("onParse",e(n)))}),t.attachEvent("onLinkValidation",function(t){return!o(t)}),t.attachEvent("onBeforeLinkAdd",function(t,e){return!o(e)}),t.attachEvent("onBeforeUndoStack",function(e){for(var n=0;n<e.commands.length;n++){var i=e.commands[n];"task"===i.entity&&i.value.type===t.config.types.placeholder&&(e.commands.splice(n,1),n--)}return!0})}},function(t,e){t.exports=function(t){var e="$resourceAssignments";t.config.resource_assignment_store="resourceAssignments",t.config.process_resource_assignments=!0;var n={auto:"auto",singleValue:"singleValue",valueArray:"valueArray",resourceValueArray:"resourceValueArray",assignmentsArray:"assignmentsArray"},i=n.auto,r={fixedDates:"fixedDates",fixedDuration:"fixedDuration",default:"default"};function a(e,n){e.start_date?e.start_date=t.date.parseDate(e.start_date,"parse_date"):e.start_date=null,e.end_date?e.end_date=t.date.parseDate(e.end_date,"parse_date"):e.end_date=null;var i=Number(e.delay),a=!1;if(isNaN(i)?(e.delay=0,a=!0):e.delay=i,t.defined(e.value)||(e.value=null),!e.task_id||!e.resource_id)return!1;if(e.mode=e.mode||r.default,e.mode===r.fixedDuration&&(isNaN(Number(e.duration))&&(n=n||t.getTask(e.task_id),e.duration=t.calculateDuration({start_date:e.start_date,end_date:e.end_date,id:n})),a&&(n=n||t.getTask(e.task_id),e.delay=t.calculateDuration({start_date:n.start_date,end_date:e.start_date,id:n}))),e.mode!==r.fixedDates&&(n||t.isTaskExists(e.task_id))){var o=s(e,n=n||t.getTask(e.task_id));e.start_date=o.start_date,e.end_date=o.end_date,e.duration=o.duration}}var o=t.createDatastore({name:t.config.resource_assignment_store,initItem:function(e){return e.id||(e.id=t.uid()),a(e),e}});function s(e,n){if(e.mode===r.fixedDates)return{start_date:e.start_date,end_date:e.end_date,duration:e.duration};var i,a,o=e.delay?t.calculateEndDate({start_date:n.start_date,duration:e.delay,task:n}):new Date(n.start_date);return e.mode===r.fixedDuration?(i=t.calculateEndDate({start_date:o,duration:e.duration,task:n}),a=e.duration):(i=new Date(n.end_date),a=n.duration-e.delay),{start_date:o,end_date:i,duration:a}}function l(e){var o=t.config.resource_property,s=e[o],l=[],c=i===n.auto;if(t.defined(s)&&s){Array.isArray(s)||(s=[s],c&&(i=n.singleValue,c=!1));var u={};s.forEach(function(o){o.resource_id||(o={resource_id:o},c&&(i=n.valueArray,c=!1)),c&&(o.id&&o.resource_id?(i=n.assignmentsArray,c=!1):(i=n.resourceValueArray,c=!1));var s,d=r.default;o.mode||(o.start_date&&o.end_date||o.start_date&&o.duration)&&(d=r.fixedDuration),s=o.id||!o.$id||u[o.$id]?o.id&&!u[o.id]?o.id:t.uid():o.$id,u[s]=!0;var h={id:s,start_date:o.start_date,duration:o.duration,end_date:o.end_date,delay:o.delay,task_id:e.id,resource_id:o.resource_id,value:o.value,mode:o.mode||d};h.start_date&&h.start_date.getMonth&&h.end_date&&h.end_date.getMonth&&"number"==typeof h.duration||a(h,e),l.push(h)})}return l}function c(e){if(t.isTaskExists(e)){var n=t.getTask(e);u(n,t.getTaskAssignments(n.id))}}function u(r,a){a.sort(function(t,e){return t.start_date&&e.start_date&&t.start_date.valueOf()!=e.start_date.valueOf()?t.start_date-e.start_date:0}),i==n.assignmentsArray?r[t.config.resource_property]=a:i==n.resourceValueArray&&(r[t.config.resource_property]=a.map(function(t){return{$id:t.id,start_date:t.start_date,duration:t.duration,end_date:t.end_date,delay:t.delay,resource_id:t.resource_id,value:t.value,mode:t.mode}})),r[e]=a}function d(e){var n=l(e),i=[];return n.forEach(function(e){e.id=e.id||t.uid(),i.push(e)}),n}function h(t,e){var a=function(t,e){var r={inBoth:[],inTaskNotInStore:[],inStoreNotInTask:[]};if(i==n.singleValue){var a=t[0],o=a?a.resource_id:null,s=!1;e.forEach(function(t){t.resource_id!=o?r.inStoreNotInTask.push(t):t.resource_id==o&&(r.inBoth.push({store:t,task:a}),s=!0)}),!s&&a&&r.inTaskNotInStore.push(a)}else if(i==n.valueArray){var l={},c={},u={};t.forEach(function(t){l[t.resource_id]=t}),e.forEach(function(t){c[t.resource_id]=t}),t.concat(e).forEach(function(t){if(!u[t.resource_id]){u[t.resource_id]=!0;var e=l[t.resource_id],n=c[t.resource_id];e&&n?r.inBoth.push({store:n,task:e}):e&&!n?r.inTaskNotInStore.push(e):!e&&n&&r.inStoreNotInTask.push(n)}})}else i!=n.assignmentsArray&&i!=n.resourceValueArray||(l={},c={},u={},t.forEach(function(t){l[t.id||t.$id]=t}),e.forEach(function(t){c[t.id]=t}),t.concat(e).forEach(function(t){var e=t.id||t.$id;if(!u[e]){u[e]=!0;var n=l[e],i=c[e];n&&i?r.inBoth.push({store:i,task:n}):n&&!i?r.inTaskNotInStore.push(n):!n&&i&&r.inStoreNotInTask.push(i)}}));return r}(l(t),e);a.inStoreNotInTask.forEach(function(t){o.removeItem(t.id)}),a.inTaskNotInStore.forEach(function(t){o.addItem(t)}),a.inBoth.forEach(function(e){if(function(t,e){var n={id:!0};for(var i in t)if(!n[i]&&String(t[i])!==String(e[i]))return!0;return!1}(e.task,e.store))!function(t,e){var n={id:!0};for(var i in t)n[i]||(e[i]=t[i])}(e.task,e.store),o.updateItem(e.store.id);else if(e.task.start_date&&e.task.end_date&&e.task.mode!==r.fixedDates){var n=s(e.store,t);e.store.start_date.valueOf()==n.start_date.valueOf()&&e.store.end_date.valueOf()==n.end_date.valueOf()||(e.store.start_date=n.start_date,e.store.end_date=n.end_date,e.store.duration=n.duration,o.updateItem(e.store.id))}}),c(t.id)}function f(t){var n=t[e]||o.find(function(e){return e.task_id==t.id});h(t,n)}t.attachEvent("onGanttReady",function(){if(t.config.process_resource_assignments){t.attachEvent("onParse",function(){t.silent(function(){o.clearAll();var e=[];t.eachTask(function(n){if(n.type!==t.config.types.project){var i=d(n);u(n,i),i.forEach(function(t){e.push(t)})}}),o.parse(e)})});var e=!1,n=!1,i={};t.attachEvent("onBeforeBatchUpdate",function(){e=!0}),t.attachEvent("onAfterBatchUpdate",function(){if(n){var r={};for(var a in i)r[a]=t.getTaskAssignments(i[a].id);for(var a in i)h(i[a],r[a])}n=!1,e=!1,i={}}),t.attachEvent("onTaskCreated",function(t){var e=d(t);return o.parse(e),u(t,e),!0}),t.attachEvent("onAfterTaskUpdate",function(t,r){e?(n=!0,i[t]=r):f(r)}),t.attachEvent("onAfterTaskAdd",function(t,r){e?(n=!0,i[t]=r):f(r)}),t.attachEvent("onRowDragEnd",function(e){f(t.getTask(e))}),t.$data.tasksStore.attachEvent("onAfterDeleteConfirmed",function(e,n){var i=[e];t.eachTask(function(t){i.push(t.id)},e),function(t){var e={};t.forEach(function(t){e[t]=!0}),o.find(function(t){return e[t.task_id]}).forEach(function(t){o.removeItem(t.id)})}(i)}),t.$data.tasksStore.attachEvent("onClearAll",function(){return r=null,a=null,s=null,o.clearAll(),!0}),t.attachEvent("onTaskIdChange",function(t,e){o.find(function(e){return e.task_id==t}).forEach(function(t){t.task_id=e,o.updateItem(t.id)}),c(e)});var r=null,a=null,s=null;o.attachEvent("onStoreUpdated",function(){return!!e||(r=null,a=null,s=null,!0)}),t.getResourceAssignments=function(e,n){var i=t.defined(n)&&null!==n;return null===r&&(r={},a={},o.eachItem(function(t){r[t.resource_id]||(r[t.resource_id]=[]),r[t.resource_id].push(t);var e=t.resource_id+"-"+t.task_id;a[e]||(a[e]=[]),a[e].push(t)})),i?(a[e+"-"+n]||[]).slice():(r[e]||[]).slice()},t.getTaskAssignments=function(t){if(null===s){var e=[];s={},o.eachItem(function(n){s[n.task_id]||(s[n.task_id]=[]),s[n.task_id].push(n),n.task_id==t&&e.push(n)})}return(s[t]||[]).slice()},t.updateTaskAssignments=c}},{once:!0})}},function(t,e,n){var i=n(2);function r(t){var e={},n=!1;t.$data.tasksStore.attachEvent("onStoreUpdated",function(){e={},n=!1}),t.attachEvent("onBeforeGanttRender",function(){e={}});var r=String(Math.random());function a(t){return null===t?r+String(t):String(t)}function o(t,e){return Array.isArray(t)?t.map(function(t){return a(t)}).join("_")+"_"+e:a(t)+"_"+e}function s(r,s){var l,c=o(s,r),u={};return i.forEach(s,function(t){u[a(t)]=!0}),e[c]?l=e[c]:(l=e[c]=[],t.eachTask(function(s){var c;s.type!=t.config.types.project&&(r in s&&(c=i.isArray(s[r])?s[r]:[s[r]],i.forEach(c,function(t){var i=t&&t.resource_id?t.resource_id:t;if(u[a(i)])l.push(s);else if(!n){var c=o(t,r);e[c]||(e[c]=[]),e[c].push(s)}})))}),n=!0),l}function l(e,n,i){var r=t.config.resource_property,a=[];if(t.getDatastore("task").exists(n)){var o=t.getTask(n);a=o[r]||[]}Array.isArray(a)||(a=[a]);for(var s=0;s<a.length;s++)a[s].resource_id==e&&i.push({task_id:o.id,resource_id:a[s].resource_id,value:a[s].value})}return{getTaskBy:function(e,n){return"function"==typeof e?function(e){var n=[];return t.eachTask(function(t){e(t)&&n.push(t)}),n}(e):i.isArray(n)?s(e,n):s(e,[n])},getResourceAssignments:function(e,n){var i=[],r=t.config.resource_property;return void 0!==n?l(e,n,i):t.getTaskBy(r,e).forEach(function(t){l(e,t.id,i)}),i}}}t.exports=function(t){var e=r(t);t.getTaskBy=e.getTaskBy,t.getResourceAssignments=e.getResourceAssignments,t.config.resource_property="owner_id",t.config.resource_store="resource",t.config.resource_render_empty_cells=!1,t.templates.histogram_cell_class=function(t,e,n,i,r){},t.templates.histogram_cell_label=function(t,e,n,i,r){return i.length+"/3"},t.templates.histogram_cell_allocated=function(t,e,n,i,r){return i.length/3},t.templates.histogram_cell_capacity=function(t,e,n,i,r){return 0},t.templates.resource_cell_class=function(t,e,n,i,r){return i.length<=1?"gantt_resource_marker_ok":"gantt_resource_marker_overtime"},t.templates.resource_cell_value=function(t,e,n,i,r){return 8*i.length}}},function(t,e){t.exports=function(t){var e=function(t){return{_needRecalc:!0,reset:function(){this._needRecalc=!0},_isRecalcNeeded:function(){return!this._isGroupSort()&&this._needRecalc},_isGroupSort:function(){return!!t.getState().group_mode},_getWBSCode:function(t){return t?(this._isRecalcNeeded()&&this._calcWBS(),t.$virtual?"":this._isGroupSort()?t.$wbs||"":(t.$wbs||(this.reset(),this._calcWBS()),t.$wbs)):""},_setWBSCode:function(t,e){t.$wbs=e},getWBSCode:function(t){return this._getWBSCode(t)},getByWBSCode:function(e){for(var n=e.split("."),i=t.config.root_id,r=0;r<n.length;r++){var a=t.getChildren(i),o=1*n[r]-1;if(!t.isTaskExists(a[o]))return null;i=a[o]}return t.isTaskExists(i)?t.getTask(i):null},_calcWBS:function(){if(this._isRecalcNeeded()){var e=!0;t.eachTask(function(n){if(e)return e=!1,void this._setWBSCode(n,"1");var i=t.getPrevSibling(n.id);if(null!==i){var r=t.getTask(i).$wbs;r&&((r=r.split("."))[r.length-1]++,this._setWBSCode(n,r.join(".")))}else{var a=t.getParent(n.id);this._setWBSCode(n,t.getTask(a).$wbs+".1")}},t.config.root_id,this),this._needRecalc=!1}}}}(t);function n(){return e.reset(),!0}t.getWBSCode=function(t){return e.getWBSCode(t)},t.getTaskByWBSCode=function(t){return e.getByWBSCode(t)},t.attachEvent("onAfterTaskMove",n),t.attachEvent("onBeforeParse",n),t.attachEvent("onAfterTaskDelete",n),t.attachEvent("onAfterTaskAdd",n),t.attachEvent("onAfterSort",n)}},function(t,e,n){var i=n(15);function r(t){var e={},n=!1;function r(t,n){n="function"==typeof n?n:function(){},e[t]||(e[t]=this[t],this[t]=n)}function a(t){e[t]&&(this[t]=e[t],e[t]=null)}function o(){for(var t in e)a.call(this,t)}function s(t){try{t()}catch(t){i.console.error(t)}}return t.$services.getService("state").registerProvider("batchUpdate",function(){return{batch_update:n}},!1),function(t,e){if(n)s(t);else{var i,a=this._dp&&"off"!=this._dp.updateMode;a&&(i=this._dp.updateMode,this._dp.setUpdateMode("off"));var l={},c={render:!0,refreshData:!0,refreshTask:!0,refreshLink:!0,resetProjectDates:function(t){l[t.id]=t}};for(var u in function(t){for(var e in t)r.call(this,e,t[e])}.call(this,c),n=!0,this.callEvent("onBeforeBatchUpdate",[]),s(t),this.callEvent("onAfterBatchUpdate",[]),o.call(this),l)this.resetProjectDates(l[u]);n=!1,e||this.render(),a&&(this._dp.setUpdateMode(i),this._dp.setGanttMode("task"),this._dp.sendData(),this._dp.setGanttMode("link"),this._dp.sendData())}}}t.exports=function(t){t.batchUpdate=r(t)}},function(t,e,n){t.exports=function(t){t.ext||(t.ext={});for(var e=[n(193),n(192),n(191),n(190),n(189),n(188),n(187)],i=0;i<e.length;i++)e[i]&&e[i](t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(0),r=function(){function t(){var t=this;this.clear=function(){t._storage={}},this.storeItem=function(e){t._storage[e.id]=i.copy(e)},this.getStoredItem=function(e){return t._storage[e]||null},this._storage={}}return t.create=function(){return new t},t}();e.default=r},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){t.getUserData=function(t,e){return this.userdata||(this.userdata={}),this.userdata[t]&&this.userdata[t][e]?this.userdata[t][e]:""},t.setUserData=function(t,e,n){this.userdata||(this.userdata={}),this.userdata[t]||(this.userdata[t]={}),this.userdata[t][e]=n},t._change_id=function(t,e){"task"!==this._dp._ganttMode?this.changeLinkId(t,e):this.changeTaskId(t,e)},t._row_style=function(e,n){"task"===this._dp._ganttMode&&t.isTaskExists(e)&&(t.getTask(e).$dataprocessor_class=n,t.refreshTask(e))},t._delete_task=function(t,e){},t._sendTaskOrder=function(t,e){e.$drop_target&&(this._dp.setGanttMode("task"),this.getTask(t).target=e.$drop_target,this._dp.setUpdated(t,!0,"order"),delete this.getTask(t).$drop_target)},t.setDp=function(){this._dp=e},t.setDp()}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(2),r=function(){function t(t,e){this.$gantt=t,this.$dp=e,this._dataProcessorHandlers=[]}return t.prototype.attach=function(){var t=this.$dp,e=this.$gantt,i=n(36),r={};function a(n){for(var i=t.updatedRows.slice(),r=!1,a=0;a<i.length&&!t._in_progress[n];a++)i[a]===n&&("inserted"===e.getUserData(n,"!nativeeditor_status")&&(r=!0),t.setUpdated(n,!1));return r}this._dataProcessorHandlers.push(e.attachEvent("onAfterTaskAdd",function(n,i){e.isTaskExists(n)&&(t.setGanttMode("tasks"),t.setUpdated(n,!0,"inserted"))})),this._dataProcessorHandlers.push(e.attachEvent("onAfterTaskUpdate",function(n,i){e.isTaskExists(n)&&(t.setGanttMode("tasks"),t.setUpdated(n,!0),e._sendTaskOrder&&e._sendTaskOrder(n,i))})),this._dataProcessorHandlers.push(e.attachEvent("onBeforeTaskDelete",function(t,n){return!e.config.cascade_delete||(r[t]={tasks:i.getSubtreeTasks(e,t),links:i.getSubtreeLinks(e,t)},!0)})),this._dataProcessorHandlers.push(e.attachEvent("onAfterTaskDelete",function(n,i){if(t.setGanttMode("tasks"),!a(n)){if(e.config.cascade_delete&&r[n]){var o=t.updateMode;t.setUpdateMode("off");var s=r[n];for(var l in s.tasks)a(l)||(t.storeItem(s.tasks[l]),t.setUpdated(l,!0,"deleted"));for(var l in t.setGanttMode("links"),s.links)a(l)||(t.storeItem(s.links[l]),t.setUpdated(l,!0,"deleted"));r[n]=null,"off"!==o&&t.sendAllData(),t.setGanttMode("tasks"),t.setUpdateMode(o)}t.storeItem(i),t.setUpdated(n,!0,"deleted"),"off"===t.updateMode||t._tSend||t.sendAllData()}})),this._dataProcessorHandlers.push(e.attachEvent("onAfterLinkUpdate",function(n,i){e.isLinkExists(n)&&(t.setGanttMode("links"),t.setUpdated(n,!0))})),this._dataProcessorHandlers.push(e.attachEvent("onAfterLinkAdd",function(n,i){e.isLinkExists(n)&&(t.setGanttMode("links"),t.setUpdated(n,!0,"inserted"))})),this._dataProcessorHandlers.push(e.attachEvent("onAfterLinkDelete",function(e,n){t.setGanttMode("links"),!a(e)&&(t.storeItem(n),t.setUpdated(e,!0,"deleted"))})),this._dataProcessorHandlers.push(e.attachEvent("onRowDragEnd",function(t,n){e._sendTaskOrder(t,e.getTask(t))}));var o=null,s=null;this._dataProcessorHandlers.push(e.attachEvent("onTaskIdChange",function(n,i){if(t._waitMode){var r=e.getChildren(i);if(r.length){o=o||{};for(var a=0;a<r.length;a++){var l=this.getTask(r[a]);o[l.id]=l}}var c=function(t){var e=[];return t.$source&&(e=e.concat(t.$source)),t.$target&&(e=e.concat(t.$target)),e}(this.getTask(i));if(c.length){s=s||{};for(a=0;a<c.length;a++){var u=this.getLink(c[a]);s[u.id]=u}}}})),t.attachEvent("onAfterUpdateFinish",function(){(o||s)&&(e.batchUpdate(function(){for(var t in o)e.updateTask(o[t].id);for(var t in s)e.updateLink(s[t].id);o=null,s=null}),o?e._dp.setGanttMode("tasks"):e._dp.setGanttMode("links"))}),t.attachEvent("onBeforeDataSending",function(){if("CUSTOM"===this._tMode)return!0;var t=this._serverProcessor;if("REST-JSON"===this._tMode||"REST"===this._tMode){var n=this._ganttMode;t=t.substring(0,t.indexOf("?")>-1?t.indexOf("?"):t.length),this.serverProcessor=t+("/"===t.slice(-1)?"":"/")+n}else{var i=this._ganttMode+"s";this.serverProcessor=t+e.ajax.urlSeparator(t)+"gantt_mode="+i}return!0}),t.attachEvent("insertCallback",function(t,n,i,r){var a=t.data||e.xml._xmlNodeToJSON(t.firstChild),o={add:e.addTask,isExist:e.isTaskExists};"links"===r&&(o.add=e.addLink,o.isExist=e.isLinkExists),o.isExist.call(e,n)||(a.id=n,o.add.call(e,a))}),t.attachEvent("updateCallback",function(t,n){var i=t.data||e.xml._xmlNodeToJSON(t.firstChild);if(e.isTaskExists(n)){var r=e.getTask(n);for(var a in i){var o=i[a];switch(a){case"id":continue;case"start_date":case"end_date":o=e.defined(e.templates.xml_date)?e.templates.xml_date(o):e.templates.parse_date(o);break;case"duration":r.end_date=e.calculateEndDate({start_date:r.start_date,duration:o,task:r})}r[a]=o}e.updateTask(n),e.refreshData()}}),t.attachEvent("deleteCallback",function(t,n,i,r){var a={delete:e.deleteTask,isExist:e.isTaskExists};"links"===r&&(a.delete=e.deleteLink,a.isExist=e.isLinkExists),a.isExist.call(e,n)&&a.delete.call(e,n)})},t.prototype.detach=function(){var t=this;i.forEach(this._dataProcessorHandlers,function(e){t.$gantt.detachEvent(e)}),this._dataProcessorHandlers=[]},t}();e.default=r},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(4),r=n(2),a=n(0),o=n(197),s=n(196),l=n(195);e.createDataProcessor=function(t){var e,n;t instanceof Function?e=t:t.hasOwnProperty("router")?e=t.router:t.hasOwnProperty("link")&&t.hasOwnProperty("task")&&(e=t),n=e?"CUSTOM":t.mode||"REST-JSON";var i=new c(t.url);return i.init(this),i.setTransactionMode({mode:n,router:e},t.batchUpdate),i};var c=function(){function t(t){this.serverProcessor=t,this.action_param="!nativeeditor_status",this.updatedRows=[],this.autoUpdate=!0,this.updateMode="cell",this._headers=null,this._payload=null,this._postDelim="_",this._routerParametersFormat="parameters",this._waitMode=0,this._in_progress={},this._storage=l.default.create(),this._invalid={},this.messages=[],this.styles={updated:"font-weight:bold;",inserted:"font-weight:bold;",deleted:"text-decoration : line-through;",invalid:"background-color:FFE0E0;",invalid_cell:"border-bottom:2px solid red;",error:"color:red;",clear:"font-weight:normal;text-decoration:none;"},this.enableUTFencoding(!0),i(this)}return t.prototype.setTransactionMode=function(t,e){"object"==typeof t?(this._tMode=t.mode||this._tMode,a.defined(t.headers)&&(this._headers=t.headers),a.defined(t.payload)&&(this._payload=t.payload),this._tSend=!!e):(this._tMode=t,this._tSend=e),"REST"===this._tMode&&(this._tSend=!1),"JSON"===this._tMode||"REST-JSON"===this._tMode?(this._tSend=!1,this._serializeAsJson=!0,this._headers=this._headers||{},this._headers["Content-Type"]="application/json"):this._headers&&!this._headers["Content-Type"]&&(this._headers["Content-Type"]="application/x-www-form-urlencoded"),"CUSTOM"===this._tMode&&(this._tSend=!1,this._router=t.router)},t.prototype.escape=function(t){return this._utf?encodeURIComponent(t):escape(t)},t.prototype.enableUTFencoding=function(t){this._utf=!!t},t.prototype.getSyncState=function(){return!this.updatedRows.length},t.prototype.setUpdateMode=function(t,e){this.autoUpdate="cell"===t,this.updateMode=t,this.dnd=e},t.prototype.ignore=function(t,e){this._silent_mode=!0,t.call(e||window),this._silent_mode=!1},t.prototype.setUpdated=function(t,e,n){if(!this._silent_mode){var i=this.findRow(t);n=n||"updated";var r=this.$gantt.getUserData(t,this.action_param);r&&"updated"===n&&(n=r),e?(this.set_invalid(t,!1),this.updatedRows[i]=t,this.$gantt.setUserData(t,this.action_param,n),this._in_progress[t]&&(this._in_progress[t]="wait")):this.is_invalid(t)||(this.updatedRows.splice(i,1),this.$gantt.setUserData(t,this.action_param,"")),this.markRow(t,e,n),e&&this.autoUpdate&&this.sendData(t)}},t.prototype.markRow=function(t,e,n){var i="",r=this.is_invalid(t);if(r&&(i=this.styles[r],e=!0),this.callEvent("onRowMark",[t,e,n,r])&&(i=this.styles[e?n:"clear"]+" "+i,this.$gantt[this._methods[0]](t,i),r&&r.details)){i+=this.styles[r+"_cell"];for(var a=0;a<r.details.length;a++)r.details[a]&&this.$gantt[this._methods[1]](t,a,i)}},t.prototype.getActionByState=function(t){return"inserted"===t?"create":"updated"===t?"update":"deleted"===t?"delete":"update"},t.prototype.getState=function(t){return this.$gantt.getUserData(t,this.action_param)},t.prototype.is_invalid=function(t){return this._invalid[t]},t.prototype.set_invalid=function(t,e,n){n&&(e={value:e,details:n,toString:function(){return this.value.toString()}}),this._invalid[t]=e},t.prototype.checkBeforeUpdate=function(t){return!0},t.prototype.sendData=function(t){return this.$gantt.editStop&&this.$gantt.editStop(),void 0===t||this._tSend?this.sendAllData():!this._in_progress[t]&&(this.messages=[],!(!this.checkBeforeUpdate(t)&&this.callEvent("onValidationError",[t,this.messages]))&&void this._beforeSendData(this._getRowData(t),t))},t.prototype.serialize=function(t,e){if(this._serializeAsJson)return this._serializeAsJSON(t);if("string"==typeof t)return t;if(void 0!==e)return this.serialize_one(t,"");var n=[],i=[];for(var r in t)t.hasOwnProperty(r)&&(n.push(this.serialize_one(t[r],r+this._postDelim)),i.push(r));return n.push("ids="+this.escape(i.join(","))),this.$gantt.security_key&&n.push("dhx_security="+this.$gantt.security_key),n.join("&")},t.prototype.serialize_one=function(t,e){if("string"==typeof t)return t;var n=[],i="";for(var r in t)if(t.hasOwnProperty(r)){if(("id"===r||r==this.action_param)&&"REST"===this._tMode)continue;i="string"==typeof t[r]||"number"==typeof t[r]?t[r]:JSON.stringify(t[r]),n.push(this.escape((e||"")+r)+"="+this.escape(i))}return n.join("&")},t.prototype.sendAllData=function(){if(this.updatedRows.length){this.messages=[];var t=!0;if(this._forEachUpdatedRow(function(e){t=t&&this.checkBeforeUpdate(e)}),!t&&!this.callEvent("onValidationError",["",this.messages]))return!1;this._tSend?this._sendData(this._getAllData()):this._forEachUpdatedRow(function(t){if(!this._in_progress[t]){if(this.is_invalid(t))return;this._beforeSendData(this._getRowData(t),t)}})}},t.prototype.findRow=function(t){var e=0;for(e=0;e<this.updatedRows.length&&t!=this.updatedRows[e];e++);return e},t.prototype.defineAction=function(t,e){this._uActions||(this._uActions={}),this._uActions[t]=e},t.prototype.afterUpdateCallback=function(t,e,n,i,r){if(this.$gantt){this.setGanttMode(r);var a=t,o="error"!==n&&"invalid"!==n;if(o||this.set_invalid(t,n),this._uActions&&this._uActions[n]&&!this._uActions[n](i))return delete this._in_progress[a];"wait"!==this._in_progress[a]&&this.setUpdated(t,!1);var s=t;switch(n){case"inserted":case"insert":e!=t&&(this.setUpdated(t,!1),this.$gantt[this._methods[2]](t,e),t=e);break;case"delete":case"deleted":return this.$gantt.setUserData(t,this.action_param,"true_deleted"),this.$gantt[this._methods[3]](t),delete this._in_progress[a],this.callEvent("onAfterUpdate",[t,n,e,i])}"wait"!==this._in_progress[a]?(o&&this.$gantt.setUserData(t,this.action_param,""),delete this._in_progress[a]):(delete this._in_progress[a],this.setUpdated(e,!0,this.$gantt.getUserData(t,this.action_param))),this.callEvent("onAfterUpdate",[s,n,e,i])}},t.prototype.afterUpdate=function(t,e,n){var i;i=3===arguments.length?arguments[1]:arguments[4];var r=this.getGanttMode(),a=i.filePath||i.url;r="REST"!==this._tMode&&"REST-JSON"!==this._tMode?-1!==a.indexOf("gantt_mode=links")?"link":"task":a.indexOf("/link")>a.indexOf("/task")?"link":"task",this.setGanttMode(r);var o,s=this.$gantt.ajax;try{o=JSON.parse(e.xmlDoc.responseText)}catch(t){e.xmlDoc.responseText.length||(o={})}if(o){var l=o.action||this.getState(n)||"updated",c=o.sid||n[0],u=o.tid||n[0];return t.afterUpdateCallback(c,u,l,o,r),t.finalizeUpdate(),void this.setGanttMode(r)}var d=s.xmltop("data",e.xmlDoc);if(!d)return this.cleanUpdate(n);var h=s.xpath("//data/action",d);if(!h.length)return this.cleanUpdate(n);for(var f=0;f<h.length;f++){var _=h[f];l=_.getAttribute("type"),c=_.getAttribute("sid"),u=_.getAttribute("tid");t.afterUpdateCallback(c,u,l,_,r)}t.finalizeUpdate()},t.prototype.cleanUpdate=function(t){if(t)for(var e=0;e<t.length;e++)delete this._in_progress[t[e]]},t.prototype.finalizeUpdate=function(){this._waitMode&&this._waitMode--,this.callEvent("onAfterUpdateFinish",[]),this.updatedRows.length||this.callEvent("onFullSync",[])},t.prototype.init=function(t){if(!this._initialized){this.$gantt=t,this.$gantt._dp_init&&this.$gantt._dp_init(this),this._setDefaultTransactionMode(),this.styles={updated:"gantt_updated",order:"gantt_updated",inserted:"gantt_inserted",deleted:"gantt_deleted",invalid:"gantt_invalid",error:"gantt_error",clear:""},this._methods=["_row_style","setCellTextStyle","_change_id","_delete_task"],s.default(this.$gantt,this);var e=new o.default(this.$gantt,this);e.attach(),this.attachEvent("onDestroy",function(){delete this.setGanttMode,delete this._getRowData,delete this.$gantt._dp,delete this.$gantt._change_id,delete this.$gantt._row_style,delete this.$gantt._delete_task,delete this.$gantt._sendTaskOrder,delete this.$gantt,e.detach()}),this.$gantt.callEvent("onDataProcessorReady",[this]),this._initialized=!0}},t.prototype.setOnAfterUpdate=function(t){this.attachEvent("onAfterUpdate",t)},t.prototype.setOnBeforeUpdateHandler=function(t){this.attachEvent("onBeforeDataSending",t)},t.prototype.setAutoUpdate=function(t,e){var n=this;t=t||2e3,this._user=e||(new Date).valueOf(),this._needUpdate=!1,this._updateBusy=!1,this.attachEvent("onAfterUpdate",this.afterAutoUpdate),this.attachEvent("onFullSync",this.fullSync),setInterval(function(){n.loadUpdate()},t)},t.prototype.afterAutoUpdate=function(t,e,n,i){return"collision"!==e||(this._needUpdate=!0,!1)},t.prototype.fullSync=function(){return this._needUpdate&&(this._needUpdate=!1,this.loadUpdate()),!0},t.prototype.getUpdates=function(t,e){var n=this.$gantt.ajax;if(this._updateBusy)return!1;this._updateBusy=!0,n.get(t,e)},t.prototype.loadUpdate=function(){var t=this,e=this.$gantt.ajax,n=this.$gantt.getUserData(0,"version"),i=this.serverProcessor+e.urlSeparator(this.serverProcessor)+["dhx_user="+this._user,"dhx_version="+n].join("&");i=i.replace("editing=true&",""),this.getUpdates(i,function(n){var i=e.xpath("//userdata",n);t.$gantt.setUserData(0,"version",t._getXmlNodeValue(i[0]));var r=e.xpath("//update",n);if(r.length){t._silent_mode=!0;for(var a=0;a<r.length;a++){var o=r[a].getAttribute("status"),s=r[a].getAttribute("id"),l=r[a].getAttribute("parent");switch(o){case"inserted":t.callEvent("insertCallback",[r[a],s,l]);break;case"updated":t.callEvent("updateCallback",[r[a],s,l]);break;case"deleted":t.callEvent("deleteCallback",[r[a],s,l])}}t._silent_mode=!1}t._updateBusy=!1})},t.prototype.destructor=function(){this.callEvent("onDestroy",[]),this.detachAllEvents(),this.updatedRows=[],this._in_progress={},this._invalid={},this._storage.clear(),this._storage=null,this._headers=null,this._payload=null,delete this._initialized},t.prototype.setGanttMode=function(t){"tasks"===t?t="task":"links"===t&&(t="link");var e=this.modes||{},n=this.getGanttMode();n&&(e[n]={_in_progress:this._in_progress,_invalid:this._invalid,_storage:this._storage,updatedRows:this.updatedRows});var i=e[t];i||(i=e[t]={_in_progress:{},_invalid:{},_storage:l.default.create(),updatedRows:[]}),this._in_progress=i._in_progress,this._invalid=i._invalid,this._storage=i._storage,this.updatedRows=i.updatedRows,this.modes=e,this._ganttMode=t},t.prototype.getGanttMode=function(){return this._ganttMode},t.prototype.storeItem=function(t){this._storage.storeItem(t)},t.prototype.url=function(t){this.serverProcessor=this._serverProcessor=t},t.prototype._beforeSendData=function(t,e){if(!this.callEvent("onBeforeUpdate",[e,this.getState(e),t]))return!1;this._sendData(t,e)},t.prototype._serializeAsJSON=function(t){if("string"==typeof t)return t;var e=a.copy(t);return"REST-JSON"===this._tMode&&(delete e.id,delete e[this.action_param]),JSON.stringify(e)},t.prototype._applyPayload=function(t){var e=this.$gantt.ajax;if(this._payload)for(var n in this._payload)t=t+e.urlSeparator(t)+this.escape(n)+"="+this.escape(this._payload[n]);return t},t.prototype._cleanupArgumentsBeforeSend=function(t){var e;if(void 0===t[this.action_param])for(var n in e={},t)e[n]=this._cleanupArgumentsBeforeSend(t[n]);else e=this._cleanupItemBeforeSend(t);return e},t.prototype._cleanupItemBeforeSend=function(t){var e=null;return t&&("deleted"===t[this.action_param]?((e={}).id=t.id,e[this.action_param]=t[this.action_param]):e=t),e},t.prototype._sendData=function(t,e){var n=this;if(t){if(!this.callEvent("onBeforeDataSending",e?[e,this.getState(e),t]:[null,null,t]))return!1;e&&(this._in_progress[e]=(new Date).valueOf());var i=this.$gantt.ajax;if("CUSTOM"!==this._tMode){var r;r={callback:function(i){var r=[];if(e)r.push(e);else if(t)for(var a in t)r.push(a);return n.afterUpdate(n,i,r)},headers:this._headers};var a,o=this.serverProcessor+(this._user?i.urlSeparator(this.serverProcessor)+["dhx_user="+this._user,"dhx_version="+this.$gantt.getUserData(0,"version")].join("&"):""),s=this._applyPayload(o);switch(this._tMode){case"GET":a=this._cleanupArgumentsBeforeSend(t),r.url=s+i.urlSeparator(s)+this.serialize(a,e),r.method="GET";break;case"POST":a=this._cleanupArgumentsBeforeSend(t),r.url=s,r.method="POST",r.data=this.serialize(a,e);break;case"JSON":a={};var l=this._cleanupItemBeforeSend(t);for(var c in l)c!==this.action_param&&"id"!==c&&"gr_id"!==c&&(a[c]=l[c]);r.url=s,r.method="POST",r.data=JSON.stringify({id:e,action:t[this.action_param],data:a});break;case"REST":case"REST-JSON":switch(s=o.replace(/(&|\?)editing=true/,""),a="",this.getState(e)){case"inserted":r.method="POST",r.data=this.serialize(t,e);break;case"deleted":r.method="DELETE",s=s+("/"===s.slice(-1)?"":"/")+e;break;default:r.method="PUT",r.data=this.serialize(t,e),s=s+("/"===s.slice(-1)?"":"/")+e}r.url=this._applyPayload(s)}return this._waitMode++,i.query(r)}var u=this.getState(e),d=this.getActionByState(u),h=this.getGanttMode(),f=function(t){var i=u||"updated",r=e,a=e;t&&(i=t.action||u,r=t.sid||r,a=t.id||t.tid||a),n.afterUpdateCallback(r,a,i,t,h)},_=void 0;if(this._router instanceof Function)if("object"===this._routerParametersFormat){var g={entity:h,action:d,data:t,id:e};_=this._router(g)}else _=this._router(h,d,t,e);else if(this._router[h]instanceof Function)_=this._router[h](d,t,e);else switch(u){case"inserted":_=this._router[h].create(t);break;case"deleted":_=this._router[h].delete(e);break;default:_=this._router[h].update(t,e)}if(_){if(!_.then&&void 0===_.id&&void 0===_.tid&&void 0===_.action)throw new Error("Incorrect router return value. A Promise or a response object is expected");_.then?_.then(f).catch(function(t){t&&t.action?f(t):f({action:"error",value:t})}):f(_)}else f(null)}},t.prototype._forEachUpdatedRow=function(t){for(var e=this.updatedRows.slice(),n=0;n<e.length;n++){var i=e[n];this.$gantt.getUserData(i,this.action_param)&&t.call(this,i)}},t.prototype._setDefaultTransactionMode=function(){this.serverProcessor&&(this.setTransactionMode("POST",!0),this.serverProcessor+=(-1!==this.serverProcessor.indexOf("?")?"&":"?")+"editing=true",this._serverProcessor=this.serverProcessor)},t.prototype._getXmlNodeValue=function(t){return t.firstChild?t.firstChild.nodeValue:""},t.prototype._getAllData=function(){var t={},e=!1;return this._forEachUpdatedRow(function(n){if(!this._in_progress[n]&&!this.is_invalid(n)){var i=this._getRowData(n);this.callEvent("onBeforeUpdate",[n,this.getState(n),i])&&(t[n]=i,e=!0,this._in_progress[n]=(new Date).valueOf())}}),e?t:null},t.prototype._prepareDate=function(t){return this.$gantt.defined(this.$gantt.templates.xml_format)?this.$gantt.templates.xml_format(t):this.$gantt.templates.format_date(t)},t.prototype._prepareArray=function(t,e){var n=this;return e.push(t),t.map(function(t){return r.isDate(t)?n._prepareDate(t):Array.isArray(t)&&!r.arrayIncludes(e,t)?n._prepareArray(t,e):t&&"object"==typeof t&&!r.arrayIncludes(e,t)?n._prepareObject(t,e):t})},t.prototype._prepareObject=function(t,e){var n={};for(var i in e.push(t),t)if("$"!==i.substr(0,1)){var a=t[i];r.isDate(a)?n[i]=this._prepareDate(a):null===a?n[i]="":Array.isArray(a)&&!r.arrayIncludes(e,a)?n[i]=this._prepareArray(a,e):a&&"object"==typeof a&&!r.arrayIncludes(e,a)?n[i]=this._prepareObject(a,e):n[i]=a}return n},t.prototype._prepareDataItem=function(t){var e=this._prepareObject(t,[]);return e[this.action_param]=this.$gantt.getUserData(t.id,this.action_param),e},t.prototype.getStoredItem=function(t){return this._storage.getStoredItem(t)},t.prototype._getRowData=function(t){var e,n=this.$gantt;return"task"===this.getGanttMode()?n.isTaskExists(t)&&(e=this.$gantt.getTask(t)):n.isLinkExists(t)&&(e=this.$gantt.getLink(t)),e||(e=this.getStoredItem(t)),e||(e={id:t}),this._prepareDataItem(e)},t}();e.DataProcessor=c},function(t,e,n){var i=n(198);t.exports={DEPRECATED_api:function(t){return new i.DataProcessor(t)},createDataProcessor:i.createDataProcessor,getDataProcessorModes:i.getAvailableModes}},function(t,e,n){var i=n(10);t.exports={bindDataStore:function(t,e){var n=e.getDatastore(t),r=function(t,e){var i=e.getLayers(),r=n.getItem(t);if(r&&n.isVisible(t))for(var a=0;a<i.length;a++)i[a].render_item(r)},a=function(t){for(var e=t.getLayers(),i=0;i<e.length;i++)e[i].clear();var r=null,a={};for(i=0;i<e.length;i++){var o,s=e[i];if(s.get_visible_range){var l=s.get_visible_range(n),c=l.start+" - "+l.end;a[c]?o=a[c]:(o=n.getIndexRange(l.start,l.end),a[c]=o)}else r||(r=n.getVisibleItems()),o=r;e[i].render_items(o)}},o=function(t){if(t.update_items){var e;if(t.get_visible_range){var i=t.get_visible_range(n);e=n.getIndexRange(i.start,i.end)}else e=n.getVisibleItems();t.update_items(e)}};function s(t){return!!t.$services.getService("state").getState("batchUpdate").batch_update}n.attachEvent("onStoreUpdated",function(n,r,a){if(i(e))return!0;var s=e.$services.getService("layers").getDataRender(t);s&&(s.onUpdateRequest=function(t){o(t)})}),n.attachEvent("onStoreUpdated",function(t,i,r){s(e)||(t&&"move"!=r&&"delete"!=r?(n.callEvent("onBeforeRefreshItem",[i.id]),n.callEvent("onAfterRefreshItem",[i.id])):(n.callEvent("onBeforeRefreshAll",[]),n.callEvent("onAfterRefreshAll",[])))}),n.attachEvent("onAfterRefreshAll",function(){if(i(e))return!0;var n=e.$services.getService("layers").getDataRender(t);n&&!s(e)&&a(n)}),n.attachEvent("onAfterRefreshItem",function(n){if(i(e))return!0;var a=e.$services.getService("layers").getDataRender(t);a&&r(n,a)}),n.attachEvent("onItemOpen",function(){if(i(e))return!0;e.render()}),n.attachEvent("onItemClose",function(){if(i(e))return!0;e.render()}),n.attachEvent("onIdChange",function(a,o){if(i(e))return!0;if(n.callEvent("onBeforeIdChange",[a,o]),!s(e)&&!n.isSilent()){var l=e.$services.getService("layers").getDataRender(t);!function(t,e,n,i){for(var r=0;r<t.length;r++)t[r].change_id(e,n)}(l.getLayers(),a,o,n.getItem(o)),r(o,l)}})}}},function(t,e){t.exports=function(t){var e=null,n=t._removeItemInner;function i(t){e=null,this.callEvent("onAfterUnselect",[t])}return t._removeItemInner=function(t){return e==t&&i.call(this,t),e&&this.eachItem&&this.eachItem(function(t){t.id==e&&i.call(this,t.id)},t),n.apply(this,arguments)},t.attachEvent("onIdChange",function(e,n){t.getSelectedId()==e&&t.silent(function(){t.unselect(e),t.select(n)})}),{select:function(t){if(t){if(e==t)return e;if(!this._skip_refresh&&!this.callEvent("onBeforeSelect",[t]))return!1;this.unselect(),e=t,this._skip_refresh||(this.refresh(t),this.callEvent("onAfterSelect",[t]))}return e},getSelectedId:function(){return e},isSelected:function(t){return t==e},unselect:function(t){(t=t||e)&&(e=null,this._skip_refresh||(this.refresh(t),i.call(this,t)))}}}},function(t,e,n){var i=n(0);t.exports=function(){return{getLinkCount:function(){return this.$data.linksStore.count()},getLink:function(t){return this.$data.linksStore.getItem(t)},getLinks:function(){return this.$data.linksStore.getItems()},isLinkExists:function(t){return this.$data.linksStore.exists(t)},addLink:function(t){return this.$data.linksStore.addItem(t)},updateLink:function(t,e){i.defined(e)||(e=this.getLink(t)),this.$data.linksStore.updateItem(t,e)},deleteLink:function(t){return this.$data.linksStore.removeItem(t)},changeLinkId:function(t,e){return this.$data.linksStore.changeId(t,e)}}}},function(t,e,n){var i=n(0),r=n(2).replaceValidZeroId;t.exports=function(){return{getTask:function(t){t=r(t,this.config.root_id),this.assert(t,"Invalid argument for gantt.getTask");var e=this.$data.tasksStore.getItem(t);return this.assert(e,"Task not found id="+t),e},getTaskByTime:function(t,e){var n=this.$data.tasksStore.getItems(),i=[];if(t||e){t=+t||-1/0,e=+e||1/0;for(var r=0;r<n.length;r++){var a=n[r];+a.start_date<e&&+a.end_date>t&&i.push(a)}}else i=n;return i},isTaskExists:function(t){return!(!this.$data||!this.$data.tasksStore)&&this.$data.tasksStore.exists(t)},updateTask:function(t,e){i.defined(e)||(e=this.getTask(t)),this.$data.tasksStore.updateItem(t,e),this.isTaskExists(t)&&this.refreshTask(t)},addTask:function(t,e,n){return i.defined(t.id)||(t.id=i.uid()),this.isTaskExists(t.id)&&this.getTask(t.id).$index!=t.$index?(t.start_date&&"string"==typeof t.start_date&&(t.start_date=this.date.parseDate(t.start_date,"parse_date")),t.end_date&&"string"==typeof t.end_date&&(t.end_date=this.date.parseDate(t.end_date,"parse_date")),this.$data.tasksStore.updateItem(t.id,t)):(i.defined(e)||(e=this.getParent(t)||0),this.isTaskExists(e)||(e=this.config.root_id),this.setParent(t,e),this.$data.tasksStore.addItem(t,n,e))},deleteTask:function(t){return t=r(t,this.config.root_id),this.$data.tasksStore.removeItem(t)},getTaskCount:function(){return this.$data.tasksStore.count()},getVisibleTaskCount:function(){return this.$data.tasksStore.countVisible()},getTaskIndex:function(t){return this.$data.tasksStore.getBranchIndex(t)},getGlobalTaskIndex:function(t){return t=r(t,this.config.root_id),this.assert(t,"Invalid argument"),this.$data.tasksStore.getIndexById(t)},eachTask:function(t,e,n){return this.$data.tasksStore.eachItem(i.bind(t,n||this),e)},eachParent:function(t,e,n){return this.$data.tasksStore.eachParent(i.bind(t,n||this),e)},changeTaskId:function(t,e){this.$data.tasksStore.changeId(t,e);var n=this.$data.tasksStore.getItem(e),i=[];n.$source&&(i=i.concat(n.$source)),n.$target&&(i=i.concat(n.$target));for(var r=0;r<i.length;r++){var a=this.getLink(i[r]);a.source==t&&(a.source=e),a.target==t&&(a.target=e)}},calculateTaskLevel:function(t){return this.$data.tasksStore.calculateItemLevel(t)},getNext:function(t){return this.$data.tasksStore.getNext(t)},getPrev:function(t){return this.$data.tasksStore.getPrev(t)},getParent:function(t){return this.$data.tasksStore.getParent(t)},setParent:function(t,e,n){return this.$data.tasksStore.setParent(t,e,n)},getSiblings:function(t){return this.$data.tasksStore.getSiblings(t).slice()},getNextSibling:function(t){return this.$data.tasksStore.getNextSibling(t)},getPrevSibling:function(t){return this.$data.tasksStore.getPrevSibling(t)},getTaskByIndex:function(t){var e=this.$data.tasksStore.getIdByIndex(t);return this.isTaskExists(e)?this.getTask(e):null},getChildren:function(t){return this.hasChild(t)?this.$data.tasksStore.getChildren(t).slice():[]},hasChild:function(t){return this.$data.tasksStore.hasChild(t)},open:function(t){this.$data.tasksStore.open(t)},close:function(t){this.$data.tasksStore.close(t)},moveTask:function(t,e,n){return n=r(n,this.config.root_id),this.$data.tasksStore.move.apply(this.$data.tasksStore,arguments)},sort:function(t,e,n,i){var r=!i;this.$data.tasksStore.sort(t,e,n),this.callEvent("onAfterSort",[t,e,n]),r&&this.render()}}}},function(t,e,n){var i=n(0),r=n(203),a=n(202),o=n(40),s=n(38),l=n(201),c=n(200),u=n(10),d=n(2).replaceValidZeroId;function h(){for(var t=this.$services.getService("datastores"),e=[],n=0;n<t.length;n++){var i=this.getDatastore(t[n]);i.$destroyed||e.push(i)}return e}o.default&&(o=o.default);var f=function(){return{createDatastore:function(t){var e="treedatastore"==(t.type||"").toLowerCase()?s:o;if(t){var n=this;t.openInitially=function(){return n.config.open_tree_initially},t.copyOnParse=function(){return n.config.deepcopy_on_parse}}var i=new e(t);if(this.mixin(i,l(i)),t.name){var r="datastore:"+t.name;i.attachEvent("onDestroy",function(){this.$services.dropService(r);for(var e=this.$services.getService("datastores"),n=0;n<e.length;n++)if(e[n]===t.name){e.splice(n,1);break}}.bind(this)),this.$services.dropService(r),this.$services.setService(r,function(){return i});var a=this.$services.getService("datastores");a?a.indexOf(t.name)<0&&a.push(t.name):(a=[],this.$services.setService("datastores",function(){return a}),a.push(t.name)),c.bindDataStore(t.name,this)}return i},getDatastore:function(t){return this.$services.getService("datastore:"+t)},_getDatastores:h,refreshData:function(){var t;u(this)||(t=this.getScrollState()),this.callEvent("onBeforeDataRender",[]);for(var e=h.call(this),n=0;n<e.length;n++)e[n].refresh();this.config.preserve_scroll&&!u(this)&&(t.x||t.y)&&this.scrollTo(t.x,t.y),this.callEvent("onDataRender",[])},isChildOf:function(t,e){return this.$data.tasksStore.isChildOf(t,e)},refreshTask:function(t,e){var n=this.getTask(t),i=this;function r(){if(void 0===e||e){for(var t=0;t<n.$source.length;t++)i.refreshLink(n.$source[t]);for(t=0;t<n.$target.length;t++)i.refreshLink(n.$target[t])}}if(n&&this.isTaskVisible(t))this.$data.tasksStore.refresh(t,!!this.getState("tasksDnd").drag_id||!1===e),r();else if(this.isTaskExists(t)&&this.isTaskExists(this.getParent(t))&&!this._bulk_dnd){this.refreshTask(this.getParent(t));var a=!1;this.eachParent(function(t){(a||this.isSplitTask(t))&&(a=!0)},t),a&&r()}},refreshLink:function(t){this.$data.linksStore.refresh(t,!!this.getState("tasksDnd").drag_id)},silent:function(t){var e=this;e.$data.tasksStore.silent(function(){e.$data.linksStore.silent(function(){t()})})},clearAll:function(){for(var t=h.call(this),e=0;e<t.length;e++)t[e].silent(function(){t[e].clearAll()});for(e=0;e<t.length;e++)t[e].clearAll();this._update_flags(),this.userdata={},this.callEvent("onClear",[]),this.render()},_clear_data:function(){this.$data.tasksStore.clearAll(),this.$data.linksStore.clearAll(),this._update_flags(),this.userdata={}},selectTask:function(t){var e=this.$data.tasksStore;return!!this.config.select_task&&((t=d(t,this.config.root_id))&&e.select(t),e.getSelectedId())},unselectTask:function(t){this.$data.tasksStore.unselect(t)},isSelectedTask:function(t){return this.$data.tasksStore.isSelected(t)},getSelectedId:function(){return this.$data.tasksStore.getSelectedId()}}};t.exports={create:function(){var t=i.mixin({},f());return i.mixin(t,r()),i.mixin(t,a()),t}}},function(t,e,n){var i=n(0),r=n(204),a=n(37),o=n(11);t.exports=function(t){var e=r.create();i.mixin(t,e);var s=t.createDatastore({name:"task",type:"treeDatastore",rootId:function(){return t.config.root_id},initItem:i.bind(function(e){this.defined(e.id)||(e.id=this.uid()),e.start_date&&(e.start_date=t.date.parseDate(e.start_date,"parse_date")),e.end_date&&(e.end_date=t.date.parseDate(e.end_date,"parse_date"));var n=null;(e.duration||0===e.duration)&&(e.duration=n=1*e.duration),n&&(e.start_date&&!e.end_date?e.end_date=this.calculateEndDate(e):!e.start_date&&e.end_date&&(e.start_date=this.calculateEndDate({start_date:e.end_date,duration:-e.duration,task:e}))),e.progress=Number(e.progress)||0,this._isAllowedUnscheduledTask(e)&&this._set_default_task_timing(e),this._init_task_timing(e),e.start_date&&e.end_date&&this.correctTaskWorkTime(e),e.$source=[],e.$target=[];var r=this.$data.tasksStore.getItem(e.id);return r&&!i.defined(e.open)&&(e.$open=r.$open),void 0===e.parent&&(e.parent=this.config.root_id),e},t),getConfig:function(){return t.config}}),l=t.createDatastore({name:"link",initItem:i.bind(function(t){return this.defined(t.id)||(t.id=this.uid()),t},t)});function c(e){var n=t.isTaskVisible(e);if(!n&&t.isTaskExists(e)){var i=t.getParent(e);t.isTaskExists(i)&&t.isTaskVisible(i)&&(i=t.getTask(i),t.isSplitTask(i)&&(n=!0))}return n}function u(e){if(t.isTaskExists(e.source)){var n=t.getTask(e.source);n.$source=n.$source||[],n.$source.push(e.id)}if(t.isTaskExists(e.target)){var i=t.getTask(e.target);i.$target=i.$target||[],i.$target.push(e.id)}}function d(e){if(t.isTaskExists(e.source))for(var n=t.getTask(e.source),i=0;i<n.$source.length;i++)if(n.$source[i]==e.id){n.$source.splice(i,1);break}if(t.isTaskExists(e.target)){var r=t.getTask(e.target);for(i=0;i<r.$target.length;i++)if(r.$target[i]==e.id){r.$target.splice(i,1);break}}}function h(){for(var e=null,n=t.$data.tasksStore.getItems(),i=0,r=n.length;i<r;i++)(e=n[i]).$source=[],e.$target=[];var a=t.$data.linksStore.getItems();for(i=0,r=a.length;i<r;i++)u(a[i])}function f(t){var e=t.source,n=t.target;for(var i in t.events)!function(t,i){e.attachEvent(t,function(){return n.callEvent(i,Array.prototype.slice.call(arguments))},i)}(i,t.events[i])}t.attachEvent("onDestroy",function(){s.destructor(),l.destructor()}),t.attachEvent("onLinkValidation",function(e){if(t.isLinkExists(e.id)||"predecessor_generated"===e.id)return!0;for(var n=t.getTask(e.source).$source,i=0;i<n.length;i++){var r=t.getLink(n[i]),a=e.source==r.source,o=e.target==r.target,s=e.type==r.type;if(a&&o&&s)return!1}return!0}),s.attachEvent("onBeforeRefreshAll",function(){for(var e=s.getVisibleItems(),n=0;n<e.length;n++){var i=e[n];i.$index=n,i.$local_index=t.getTaskIndex(i.id),t.resetProjectDates(i)}}),s.attachEvent("onFilterItem",function(e,n){if(t.config.show_tasks_outside_timescale)return!0;var i=null,r=null;if(t.config.start_date&&t.config.end_date){if(t._isAllowedUnscheduledTask(n))return!0;if(i=t.config.start_date.valueOf(),r=t.config.end_date.valueOf(),+n.start_date>r||+n.end_date<+i)return!1}return!0}),s.attachEvent("onIdChange",function(e,n){t._update_flags(e,n);var i=t.getTask(n);s.isSilent()||(i.$split_subtask||i.rollup)&&t.eachParent(function(e){t.refreshTask(e.id)},n)}),s.attachEvent("onAfterUpdate",function(e){if(t._update_parents(e),t.getState("batchUpdate").batch_update)return!0;var n=s.getItem(e);n.$source||(n.$source=[]);for(var i=0;i<n.$source.length;i++)l.refresh(n.$source[i]);for(n.$target||(n.$target=[]),i=0;i<n.$target.length;i++)l.refresh(n.$target[i])}),s.attachEvent("onBeforeItemMove",function(e,n,i){return!o(e,t,s)||(console.log("The placeholder task cannot be moved to another position."),!1)}),s.attachEvent("onAfterItemMove",function(e,n,i){var r=t.getTask(e);null!==this.getNextSibling(e)?r.$drop_target=this.getNextSibling(e):null!==this.getPrevSibling(e)?r.$drop_target="next:"+this.getPrevSibling(e):r.$drop_target="next:null"}),s.attachEvent("onStoreUpdated",function(e,n,i){if("delete"==i&&t._update_flags(e,null),!t.$services.getService("state").getState("batchUpdate").batch_update){if(t.config.fit_tasks&&"paint"!==i){var r=t.getState();a(t);var o=t.getState();if(+r.min_date!=+o.min_date||+r.max_date!=+o.max_date)return t.render(),t.callEvent("onScaleAdjusted",[]),!0}"add"==i||"move"==i||"delete"==i?t.$layout&&t.$layout.resize():e||l.refresh()}}),l.attachEvent("onAfterAdd",function(t,e){u(e)}),l.attachEvent("onAfterUpdate",function(t,e){h()}),l.attachEvent("onAfterDelete",function(t,e){d(e)}),l.attachEvent("onBeforeIdChange",function(e,n){d(t.mixin({id:e},t.$data.linksStore.getItem(n))),u(t.$data.linksStore.getItem(n))}),l.attachEvent("onFilterItem",function(e,n){if(!t.config.show_links)return!1;var i=c(n.source),r=c(n.target);return!(!i||!r||t._isAllowedUnscheduledTask(t.getTask(n.source))||t._isAllowedUnscheduledTask(t.getTask(n.target)))&&t.callEvent("onBeforeLinkDisplay",[e,n])}),function(){var e=n(36),i={};t.attachEvent("onBeforeTaskDelete",function(n,r){return i[n]=e.getSubtreeLinks(t,n),!0}),t.attachEvent("onAfterTaskDelete",function(e,n){i[e]&&t.$data.linksStore.silent(function(){for(var n in i[e])t.$data.linksStore.removeItem(n),d(i[e][n]);i[e]=null})})}(),t.attachEvent("onAfterLinkDelete",function(e,n){t.refreshTask(n.source),t.refreshTask(n.target)}),t.attachEvent("onParse",h),f({source:l,target:t,events:{onItemLoading:"onLinkLoading",onBeforeAdd:"onBeforeLinkAdd",onAfterAdd:"onAfterLinkAdd",onBeforeUpdate:"onBeforeLinkUpdate",onAfterUpdate:"onAfterLinkUpdate",onBeforeDelete:"onBeforeLinkDelete",onAfterDelete:"onAfterLinkDelete",onIdChange:"onLinkIdChange"}}),f({source:s,target:t,events:{onItemLoading:"onTaskLoading",onBeforeAdd:"onBeforeTaskAdd",onAfterAdd:"onAfterTaskAdd",onBeforeUpdate:"onBeforeTaskUpdate",onAfterUpdate:"onAfterTaskUpdate",onBeforeDelete:"onBeforeTaskDelete",onAfterDelete:"onAfterTaskDelete",onIdChange:"onTaskIdChange",onBeforeItemMove:"onBeforeTaskMove",onAfterItemMove:"onAfterTaskMove",onFilterItem:"onBeforeTaskDisplay",onItemOpen:"onTaskOpened",onItemClose:"onTaskClosed",onBeforeSelect:"onBeforeTaskSelected",onAfterSelect:"onTaskSelected",onAfterUnselect:"onTaskUnselected"}}),t.$data={tasksStore:s,linksStore:l}}},function(t,e,n){(function(t,e){!function(t,n){"use strict";if(!t.setImmediate){var i,r=1,a={},o=!1,s=t.document,l=Object.getPrototypeOf&&Object.getPrototypeOf(t);l=l&&l.setTimeout?l:t,"[object process]"==={}.toString.call(t.process)?i=function(t){e.nextTick(function(){u(t)})}:function(){if(t.postMessage&&!t.importScripts){var e=!0,n=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=n,e}}()?function(){var e="setImmediate$"+Math.random()+"$",n=function(n){n.source===t&&"string"==typeof n.data&&0===n.data.indexOf(e)&&u(+n.data.slice(e.length))};t.addEventListener?t.addEventListener("message",n,!1):t.attachEvent("onmessage",n),i=function(n){t.postMessage(e+n,"*")}}():t.MessageChannel?function(){var t=new MessageChannel;t.port1.onmessage=function(t){u(t.data)},i=function(e){t.port2.postMessage(e)}}():s&&"onreadystatechange"in s.createElement("script")?function(){var t=s.documentElement;i=function(e){var n=s.createElement("script");n.onreadystatechange=function(){u(e),n.onreadystatechange=null,t.removeChild(n),n=null},t.appendChild(n)}}():i=function(t){setTimeout(u,0,t)},l.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var o={callback:t,args:e};return a[r]=o,i(r),r++},l.clearImmediate=c}function c(t){delete a[t]}function u(t){if(o)setTimeout(u,0,t);else{var e=a[t];if(e){o=!0;try{!function(t){var e=t.callback,i=t.args;switch(i.length){case 0:e();break;case 1:e(i[0]);break;case 2:e(i[0],i[1]);break;case 3:e(i[0],i[1],i[2]);break;default:e.apply(n,i)}}(e)}finally{c(t),o=!1}}}}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,n(14),n(41))},function(t,e,n){(function(t){var i=void 0!==t&&t||"undefined"!=typeof self&&self||window,r=Function.prototype.apply;function a(t,e){this._id=t,this._clearFn=e}e.setTimeout=function(){return new a(r.call(setTimeout,i,arguments),clearTimeout)},e.setInterval=function(){return new a(r.call(setInterval,i,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},a.prototype.unref=a.prototype.ref=function(){},a.prototype.close=function(){this._clearFn.call(i,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},n(206),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(this,n(14))},function(t,e,n){(function(n,i,r){var a,o,s;function l(t){"@babel/helpers - typeof";return(l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)} /* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2018 Petka Antonov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */!function(n){"object"==l(e)&&void 0!==t?t.exports=n():(o=[],void 0===(s="function"==typeof(a=n)?a.apply(e,o):a)||(t.exports=s))}(function(){var t,e,a;return function t(e,n,i){function r(o,s){if(!n[o]){if(!e[o]){var l="function"==typeof _dereq_&&_dereq_;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[o]={exports:{}};e[o][0].call(u.exports,function(t){var n=e[o][1][t];return r(n||t)},u,u.exports,t,e,n,i)}return n[o].exports}for(var a="function"==typeof _dereq_&&_dereq_,o=0;o<i.length;o++)r(i[o]);return r}({1:[function(t,e,n){"use strict";e.exports=function(t){var e=t._SomePromiseArray;function n(t){var n=new e(t),i=n.promise();return n.setHowMany(1),n.setUnwrap(),n.init(),i}t.any=function(t){return n(t)},t.prototype.any=function(){return n(this)}}},{}],2:[function(t,e,i){"use strict";var r;try{throw new Error}catch(t){r=t}var a=t("./schedule"),o=t("./queue"),s=t("./util");function l(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new o(16),this._normalQueue=new o(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=a}function c(t,e,n){this._lateQueue.push(t,e,n),this._queueTick()}function u(t,e,n){this._normalQueue.push(t,e,n),this._queueTick()}function d(t){this._normalQueue._pushOne(t),this._queueTick()}function h(t){for(;t.length()>0;)f(t)}function f(t){var e=t.shift();if("function"!=typeof e)e._settlePromises();else{var n=t.shift(),i=t.shift();e.call(n,i)}}l.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},l.prototype.hasCustomScheduler=function(){return this._customScheduler},l.prototype.enableTrampoline=function(){this._trampolineEnabled=!0},l.prototype.disableTrampolineIfNecessary=function(){s.hasDevTools&&(this._trampolineEnabled=!1)},l.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},l.prototype.fatalError=function(t,e){e?(n.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),n.exit(2)):this.throwLater(t)},l.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(t){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},s.hasDevTools?(l.prototype.invokeLater=function(t,e,n){this._trampolineEnabled?c.call(this,t,e,n):this._schedule(function(){setTimeout(function(){t.call(e,n)},100)})},l.prototype.invoke=function(t,e,n){this._trampolineEnabled?u.call(this,t,e,n):this._schedule(function(){t.call(e,n)})},l.prototype.settlePromises=function(t){this._trampolineEnabled?d.call(this,t):this._schedule(function(){t._settlePromises()})}):(l.prototype.invokeLater=c,l.prototype.invoke=u,l.prototype.settlePromises=d),l.prototype._drainQueues=function(){h(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,h(this._lateQueue)},l.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},l.prototype._reset=function(){this._isTickUsed=!1},e.exports=l,e.exports.firstLineError=r},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,i){var r=!1,a=function(t,e){this._reject(e)},o=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(a,a,null,this,t)},s=function(t,e){0==(50397184&this._bitField)&&this._resolveCallback(e.target)},l=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(a){r||(r=!0,t.prototype._propagateFrom=i.propagateFromFunction(),t.prototype._boundValue=i.boundValueFunction());var c=n(a),u=new t(e);u._propagateFrom(this,1);var d=this._target();if(u._setBoundTo(c),c instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:d,bindingPromise:c};d._then(e,o,void 0,u,h),c._then(s,l,void 0,u,h),u._setOnCancel(c)}else u._resolveCallback(d);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152==(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";var i;"undefined"!=typeof Promise&&(i=Promise);var r=t("./promise")();r.noConflict=function(){try{Promise===r&&(Promise=i)}catch(t){}return r},e.exports=r},{"./promise":22}],5:[function(t,e,n){"use strict";var i=Object.create;if(i){var r=i(null),a=i(null);r[" size"]=a[" size"]=0}e.exports=function(e){var n=t("./util"),i=n.canEvaluate;n.isIdentifier;function r(t){return function(t,i){var r;if(null!=t&&(r=t[i]),"function"!=typeof r){var a="Object "+n.classString(t)+" has no method '"+n.toString(i)+"'";throw new e.TypeError(a)}return r}(t,this.pop()).apply(t,this)}function a(t){return t[this]}function o(t){var e=+this;return e<0&&(e=Math.max(0,e+t.length)),t[e]}e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e;if("number"==typeof t)e=o;else if(i){var n=(void 0)(t);e=null!==n?n:a}else e=a;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,i,r){var a=t("./util"),o=a.tryCatch,s=a.errorObj,l=e._async;e.prototype.break=e.prototype.cancel=function(){if(!r.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),l.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(a.isArray(t))for(var n=0;n<t.length;++n)this._doInvokeOnCancel(t[n],e);else if(void 0!==t)if("function"==typeof t){if(!e){var i=o(t).call(this._boundValue());i===s&&(this._attachExtraTrace(i.e),l.throwLater(i.e))}}else t._resultCancelled(this)},e.prototype._invokeOnCancel=function(){var t=this._onCancel();this._unsetOnCancel(),l.invoke(this._doInvokeOnCancel,this,t)},e.prototype._invokeInternalOnCancel=function(){this._isCancellable()&&(this._doInvokeOnCancel(this._onCancel(),!0),this._unsetOnCancel())},e.prototype._resultCancelled=function(){this.cancel()}}},{"./util":36}],7:[function(t,e,n){"use strict";e.exports=function(e){var n=t("./util"),i=t("./es5").keys,r=n.tryCatch,a=n.errorObj;return function(t,o,s){return function(l){var c=s._boundValue();t:for(var u=0;u<t.length;++u){var d=t[u];if(d===Error||null!=d&&d.prototype instanceof Error){if(l instanceof d)return r(o).call(c,l)}else if("function"==typeof d){var h=r(d).call(c,l);if(h===a)return h;if(h)return r(o).call(c,l)}else if(n.isObject(l)){for(var f=i(d),_=0;_<f.length;++_){var g=f[_];if(d[g]!=l[g])continue t}return r(o).call(c,l)}}return e}}}},{"./es5":13,"./util":36}],8:[function(t,e,n){"use strict";e.exports=function(t){var e=!1,n=[];function i(){this._trace=new i.CapturedTrace(r())}function r(){var t=n.length-1;if(t>=0)return n[t]}return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},i.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,n.push(this._trace))},i.prototype._popContext=function(){if(void 0!==this._trace){var t=n.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},i.CapturedTrace=null,i.create=function(){if(e)return new i},i.deactivateLongStackTraces=function(){},i.activateLongStackTraces=function(){var n=t.prototype._pushContext,a=t.prototype._popContext,o=t._peekContext,s=t.prototype._peekContext,l=t.prototype._promiseCreated;i.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=a,t._peekContext=o,t.prototype._peekContext=s,t.prototype._promiseCreated=l,e=!1},e=!0,t.prototype._pushContext=i.prototype._pushContext,t.prototype._popContext=i.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},i}},{}],9:[function(t,e,i){"use strict";e.exports=function(e,i){var r,a,o,s=e._getDomain,c=e._async,u=t("./errors").Warning,d=t("./util"),h=t("./es5"),f=d.canAttachTrace,_=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,g=/\((?:timers\.js):\d+:\d+\)/,p=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,v=null,m=null,y=!1,k=!(0==d.env("BLUEBIRD_DEBUG")),b=!(0==d.env("BLUEBIRD_WARNINGS")||!k&&!d.env("BLUEBIRD_WARNINGS")),w=!(0==d.env("BLUEBIRD_LONG_STACK_TRACES")||!k&&!d.env("BLUEBIRD_LONG_STACK_TRACES")),x=0!=d.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(b||!!d.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0==(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){q("rejectionHandled",r,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!=(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),q("unhandledRejection",a,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return z(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=s();a="function"==typeof t?null===e?t:d.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=s();r="function"==typeof t?null===e?t:d.domainBind(e,t):void 0};var $=function(){};e.longStackTraces=function(){if(c.haveItemsQueued()&&!tt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!tt.longStackTraces&&Y()){var t=e.prototype._captureStackTrace,n=e.prototype._attachExtraTrace,r=e.prototype._dereferenceTrace;tt.longStackTraces=!0,$=function(){if(c.haveItemsQueued()&&!tt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=n,e.prototype._dereferenceTrace=r,i.deactivateLongStackTraces(),c.enableTrampoline(),tt.longStackTraces=!1},e.prototype._captureStackTrace=H,e.prototype._attachExtraTrace=F,e.prototype._dereferenceTrace=B,i.activateLongStackTraces(),c.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return tt.longStackTraces&&Y()};var S=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return d.global.dispatchEvent(t),function(t,e){var n={detail:e,cancelable:!0};h.defineProperty(n,"promise",{value:e.promise}),h.defineProperty(n,"reason",{value:e.reason});var i=new CustomEvent(t.toLowerCase(),n);return!d.global.dispatchEvent(i)}}if("function"==typeof Event){t=new Event("CustomEvent");return d.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,h.defineProperty(n,"promise",{value:e.promise}),h.defineProperty(n,"reason",{value:e.reason}),!d.global.dispatchEvent(n)}}return(t=document.createEvent("CustomEvent")).initCustomEvent("testingtheevent",!1,!0,{}),d.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!d.global.dispatchEvent(n)}}catch(t){}return function(){return!1}}(),T=d.isNode?function(){return n.emit.apply(n,arguments)}:d.global?function(t){var e="on"+t.toLowerCase(),n=d.global[e];return!!n&&(n.apply(d.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function C(t,e){return{promise:e}}var E={promiseCreated:C,promiseFulfilled:C,promiseRejected:C,promiseResolved:C,promiseCancelled:C,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:C},D=function(t){var e=!1;try{e=T.apply(null,arguments)}catch(t){c.throwLater(t),e=!0}var n=!1;try{n=S(t,E[t].apply(null,arguments))}catch(t){c.throwLater(t),n=!0}return n||e};function A(){return!1}function M(t,e,n){var i=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+d.toString(t));i._attachCancellationCallback(t)})}catch(t){return t}}function I(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?d.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function N(){return this._onCancelField}function P(t){this._onCancelField=t}function L(){this._cancellationParent=void 0,this._onCancelField=void 0}function O(t,e){if(0!=(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!=(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}e.config=function(t){if("longStackTraces"in(t=Object(t))&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&$()),"warnings"in t){var n=t.warnings;tt.warnings=!!n,x=tt.warnings,d.isObject(n)&&"wForgottenReturn"in n&&(x=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!tt.cancellation){if(c.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=L,e.prototype._propagateFrom=O,e.prototype._onCancel=N,e.prototype._setOnCancel=P,e.prototype._attachCancellationCallback=I,e.prototype._execute=M,R=O,tt.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!tt.monitoring?(tt.monitoring=!0,e.prototype._fireEvent=D):!t.monitoring&&tt.monitoring&&(tt.monitoring=!1,e.prototype._fireEvent=A)),e},e.prototype._fireEvent=A,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(t){return t}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._dereferenceTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var R=function(t,e){0!=(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)};function j(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function H(){this._trace=new Q(this._peekContext())}function F(t,e){if(f(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=W(t);d.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),d.notEnumerableProp(t,"__stackCleaned__",!0)}}}function B(){this._trace=void 0}function z(t,n,i){if(tt.warnings){var r,a=new u(t);if(n)i._attachExtraTrace(a);else if(tt.longStackTraces&&(r=e._peekContext()))r.attachExtraTrace(a);else{var o=W(a);a.stack=o.message+"\n"+o.stack.join("\n")}D("warning",a)||U(a,"",!0)}}function V(t){for(var e=[],n=0;n<t.length;++n){var i=t[n],r=" (No stack trace)"===i||v.test(i),a=r&&K(i);r&&!a&&(y&&" "!==i.charAt(0)&&(i=" "+i),e.push(i))}return e}function W(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?function(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),n=0;n<e.length;++n){var i=e[n];if(" (No stack trace)"===i||v.test(i))break}return n>0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:V(e)}}function U(t,e,n){if("undefined"!=typeof console){var i;if(d.isObject(t)){var r=t.stack;i=e+m(r,t)}else i=e+String(t);"function"==typeof o?o(i,n):"function"!=typeof console.log&&"object"!==l(console.log)||console.log(i)}}function q(t,e,n,i){var r=!1;try{"function"==typeof e&&(r=!0,"rejectionHandled"===t?e(i):e(n,i))}catch(t){c.throwLater(t)}"unhandledRejection"===t?D(t,n,i)||r||U(n,"Unhandled rejection "):D(t,i)}function G(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():d.toString(t);if(/\[object [a-zA-Z0-9$_]+\]/.test(e))try{e=JSON.stringify(t)}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+function(t){if(t.length<41)return t;return t.substr(0,38)+"..."}(e)+">, no stack trace)"}function Y(){return"function"==typeof Z}var K=function(){return!1},J=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function X(t){var e=t.match(J);if(e)return{fileName:e[1],line:parseInt(e[2],10)}}function Q(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);Z(this,Q),e>32&&this.uncycle()}d.inherits(Q,Error),i.CapturedTrace=Q,Q.prototype.uncycle=function(){var t=this._length;if(!(t<2)){for(var e=[],n={},i=0,r=this;void 0!==r;++i)e.push(r),r=r._parent;for(i=(t=this._length=i)-1;i>=0;--i){var a=e[i].stack;void 0===n[a]&&(n[a]=i)}for(i=0;i<t;++i){var o=n[e[i].stack];if(void 0!==o&&o!==i){o>0&&(e[o-1]._parent=void 0,e[o-1]._length=1),e[i]._parent=void 0,e[i]._length=1;var s=i>0?e[i-1]:this;o<t-1?(s._parent=e[o+1],s._parent.uncycle(),s._length=s._parent._length+1):(s._parent=void 0,s._length=1);for(var l=s._length+1,c=i-2;c>=0;--c)e[c]._length=l,l++;return}}}},Q.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=W(t),n=e.message,i=[e.stack],r=this;void 0!==r;)i.push(V(r.stack.split("\n"))),r=r._parent;!function(t){for(var e=t[0],n=1;n<t.length;++n){for(var i=t[n],r=e.length-1,a=e[r],o=-1,s=i.length-1;s>=0;--s)if(i[s]===a){o=s;break}for(s=o;s>=0;--s){var l=i[s];if(e[r]!==l)break;e.pop(),r--}e=i}}(i),function(t){for(var e=0;e<t.length;++e)(0===t[e].length||e+1<t.length&&t[e][0]===t[e+1][0])&&(t.splice(e,1),e--)}(i),d.notEnumerableProp(t,"stack",function(t,e){for(var n=0;n<e.length-1;++n)e[n].push("From previous event:"),e[n]=e[n].join("\n");return n<e.length&&(e[n]=e[n].join("\n")),t+"\n"+e.join("\n")}(n,i)),d.notEnumerableProp(t,"__stackCleaned__",!0)}};var Z=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():G(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,v=t,m=e;var n=Error.captureStackTrace;return K=function(t){return _.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var i,r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return v=/@/,m=e,y=!0,function(t){t.stack=(new Error).stack};try{throw new Error}catch(t){i="stack"in t}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(m=function(t,e){return"string"==typeof t?t:"object"!==l(e)&&"function"!=typeof e||void 0===e.name||void 0===e.message?G(e):e.toString()},null):(v=t,m=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}();"undefined"!=typeof console&&void 0!==console.warn&&(o=function(t){console.warn(t)},d.isNode&&n.stderr.isTTY?o=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:d.isNode||"string"!=typeof(new Error).stack||(o=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var tt={warnings:b,longStackTraces:!1,cancellation:!1,monitoring:!1};return w&&e.longStackTraces(),{longStackTraces:function(){return tt.longStackTraces},warnings:function(){return tt.warnings},cancellation:function(){return tt.cancellation},monitoring:function(){return tt.monitoring},propagateFromFunction:function(){return R},boundValueFunction:function(){return j},checkForgottenReturns:function(t,e,n,i,r){if(void 0===t&&null!==e&&x){if(void 0!==r&&r._returnedNonUndefined())return;if(0==(65535&i._bitField))return;n&&(n+=" ");var a="",o="";if(e._trace){for(var s=e._trace.stack.split("\n"),l=V(s),c=l.length-1;c>=0;--c){var u=l[c];if(!g.test(u)){var d=u.match(p);d&&(a="at "+d[1]+":"+d[2]+":"+d[3]+" ");break}}if(l.length>0){var h=l[0];for(c=0;c<s.length;++c)if(s[c]===h){c>0&&(o="\n"+s[c-1]);break}}}var f="a promise was created in a "+n+"handler "+a+"but was not returned from it, see http://goo.gl/rRqMUw"+o;i._warn(f,!0,e)}},setBounds:function(t,e){if(Y()){for(var n,i,r=t.stack.split("\n"),a=e.stack.split("\n"),o=-1,s=-1,l=0;l<r.length;++l)if(c=X(r[l])){n=c.fileName,o=c.line;break}for(l=0;l<a.length;++l){var c;if(c=X(a[l])){i=c.fileName,s=c.line;break}}o<0||s<0||!n||!i||n!==i||o>=s||(K=function(t){if(_.test(t))return!0;var e=X(t);return!!(e&&e.fileName===n&&o<=e.line&&e.line<=s)})}},warn:z,deprecated:function(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),z(n)},CapturedTrace:Q,fireDomEvent:S,fireGlobalEvent:T}}},{"./errors":12,"./es5":13,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype.return=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype.throw=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1];return this.caught(t,function(){throw e})},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var i=arguments[1];i instanceof t&&i.suppressUnhandledRejections();return this.caught(n,function(){return i})}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){var n=t.reduce,i=t.all;function r(){return i(this)}t.prototype.each=function(t){return n(this,t,e,0)._then(r,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return n(this,t,e,e)},t.each=function(t,i){return n(t,i,e,0)._then(r,void 0,void 0,t,void 0)},t.mapSeries=function(t,i){return n(t,i,e,e)}}},{}],12:[function(t,e,n){"use strict";var i,r,a=t("./es5"),o=a.freeze,s=t("./util"),l=s.inherits,c=s.notEnumerableProp;function u(t,e){function n(i){if(!(this instanceof n))return new n(i);c(this,"message","string"==typeof i?i:e),c(this,"name",t),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return l(n,Error),n}var d=u("Warning","warning"),h=u("CancellationError","cancellation error"),f=u("TimeoutError","timeout error"),_=u("AggregateError","aggregate error");try{i=TypeError,r=RangeError}catch(t){i=u("TypeError","type error"),r=u("RangeError","range error")}for(var g="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),p=0;p<g.length;++p)"function"==typeof Array.prototype[g[p]]&&(_.prototype[g[p]]=Array.prototype[g[p]]);a.defineProperty(_.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),_.prototype.isOperational=!0;var v=0;function m(t){if(!(this instanceof m))return new m(t);c(this,"name","OperationalError"),c(this,"message",t),this.cause=t,this.isOperational=!0,t instanceof Error?(c(this,"message",t.message),c(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}_.prototype.toString=function(){var t=Array(4*v+1).join(" "),e="\n"+t+"AggregateError of:\n";v++,t=Array(4*v+1).join(" ");for(var n=0;n<this.length;++n){for(var i=this[n]===this?"[Circular AggregateError]":this[n]+"",r=i.split("\n"),a=0;a<r.length;++a)r[a]=t+r[a];e+=(i=r.join("\n"))+"\n"}return v--,e},l(m,Error);var y=Error.__BluebirdErrorTypes__;y||(y=o({CancellationError:h,TimeoutError:f,OperationalError:m,RejectionError:m,AggregateError:_}),a.defineProperty(Error,"__BluebirdErrorTypes__",{value:y,writable:!1,enumerable:!1,configurable:!1})),e.exports={Error:Error,TypeError:i,RangeError:r,CancellationError:y.CancellationError,OperationalError:y.OperationalError,TimeoutError:y.TimeoutError,AggregateError:y.AggregateError,Warning:d}},{"./es5":13,"./util":36}],13:[function(t,e,n){var i=function(){"use strict";return void 0===this}();if(i)e.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:i,propertyIsWritable:function(t,e){var n=Object.getOwnPropertyDescriptor(t,e);return!(n&&!n.writable&&!n.set)}};else{var r={}.hasOwnProperty,a={}.toString,o={}.constructor.prototype,s=function(t){var e=[];for(var n in t)r.call(t,n)&&e.push(n);return e};e.exports={isArray:function(t){try{return"[object Array]"===a.call(t)}catch(t){return!1}},keys:s,names:s,defineProperty:function(t,e,n){return t[e]=n.value,t},getDescriptor:function(t,e){return{value:t[e]}},freeze:function(t){return t},getPrototypeOf:function(t){try{return Object(t).constructor.prototype}catch(t){return o}},isES5:i,propertyIsWritable:function(){return!0}}}},{}],14:[function(t,e,n){"use strict";e.exports=function(t,e){var n=t.map;t.prototype.filter=function(t,i){return n(this,t,i,e)},t.filter=function(t,i,r){return n(t,i,r,e)}}},{}],15:[function(t,e,n){"use strict";e.exports=function(e,n,i){var r=t("./util"),a=e.CancellationError,o=r.errorObj,s=t("./catch_filter")(i);function l(t,e,n){this.promise=t,this.type=e,this.handler=n,this.called=!1,this.cancelPromise=null}function c(t){this.finallyHandler=t}function u(t,e){return null!=t.cancelPromise&&(arguments.length>1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0)}function d(){return f.call(this,this.promise._target()._settledValue())}function h(t){if(!u(this,t))return o.e=t,o}function f(t){var r=this.promise,s=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?s.call(r._boundValue()):s.call(r._boundValue(),t);if(l===i)return l;if(void 0!==l){r._setReturnedNonUndefined();var f=n(l,r);if(f instanceof e){if(null!=this.cancelPromise){if(f._isCancelled()){var _=new a("late cancellation observer");return r._attachExtraTrace(_),o.e=_,o}f.isPending()&&f._attachCancellationCallback(new c(this))}return f._then(d,h,void 0,this,void 0)}}}return r.isRejected()?(u(this),o.e=t,o):(u(this),t)}return l.prototype.isFinallyHandler=function(){return 0===this.type},c.prototype._resultCancelled=function(){u(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,i){return"function"!=typeof t?this.then():this._then(n,i,void 0,new l(this,e,t),void 0)},e.prototype.lastly=e.prototype.finally=function(t){return this._passThrough(t,0,f,f)},e.prototype.tap=function(t){return this._passThrough(t,1,f)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,f);var i,a=new Array(n-1),o=0;for(i=0;i<n-1;++i){var l=arguments[i];if(!r.isObject(l))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+r.classString(l)));a[o++]=l}a.length=o;var c=arguments[i];return this._passThrough(s(a,c,this),1,void 0,f)},l}},{"./catch_filter":7,"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,i,r,a,o){var s=t("./errors").TypeError,l=t("./util"),c=l.errorObj,u=l.tryCatch,d=[];function h(t,n,r,a){if(o.cancellation()){var s=new e(i),l=this._finallyPromise=new e(i);this._promise=s.lastly(function(){return l}),s._captureStackTrace(),s._setOnCancel(this)}else{(this._promise=new e(i))._captureStackTrace()}this._stack=a,this._generatorFunction=t,this._receiver=n,this._generator=void 0,this._yieldHandlers="function"==typeof r?[r].concat(d):d,this._yieldedPromise=null,this._cancellationPhase=!1}l.inherits(h,a),h.prototype._isResolved=function(){return null===this._promise},h.prototype._cleanup=function(){this._promise=this._generator=null,o.cancellation()&&null!==this._finallyPromise&&(this._finallyPromise._fulfill(),this._finallyPromise=null)},h.prototype._promiseCancelled=function(){if(!this._isResolved()){var t;if(void 0!==this._generator.return)this._promise._pushContext(),t=u(this._generator.return).call(this._generator,void 0),this._promise._popContext();else{var n=new e.CancellationError("generator .return() sentinel");e.coroutine.returnSentinel=n,this._promise._attachExtraTrace(n),this._promise._pushContext(),t=u(this._generator.throw).call(this._generator,n),this._promise._popContext()}this._cancellationPhase=!0,this._yieldedPromise=null,this._continue(t)}},h.prototype._promiseFulfilled=function(t){this._yieldedPromise=null,this._promise._pushContext();var e=u(this._generator.next).call(this._generator,t);this._promise._popContext(),this._continue(e)},h.prototype._promiseRejected=function(t){this._yieldedPromise=null,this._promise._attachExtraTrace(t),this._promise._pushContext();var e=u(this._generator.throw).call(this._generator,t);this._promise._popContext(),this._continue(e)},h.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof e){var t=this._yieldedPromise;this._yieldedPromise=null,t.cancel()}},h.prototype.promise=function(){return this._promise},h.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver),this._receiver=this._generatorFunction=void 0,this._promiseFulfilled(void 0)},h.prototype._continue=function(t){var n=this._promise;if(t===c)return this._cleanup(),this._cancellationPhase?n.cancel():n._rejectCallback(t.e,!1);var i=t.value;if(!0===t.done)return this._cleanup(),this._cancellationPhase?n.cancel():n._resolveCallback(i);var a=r(i,this._promise);if(a instanceof e||null!==(a=function(t,n,i){for(var a=0;a<n.length;++a){i._pushContext();var o=u(n[a])(t);if(i._popContext(),o===c){i._pushContext();var s=e.reject(c.e);return i._popContext(),s}var l=r(o,i);if(l instanceof e)return l}return null}(a,this._yieldHandlers,this._promise))){var o=(a=a._target())._bitField;0==(50397184&o)?(this._yieldedPromise=a,a._proxy(this,null)):0!=(33554432&o)?e._async.invoke(this._promiseFulfilled,this,a._value()):0!=(16777216&o)?e._async.invoke(this._promiseRejected,this,a._reason()):this._promiseCancelled()}else this._promiseRejected(new s("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s",String(i))+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")))},e.coroutine=function(t,e){if("function"!=typeof t)throw new s("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");var n=Object(e).yieldHandler,i=h,r=(new Error).stack;return function(){var e=t.apply(this,arguments),a=new i(void 0,void 0,n,r),o=a.promise();return a._generator=e,a._promiseFulfilled(void 0),o}},e.coroutine.addYieldHandler=function(t){if("function"!=typeof t)throw new s("expecting a function but got "+l.classString(t));d.push(t)},e.spawn=function(t){if(o.deprecated("Promise.spawn()","Promise.coroutine()"),"function"!=typeof t)return n("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");var i=new h(t,this),r=i.promise();return i._run(e.spawn),r}}},{"./errors":12,"./util":36}],17:[function(t,e,n){"use strict";e.exports=function(e,n,i,r,a,o){var s=t("./util");s.canEvaluate,s.tryCatch,s.errorObj;e.join=function(){var t,e=arguments.length-1;e>0&&"function"==typeof arguments[e]&&(t=arguments[e]);var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,i,r,a,o){var s=e._getDomain,c=t("./util"),u=c.tryCatch,d=c.errorObj,h=e._async;function f(t,e,n,i){this.constructor$(t),this._promise._captureStackTrace();var r=s();this._callback=null===r?e:c.domainBind(r,e),this._preservedValues=i===a?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],h.invoke(this._asyncInit,this,void 0)}function _(t,n,r,a){if("function"!=typeof n)return i("expecting a function but got "+c.classString(n));var o=0;if(void 0!==r){if("object"!==l(r)||null===r)return e.reject(new TypeError("options argument must be an object but it is "+c.classString(r)));if("number"!=typeof r.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+c.classString(r.concurrency)));o=r.concurrency}return new f(t,n,o="number"==typeof o&&isFinite(o)&&o>=1?o:0,a).promise()}c.inherits(f,n),f.prototype._asyncInit=function(){this._init$(void 0,-2)},f.prototype._init=function(){},f.prototype._promiseFulfilled=function(t,n){var i=this._values,a=this.length(),s=this._preservedValues,l=this._limit;if(n<0){if(i[n=-1*n-1]=t,l>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(l>=1&&this._inFlight>=l)return i[n]=t,this._queue.push(n),!1;null!==s&&(s[n]=t);var c=this._promise,h=this._callback,f=c._boundValue();c._pushContext();var _=u(h).call(f,t,n,a),g=c._popContext();if(o.checkForgottenReturns(_,g,null!==s?"Promise.filter":"Promise.map",c),_===d)return this._reject(_.e),!0;var p=r(_,this._promise);if(p instanceof e){var v=(p=p._target())._bitField;if(0==(50397184&v))return l>=1&&this._inFlight++,i[n]=p,p._proxy(this,-1*(n+1)),!1;if(0==(33554432&v))return 0!=(16777216&v)?(this._reject(p._reason()),!0):(this._cancel(),!0);_=p._value()}i[n]=_}return++this._totalResolved>=a&&(null!==s?this._filter(i,s):this._resolve(i),!0)},f.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlight<e;){if(this._isResolved())return;var i=t.pop();this._promiseFulfilled(n[i],i)}},f.prototype._filter=function(t,e){for(var n=e.length,i=new Array(n),r=0,a=0;a<n;++a)t[a]&&(i[r++]=e[a]);i.length=r,this._resolve(i)},f.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return _(this,t,e,null)},e.map=function(t,e,n,i){return _(t,e,n,i)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,i,r,a){var o=t("./util"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+o.classString(t));return function(){var i=new e(n);i._captureStackTrace(),i._pushContext();var r=s(t).apply(this,arguments),o=i._popContext();return a.checkForgottenReturns(r,o,"Promise.method",i),i._resolveFromSyncValue(r),i}},e.attempt=e.try=function(t){if("function"!=typeof t)return r("expecting a function but got "+o.classString(t));var i,l=new e(n);if(l._captureStackTrace(),l._pushContext(),arguments.length>1){a.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],u=arguments[2];i=o.isArray(c)?s(t).apply(u,c):s(t).call(u,c)}else i=s(t)();var d=l._popContext();return a.checkForgottenReturns(i,d,"Promise.try",l),l._resolveFromSyncValue(i),l},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";var i=t("./util"),r=i.maybeWrapAsError,a=t("./errors").OperationalError,o=t("./es5");var s=/^(?:name|message|stack|cause)$/;function l(t){var e;if(function(t){return t instanceof Error&&o.getPrototypeOf(t)===Error.prototype}(t)){(e=new a(t)).name=t.name,e.message=t.message,e.stack=t.stack;for(var n=o.keys(t),r=0;r<n.length;++r){var l=n[r];s.test(l)||(e[l]=t[l])}return e}return i.markAsOriginatingFromRejection(t),t}e.exports=function(t,e){return function(n,i){if(null!==t){if(n){var a=l(r(n));t._attachExtraTrace(a),t._reject(a)}else if(e){var o=[].slice.call(arguments,1);t._fulfill(o)}else t._fulfill(i);t=null}}}},{"./errors":12,"./es5":13,"./util":36}],21:[function(t,e,n){"use strict";e.exports=function(e){var n=t("./util"),i=e._async,r=n.tryCatch,a=n.errorObj;function o(t,e){if(!n.isArray(t))return s.call(this,t,e);var o=r(e).apply(this._boundValue(),[null].concat(t));o===a&&i.throwLater(o.e)}function s(t,e){var n=this._boundValue(),o=void 0===t?r(e).call(n,null):r(e).call(n,null,t);o===a&&i.throwLater(o.e)}function l(t,e){if(!t){var n=new Error(t+"");n.cause=t,t=n}var o=r(e).call(this._boundValue(),t);o===a&&i.throwLater(o.e)}e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var n=s;void 0!==e&&Object(e).spread&&(n=o),this._then(n,l,void 0,this,t)}return this}}},{"./util":36}],22:[function(t,e,i){"use strict";e.exports=function(){var i=function(){return new _("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n")},r=function(){return new D.PromiseInspection(this._target())},a=function(t){return D.reject(new _(t))};function o(){}var s,l={},c=t("./util");s=c.isNode?function(){var t=n.domain;return void 0===t&&(t=null),t}:function(){return null},c.notEnumerableProp(D,"_getDomain",s);var u=t("./es5"),d=t("./async"),h=new d;u.defineProperty(D,"_async",{value:h});var f=t("./errors"),_=D.TypeError=f.TypeError;D.RangeError=f.RangeError;var g=D.CancellationError=f.CancellationError;D.TimeoutError=f.TimeoutError,D.OperationalError=f.OperationalError,D.RejectionError=f.OperationalError,D.AggregateError=f.AggregateError;var p=function(){},v={},m={},y=t("./thenables")(D,p),k=t("./promise_array")(D,p,y,a,o),b=t("./context")(D),w=b.create,x=t("./debuggability")(D,b),$=(x.CapturedTrace,t("./finally")(D,y,m)),S=t("./catch_filter")(m),T=t("./nodeback"),C=c.errorObj,E=c.tryCatch;function D(t){t!==p&&function(t,e){if(null==t||t.constructor!==D)throw new _("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n");if("function"!=typeof e)throw new _("expecting a function but got "+c.classString(e))}(this,t),this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._resolveFromExecutor(t),this._promiseCreated(),this._fireEvent("promiseCreated",this)}function A(t){this.promise._resolveCallback(t)}function M(t){this.promise._rejectCallback(t,!1)}function I(t){var e=new D(p);e._fulfillmentHandler0=t,e._rejectionHandler0=t,e._promise0=t,e._receiver0=t}return D.prototype.toString=function(){return"[object Promise]"},D.prototype.caught=D.prototype.catch=function(t){var e=arguments.length;if(e>1){var n,i=new Array(e-1),r=0;for(n=0;n<e-1;++n){var o=arguments[n];if(!c.isObject(o))return a("Catch statement predicate: expecting an object but got "+c.classString(o));i[r++]=o}return i.length=r,t=arguments[n],this.then(void 0,S(i,t,this))}return this.then(void 0,t)},D.prototype.reflect=function(){return this._then(r,r,void 0,this,void 0)},D.prototype.then=function(t,e){if(x.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+c.classString(t);arguments.length>1&&(n+=", "+c.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},D.prototype.done=function(t,e){this._then(t,e,void 0,void 0,void 0)._setIsFinal()},D.prototype.spread=function(t){return"function"!=typeof t?a("expecting a function but got "+c.classString(t)):this.all()._then(t,void 0,void 0,v,void 0)},D.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},D.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new k(this).promise()},D.prototype.error=function(t){return this.caught(c.originatesFromRejection,t)},D.getNewLibraryCopy=e.exports,D.is=function(t){return t instanceof D},D.fromNode=D.fromCallback=function(t){var e=new D(p);e._captureStackTrace();var n=arguments.length>1&&!!Object(arguments[1]).multiArgs,i=E(t)(T(e,n));return i===C&&e._rejectCallback(i.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},D.all=function(t){return new k(t).promise()},D.cast=function(t){var e=y(t);return e instanceof D||((e=new D(p))._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},D.resolve=D.fulfilled=D.cast,D.reject=D.rejected=function(t){var e=new D(p);return e._captureStackTrace(),e._rejectCallback(t,!0),e},D.setScheduler=function(t){if("function"!=typeof t)throw new _("expecting a function but got "+c.classString(t));return h.setScheduler(t)},D.prototype._then=function(t,e,n,i,r){var a=void 0!==r,o=a?r:new D(p),l=this._target(),u=l._bitField;a||(o._propagateFrom(this,3),o._captureStackTrace(),void 0===i&&0!=(2097152&this._bitField)&&(i=0!=(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,o));var d=s();if(0!=(50397184&u)){var f,_,v=l._settlePromiseCtx;0!=(33554432&u)?(_=l._rejectionHandler0,f=t):0!=(16777216&u)?(_=l._fulfillmentHandler0,f=e,l._unsetRejectionIsUnhandled()):(v=l._settlePromiseLateCancellationObserver,_=new g("late cancellation observer"),l._attachExtraTrace(_),f=e),h.invoke(v,l,{handler:null===d?f:"function"==typeof f&&c.domainBind(d,f),promise:o,receiver:i,value:_})}else l._addCallbacks(t,e,o,i,d);return o},D.prototype._length=function(){return 65535&this._bitField},D.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},D.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},D.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},D.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},D.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},D.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},D.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},D.prototype._isFinal=function(){return(4194304&this._bitField)>0},D.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},D.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},D.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},D.prototype._setAsyncGuaranteed=function(){h.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},D.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];if(e!==l)return void 0===e&&this._isBound()?this._boundValue():e},D.prototype._promiseAt=function(t){return this[4*t-4+2]},D.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},D.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},D.prototype._boundValue=function(){},D.prototype._migrateCallback0=function(t){t._bitField;var e=t._fulfillmentHandler0,n=t._rejectionHandler0,i=t._promise0,r=t._receiverAt(0);void 0===r&&(r=l),this._addCallbacks(e,n,i,r,null)},D.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),i=t._rejectionHandlerAt(e),r=t._promiseAt(e),a=t._receiverAt(e);void 0===a&&(a=l),this._addCallbacks(n,i,r,a,null)},D.prototype._addCallbacks=function(t,e,n,i,r){var a=this._length();if(a>=65531&&(a=0,this._setLength(0)),0===a)this._promise0=n,this._receiver0=i,"function"==typeof t&&(this._fulfillmentHandler0=null===r?t:c.domainBind(r,t)),"function"==typeof e&&(this._rejectionHandler0=null===r?e:c.domainBind(r,e));else{var o=4*a-4;this[o+2]=n,this[o+3]=i,"function"==typeof t&&(this[o+0]=null===r?t:c.domainBind(r,t)),"function"==typeof e&&(this[o+1]=null===r?e:c.domainBind(r,e))}return this._setLength(a+1),a},D.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},D.prototype._resolveCallback=function(t,e){if(0==(117506048&this._bitField)){if(t===this)return this._rejectCallback(i(),!1);var n=y(t,this);if(!(n instanceof D))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r!==this){var a=r._bitField;if(0==(50397184&a)){var o=this._length();o>0&&r._migrateCallback0(this);for(var s=1;s<o;++s)r._migrateCallbackAt(this,s);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!=(33554432&a))this._fulfill(r._value());else if(0!=(16777216&a))this._reject(r._reason());else{var l=new g("late cancellation observer");r._attachExtraTrace(l),this._reject(l)}}else this._reject(i())}},D.prototype._rejectCallback=function(t,e,n){var i=c.ensureErrorObject(t),r=i===t;if(!r&&!n&&x.warnings()){var a="a promise was rejected with a non-error: "+c.classString(t);this._warn(a,!0)}this._attachExtraTrace(i,!!e&&r),this._reject(t)},D.prototype._resolveFromExecutor=function(t){if(t!==p){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,i=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==i&&e._rejectCallback(i,!0)}},D.prototype._settlePromiseFromHandler=function(t,e,n,i){var r=i._bitField;if(0==(65536&r)){var a;i._pushContext(),e===v?n&&"number"==typeof n.length?a=E(t).apply(this._boundValue(),n):(a=C).e=new _("cannot .spread() a non-array: "+c.classString(n)):a=E(t).call(e,n);var o=i._popContext();0==(65536&(r=i._bitField))&&(a===m?i._reject(n):a===C?i._rejectCallback(a.e,!1):(x.checkForgottenReturns(a,o,"",i,this),i._resolveCallback(a)))}},D.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},D.prototype._followee=function(){return this._rejectionHandler0},D.prototype._setFollowee=function(t){this._rejectionHandler0=t},D.prototype._settlePromise=function(t,e,n,i){var a=t instanceof D,s=this._bitField,l=0!=(134217728&s);0!=(65536&s)?(a&&t._invokeInternalOnCancel(),n instanceof $&&n.isFinallyHandler()?(n.cancelPromise=t,E(e).call(n,i)===C&&t._reject(C.e)):e===r?t._fulfill(r.call(n)):n instanceof o?n._promiseCancelled(t):a||t instanceof k?t._cancel():n.cancel()):"function"==typeof e?a?(l&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,n,i,t)):e.call(n,i,t):n instanceof o?n._isResolved()||(0!=(33554432&s)?n._promiseFulfilled(i,t):n._promiseRejected(i,t)):a&&(l&&t._setAsyncGuaranteed(),0!=(33554432&s)?t._fulfill(i):t._reject(i))},D.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,i=t.receiver,r=t.value;"function"==typeof e?n instanceof D?this._settlePromiseFromHandler(e,i,r,n):e.call(i,r,n):n instanceof D&&n._reject(r)},D.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},D.prototype._settlePromise0=function(t,e,n){var i=this._promise0,r=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(i,t,r,e)},D.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},D.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=i();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!=(134217728&e)?this._settlePromises():h.settlePromises(this),this._dereferenceTrace())}},D.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=t,this._isFinal())return h.fatalError(t,c.isNode);(65535&e)>0?h.settlePromises(this):this._ensurePossibleRejectionHandled()}},D.prototype._fulfillPromises=function(t,e){for(var n=1;n<t;n++){var i=this._fulfillmentHandlerAt(n),r=this._promiseAt(n),a=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(r,i,a,e)}},D.prototype._rejectPromises=function(t,e){for(var n=1;n<t;n++){var i=this._rejectionHandlerAt(n),r=this._promiseAt(n),a=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(r,i,a,e)}},D.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!=(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var i=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,i,t),this._fulfillPromises(e,i)}this._setLength(0)}this._clearCancellationData()},D.prototype._settledValue=function(){var t=this._bitField;return 0!=(33554432&t)?this._rejectionHandler0:0!=(16777216&t)?this._fulfillmentHandler0:void 0},D.defer=D.pending=function(){return x.deprecated("Promise.defer","new Promise"),{promise:new D(p),resolve:A,reject:M}},c.notEnumerableProp(D,"_makeSelfResolutionError",i),t("./method")(D,p,y,a,x),t("./bind")(D,p,y,x),t("./cancel")(D,k,a,x),t("./direct_resolve")(D),t("./synchronous_inspection")(D),t("./join")(D,k,y,p,h,s),D.Promise=D,D.version="3.5.4",t("./map.js")(D,k,a,y,p,x),t("./call_get.js")(D),t("./using.js")(D,a,y,w,p,x),t("./timers.js")(D,p,x),t("./generators.js")(D,a,p,y,o,x),t("./nodeify.js")(D),t("./promisify.js")(D,p),t("./props.js")(D,k,y,a),t("./race.js")(D,p,y,a),t("./reduce.js")(D,k,a,y,p,x),t("./settle.js")(D,k,x),t("./some.js")(D,k,a),t("./filter.js")(D,p),t("./each.js")(D,p),t("./any.js")(D),c.toFastProperties(D),c.toFastProperties(D.prototype),I({a:1}),I({b:2}),I({c:3}),I(1),I(function(){}),I(void 0),I(!1),I(new D(p)),x.setBounds(d.firstLineError,c.lastLineError),D}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e,n){"use strict";e.exports=function(e,n,i,r,a){var o=t("./util");o.isArray;function s(t){var i=this._promise=new e(n);t instanceof e&&i._propagateFrom(t,3),i._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return o.inherits(s,a),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function t(n,a){var s=i(this._values,this._promise);if(s instanceof e){var l=(s=s._target())._bitField;if(this._values=s,0==(50397184&l))return this._promise._setAsyncGuaranteed(),s._then(t,this._reject,void 0,this,a);if(0==(33554432&l))return 0!=(16777216&l)?this._reject(s._reason()):this._cancel();s=s._value()}if(null!==(s=o.asArray(s)))0!==s.length?this._iterate(s):-5===a?this._resolveEmptyArray():this._resolve(function(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}(a));else{var c=r("expecting an array or an iterable object but got "+o.classString(s)).reason();this._promise._rejectCallback(c,!1)}},s.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var r=this._promise,a=!1,o=null,s=0;s<n;++s){var l=i(t[s],r);o=l instanceof e?(l=l._target())._bitField:null,a?null!==o&&l.suppressUnhandledRejections():null!==o?0==(50397184&o)?(l._proxy(this,s),this._values[s]=l):a=0!=(33554432&o)?this._promiseFulfilled(l._value(),s):0!=(16777216&o)?this._promiseRejected(l._reason(),s):this._promiseCancelled(s):a=this._promiseFulfilled(l,s)}a||r._setAsyncGuaranteed()},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},s.prototype._promiseFulfilled=function(t,e){return this._values[e]=t,++this._totalResolved>=this._length&&(this._resolve(this._values),!0)},s.prototype._promiseCancelled=function(){return this._cancel(),!0},s.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},s.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;n<t.length;++n)t[n]instanceof e&&t[n].cancel()}},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util":36}],24:[function(t,e,n){"use strict";e.exports=function(e,n){var i={},r=t("./util"),a=t("./nodeback"),o=r.withAppended,s=r.maybeWrapAsError,c=r.canEvaluate,u=t("./errors").TypeError,d={__isPromisified__:!0},h=new RegExp("^(?:"+["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"].join("|")+")$"),f=function(t){return r.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t};function _(t){return!h.test(t)}function g(t){try{return!0===t.__isPromisified__}catch(t){return!1}}function p(t,e,n){var i=r.getDataPropertyOrDefault(t,e+n,d);return!!i&&g(i)}function v(t,e,n,i){for(var a=r.inheritedDataKeys(t),o=[],s=0;s<a.length;++s){var l=a[s],c=t[l],d=i===f||f(l,c,t);"function"!=typeof c||g(c)||p(t,l,e)||!i(l,c,t,d)||o.push(l,c)}return function(t,e,n){for(var i=0;i<t.length;i+=2){var r=t[i];if(n.test(r))for(var a=r.replace(n,""),o=0;o<t.length;o+=2)if(t[o]===a)throw new u("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s",e))}}(o,e,n),o}var m=function(t){return t.replace(/([$])/,"\\$")};var y=c?void 0:function(t,l,c,u,d,h){var f=function(){return this}(),_=t;function g(){var r=l;l===i&&(r=this);var c=new e(n);c._captureStackTrace();var u="string"==typeof _&&this!==f?this[_]:t,d=a(c,h);try{u.apply(r,o(arguments,d))}catch(t){c._rejectCallback(s(t),!0,!0)}return c._isFateSealed()||c._setAsyncGuaranteed(),c}return"string"==typeof _&&(t=u),r.notEnumerableProp(g,"__isPromisified__",!0),g};function k(t,e,n,a,o){for(var s=new RegExp(m(e)+"$"),l=v(t,e,s,n),c=0,u=l.length;c<u;c+=2){var d=l[c],h=l[c+1],f=d+e;if(a===y)t[f]=y(d,i,d,h,e,o);else{var _=a(h,function(){return y(d,i,d,h,e,o)});r.notEnumerableProp(_,"__isPromisified__",!0),t[f]=_}}return r.toFastProperties(t),t}e.promisify=function(t,e){if("function"!=typeof t)throw new u("expecting a function but got "+r.classString(t));if(g(t))return t;var n=function(t,e,n){return y(t,e,void 0,t,null,n)}(t,void 0===(e=Object(e)).context?i:e.context,!!e.multiArgs);return r.copyDescriptors(t,n,_),n},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!==l(t))throw new u("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");var n=!!(e=Object(e)).multiArgs,i=e.suffix;"string"!=typeof i&&(i="Async");var a=e.filter;"function"!=typeof a&&(a=f);var o=e.promisifier;if("function"!=typeof o&&(o=y),!r.isIdentifier(i))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=r.inheritedDataKeys(t),c=0;c<s.length;++c){var d=t[s[c]];"constructor"!==s[c]&&r.isClass(d)&&(k(d.prototype,i,a,o,n),k(d,i,a,o,n))}return k(t,i,a,o,n)}}},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(t,e,n){"use strict";e.exports=function(e,n,i,r){var a,o=t("./util"),s=o.isObject,l=t("./es5");"function"==typeof Map&&(a=Map);var c=function(){var t=0,e=0;function n(n,i){this[t]=n,this[t+e]=i,t++}return function(i){e=i.size,t=0;var r=new Array(2*i.size);return i.forEach(n,r),r}}();function u(t){var e,n=!1;if(void 0!==a&&t instanceof a)e=c(t),n=!0;else{var i=l.keys(t),r=i.length;e=new Array(2*r);for(var o=0;o<r;++o){var s=i[o];e[o]=t[s],e[o+r]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,n?-6:-3)}function d(t){var n,a=i(t);return s(a)?(n=a instanceof e?a._then(e.props,void 0,void 0,void 0,void 0):new u(a).promise(),a instanceof e&&n._propagateFrom(a,2),n):r("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}o.inherits(u,n),u.prototype._init=function(){},u.prototype._promiseFulfilled=function(t,e){if(this._values[e]=t,++this._totalResolved>=this._length){var n;if(this._isMap)n=function(t){for(var e=new a,n=t.length/2|0,i=0;i<n;++i){var r=t[n+i],o=t[i];e.set(r,o)}return e}(this._values);else{n={};for(var i=this.length(),r=0,o=this.length();r<o;++r)n[this._values[r+i]]=this._values[r]}return this._resolve(n),!0}return!1},u.prototype.shouldCopyValues=function(){return!1},u.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return d(this)},e.props=function(t){return d(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacity<t},i.prototype._pushOne=function(t){var e=this.length();this._checkCapacity(e+1),this[this._front+e&this._capacity-1]=t,this._length=e+1},i.prototype.push=function(t,e,n){var i=this.length()+3;if(this._willBeOverCapacity(i))return this._pushOne(t),this._pushOne(e),void this._pushOne(n);var r=this._front+i-3;this._checkCapacity(i);var a=this._capacity-1;this[r+0&a]=t,this[r+1&a]=e,this[r+2&a]=n,this._length=i},i.prototype.shift=function(){var t=this._front,e=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length--,e},i.prototype.length=function(){return this._length},i.prototype._checkCapacity=function(t){this._capacity<t&&this._resizeTo(this._capacity<<1)},i.prototype._resizeTo=function(t){var e=this._capacity;this._capacity=t,function(t,e,n,i,r){for(var a=0;a<r;++a)n[a+i]=t[a+e],t[a+e]=void 0}(this,0,this,e,this._front+this._length&e-1)},e.exports=i},{}],27:[function(t,e,n){"use strict";e.exports=function(e,n,i,r){var a=t("./util"),o=function(t){return t.then(function(e){return s(e,t)})};function s(t,s){var l=i(t);if(l instanceof e)return o(l);if(null===(t=a.asArray(t)))return r("expecting an array or an iterable object but got "+a.classString(t));var c=new e(n);void 0!==s&&c._propagateFrom(s,3);for(var u=c._fulfill,d=c._reject,h=0,f=t.length;h<f;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,d,void 0,c,null)}return c}e.race=function(t){return s(t,void 0)},e.prototype.race=function(){return s(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,i,r,a,o){var s=e._getDomain,l=t("./util"),c=l.tryCatch;function u(t,n,i,r){this.constructor$(t);var o=s();this._fn=null===o?n:l.domainBind(o,n),void 0!==i&&(i=e.resolve(i))._attachCancellationCallback(this),this._initialValue=i,this._currentCancellable=null,this._eachValues=r===a?Array(this._length):0===r?null:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function d(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function h(t,e,n,r){return"function"!=typeof e?i("expecting a function but got "+l.classString(e)):new u(t,e,n,r).promise()}function f(t){this.accum=t,this.array._gotAccum(t);var n=r(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(_,void 0,void 0,this,void 0)):_.call(this,n)}function _(t){var n,i=this.array,r=i._promise,a=c(i._fn);r._pushContext(),(n=void 0!==i._eachValues?a.call(r._boundValue(),t,this.index,this.length):a.call(r._boundValue(),this.accum,t,this.index,this.length))instanceof e&&(i._currentCancellable=n);var s=r._popContext();return o.checkForgottenReturns(n,s,void 0!==i._eachValues?"Promise.each":"Promise.reduce",r),n}l.inherits(u,n),u.prototype._gotAccum=function(t){void 0!==this._eachValues&&null!==this._eachValues&&t!==a&&this._eachValues.push(t)},u.prototype._eachComplete=function(t){return null!==this._eachValues&&this._eachValues.push(t),this._eachValues},u.prototype._init=function(){},u.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},u.prototype.shouldCopyValues=function(){return!1},u.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},u.prototype._resultCancelled=function(t){if(t===this._initialValue)return this._cancel();this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel())},u.prototype._iterate=function(t){var n,i;this._values=t;var r=t.length;if(void 0!==this._initialValue?(n=this._initialValue,i=0):(n=e.resolve(t[0]),i=1),this._currentCancellable=n,!n.isRejected())for(;i<r;++i){var a={accum:null,value:t[i],index:i,length:r,array:this};n=n._then(f,void 0,void 0,a,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(d,d,void 0,n,this)},e.prototype.reduce=function(t,e){return h(this,t,e,null)},e.reduce=function(t,e,n,i){return h(t,e,n,i)}}},{"./util":36}],29:[function(t,e,a){"use strict";var o,s=t("./util"),l=s.getNativePromise();if(s.isNode&&"undefined"==typeof MutationObserver){var c=i.setImmediate,u=n.nextTick;o=s.isRecentNode?function(t){c.call(i,t)}:function(t){u.call(n,t)}}else if("function"==typeof l&&"function"==typeof l.resolve){var d=l.resolve();o=function(t){d.then(t)}}else o="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)?void 0!==r?function(t){r(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}:function(){var t=document.createElement("div"),e={attributes:!0},n=!1,i=document.createElement("div");new MutationObserver(function(){t.classList.toggle("foo"),n=!1}).observe(i,e);return function(r){var a=new MutationObserver(function(){a.disconnect(),r()});a.observe(t,e),n||(n=!0,i.classList.toggle("foo"))}}();e.exports=o},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,i){var r=e.PromiseInspection;function a(t){this.constructor$(t)}t("./util").inherits(a,n),a.prototype._promiseResolved=function(t,e){return this._values[t]=e,++this._totalResolved>=this._length&&(this._resolve(this._values),!0)},a.prototype._promiseFulfilled=function(t,e){var n=new r;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},a.prototype._promiseRejected=function(t,e){var n=new r;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return i.deprecated(".settle()",".reflect()"),new a(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,i){var r=t("./util"),a=t("./errors").RangeError,o=t("./errors").AggregateError,s=r.isArray,l={};function c(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function u(t,e){if((0|e)!==e||e<0)return i("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new c(t),r=n.promise();return n.setHowMany(e),n.init(),r}r.inherits(c,n),c.prototype._init=function(){if(this._initialized)if(0!==this._howMany){this._init$(void 0,-5);var t=s(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}else this._resolve([])},c.prototype.init=function(){this._initialized=!0,this._init()},c.prototype.setUnwrap=function(){this._unwrap=!0},c.prototype.howMany=function(){return this._howMany},c.prototype.setHowMany=function(t){this._howMany=t},c.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},c.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},c.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(l),this._checkOutcome())},c.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new o,e=this.length();e<this._values.length;++e)this._values[e]!==l&&t.push(this._values[e]);return t.length>0?this._reject(t):this._cancel(),!0}return!1},c.prototype._fulfilled=function(){return this._totalResolved},c.prototype._rejected=function(){return this._values.length-this.length()},c.prototype._addRejected=function(t){this._values.push(t)},c.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},c.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},c.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},c.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return u(t,e)},e.prototype.some=function(t){return u(this,t)},e._SomePromiseArray=c}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.isFulfilled=function(){return 0!=(33554432&this._bitField)},a=e.prototype.isRejected=function(){return 0!=(16777216&this._bitField)},o=e.prototype.isPending=function(){return 0==(50397184&this._bitField)},s=e.prototype.isResolved=function(){return 0!=(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!=(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536==(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!=(8454144&this._target()._bitField)},t.prototype.isPending=function(){return o.call(this._target())},t.prototype.isRejected=function(){return a.call(this._target())},t.prototype.isFulfilled=function(){return r.call(this._target())},t.prototype.isResolved=function(){return s.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),i.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){var i=t("./util"),r=i.errorObj,a=i.isObject;var o={}.hasOwnProperty;return function(t,s){if(a(t)){if(t instanceof e)return t;var l=function(t){try{return function(t){return t.then}(t)}catch(t){return r.e=t,r}}(t);if(l===r){s&&s._pushContext();var c=e.reject(l.e);return s&&s._popContext(),c}if("function"==typeof l)return function(t){try{return o.call(t,"_promise0")}catch(t){return!1}}(t)?(c=new e(n),t._then(c._fulfill,c._reject,void 0,c,null),c):function(t,a,o){var s=new e(n),l=s;o&&o._pushContext(),s._captureStackTrace(),o&&o._popContext();var c=!0,u=i.tryCatch(a).call(t,function(t){s&&(s._resolveCallback(t),s=null)},function(t){s&&(s._rejectCallback(t,c,!0),s=null)});return c=!1,s&&u===r&&(s._rejectCallback(u.e,!0,!0),s=null),l}(t,l,s)}return t}}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n,i){var r=t("./util"),a=e.TimeoutError;function o(t){this.handle=t}o.prototype._resultCancelled=function(){clearTimeout(this.handle)};var s=function(t){return l(+this).thenReturn(t)},l=e.delay=function(t,r){var a,l;return void 0!==r?(a=e.resolve(r)._then(s,null,null,t,void 0),i.cancellation()&&r instanceof e&&a._setOnCancel(r)):(a=new e(n),l=setTimeout(function(){a._fulfill()},+t),i.cancellation()&&a._setOnCancel(new o(l)),a._captureStackTrace()),a._setAsyncGuaranteed(),a};e.prototype.delay=function(t){return l(t,this)};function c(t){return clearTimeout(this.handle),t}function u(t){throw clearTimeout(this.handle),t}e.prototype.timeout=function(t,e){var n,s;t=+t;var l=new o(setTimeout(function(){n.isPending()&&function(t,e,n){var i;i="string"!=typeof e?e instanceof Error?e:new a("operation timed out"):new a(e),r.markAsOriginatingFromRejection(i),t._attachExtraTrace(i),t._reject(i),null!=n&&n.cancel()}(n,e,s)},t));return i.cancellation()?(s=this.then(),(n=s._then(c,u,void 0,l,void 0))._setOnCancel(l)):n=this._then(c,u,void 0,l,void 0),n}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,i,r,a,o){var s=t("./util"),l=t("./errors").TypeError,c=t("./util").inherits,u=s.errorObj,d=s.tryCatch,h={};function f(t){setTimeout(function(){throw t},0)}function _(t,n){var r=0,o=t.length,s=new e(a);return function a(){if(r>=o)return s._fulfill();var l=function(t){var e=i(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}(t[r++]);if(l instanceof e&&l._isDisposable()){try{l=i(l._getDisposer().tryDispose(n),t.promise)}catch(t){return f(t)}if(l instanceof e)return l._then(a,f,null,null,null)}a()}(),s}function g(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function v(t){return g.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function m(t){this.length=t,this.promise=null,this[t-1]=null}g.prototype.data=function(){return this._data},g.prototype.promise=function(){return this._promise},g.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():h},g.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var i=e!==h?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,i},g.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},c(p,g),p.prototype.doDispose=function(t,e){return this.data().call(t,t,e)},m.prototype._resultCancelled=function(){for(var t=this.length,n=0;n<t;++n){var i=this[n];i instanceof e&&i.cancel()}},e.using=function(){var t=arguments.length;if(t<2)return n("you must pass at least 2 arguments to Promise.using");var r,a=arguments[t-1];if("function"!=typeof a)return n("expecting a function but got "+s.classString(a));var l=!0;2===t&&Array.isArray(arguments[0])?(t=(r=arguments[0]).length,l=!1):(r=arguments,t--);for(var c=new m(t),h=0;h<t;++h){var f=r[h];if(g.isDisposer(f)){var p=f;(f=f.promise())._setDisposable(p)}else{var y=i(f);y instanceof e&&(f=y._then(v,null,null,{resources:c,index:h},void 0))}c[h]=f}var k=new Array(c.length);for(h=0;h<k.length;++h)k[h]=e.resolve(c[h]).reflect();var b=e.all(k).then(function(t){for(var e=0;e<t.length;++e){var n=t[e];if(n.isRejected())return u.e=n.error(),u;if(!n.isFulfilled())return void b.cancel();t[e]=n.value()}w._pushContext(),a=d(a);var i=l?a.apply(void 0,t):a(t),r=w._popContext();return o.checkForgottenReturns(i,r,"Promise.using",w),i}),w=b.lastly(function(){var t=new e.PromiseInspection(b);return _(c,t)});return c.promise=w,w._setOnCancel(c),w},e.prototype._setDisposable=function(t){this._bitField=131072|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(131072&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,r());throw new l}}},{"./errors":12,"./util":36}],36:[function(t,e,r){"use strict";var a=t("./es5"),o="undefined"==typeof navigator,s={e:{}},c,u="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==i?i:void 0!==this?this:null;function d(){try{var t=c;return c=null,t.apply(this,arguments)}catch(t){return s.e=t,s}}function h(t){return c=t,d}var f=function(t,e){var n={}.hasOwnProperty;function i(){for(var i in this.constructor=t,this.constructor$=e,e.prototype)n.call(e.prototype,i)&&"$"!==i.charAt(i.length-1)&&(this[i+"$"]=e.prototype[i])}return i.prototype=e.prototype,t.prototype=new i,t.prototype};function _(t){return null==t||!0===t||!1===t||"string"==typeof t||"number"==typeof t}function g(t){return"function"==typeof t||"object"===l(t)&&null!==t}function p(t){return _(t)?new Error(E(t)):t}function v(t,e){var n,i=t.length,r=new Array(i+1);for(n=0;n<i;++n)r[n]=t[n];return r[n]=e,r}function m(t,e,n){if(!a.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var i=Object.getOwnPropertyDescriptor(t,e);return null!=i?null==i.get&&null==i.set?i.value:n:void 0}function y(t,e,n){if(_(t))return t;var i={value:n,configurable:!0,enumerable:!1,writable:!0};return a.defineProperty(t,e,i),t}function k(t){throw t}var b=function(){var t=[Array.prototype,Object.prototype,Function.prototype],e=function(e){for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1};if(a.isES5){var n=Object.getOwnPropertyNames;return function(t){for(var i=[],r=Object.create(null);null!=t&&!e(t);){var o;try{o=n(t)}catch(t){return i}for(var s=0;s<o.length;++s){var l=o[s];if(!r[l]){r[l]=!0;var c=Object.getOwnPropertyDescriptor(t,l);null!=c&&null==c.get&&null==c.set&&i.push(l)}}t=a.getPrototypeOf(t)}return i}}var i={}.hasOwnProperty;return function(n){if(e(n))return[];var r=[];t:for(var a in n)if(i.call(n,a))r.push(a);else{for(var o=0;o<t.length;++o)if(i.call(t[o],a))continue t;r.push(a)}return r}}(),w=/this\s*\.\s*\S+\s*=/;function x(t){try{if("function"==typeof t){var e=a.names(t.prototype),n=a.isES5&&e.length>1,i=e.length>0&&!(1===e.length&&"constructor"===e[0]),r=w.test(t+"")&&a.names(t).length>0;if(n||i||r)return!0}return!1}catch(t){return!1}}function $(t){function e(){}e.prototype=t;var n=new e;function i(){return l(n.foo)}return i(),i(),t}var S=/^[a-z$_][a-z$_0-9]*$/i;function T(t){return S.test(t)}function C(t,e,n){for(var i=new Array(t),r=0;r<t;++r)i[r]=e+r+n;return i}function E(t){try{return t+""}catch(t){return"[no string representation]"}}function D(t){return t instanceof Error||null!==t&&"object"===l(t)&&"string"==typeof t.message&&"string"==typeof t.name}function A(t){try{y(t,"isOperational",!0)}catch(t){}}function M(t){return null!=t&&(t instanceof Error.__BluebirdErrorTypes__.OperationalError||!0===t.isOperational)}function I(t){return D(t)&&a.propertyIsWritable(t,"stack")}var N="stack"in new Error?function(t){return I(t)?t:new Error(E(t))}:function(t){if(I(t))return t;try{throw new Error(E(t))}catch(t){return t}};function P(t){return{}.toString.call(t)}function L(t,e,n){for(var i=a.names(t),r=0;r<i.length;++r){var o=i[r];if(n(o))try{a.defineProperty(e,o,a.getDescriptor(t,o))}catch(t){}}}var O=function(t){return a.isArray(t)?t:null};if("undefined"!=typeof Symbol&&Symbol.iterator){var R="function"==typeof Array.from?function(t){return Array.from(t)}:function(t){for(var e,n=[],i=t[Symbol.iterator]();!(e=i.next()).done;)n.push(e.value);return n};O=function(t){return a.isArray(t)?t:null!=t&&"function"==typeof t[Symbol.iterator]?R(t):null}}var j=void 0!==n&&"[object process]"===P(n).toLowerCase(),H=void 0!==n&&void 0!==n.env;function F(t){return H?n.env[t]:void 0}function B(){if("function"==typeof Promise)try{var t=new Promise(function(){});if("[object Promise]"==={}.toString.call(t))return Promise}catch(t){}}function z(t,e){return t.bind(e)}var V={isClass:x,isIdentifier:T,inheritedDataKeys:b,getDataPropertyOrDefault:m,thrower:k,isArray:a.isArray,asArray:O,notEnumerableProp:y,isPrimitive:_,isObject:g,isError:D,canEvaluate:o,errorObj:s,tryCatch:h,inherits:f,withAppended:v,maybeWrapAsError:p,toFastProperties:$,filledRange:C,toString:E,canAttachTrace:I,ensureErrorObject:N,originatesFromRejection:M,markAsOriginatingFromRejection:A,classString:P,copyDescriptors:L,hasDevTools:"undefined"!=typeof chrome&&chrome&&"function"==typeof chrome.loadTimes,isNode:j,hasEnvVariables:H,env:F,global:u,getNativePromise:B,domainBind:z};V.isRecentNode=V.isNode&&function(){var t;return n.versions&&n.versions.node?t=n.versions.node.split(".").map(Number):n.version&&(t=n.version.split(".").map(Number)),0===t[0]&&t[1]>10||t[0]>0}(),V.isNode&&V.toFastProperties(n);try{throw new Error}catch(t){V.lastLineError=t}e.exports=V},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,n(41),n(14),n(207).setImmediate)},function(t,e,n){t.exports=n(208)},function(t,e,n){var i=n(0);t.exports=function(){var t={};return{getState:function(e){if(t[e])return t[e].method();var n={};for(var r in t)t[r].internal||i.mixin(n,t[r].method(),!0);return n},registerProvider:function(e,n,i){t[e]={method:n,internal:i}},unregisterProvider:function(e){delete t[e]}}}},function(t,e){t.exports=function(t){var e={};function n(n,i,r){r=r||n;var a=t.config,o=t.templates;t.config[n]&&e[r]!=a[n]&&(i&&o[r]||(o[r]=t.date.date_to_str(a[n]),e[r]=a[n]))}return{initTemplates:function(){var e=t.locale.labels;e.gantt_save_btn=e.icon_save,e.gantt_cancel_btn=e.icon_cancel,e.gantt_delete_btn=e.icon_delete;var i=t.date,r=i.date_to_str,a=t.config,o=r(a.xml_date||a.date_format,a.server_utc),s=i.str_to_date(a.xml_date||a.date_format,a.server_utc);n("date_scale",!0,void 0,t.config,t.templates),n("date_grid",!0,"grid_date_format",t.config,t.templates),n("task_date",!0,void 0,t.config,t.templates),t.mixin(t.templates,{xml_format:void 0,format_date:o,xml_date:void 0,parse_date:s,progress_text:function(t,e,n){return""},grid_header_class:function(t,e){return""},task_text:function(t,e,n){return n.text},task_class:function(t,e,n){return""},task_end_date:function(e){return t.templates.task_date(e)},grid_row_class:function(t,e,n){return""},task_row_class:function(t,e,n){return""},timeline_cell_class:function(t,e){return""},scale_cell_class:function(t){return""},scale_row_class:function(t){return""},grid_indent:function(t){return"<div class='gantt_tree_indent'></div>"},grid_folder:function(t){return"<div class='gantt_tree_icon gantt_folder_"+(t.$open?"open":"closed")+"'></div>"},grid_file:function(t){return"<div class='gantt_tree_icon gantt_file'></div>"},grid_open:function(t){return"<div class='gantt_tree_icon gantt_"+(t.$open?"close":"open")+"'></div>"},grid_blank:function(t){return"<div class='gantt_tree_icon gantt_blank'></div>"},date_grid:function(e,n,i){return n&&t.isUnscheduledTask(n)&&t.config.show_unscheduled?t.templates.task_unscheduled_time(n):t.templates.grid_date_format(e,i)},task_time:function(e,n,i){return t.isUnscheduledTask(i)&&t.config.show_unscheduled?t.templates.task_unscheduled_time(i):t.templates.task_date(e)+" - "+t.templates.task_end_date(n)},task_unscheduled_time:function(t){return""},time_picker:r(a.time_picker),link_class:function(t){return""},link_description:function(e){var n=t.getTask(e.source),i=t.getTask(e.target);return"<b>"+n.text+"</b> &ndash; <b>"+i.text+"</b>"},drag_link:function(e,n,i,r){e=t.getTask(e);var a=t.locale.labels,o="<b>"+e.text+"</b> "+(n?a.link_start:a.link_end)+"<br/>";return i&&(o+="<b> "+(i=t.getTask(i)).text+"</b> "+(r?a.link_start:a.link_end)+"<br/>"),o},drag_link_class:function(e,n,i,r){var a="";return e&&i&&(a=" "+(t.isLinkAllowed(e,i,n,r)?"gantt_link_allow":"gantt_link_deny")),"gantt_link_tooltip"+a},tooltip_date_format:i.date_to_str("%Y-%m-%d"),tooltip_text:function(e,n,i){return"<b>Task:</b> "+i.text+"<br/><b>Start date:</b> "+t.templates.tooltip_date_format(e)+"<br/><b>End date:</b> "+t.templates.tooltip_date_format(n)}})},initTemplate:n}}},function(t,e,n){var i=n(4),r=n(0),a=n(42),o=n(15),s=n(1);t.exports=function(t){function e(t){return{target:t.target||t.srcElement,pageX:t.pageX,pageY:t.pageY,clientX:t.clientX,clientY:t.clientY,metaKey:t.metaKey,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey}}function n(n,a){this._obj=n,this._settings=a||{},i(this);var o=this.getInputMethods();this._drag_start_timer=null,t.attachEvent("onGanttScroll",r.bind(function(t,e){this.clearDragTimer()},this));for(var l={passive:!1},c=0;c<o.length;c++)r.bind(function(i){t.event(n,i.down,r.bind(function(o){i.accessor(o)&&(a.preventDefault&&a.selector&&s.closest(o.target,a.selector)&&o.preventDefault(),t.config.touch&&o.timeStamp&&o.timeStamp-0<300||(this._settings.original_target=e(o),t.config.touch?(this.clearDragTimer(),this._drag_start_timer=setTimeout(r.bind(function(){t.getState().lightbox||this.dragStart(n,o,i)},this),t.config.touch_drag)):this.dragStart(n,o,i)))},this),l);var o=document.body;t.event(o,i.up,r.bind(function(t){i.accessor(t)&&this.clearDragTimer()},this),l)},this)(o[c])}return n.prototype={traceDragEvents:function(e,n){var i=r.bind(function(t){return this.dragMove(e,t,n.accessor)},this);r.bind(function(t){return this.dragScroll(e,t)},this);var o=r.bind(function(t){if(!this.config.started||!r.defined(this.config.updates_per_second)||a(this,this.config.updates_per_second)){var e=i(t);if(e)try{t&&t.preventDefault&&t.cancelable&&t.preventDefault()}catch(t){}return e}},this),l=s.getRootNode(t.$root),c=this.config.mousemoveContainer||s.getRootNode(t.$root),u={passive:!1},d=r.bind(function(i){return t.eventRemove(c,n.move,o),t.eventRemove(l,n.up,d,u),this.dragEnd(e)},this);t.event(c,n.move,o,u),t.event(l,n.up,d,u)},checkPositionChange:function(t){var e=t.x-this.config.pos.x,n=t.y-this.config.pos.y;return Math.sqrt(Math.pow(Math.abs(e),2)+Math.pow(Math.abs(n),2))>this.config.sensitivity},initDnDMarker:function(){var t=this.config.marker=document.createElement("div");t.className="gantt_drag_marker",t.innerHTML="",document.body.appendChild(t)},backupEventTarget:function(n,i){if(t.config.touch){var r=i(n),a=r.target||r.srcElement,o=a.cloneNode(!0);this.config.original_target=e(r),this.config.original_target.target=o,this.config.backup_element=a,a.parentNode.appendChild(o),a.style.display="none",(this.config.mousemoveContainer||document.body).appendChild(a)}},getInputMethods:function(){var e=[];if(e.push({move:"mousemove",down:"mousedown",up:"mouseup",accessor:function(t){return t}}),t.config.touch){var n=!0;try{document.createEvent("TouchEvent")}catch(t){n=!1}n?e.push({move:"touchmove",down:"touchstart",up:"touchend",accessor:function(t){return t.touches&&t.touches.length>1?null:t.touches[0]?{target:document.elementFromPoint(t.touches[0].clientX,t.touches[0].clientY),pageX:t.touches[0].pageX,pageY:t.touches[0].pageY,clientX:t.touches[0].clientX,clientY:t.touches[0].clientY}:t}}):o.navigator.pointerEnabled?e.push({move:"pointermove",down:"pointerdown",up:"pointerup",accessor:function(t){return"mouse"==t.pointerType?null:t}}):o.navigator.msPointerEnabled&&e.push({move:"MSPointerMove",down:"MSPointerDown",up:"MSPointerUp",accessor:function(t){return t.pointerType==t.MSPOINTER_TYPE_MOUSE?null:t}})}return e},clearDragTimer:function(){this._drag_start_timer&&(clearTimeout(this._drag_start_timer),this._drag_start_timer=null)},dragStart:function(e,n,i){this.config&&this.config.started||(this.config={obj:e,marker:null,started:!1,pos:this.getPosition(n),sensitivity:4},this._settings&&r.mixin(this.config,this._settings,!0),this.traceDragEvents(e,i),t._prevent_touch_scroll=!0,document.body.className+=" gantt_noselect",t.config.touch&&this.dragMove(e,n,i.accessor))},dragMove:function(e,n,i){var r=i(n);if(!r)return!1;if(!this.config.marker&&!this.config.started){var a=this.getPosition(r);if(t.config.touch||this.checkPositionChange(a)){if(this.config.started=!0,this.config.ignore=!1,!1===this.callEvent("onBeforeDragStart",[e,this.config.original_target]))return this.config.ignore=!0,!1;this.backupEventTarget(n,i),this.initDnDMarker(),t._touch_feedback(),this.callEvent("onAfterDragStart",[e,this.config.original_target])}else this.config.ignore=!0}if(!this.config.ignore){if(n.targetTouches&&!r.target)return;return r.pos=this.getPosition(r),this.config.marker.style.left=r.pos.x+"px",this.config.marker.style.top=r.pos.y+"px",this.callEvent("onDragMove",[e,r]),!0}return!1},dragEnd:function(e){var n=this.config.backup_element;n&&n.parentNode&&n.parentNode.removeChild(n),t._prevent_touch_scroll=!1,this.config.marker&&(this.config.marker.parentNode.removeChild(this.config.marker),this.config.marker=null,this.callEvent("onDragEnd",[])),this.config.started=!1,document.body.className=document.body.className.replace(" gantt_noselect","")},getPosition:function(t){var e=0,n=0;return t.pageX||t.pageY?(e=t.pageX,n=t.pageY):(t.clientX||t.clientY)&&(e=t.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,n=t.clientY+document.body.scrollTop+document.documentElement.scrollTop),{x:e,y:n}}},n}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i={date_to_str:function(t,e,n){return function(i){return t.replace(/%[a-zA-Z]/g,function(t){switch(t){case"%d":return e?n.date.to_fixed(i.getUTCDate()):n.date.to_fixed(i.getDate());case"%m":return e?n.date.to_fixed(i.getUTCMonth()+1):n.date.to_fixed(i.getMonth()+1);case"%j":return e?i.getUTCDate():i.getDate();case"%n":return e?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return e?n.date.to_fixed(i.getUTCFullYear()%100):n.date.to_fixed(i.getFullYear()%100);case"%Y":return e?i.getUTCFullYear():i.getFullYear();case"%D":return e?n.locale.date.day_short[i.getUTCDay()]:n.locale.date.day_short[i.getDay()];case"%l":return e?n.locale.date.day_full[i.getUTCDay()]:n.locale.date.day_full[i.getDay()];case"%M":return e?n.locale.date.month_short[i.getUTCMonth()]:n.locale.date.month_short[i.getMonth()];case"%F":return e?n.locale.date.month_full[i.getUTCMonth()]:n.locale.date.month_full[i.getMonth()];case"%h":return e?n.date.to_fixed((i.getUTCHours()+11)%12+1):n.date.to_fixed((i.getHours()+11)%12+1);case"%g":return e?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return e?i.getUTCHours():i.getHours();case"%H":return e?n.date.to_fixed(i.getUTCHours()):n.date.to_fixed(i.getHours());case"%i":return e?n.date.to_fixed(i.getUTCMinutes()):n.date.to_fixed(i.getMinutes());case"%a":return e?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return e?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return e?n.date.to_fixed(i.getUTCSeconds()):n.date.to_fixed(i.getSeconds());case"%W":return e?n.date.to_fixed(n.date.getUTCISOWeek(i)):n.date.to_fixed(n.date.getISOWeek(i));default:return t}})}},str_to_date:function(t,e,n){return function(i){for(var r=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),o=t.match(/%[a-zA-Z]/g),s=0;s<o.length;s++)switch(o[s]){case"%j":case"%d":r[2]=a[s]||1;break;case"%n":case"%m":r[1]=(a[s]||1)-1;break;case"%y":r[0]=1*a[s]+(a[s]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":r[3]=a[s]||0;break;case"%i":r[4]=a[s]||0;break;case"%Y":r[0]=a[s]||0;break;case"%a":case"%A":r[3]=r[3]%12+("am"===(a[s]||"").toLowerCase()?0:12);break;case"%s":r[5]=a[s]||0;break;case"%M":r[1]=n.locale.date.month_short_hash[a[s]]||0;break;case"%F":r[1]=n.locale.date.month_full_hash[a[s]]||0}return e?new Date(Date.UTC(r[0],r[1],r[2],r[3],r[4],r[5])):new Date(r[0],r[1],r[2],r[3],r[4],r[5])}}};e.default=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i={date_to_str:function(t,e,n){t=t.replace(/%[a-zA-Z]/g,function(t){switch(t){case"%d":return'"+to_fixed(date.get'+(e?"UTC":"")+'Date())+"';case"%m":return'"+to_fixed((date.get'+(e?"UTC":"")+'Month()+1))+"';case"%j":return'"+date.get'+(e?"UTC":"")+'Date()+"';case"%n":return'"+(date.get'+(e?"UTC":"")+'Month()+1)+"';case"%y":return'"+to_fixed(date.get'+(e?"UTC":"")+'FullYear()%100)+"';case"%Y":return'"+date.get'+(e?"UTC":"")+'FullYear()+"';case"%D":return'"+locale.date.day_short[date.get'+(e?"UTC":"")+'Day()]+"';case"%l":return'"+locale.date.day_full[date.get'+(e?"UTC":"")+'Day()]+"';case"%M":return'"+locale.date.month_short[date.get'+(e?"UTC":"")+'Month()]+"';case"%F":return'"+locale.date.month_full[date.get'+(e?"UTC":"")+'Month()]+"';case"%h":return'"+to_fixed((date.get'+(e?"UTC":"")+'Hours()+11)%12+1)+"';case"%g":return'"+((date.get'+(e?"UTC":"")+'Hours()+11)%12+1)+"';case"%G":return'"+date.get'+(e?"UTC":"")+'Hours()+"';case"%H":return'"+to_fixed(date.get'+(e?"UTC":"")+'Hours())+"';case"%i":return'"+to_fixed(date.get'+(e?"UTC":"")+'Minutes())+"';case"%a":return'"+(date.get'+(e?"UTC":"")+'Hours()>11?"pm":"am")+"';case"%A":return'"+(date.get'+(e?"UTC":"")+'Hours()>11?"PM":"AM")+"';case"%s":return'"+to_fixed(date.get'+(e?"UTC":"")+'Seconds())+"';case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return t}});var i=new Function("date","to_fixed","locale","getISOWeek","getWeek",'return "'+t+'";');return function(t){return i(t,n.date.to_fixed,n.locale,n.date.getISOWeek,n.date.getWeek)}},str_to_date:function(t,e,n){for(var i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",r=t.match(/%[a-zA-Z]/g),a=0;a<r.length;a++)switch(r[a]){case"%j":case"%d":i+="set[2]=temp["+a+"]||1;";break;case"%n":case"%m":i+="set[1]=(temp["+a+"]||1)-1;";break;case"%y":i+="set[0]=temp["+a+"]*1+(temp["+a+"]>50?1900:2000);";break;case"%g":case"%G":case"%h":case"%H":i+="set[3]=temp["+a+"]||0;";break;case"%i":i+="set[4]=temp["+a+"]||0;";break;case"%Y":i+="set[0]=temp["+a+"]||0;";break;case"%a":case"%A":i+="set[3]=set[3]%12+((temp["+a+"]||'').toLowerCase()=='am'?0:12);";break;case"%s":i+="set[5]=temp["+a+"]||0;";break;case"%M":i+="set[1]=locale.date.month_short_hash[temp["+a+"]]||0;";break;case"%F":i+="set[1]=locale.date.month_full_hash[temp["+a+"]]||0;"}var o="set[0],set[1],set[2],set[3],set[4],set[5]";e&&(o=" Date.UTC("+o+")");var s=new Function("date","locale","var set=[0,0,1,0,0,0]; "+i+" return new Date("+o+");");return function(t){return s(t,n.locale)}}};e.default=i},function(t,e,n){var i=n(214).default,r=n(213).default;t.exports=function(t){var e=null;function n(){var n=!1;return"auto"===t.config.csp?(null===e&&function(){try{new Function("canUseCsp = false;")}catch(t){e=!0}}(),n=e):n=t.config.csp,n}return{init:function(){for(var e=t.locale,n=e.date.month_short,i=e.date.month_short_hash={},r=0;r<n.length;r++)i[n[r]]=r;for(n=e.date.month_full,i=e.date.month_full_hash={},r=0;r<n.length;r++)i[n[r]]=r},date_part:function(t){var e=new Date(t);return t.setHours(0),this.hour_start(t),t.getHours()&&(t.getDate()<e.getDate()||t.getMonth()<e.getMonth()||t.getFullYear()<e.getFullYear())&&t.setTime(t.getTime()+36e5*(24-t.getHours())),t},time_part:function(t){return(t.valueOf()/1e3-60*t.getTimezoneOffset())%86400},week_start:function(e){var n=e.getDay();return t.config.start_on_monday&&(0===n?n=6:n--),this.date_part(this.add(e,-1*n,"day"))},month_start:function(t){return t.setDate(1),this.date_part(t)},quarter_start:function(t){this.month_start(t);var e,n=t.getMonth();return e=n>=9?9:n>=6?6:n>=3?3:0,t.setMonth(e),t},year_start:function(t){return t.setMonth(0),this.month_start(t)},day_start:function(t){return this.date_part(t)},hour_start:function(t){return t.getMinutes()&&t.setMinutes(0),this.minute_start(t),t},minute_start:function(t){return t.getSeconds()&&t.setSeconds(0),t.getMilliseconds()&&t.setMilliseconds(0),t},_add_days:function(t,e,n){t.setDate(t.getDate()+e);var i=e>=0,r=!n.getHours()&&t.getHours(),a=t.getDate()<=n.getDate()||t.getMonth()<n.getMonth()||t.getFullYear()<n.getFullYear();return i&&r&&a&&t.setTime(t.getTime()+36e5*(24-t.getHours())),t},add:function(t,e,n){var i=new Date(t.valueOf());switch(n){case"day":i=this._add_days(i,e,t);break;case"week":i=this._add_days(i,7*e,t);break;case"month":i.setMonth(i.getMonth()+e);break;case"year":i.setYear(i.getFullYear()+e);break;case"hour":i.setTime(i.getTime()+60*e*60*1e3);break;case"minute":i.setTime(i.getTime()+60*e*1e3);break;default:return this["add_"+n](t,e,n)}return i},add_quarter:function(t,e){return this.add(t,3*e,"month")},to_fixed:function(t){return t<10?"0"+t:t},copy:function(t){return new Date(t.valueOf())},date_to_str:function(e,a){var o=i;return n()&&(o=r),o.date_to_str(e,a,t)},str_to_date:function(e,a){var o=i;return n()&&(o=r),o.str_to_date(e,a,t)},getISOWeek:function(e){return t.date._getWeekNumber(e,!0)},_getWeekNumber:function(t,e){if(!t)return!1;var n=t.getDay();e&&0===n&&(n=7);var i=new Date(t.valueOf());i.setDate(t.getDate()+(4-n));var r=i.getFullYear(),a=Math.round((i.getTime()-new Date(r,0,1).getTime())/864e5);return 1+Math.floor(a/7)},getWeek:function(e){return t.date._getWeekNumber(e,t.config.start_on_monday)},getUTCISOWeek:function(e){return t.date.getISOWeek(e)},convert_to_utc:function(t){return new Date(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())},parseDate:function(e,n){return e&&!e.getFullYear&&("function"!=typeof n&&(n="string"==typeof n?"parse_date"===n||"xml_date"===n?t.defined(t.templates.xml_date)?t.templates.xml_date:t.templates.parse_date:t.defined(t.templates[n])?t.templates[n]:t.date.str_to_date(n):t.defined(t.templates.xml_date)?t.templates.xml_date:t.templates.parse_date),e=e?n(e):null),e}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){if("string"==typeof t||"number"==typeof t)return t;var e="";for(var n in t){var i="";t.hasOwnProperty(n)&&(i=n+"="+(i="string"==typeof t[n]?encodeURIComponent(t[n]):"number"==typeof t[n]?t[n]:encodeURIComponent(JSON.stringify(t[n]))),e.length&&(i="&"+i),e+=i)}return e}},function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var r=n(8),a=n(15),o=n(216).default;function s(t,e){var n={method:t};if(0===e.length)throw new Error("Arguments list of query is wrong.");if(1===e.length)return"string"==typeof e[0]?(n.url=e[0],n.async=!0):(n.url=e[0].url,n.async=e[0].async||!0,n.callback=e[0].callback,n.headers=e[0].headers),e[0].data?"string"!=typeof e[0].data?n.data=o(e[0].data):n.data=e[0].data:n.data="",n;switch(n.url=e[0],t){case"GET":case"DELETE":n.callback=e[1],n.headers=e[2];break;case"POST":case"PUT":e[1]?"string"!=typeof e[1]?n.data=o(e[1]):n.data=e[1]:n.data="",n.callback=e[2],n.headers=e[3]}return n}t.exports=function(t){return{cache:!0,method:"get",parse:function(t){return"string"!=typeof t?t:(t=t.replace(/^[\s]+/,""),"undefined"==typeof DOMParser||r.isIE?void 0!==a.ActiveXObject&&((e=new a.ActiveXObject("Microsoft.XMLDOM")).async="false",e.loadXML(t)):e=(new DOMParser).parseFromString(t,"text/xml"),e);var e},xmltop:function(e,n,i){if(void 0===n.status||n.status<400){var r=n.responseXML?n.responseXML||n:this.parse(n.responseText||n);if(r&&null!==r.documentElement&&!r.getElementsByTagName("parsererror").length)return r.getElementsByTagName(e)[0]}return-1!==i&&t.callEvent("onLoadXMLError",["Incorrect XML",arguments[1],i]),document.createElement("DIV")},xpath:function(t,e){if(e.nodeName||(e=e.responseXML||e),r.isIE)return e.selectNodes(t)||[];for(var n,i=[],a=(e.ownerDocument||e).evaluate(t,e,null,XPathResult.ANY_TYPE,null);n=a.iterateNext();)i.push(n);return i},query:function(t){return this._call(t.method||"GET",t.url,t.data||"",t.async||!0,t.callback,t.headers)},get:function(t,e,n){var i=s("GET",arguments);return this.query(i)},getSync:function(t,e){var n=s("GET",arguments);return n.async=!1,this.query(n)},put:function(t,e,n,i){var r=s("PUT",arguments);return this.query(r)},del:function(t,e,n){var i=s("DELETE",arguments);return this.query(i)},post:function(t,e,n,i){1==arguments.length?e="":2==arguments.length&&"function"==typeof e&&(e,e="");var r=s("POST",arguments);return this.query(r)},postSync:function(t,e,n){e=null===e?"":String(e);var i=s("POST",arguments);return i.async=!1,this.query(i)},_call:function(e,n,o,s,l,c){return new t.Promise(function(u,d){var h=void 0===("undefined"==typeof XMLHttpRequest?"undefined":i(XMLHttpRequest))||r.isIE?new a.ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest,f=null!==navigator.userAgent.match(/AppleWebKit/)&&null!==navigator.userAgent.match(/Qt/)&&null!==navigator.userAgent.match(/Safari/);if(s&&(h.onreadystatechange=function(){if(4==h.readyState||f&&3==h.readyState){if((200!=h.status||""===h.responseText)&&!t.callEvent("onAjaxError",[h]))return;setTimeout(function(){"function"==typeof l&&l.apply(a,[{xmlDoc:h,filePath:n}]),u(h),"function"==typeof l&&(l=null,h=null)},0)}}),"GET"!=e||this.cache||(n+=(n.indexOf("?")>=0?"&":"?")+"dhxr"+(new Date).getTime()+"=1"),h.open(e,n,s),c)for(var _ in c)h.setRequestHeader(_,c[_]);else"POST"==e.toUpperCase()||"PUT"==e||"DELETE"==e?h.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):"GET"==e&&(o=null);if(h.setRequestHeader("X-Requested-With","XMLHttpRequest"),h.send(o),!s)return{xmlDoc:h,filePath:n}})},urlSeparator:function(t){return-1!=t.indexOf("?")?"&":"?"}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),t.exports=function(){return{layout:{css:"gantt_container",rows:[{cols:[{view:"grid",scrollX:"scrollHor",scrollY:"scrollVer"},{resizer:!0,width:1},{view:"timeline",scrollX:"scrollHor",scrollY:"scrollVer"},{view:"scrollbar",id:"scrollVer"}]},{view:"scrollbar",id:"scrollHor",height:20}]},links:{finish_to_start:"0",start_to_start:"1",finish_to_finish:"2",start_to_finish:"3"},types:{task:"task",project:"project",milestone:"milestone"},auto_types:!1,duration_unit:"day",work_time:!1,correct_work_time:!1,skip_off_time:!1,cascade_delete:!0,autosize:!1,autosize_min_width:0,autoscroll:!0,autoscroll_speed:30,deepcopy_on_parse:!1,show_links:!0,show_task_cells:!0,static_background:!1,static_background_cells:!0,branch_loading:!1,branch_loading_property:"$has_child",show_loading:!1,show_chart:!0,show_grid:!0,min_duration:36e5,date_format:"%d-%m-%Y %H:%i",xml_date:void 0,start_on_monday:!0,server_utc:!1,show_progress:!0,fit_tasks:!1,select_task:!0,scroll_on_click:!0,smart_rendering:!0,preserve_scroll:!0,readonly:!1,container_resize_timeout:20,date_grid:"%Y-%m-%d",drag_links:!0,drag_progress:!0,drag_resize:!0,drag_project:!1,drag_move:!0,drag_mode:{resize:"resize",progress:"progress",move:"move",ignore:"ignore"},round_dnd_dates:!0,link_wrapper_width:20,root_id:0,autofit:!1,columns:[{name:"text",tree:!0,width:"*",resize:!0},{name:"start_date",align:"center",resize:!0},{name:"duration",align:"center"},{name:"add",width:44}],scale_offset_minimal:!0,inherit_scale_class:!1,scales:[{unit:"day",step:1,date:"%d %M"}],time_step:60,duration_step:1,task_date:"%d %F %Y",time_picker:"%H:%i",task_attribute:"data-task-id",link_attribute:"data-link-id",layer_attribute:"data-layer",buttons_left:["gantt_save_btn","gantt_cancel_btn"],_migrate_buttons:{dhx_save_btn:"gantt_save_btn",dhx_cancel_btn:"gantt_cancel_btn",dhx_delete_btn:"gantt_delete_btn"},buttons_right:["gantt_delete_btn"],lightbox:{sections:[{name:"description",height:70,map_to:"text",type:"textarea",focus:!0},{name:"time",type:"duration",map_to:"auto"}],project_sections:[{name:"description",height:70,map_to:"text",type:"textarea",focus:!0},{name:"type",type:"typeselect",map_to:"type"},{name:"time",type:"duration",readonly:!0,map_to:"auto"}],milestone_sections:[{name:"description",height:70,map_to:"text",type:"textarea",focus:!0},{name:"type",type:"typeselect",map_to:"type"},{name:"time",type:"duration",single_date:!0,map_to:"auto"}]},drag_lightbox:!0,sort:!1,details_on_create:!0,details_on_dblclick:!0,initial_scroll:!0,task_scroll_offset:100,order_branch:!1,order_branch_free:!1,task_height:void 0,bar_height:"full",min_column_width:70,min_grid_column_width:70,grid_resizer_column_attribute:"data-column-index",keep_grid_width:!1,grid_resize:!1,grid_elastic_columns:!1,show_tasks_outside_timescale:!1,show_unscheduled:!0,resize_rows:!1,task_grid_row_resizer_attribute:"data-row-index",min_task_grid_row_height:30,readonly_property:"readonly",editable_property:"editable",calendar_property:"calendar_id",resource_calendars:{},dynamic_resource_calendars:!1,inherit_calendar:!1,type_renderers:{},open_tree_initially:!1,optimize_render:!0,prevent_default_scroll:!1,show_errors:!0,wai_aria_attributes:!0,smart_scales:!0,rtl:!1,placeholder_task:!1,horizontal_scroll_key:"shiftKey",drag_timeline:{useKey:void 0,ignore:".gantt_task_line, .gantt_task_link"},drag_multiple:!0,csp:"auto"}}},function(t,e){t.exports=function(){var t={};return{services:{},setService:function(e,n){t[e]=n},getService:function(e){return t[e]?t[e]():null},dropService:function(e){t[e]&&delete t[e]},destructor:function(){for(var e in t)if(t[e]){var n=t[e];n&&n.destructor&&n.destructor()}t=null}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){return function(t){var e=this;for(var n in this.addExtension=function(t,n){e._extensions[t]=n},this.getExtension=function(t){return e._extensions[t]},this._extensions={},t)this._extensions[n]=t[n]}}();e.default=i},function(t,e){t.exports={KEY_CODES:{UP:38,DOWN:40,LEFT:37,RIGHT:39,SPACE:32,ENTER:13,DELETE:46,ESC:27,TAB:9}}},function(t,e,n){function i(t){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}t.exports=function(t){var e=new function(){this.constants=n(221),this.version="7.1.9",this.license="gpl",this.templates={},this.ext={},this.keys={edit_save:this.constants.KEY_CODES.ENTER,edit_cancel:this.constants.KEY_CODES.ESC}},r=new(0,n(220).default)(t),a={};e.plugins=function(t){for(var n in t)if(t[n]&&!a[n]){var i=r.getExtension(n);i&&(i(e),a[n]=!0)}},e.$services=n(219)(),e.config=n(218)(),e.ajax=n(217)(e),e.date=n(215)(e);var o=n(212)(e);e.$services.setService("dnd",function(){return o});var s=n(211)(e);e.$services.setService("templateLoader",function(){return s}),n(4)(e);var l=new(n(210));l.registerProvider("global",function(){var t={min_date:e._min_date,max_date:e._max_date,selected_task:null};return e.$data&&e.$data.tasksStore&&(t.selected_task=e.$data.tasksStore.getSelectedId()),t}),e.getState=l.getState,e.$services.setService("state",function(){return l});var c=n(0);c.mixin(e,c),e.Promise=n(209),e.env=n(8),n(205)(e);var u=n(199);e.dataProcessor=u.DEPRECATED_api,e.createDataProcessor=u.createDataProcessor,n(194)(e),n(185)(e),n(184)(e),n(176)(e),n(175)(e),n(174)(e),n(161)(e),n(160).default(e),n(159)(e),n(158)(e),n(157)(e),n(154)(e),n(153).default(e);var d=n(152).default();return e.i18n={addLocale:d.addLocale,setLocale:function(t){if("string"==typeof t){var n=d.getLocale(t);n||(n=d.getLocale("en")),e.locale=n}else if(t)if(e.locale)for(var r in t)t[r]&&"object"===i(t[r])?(e.locale[r]||(e.locale[r]={}),e.mixin(e.locale[r],t[r],!0)):e.locale[r]=t[r];else e.locale=t},getLocale:d.getLocale},e.i18n.setLocale("en"),e}},function(t,e,n){n(28);var i=n(222);t.exports=function(t){var e=i(t);return e.env.isNode||n(118)(e),e}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=10,r=function(){function t(t){var e=this;this.maxSteps=i,this.undoEnabled=!0,this.redoEnabled=!0,this.action={create:function(t){return{commands:t?t.slice():[]}},invert:function(t){for(var n,i=e._gantt.copy(t),r=e.command,a=0;a<t.commands.length;a++){var o=i.commands[a]=r.invert(i.commands[a]);o.type!==r.type.update&&o.type!==r.type.move||(n=[o.oldValue,o.value],o.value=n[0],o.oldValue=n[1])}return i}},this.command={entity:null,type:null,create:function(t,n,i,r){var a=e._gantt;return{entity:r,type:i,value:a.copy(t),oldValue:a.copy(n||t)}},invert:function(t){var n=e._gantt.copy(t);return n.type=e.command.inverseCommands(t.type),n},inverseCommands:function(t){var n=e._gantt,i=e.command.type;switch(t){case i.update:return i.update;case i.remove:return i.add;case i.add:return i.remove;case i.move:return i.move;default:return n.assert(!1,"Invalid command "+t),null}}},this._undoStack=[],this._redoStack=[],this._gantt=t}return t.prototype.getUndoStack=function(){return this._undoStack},t.prototype.getRedoStack=function(){return this._redoStack},t.prototype.clearUndoStack=function(){this._undoStack=[]},t.prototype.clearRedoStack=function(){this._redoStack=[]},t.prototype.updateConfigs=function(){var t=this._gantt;this.maxSteps=t.config.undo_steps||i,this.command.entity=t.config.undo_types,this.command.type=t.config.undo_actions,this.undoEnabled=!!t.config.undo,this.redoEnabled=!!t.config.redo},t.prototype.undo=function(){var t=this._gantt;if(this.updateConfigs(),this.undoEnabled){var e=this._pop(this._undoStack);if(e&&this._reorderCommands(e),!1!==t.callEvent("onBeforeUndo",[e])&&e)return this._applyAction(this.action.invert(e)),this._push(this._redoStack,t.copy(e)),void t.callEvent("onAfterUndo",[e]);t.callEvent("onAfterUndo",[null])}},t.prototype.redo=function(){var t=this._gantt;if(this.updateConfigs(),this.redoEnabled){var e=this._pop(this._redoStack);if(e&&this._reorderCommands(e),!1!==t.callEvent("onBeforeRedo",[e])&&e)return this._applyAction(e),this._push(this._undoStack,t.copy(e)),void t.callEvent("onAfterRedo",[e]);t.callEvent("onAfterRedo",[null])}},t.prototype.logAction=function(t){this._push(this._undoStack,t),this._redoStack=[]},t.prototype._push=function(t,e){var n=this._gantt;if(e.commands.length){var i=t===this._undoStack?"onBeforeUndoStack":"onBeforeRedoStack";if(!1!==n.callEvent(i,[e])&&e.commands.length){for(t.push(e);t.length>this.maxSteps;)t.shift();return e}}},t.prototype._pop=function(t){return t.pop()},t.prototype._reorderCommands=function(t){var e={any:0,link:1,task:2},n={move:1,any:0};t.commands.sort(function(t,i){if("task"===t.entity&&"task"===i.entity)return t.type!==i.type?(n[i.type]||0)-(n[t.type]||0):"move"===t.type&&t.oldValue&&i.oldValue&&i.oldValue.parent===t.oldValue.parent?t.oldValue.$index-i.oldValue.$index:0;var r=e[t.entity]||e.any;return(e[i.entity]||e.any)-r})},t.prototype._applyAction=function(t){var e=null,n=this.command.entity,i=this.command.type,r=this._gantt,a={};a[n.task]={add:"addTask",get:"getTask",update:"updateTask",remove:"deleteTask",move:"moveTask",isExists:"isTaskExists"},a[n.link]={add:"addLink",get:"getLink",update:"updateLink",remove:"deleteLink",isExists:"isLinkExists"},r.batchUpdate(function(){for(var n=0;n<t.commands.length;n++){e=t.commands[n];var o=a[e.entity][e.type],s=a[e.entity].get,l=a[e.entity].isExists;if(e.type===i.add)r[o](e.oldValue,e.oldValue.parent,e.oldValue.$local_index);else if(e.type===i.remove)r[l](e.value.id)&&r[o](e.value.id);else if(e.type===i.update){var c=r[s](e.value.id);for(var u in e.value)u.startsWith("$")||u.startsWith("_")||(c[u]=e.value[u]);r[o](e.value.id)}else e.type===i.move&&(r[o](e.value.id,e.value.$local_index,e.value.parent),r.callEvent("onRowDragEnd",[e.value.id]))}})},t}();e.Undo=r},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i={onBeforeUndo:"onAfterUndo",onBeforeRedo:"onAfterRedo"},r=["onTaskDragStart","onAfterTaskUpdate","onAfterTaskDelete","onBeforeBatchUpdate"],a=function(){function t(t,e){this._batchAction=null,this._batchMode=!1,this._ignore=!1,this._ignoreMoveEvents=!1,this._initialTasks={},this._initialLinks={},this._nestedTasks={},this._nestedLinks={},this._undo=t,this._gantt=e,this._attachEvents()}return t.prototype.store=function(t,e,n){return void 0===n&&(n=!1),e===this._gantt.config.undo_types.task?this._storeTask(t,n):e===this._gantt.config.undo_types.link&&this._storeLink(t,n)},t.prototype.isMoveEventsIgnored=function(){return this._ignoreMoveEvents},t.prototype.toggleIgnoreMoveEvents=function(t){this._ignoreMoveEvents=t||!1},t.prototype.startIgnore=function(){this._ignore=!0},t.prototype.stopIgnore=function(){this._ignore=!1},t.prototype.startBatchAction=function(){var t=this;this._timeout||(this._timeout=setTimeout(function(){t.stopBatchAction(),t._timeout=null},10)),this._ignore||this._batchMode||(this._batchMode=!0,this._batchAction=this._undo.action.create())},t.prototype.stopBatchAction=function(){if(!this._ignore){var t=this._undo;this._batchAction&&t.logAction(this._batchAction),this._batchMode=!1,this._batchAction=null}},t.prototype.onTaskAdded=function(t){this._ignore||this._storeTaskCommand(t,this._undo.command.type.add)},t.prototype.onTaskUpdated=function(t){this._ignore||this._storeTaskCommand(t,this._undo.command.type.update)},t.prototype.onTaskMoved=function(t){if(!this._ignore){t.$local_index=this._gantt.getTaskIndex(t.id);var e=this.getInitialTask(t.id);if(t.$local_index===e.$local_index&&this._gantt.getParent(t)===this._gantt.getParent(e))return;this._storeEntityCommand(t,this.getInitialTask(t.id),this._undo.command.type.move,this._undo.command.entity.task)}},t.prototype.onTaskDeleted=function(t){if(!this._ignore){if(this._storeTaskCommand(t,this._undo.command.type.remove),this._nestedTasks[t.id])for(var e=this._nestedTasks[t.id],n=0;n<e.length;n++)this._storeTaskCommand(e[n],this._undo.command.type.remove);if(this._nestedLinks[t.id]){var i=this._nestedLinks[t.id];for(n=0;n<i.length;n++)this._storeLinkCommand(i[n],this._undo.command.type.remove)}}},t.prototype.onLinkAdded=function(t){this._ignore||this._storeLinkCommand(t,this._undo.command.type.add)},t.prototype.onLinkUpdated=function(t){this._ignore||this._storeLinkCommand(t,this._undo.command.type.update)},t.prototype.onLinkDeleted=function(t){this._ignore||this._storeLinkCommand(t,this._undo.command.type.remove)},t.prototype.setNestedTasks=function(t,e){for(var n=this._gantt,i=null,r=[],a=this._getLinks(n.getTask(t)),o=0;o<e.length;o++)i=this.setInitialTask(e[o]),a=a.concat(this._getLinks(i)),r.push(i);var s={};for(o=0;o<a.length;o++)s[a[o]]=!0;var l=[];for(var o in s)l.push(this.setInitialLink(o));this._nestedTasks[t]=r,this._nestedLinks[t]=l},t.prototype.setInitialTask=function(t,e){var n=this._gantt;if(e||!this._initialTasks[t]||!this._batchMode){var i=n.copy(n.getTask(t));i.$index=n.getGlobalTaskIndex(t),i.$local_index=n.getTaskIndex(t),this.setInitialTaskObject(t,i)}return this._initialTasks[t]},t.prototype.getInitialTask=function(t){return this._initialTasks[t]},t.prototype.clearInitialTasks=function(){this._initialTasks={}},t.prototype.setInitialTaskObject=function(t,e){this._initialTasks[t]=e},t.prototype.setInitialLink=function(t,e){return this._initialLinks[t]&&this._batchMode||(this._initialLinks[t]=this._gantt.copy(this._gantt.getLink(t))),this._initialLinks[t]},t.prototype.getInitialLink=function(t){return this._initialLinks[t]},t.prototype.clearInitialLinks=function(){this._initialLinks={}},t.prototype._attachEvents=function(){var t=this,e=null,n=this._gantt,a=function(){e||(e=setTimeout(function(){e=null}),t.clearInitialTasks(),n.eachTask(function(e){t.setInitialTask(e.id)}),t.clearInitialLinks(),n.getLinks().forEach(function(e){t.setInitialLink(e.id)}))},o=function(t){return n.copy(n.getTask(t))};for(var s in i)n.attachEvent(s,function(){return t.startIgnore(),!0}),n.attachEvent(i[s],function(){return t.stopIgnore(),!0});for(s=0;s<r.length;s++)n.attachEvent(r[s],function(){return t.startBatchAction(),!0});n.attachEvent("onParse",function(){t._undo.clearUndoStack(),t._undo.clearRedoStack(),a()}),n.attachEvent("onAfterTaskAdd",function(e,n){t.setInitialTask(e,!0),t.onTaskAdded(n)}),n.attachEvent("onAfterTaskUpdate",function(e,n){t.onTaskUpdated(n)}),n.attachEvent("onAfterTaskDelete",function(e,n){t.onTaskDeleted(n)}),n.attachEvent("onAfterLinkAdd",function(e,n){t.setInitialLink(e,!0),t.onLinkAdded(n)}),n.attachEvent("onAfterLinkUpdate",function(e,n){t.onLinkUpdated(n)}),n.attachEvent("onAfterLinkDelete",function(e,n){t.onLinkDeleted(n)}),n.attachEvent("onRowDragEnd",function(e,n){return t.onTaskMoved(o(e)),t.toggleIgnoreMoveEvents(),!0}),n.attachEvent("onBeforeTaskDelete",function(e){t.store(e,n.config.undo_types.task);var i=[];return a(),n.eachTask(function(t){i.push(t.id)},e),t.setNestedTasks(e,i),!0});var l=n.getDatastore("task");l.attachEvent("onBeforeItemMove",function(e,n,i){return t.isMoveEventsIgnored()||a(),!0}),l.attachEvent("onAfterItemMove",function(e,n,i){return t.isMoveEventsIgnored()||t.onTaskMoved(o(e)),!0}),n.attachEvent("onRowDragStart",function(e,n,i){return t.toggleIgnoreMoveEvents(!0),a(),!0}),n.attachEvent("onBeforeTaskDrag",function(e){return t.store(e,n.config.undo_types.task)}),n.attachEvent("onLightbox",function(e){return t.store(e,n.config.undo_types.task)}),n.attachEvent("onBeforeTaskAutoSchedule",function(e){return t.store(e.id,n.config.undo_types.task),!0}),n.ext.inlineEditors&&n.ext.inlineEditors.attachEvent("onEditStart",function(e){t.store(e.id,n.config.undo_types.task)})},t.prototype._storeCommand=function(t){var e=this._undo;if(e.updateConfigs(),e.undoEnabled)if(this._batchMode)this._batchAction.commands.push(t);else{var n=e.action.create([t]);e.logAction(n)}},t.prototype._storeEntityCommand=function(t,e,n,i){var r=this._undo.command.create(t,e,n,i);this._storeCommand(r)},t.prototype._storeTaskCommand=function(t,e){this._gantt.isTaskExists(t.id)&&(t.$local_index=this._gantt.getTaskIndex(t.id)),this._storeEntityCommand(t,this.getInitialTask(t.id),e,this._undo.command.entity.task)},t.prototype._storeLinkCommand=function(t,e){this._storeEntityCommand(t,this.getInitialLink(t.id),e,this._undo.command.entity.link)},t.prototype._getLinks=function(t){return t.$source.concat(t.$target)},t.prototype._storeTask=function(t,e){var n=this;void 0===e&&(e=!1);var i=this._gantt;return this.setInitialTask(t,e),i.eachTask(function(t){n.setInitialTask(t.id)},t),!0},t.prototype._storeLink=function(t,e){return void 0===e&&(e=!1),this.setInitialLink(t,e),!0},t}();e.Monitor=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(225),r=n(224);e.default=function(t){var e=new r.Undo(t),n=new i.Monitor(e,t);function a(t,e,n){t&&(t.id===e&&(t.id=n),t.parent===e&&(t.parent=n))}function o(t,e,n){a(t.value,e,n),a(t.oldValue,e,n)}function s(t,e,n){t&&(t.source===e&&(t.source=n),t.target===e&&(t.target=n))}function l(t,e,n){s(t.value,e,n),s(t.oldValue,e,n)}function c(t,n,i){for(var r=e,a=0;a<t.length;a++)for(var s=t[a],c=0;c<s.commands.length;c++)s.commands[c].entity===r.command.entity.task?o(s.commands[c],n,i):s.commands[c].entity===r.command.entity.link&&l(s.commands[c],n,i)}function u(t,n,i){for(var r=e,a=0;a<t.length;a++)for(var o=t[a],s=0;s<o.commands.length;s++){var l=o.commands[s];l.entity===r.command.entity.link&&(l.value&&l.value.id===n&&(l.value.id=i),l.oldValue&&l.oldValue.id===n&&(l.oldValue.id=i))}}t.config.undo=!0,t.config.redo=!0,t.config.undo_types={link:"link",task:"task"},t.config.undo_actions={update:"update",remove:"remove",add:"add",move:"move"},t.ext||(t.ext={}),t.ext.undo={undo:function(){return e.undo()},redo:function(){return e.redo()},getUndoStack:function(){return e.getUndoStack()},getRedoStack:function(){return e.getRedoStack()},clearUndoStack:function(){return e.clearUndoStack()},clearRedoStack:function(){return e.clearRedoStack()},saveState:function(t,e){return n.store(t,e,!0)}},t.undo=t.ext.undo.undo,t.redo=t.ext.undo.redo,t.getUndoStack=t.ext.undo.getUndoStack,t.getRedoStack=t.ext.undo.getRedoStack,t.clearUndoStack=t.ext.undo.clearUndoStack,t.clearRedoStack=t.ext.undo.clearRedoStack,t.attachEvent("onTaskIdChange",function(t,n){var i=e;c(i.getUndoStack(),t,n),c(i.getRedoStack(),t,n)}),t.attachEvent("onLinkIdChange",function(t,n){var i=e;u(i.getUndoStack(),t,n),u(i.getRedoStack(),t,n)}),t.attachEvent("onGanttReady",function(){e.updateConfigs()})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),r=function(){function t(t){this._gantt=t}return t.prototype.getNode=function(){var t=this._gantt;return this._tooltipNode||(this._tooltipNode=document.createElement("div"),this._tooltipNode.className="gantt_tooltip",t._waiAria.tooltipAttr(this._tooltipNode)),this._tooltipNode},t.prototype.setViewport=function(t){return this._root=t,this},t.prototype.show=function(t,e){var n=this._gantt,r=document.body,a=this.getNode();if(i.isChildOf(a,r)||(this.hide(),r.appendChild(a)),this._isLikeMouseEvent(t)){var o=this._calculateTooltipPosition(t);e=o.top,t=o.left}return a.style.top=e+"px",a.style.left=t+"px",n._waiAria.tooltipVisibleAttr(a),this},t.prototype.hide=function(){var t=this._gantt,e=this.getNode();return e&&e.parentNode&&e.parentNode.removeChild(e),t._waiAria.tooltipHiddenAttr(e),this},t.prototype.setContent=function(t){return this.getNode().innerHTML=t,this},t.prototype._isLikeMouseEvent=function(t){return!(!t||"object"!=typeof t)&&("clientX"in t&&"clientY"in t)},t.prototype._getViewPort=function(){return this._root||document.body},t.prototype._calculateTooltipPosition=function(t){var e=this._gantt,n=this._getViewPortSize(),r=this.getNode(),a={top:0,left:0,width:r.offsetWidth,height:r.offsetHeight,bottom:0,right:0},o=e.config.tooltip_offset_x,s=e.config.tooltip_offset_y,l=document.body,c=i.getRelativeEventPosition(t,l),u=i.getNodePosition(l);c.y+=u.y,a.top=c.y,a.left=c.x,a.top+=s,a.left+=o,a.bottom=a.top+a.height,a.right=a.left+a.width;var d=window.scrollY+l.scrollTop;return a.top<n.top-d?(a.top=n.top,a.bottom=a.top+a.height):a.bottom>n.bottom&&(a.bottom=n.bottom,a.top=a.bottom-a.height),a.left<n.left?(a.left=n.left,a.right=n.left+a.width):a.right>n.right&&(a.right=n.right,a.left=a.right-a.width),c.x>=a.left&&c.x<=a.right&&(a.left=c.x-a.width-o,a.right=a.left+a.width),c.y>=a.top&&c.y<=a.bottom&&(a.top=c.y-a.height-s,a.bottom=a.top+a.height),a},t.prototype._getViewPortSize=function(){var t,e=this._gantt,n=this._getViewPort(),r=n,a=window.scrollY+document.body.scrollTop,o=window.scrollX+document.body.scrollLeft;return n===e.$task_data?(r=e.$task,a=0,o=0,t=i.getNodePosition(e.$task)):t=i.getNodePosition(r),{left:t.x+o,top:t.y+a,width:t.width,height:t.height,bottom:t.y+t.height+a,right:t.x+t.width+o}},t}();e.Tooltip=r},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(43),r=n(1),a=n(2),o=n(227),s=function(){function t(t){this._listeners={},this.tooltip=new o.Tooltip(t),this._gantt=t,this._domEvents=i(),this._initDelayedFunctions()}return t.prototype.destructor=function(){this.tooltip.hide(),this._domEvents.detachAll()},t.prototype.hideTooltip=function(){this.delayHide()},t.prototype.attach=function(t){var e=this,n=document.body,i=this._gantt;t.global||(n=i.$root);var a=null,o=function(n){var i=r.getTargetNode(n),o=r.closest(i,t.selector);if(!r.isChildOf(i,e.tooltip.getNode())){var s=function(){a=o,t.onmouseenter(n,o)};a?o&&o===a?t.onmousemove(n,o):(t.onmouseleave(n,a),a=null,o&&o!==a&&s()):o&&s()}};this.detach(t.selector),this._domEvents.attach(n,"mousemove",o),this._listeners[t.selector]={node:n,handler:o}},t.prototype.detach=function(t){var e=this._listeners[t];e&&this._domEvents.detach(e.node,"mousemove",e.handler)},t.prototype.tooltipFor=function(t){var e=this,n=function(t){var e=t;return document.createEventObject&&!document.createEvent&&(e=document.createEventObject(t)),e};this._initDelayedFunctions(),this.attach({selector:t.selector,global:t.global,onmouseenter:function(i,r){var a=t.html(i,r);a&&e.delayShow(n(i),a)},onmousemove:function(i,r){var a=t.html(i,r);a?e.delayShow(n(i),a):(e.delayShow.$cancelTimeout(),e.delayHide())},onmouseleave:function(){e.delayShow.$cancelTimeout(),e.delayHide()}})},t.prototype._initDelayedFunctions=function(){var t=this,e=this._gantt;this.delayShow&&this.delayShow.$cancelTimeout(),this.delayHide&&this.delayHide.$cancelTimeout(),this.tooltip.hide(),this.delayShow=a.delay(function(n,i){!1===e.callEvent("onBeforeTooltip",[n])?t.tooltip.hide():(t.tooltip.setContent(i),t.tooltip.show(n))},e.config.tooltip_timeout||1),this.delayHide=a.delay(function(){t.delayShow.$cancelTimeout(),t.tooltip.hide()},e.config.tooltip_hide_timeout||1)},t}();e.TooltipManager=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(228);e.default=function(t){t.config.tooltip_timeout=30,t.config.tooltip_offset_y=20,t.config.tooltip_offset_x=10,t.config.tooltip_hide_timeout=30;var e=new i.TooltipManager(t);t.ext.tooltips=e,t.attachEvent("onGanttReady",function(){e.tooltipFor({selector:"["+t.config.task_attribute+"]:not(.gantt_task_row)",html:function(e){if(!t.config.touch||t.config.touch_tooltip){var n=t.locate(e);if(t.isTaskExists(n)){var i=t.getTask(n);return t.templates.tooltip_text(i.start_date,i.end_date,i)}return null}},global:!1})}),t.attachEvent("onDestroy",function(){e.destructor()}),t.attachEvent("onLightbox",function(){e.hideTooltip()}),t.attachEvent("onBeforeTooltip",function(){if(t.getState().link_source_id)return!1}),t.attachEvent("onGanttScroll",function(){e.hideTooltip()})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t){var e=this;this.show=function(t,n){void 0===n?e._showForTask(t):e._showAtCoordinates(t,n)},this.hide=function(t){var n=e._gantt,i=e._quickInfoBox;e._quickInfoBoxId=0;var r=e._quickInfoTask;if(e._quickInfoTask=null,i&&i.parentNode){if(n.config.quick_info_detached)return n.callEvent("onAfterQuickInfo",[r]),i.parentNode.removeChild(i);i.className+=" gantt_qi_hidden","auto"===i.style.right?i.style.left="-350px":i.style.right="-350px",t&&(i.style.left=i.style.right="",i.parentNode.removeChild(i)),n.callEvent("onAfterQuickInfo",[r])}},this.getNode=function(){return e._quickInfoBox?e._quickInfoBox:null},this.setContainer=function(t){t&&(e._container="string"==typeof t?document.getElementById(t):t)},this.setContent=function(t){var n=e._gantt,i={taskId:null,header:{title:"",date:""},content:"",buttons:n.config.quickinfo_buttons};t||(t=i),t.taskId||(t.taskId=i.taskId),t.header||(t.header=i.header),t.header.title||(t.header.title=i.header.title),t.header.date||(t.header.date=i.header.date),t.content||(t.content=i.content),t.buttons||(t.buttons=i.buttons);var r=e.getNode();r||(r=e._createQuickInfoElement()),t.taskId&&(e._quickInfoBoxId=t.taskId);var a=r.querySelector(".gantt_cal_qi_title"),o=a.querySelector(".gantt_cal_qi_tcontent"),s=a.querySelector(".gantt_cal_qi_tdate"),l=r.querySelector(".gantt_cal_qi_content"),c=r.querySelector(".gantt_cal_qi_controls");n._waiAria.quickInfoHeader(r,[t.header.title,t.header.date].join(" ")),o.innerHTML=t.header.title,s.innerHTML=t.header.date,t.header.title||t.header.date?a.style.display="":a.style.display="none",l.innerHTML=t.content;var u=t.buttons;u.length?c.style.display="":c.style.display="none";for(var d="",h=0;h<u.length;h++){var f=n._waiAria.quickInfoButtonAttrString(n.locale.labels[u[h]]);d+='<div class="gantt_qi_big_icon '+u[h]+'" title="'+n.locale.labels[u[h]]+'" '+f+"><div class='gantt_menu_icon "+u[h]+"'></div><div>"+n.locale.labels[u[h]]+"</div></div>"}c.innerHTML=d,n.eventRemove(r,"click",e._qiButtonClickHandler),n.eventRemove(r,"keypress",e._qiKeyPressHandler),n.event(r,"click",e._qiButtonClickHandler),n.event(r,"keypress",e._qiKeyPressHandler)},this._qiButtonClickHandler=function(t){t=t||event,e._qi_button_click(t.target||t.srcElement)},this._qiKeyPressHandler=function(t){var n=(t=t||event).which||event.keyCode;13!==n&&32!==n||setTimeout(function(){e._qi_button_click(t.target||t.srcElement)},1)},this._gantt=t}return t.prototype._showAtCoordinates=function(t,e){this.hide(!0),this._quickInfoBoxId=0,this._quickInfoTask=null,this._quickInfoBox||(this._createQuickInfoElement(),this.setContent()),this._appendAtCoordinates(t,e),this._gantt.callEvent("onQuickInfo",[null])},t.prototype._showForTask=function(t){var e=this._gantt;if((t!==this._quickInfoBoxId||!e.utils.dom.isChildOf(this._quickInfoBox,document.body))&&e.config.show_quick_info){this.hide(!0);var n=this._getContainer(),i=this._get_event_counter_part(t,6,n.xViewport,n.yViewport);i&&(this._quickInfoBox=this._init_quick_info(t),this._quickInfoTask=t,this._quickInfoBox.className=this._prepare_quick_info_classname(t),this._fill_quick_data(t),this._show_quick_info(i,6),e.callEvent("onQuickInfo",[t]))}},t.prototype._get_event_counter_part=function(t,e,n,i){var r=this._gantt,a=r.getTaskNode(t);if(!a&&!(a=r.getTaskRowNode(t)))return null;var o=0,s=e+a.offsetTop+a.offsetHeight,l=a;if(r.utils.dom.isChildOf(l,n))for(;l&&l!==n;)o+=l.offsetLeft,l=l.offsetParent;var c=r.getScrollState();return l?{left:o,top:s,dx:o+a.offsetWidth/2-c.x>n.offsetWidth/2?1:0,dy:s+a.offsetHeight/2-c.y>i.offsetHeight/2?1:0,width:a.offsetWidth,height:a.offsetHeight}:null},t.prototype._createQuickInfoElement=function(){var t=this,e=this._gantt,n=document.createElement("div");n.className+="gantt_cal_quick_info",e._waiAria.quickInfoAttr(n);var i='<div class="gantt_cal_qi_title" '+e._waiAria.quickInfoHeaderAttrString()+'><div class="gantt_cal_qi_tcontent"></div><div class="gantt_cal_qi_tdate"></div></div><div class="gantt_cal_qi_content"></div>';if(i+='<div class="gantt_cal_qi_controls">',i+="</div>",n.innerHTML=i,e.config.quick_info_detached){var r=this._getContainer();e.event(r.parent,"scroll",function(){t.hide()})}return this._quickInfoBox=n,n},t.prototype._init_quick_info=function(t){var e=this._gantt,n=e.getTask(t);return"boolean"==typeof this._quickInfoReadonly&&e.isReadonly(n)!==this._quickInfoReadonly&&(this.hide(!0),this._quickInfoBox=null),this._quickInfoReadonly=e.isReadonly(n),this._quickInfoBox||(this._quickInfoBox=this._createQuickInfoElement()),this._quickInfoBox},t.prototype._prepare_quick_info_classname=function(t){var e=this._gantt,n=e.getTask(t),i="gantt_cal_quick_info",r=e.templates.quick_info_class(n.start_date,n.end_date,n);return r&&(i+=" "+r),i},t.prototype._fill_quick_data=function(t){var e=this._gantt,n=e.getTask(t);this._quickInfoBoxId=t;var i=[];if(this._quickInfoReadonly)for(var r=e.config.quickinfo_buttons,a={icon_delete:!0,icon_edit:!0},o=0;o<r.length;o++)this._quickInfoReadonly&&a[r[o]]||i.push(r[o]);else i=e.config.quickinfo_buttons;this.setContent({header:{title:e.templates.quick_info_title(n.start_date,n.end_date,n),date:e.templates.quick_info_date(n.start_date,n.end_date,n)},content:e.templates.quick_info_content(n.start_date,n.end_date,n),buttons:i})},t.prototype._appendAtCoordinates=function(t,e){var n=this._quickInfoBox,i=this._getContainer();n.parentNode&&"#document-fragment"!==n.parentNode.nodeName.toLowerCase()||i.parent.appendChild(n),n.style.left=t+"px",n.style.top=e+"px"},t.prototype._show_quick_info=function(t,e){var n=this._gantt,i=this._quickInfoBox;if(n.config.quick_info_detached){var r=this._getContainer();i.parentNode&&"#document-fragment"!==i.parentNode.nodeName.toLowerCase()||r.parent.appendChild(i);var a=i.offsetWidth,o=i.offsetHeight,s=n.getScrollState(),l=r.xViewport,c=r.yViewport,u=l.offsetWidth+s.x-a,d=t.top-s.y+o,h=t.top;d>c.offsetHeight/2&&(h=t.top-(o+t.height+2*e))<s.y&&d<=c.offsetHeight&&(h=t.top),h<s.y&&(h=s.y);var f=Math.min(Math.max(s.x,t.left-t.dx*(a-t.width)),u),_=h;this._appendAtCoordinates(f,_)}else i.style.top="20px",1===t.dx?(i.style.right="auto",i.style.left="-300px",setTimeout(function(){i.style.left="10px"},1)):(i.style.left="auto",i.style.right="-300px",setTimeout(function(){i.style.right="10px"},1)),i.className+=" gantt_qi_"+(1===t.dx?"left":"right"),n.$root.appendChild(i)},t.prototype._qi_button_click=function(t){var e=this._gantt,n=this._quickInfoBox;if(t&&t!==n){var i=t.className;if(-1!==i.indexOf("_icon")){var r=this._quickInfoBoxId;e.$click.buttons[i.split(" ")[1].replace("icon_","")](r)}else this._qi_button_click(t.parentNode)}},t.prototype._getContainer=function(){var t=this._gantt,e=this._container?this._container:t.$task_data;return e&&e.offsetHeight&&e.offsetWidth?{parent:e,xViewport:t.$task,yViewport:t.$task_data}:(e=this._container?this._container:t.$grid_data)&&e.offsetHeight&&e.offsetWidth?{parent:e,xViewport:t.$grid,yViewport:t.$grid_data}:{parent:this._container?this._container:t.$layout,xViewport:t.$layout,yViewport:t.$layout}},t}();e.QuickInfo=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(230);e.default=function(t){t.ext||(t.ext={}),t.ext.quickInfo=new i.QuickInfo(t),t.config.quickinfo_buttons=["icon_delete","icon_edit"],t.config.quick_info_detached=!0,t.config.show_quick_info=!0,t.templates.quick_info_title=function(t,e,n){return n.text.substr(0,50)},t.templates.quick_info_content=function(t,e,n){return n.details||n.text},t.templates.quick_info_date=function(e,n,i){return t.templates.task_time(e,n,i)},t.templates.quick_info_class=function(t,e,n){return""},t.attachEvent("onTaskClick",function(e,n){return t.utils.dom.closest(n.target,".gantt_add")||setTimeout(function(){t.ext.quickInfo.show(e)},0),!0});for(var e=["onViewChange","onLightbox","onBeforeTaskDelete","onBeforeDrag"],n=function(){return t.ext.quickInfo.hide(),!0},r=0;r<e.length;r++)t.attachEvent(e[r],n);function a(){return t.ext.quickInfo.hide(),t.ext.quickInfo._quickInfoBox=null,!0}t.attachEvent("onEmptyClick",function(e){var i=!0,r=document.querySelector(".gantt_cal_quick_info");r&&t.utils.dom.isChildOf(e.target,r)&&(i=!1),i&&n()}),t.attachEvent("onGanttReady",a),t.attachEvent("onDestroy",a),t.event(window,"keydown",function(e){27===e.keyCode&&t.ext.quickInfo.hide()})}},function(t,e,n){var i=n(2).replaceValidZeroId;t.exports=function(t){t.config.multiselect=!0,t.config.multiselect_one_level=!1,t._multiselect={_selected:{},_one_level:!1,_active:!0,_first_selected_when_shift:null,getDefaultSelected:function(){var t=this.getSelected();return t.length?t[t.length-1]:null},setFirstSelected:function(t){this._first_selected_when_shift=t},getFirstSelected:function(){return this._first_selected_when_shift},isActive:function(){return this.updateState(),this._active},updateState:function(){this._one_level=t.config.multiselect_one_level;var e=this._active;this._active=t.config.select_task,this._active!=e&&this.reset()},reset:function(){this._selected={}},setLastSelected:function(e){t.$data.tasksStore.silent(function(){var n=t.$data.tasksStore;e?n.select(e+""):n.unselect(null)})},getLastSelected:function(){var e=t.$data.tasksStore.getSelectedId();return e&&t.isTaskExists(e)?e:null},select:function(e,n){return!!(e&&t.callEvent("onBeforeTaskMultiSelect",[e,!0,n])&&t.callEvent("onBeforeTaskSelected",[e]))&&(this._selected[e]=!0,this.setLastSelected(e),this.afterSelect(e),t.callEvent("onTaskMultiSelect",[e,!0,n]),t.callEvent("onTaskSelected",[e]),!0)},toggle:function(t,e){this._selected[t]?this.unselect(t,e):this.select(t,e)},unselect:function(e,n){e&&t.callEvent("onBeforeTaskMultiSelect",[e,!1,n])&&(this._selected[e]=!1,this.getLastSelected()==e&&this.setLastSelected(this.getDefaultSelected()),this.afterSelect(e),t.callEvent("onTaskMultiSelect",[e,!1,n]),t.callEvent("onTaskUnselected",[e]))},isSelected:function(e){return!(!t.isTaskExists(e)||!this._selected[e])},getSelected:function(){var e=[];for(var n in this._selected)this._selected[n]&&t.isTaskExists(n)?e.push(n):this._selected[n]=!1;return e.sort(function(e,n){return t.getGlobalTaskIndex(e)>t.getGlobalTaskIndex(n)?1:-1}),e},forSelected:function(t){for(var e=this.getSelected(),n=0;n<e.length;n++)t(e[n])},isSameLevel:function(e){if(!this._one_level)return!0;var n=this.getLastSelected();return!n||(!t.isTaskExists(n)||!t.isTaskExists(e)||!(t.calculateTaskLevel(t.getTask(n))!=t.calculateTaskLevel(t.getTask(e))))},afterSelect:function(e){t.isTaskExists(e)&&t._quickRefresh(function(){t.refreshTask(e)})},doSelection:function(e){if(!this.isActive())return!1;if(t._is_icon_open_click(e))return!1;var n=t.locate(e);if(!n)return!1;if(!t.callEvent("onBeforeMultiSelect",[e]))return!1;var i=this.getSelected(),r=this.getFirstSelected(),a=!1,o=this.getLastSelected(),s=t.config.multiselect,l=function(){this.setFirstSelected(n),this.isSelected(n)||this.select(n,e),i=this.getSelected();for(var t=0;t<i.length;t++)i[t]!==n&&this.unselect(i[t],e)}.bind(this),c=function(){if(o){if(n){for(var i=t.getGlobalTaskIndex(this.getFirstSelected()),s=t.getGlobalTaskIndex(n),l=t.getGlobalTaskIndex(o),c=o;t.getGlobalTaskIndex(c)!==i;)this.unselect(c,e),c=i>l?t.getNext(c):t.getPrev(c);for(c=n;t.getGlobalTaskIndex(c)!==i;)this.select(c,e)&&!a&&(a=!0,r=c),c=i>s?t.getNext(c):t.getPrev(c)}}else o=n}.bind(this);return s&&(e.ctrlKey||e.metaKey)?(this.isSelected(n)||this.setFirstSelected(n),n&&this.toggle(n,e)):s&&e.shiftKey?(t.isTaskExists(this.getFirstSelected())&&null!==this.getFirstSelected()||this.setFirstSelected(n),i.length?c():l()):l(),this.isSelected(n)?this.setLastSelected(n):r?n==o&&this.setLastSelected(e.shiftKey?r:this.getDefaultSelected()):this.setLastSelected(null),this.getSelected().length||this.setLastSelected(null),this.getLastSelected()&&this.isSelected(this.getFirstSelected())||this.setFirstSelected(this.getLastSelected()),!0}},function(){var e=t.selectTask;t.selectTask=function(n){if(!(n=i(n,this.config.root_id)))return!1;var r=t._multiselect,a=n;return r.isActive()?(r.select(n,null)&&r.setLastSelected(n),r.setFirstSelected(r.getLastSelected())):a=e.call(this,n),a};var n=t.unselectTask;t.unselectTask=function(e){var i=t._multiselect,r=i.isActive();(e=e||i.getLastSelected())&&r&&(i.unselect(e,null),e==i.getLastSelected()&&i.setLastSelected(null),t.refreshTask(e),i.setFirstSelected(i.getLastSelected()));var a=e;return r||(a=n.call(this,e)),a},t.toggleTaskSelection=function(e){var n=t._multiselect;e&&n.isActive()&&(n.toggle(e),n.setFirstSelected(n.getLastSelected()))},t.getSelectedTasks=function(){var e=t._multiselect;return e.isActive(),e.getSelected()},t.eachSelectedTask=function(t){return this._multiselect.forSelected(t)},t.isSelectedTask=function(t){return this._multiselect.isSelected(t)},t.getLastSelectedTask=function(){return this._multiselect.getLastSelected()},t.attachEvent("onGanttReady",function(){var e=t.$data.tasksStore.isSelected;t.$data.tasksStore.isSelected=function(n){return t._multiselect.isActive()?t._multiselect.isSelected(n):e.call(this,n)}})}(),t.attachEvent("onTaskIdChange",function(e,n){var i=t._multiselect;if(!i.isActive())return!0;t.isSelectedTask(e)&&(i.unselect(e,null),i.select(n,null))}),t.attachEvent("onAfterTaskDelete",function(e,n){var i=t._multiselect;if(!i.isActive())return!0;i._selected[e]&&(i.unselect(e,null),i._selected[e]=!1,i.setLastSelected(i.getDefaultSelected())),i.forSelected(function(e){t.isTaskExists(e)||i.unselect(e,null)})}),t.attachEvent("onBeforeTaskMultiSelect",function(e,n,i){var r=t._multiselect;return!(n&&r.isActive()&&r._one_level)||r.isSameLevel(e)}),t.attachEvent("onTaskClick",function(e,n){return t._multiselect.doSelection(n)&&t.callEvent("onMultiSelect",[n]),!0})}},function(t,e){t.exports=function(t){function e(e){if(!t.config.show_markers)return!1;if(!e.start_date)return!1;var n=t.getState();if(!(+e.start_date>+n.max_date||(!e.end_date||+e.end_date<+n.min_date)&&+e.start_date<+n.min_date)){var i=document.createElement("div");i.setAttribute("data-marker-id",e.id);var r="gantt_marker";t.templates.marker_class&&(r+=" "+t.templates.marker_class(e)),e.css&&(r+=" "+e.css),e.title&&(i.title=e.title),i.className=r;var a=t.posFromDate(e.start_date);if(i.style.left=a+"px",i.style.height=Math.max(t.getRowTop(t.getVisibleTaskCount()),0)+"px",e.end_date){var o=t.posFromDate(e.end_date);i.style.width=Math.max(o-a,0)+"px"}return e.text&&(i.innerHTML="<div class='gantt_marker_content' >"+e.text+"</div>"),i}}function n(){if(t.$task_data){var e=document.createElement("div");e.className="gantt_marker_area",t.$task_data.appendChild(e),t.$marker_area=e}}t._markers||(t._markers=t.createDatastore({name:"marker",initItem:function(e){return e.id=e.id||t.uid(),e}})),t.config.show_markers=!0,t.attachEvent("onBeforeGanttRender",function(){t.$marker_area||n()}),t.attachEvent("onDataRender",function(){t.$marker_area||(n(),t.renderMarkers())}),t.attachEvent("onGanttLayoutReady",function(){t.attachEvent("onBeforeGanttRender",function(){n(),t.$services.getService("layers").createDataRender({name:"marker",defaultContainer:function(){return t.$marker_area}}).addLayer(e)},{once:!0})}),t.getMarker=function(t){return this._markers?this._markers.getItem(t):null},t.addMarker=function(t){return this._markers.addItem(t)},t.deleteMarker=function(t){return!!this._markers.exists(t)&&(this._markers.removeItem(t),!0)},t.updateMarker=function(t){this._markers.refresh(t)},t._getMarkers=function(){return this._markers.getItems()},t.renderMarkers=function(){this._markers.refresh()}}},function(t,e){t.exports=function(t){t.$keyboardNavigation.dispatcher={isActive:!1,activeNode:null,globalNode:new t.$keyboardNavigation.GanttNode,enable:function(){this.isActive=!0,this.setActiveNode(this.getActiveNode())},disable:function(){this.isActive=!1},isEnabled:function(){return!!this.isActive},getDefaultNode:function(){var e;return(e=t.config.keyboard_navigation_cells?new t.$keyboardNavigation.TaskCell:new t.$keyboardNavigation.TaskRow).isValid()||(e=e.fallback()),e},setDefaultNode:function(){this.setActiveNode(this.getDefaultNode())},getActiveNode:function(){var t=this.activeNode;return t&&!t.isValid()&&(t=t.fallback()),t},fromDomElement:function(e){for(var n=[t.$keyboardNavigation.TaskRow,t.$keyboardNavigation.TaskCell,t.$keyboardNavigation.HeaderCell],i=0;i<n.length;i++)if(n[i].prototype.fromDomElement){var r=n[i].prototype.fromDomElement(e);if(r)return r}return null},focusGlobalNode:function(){this.blurNode(this.globalNode),this.focusNode(this.globalNode)},setActiveNode:function(t){var e=!0;this.activeNode&&this.activeNode.compareTo(t)&&(e=!1),this.isEnabled()&&(e&&this.blurNode(this.activeNode),this.activeNode=t,this.focusNode(this.activeNode,!e))},focusNode:function(t,e){t&&t.focus&&t.focus(e)},blurNode:function(t){t&&t.blur&&t.blur()},keyDownHandler:function(e){if(!t.$keyboardNavigation.isModal()&&this.isEnabled()&&!e.defaultPrevented){var n=this.globalNode,i=t.$keyboardNavigation.shortcuts.getCommandFromEvent(e),r=this.getActiveNode();!1!==t.$keyboardNavigation.facade.callEvent("onKeyDown",[i,e])&&(r?r.findHandler(i)?r.doAction(i,e):n.findHandler(i)&&n.doAction(i,e):this.setDefaultNode())}},_timeout:null,awaitsFocus:function(){return null!==this._timeout},delay:function(e,n){clearTimeout(this._timeout),this._timeout=setTimeout(t.bind(function(){this._timeout=null,e()},this),n||1)},clearDelay:function(){clearTimeout(this._timeout)}}}},function(t,e){t.exports=function(t){!function(){var e=[];function n(){return!!e.length}function i(e){setTimeout(function(){n()||t.$destroyed||t.focus()},1)}function r(n){t.eventRemove(n,"keydown",o),t.event(n,"keydown",o),e.push(n)}function a(){var n=e.pop();n&&t.eventRemove(n,"keydown",o),i()}function o(n){var i=n.currentTarget;(function(t){return t==e[e.length-1]})(i)&&t.$keyboardNavigation.trapFocus(i,n)}function s(){r(t.getLightbox())}t.attachEvent("onLightbox",s),t.attachEvent("onAfterLightbox",a),t.attachEvent("onLightboxChange",function(){a(),s()}),t.attachEvent("onAfterQuickInfo",function(){i()}),t.attachEvent("onMessagePopup",function(e){l=t.utils.dom.getActiveElement(),r(e)}),t.attachEvent("onAfterMessagePopup",function(){a(),setTimeout(function(){l&&(l.focus(),l=null)},1)});var l=null;t.$keyboardNavigation.isModal=n}()}},function(t,e,n){t.exports=function(t){var e=n(1),i=n(2).replaceValidZeroId;t.$keyboardNavigation.TaskCell=function(e,n){if(!(e=i(e,t.config.root_id))){var r=t.getChildren(t.config.root_id);r[0]&&(e=r[0])}this.taskId=e,this.columnIndex=n||0,t.isTaskExists(this.taskId)&&(this.index=t.getTaskIndex(this.taskId))},t.$keyboardNavigation.TaskCell.prototype=t._compose(t.$keyboardNavigation.TaskRow,{_handlers:null,isValid:function(){return t.$keyboardNavigation.TaskRow.prototype.isValid.call(this)&&!!t.getGridColumns()[this.columnIndex]},fallback:function(){var e=t.$keyboardNavigation.TaskRow.prototype.fallback.call(this),n=e;if(e instanceof t.$keyboardNavigation.TaskRow){for(var i=t.getGridColumns(),r=this.columnIndex;r>=0&&!i[r];)r--;i[r]&&(n=new t.$keyboardNavigation.TaskCell(e.taskId,r))}return n},fromDomElement:function(n){if(!t.config.keyboard_navigation_cells)return null;var i=t.locate(n);if(t.isTaskExists(i)){var r=0,a=e.locateAttribute(n,"data-column-index");return a&&(r=1*a.getAttribute("data-column-index")),new t.$keyboardNavigation.TaskCell(i,r)}return null},getNode:function(){if(t.isTaskExists(this.taskId)&&t.isTaskVisible(this.taskId)){if(t.config.show_grid){var e=t.$grid.querySelector(".gantt_row["+t.config.task_attribute+"='"+this.taskId+"']");return e?e.querySelector("[data-column-index='"+this.columnIndex+"']"):null}return t.getTaskNode(this.taskId)}},keys:{up:function(){var e=null,n=t.getPrev(this.taskId);e=t.isTaskExists(n)?new t.$keyboardNavigation.TaskCell(n,this.columnIndex):new t.$keyboardNavigation.HeaderCell(this.columnIndex),this.moveTo(e)},down:function(){var e=t.getNext(this.taskId);t.isTaskExists(e)&&this.moveTo(new t.$keyboardNavigation.TaskCell(e,this.columnIndex))},left:function(){this.columnIndex>0&&this.moveTo(new t.$keyboardNavigation.TaskCell(this.taskId,this.columnIndex-1))},right:function(){var e=t.getGridColumns();this.columnIndex<e.length-1&&this.moveTo(new t.$keyboardNavigation.TaskCell(this.taskId,this.columnIndex+1))},end:function(){var e=t.getGridColumns();this.moveTo(new t.$keyboardNavigation.TaskCell(this.taskId,e.length-1))},home:function(){this.moveTo(new t.$keyboardNavigation.TaskCell(this.taskId,0))},pagedown:function(){t.getVisibleTaskCount()&&this.moveTo(new t.$keyboardNavigation.TaskCell(t.getTaskByIndex(t.getVisibleTaskCount()-1).id,this.columnIndex))},pageup:function(){t.getVisibleTaskCount()&&this.moveTo(new t.$keyboardNavigation.TaskCell(t.getTaskByIndex(0).id,this.columnIndex))}}}),t.$keyboardNavigation.TaskCell.prototype.bindAll(t.$keyboardNavigation.TaskRow.prototype.keys),t.$keyboardNavigation.TaskCell.prototype.bindAll(t.$keyboardNavigation.TaskCell.prototype.keys)}},function(t,e){t.exports=function(t){t.$keyboardNavigation.TaskRow=function(e){if(!e){var n=t.getChildren(t.config.root_id);n[0]&&(e=n[0])}this.taskId=e,t.isTaskExists(this.taskId)&&(this.index=t.getTaskIndex(this.taskId))},t.$keyboardNavigation.TaskRow.prototype=t._compose(t.$keyboardNavigation.KeyNavNode,{_handlers:null,isValid:function(){return t.isTaskExists(this.taskId)&&t.getTaskIndex(this.taskId)>-1},fallback:function(){if(!t.getVisibleTaskCount()){var e=new t.$keyboardNavigation.HeaderCell;return e.isValid()?e:null}var n=-1;if(t.getTaskByIndex(this.index-1))n=this.index-1;else if(t.getTaskByIndex(this.index+1))n=this.index+1;else for(var i=this.index;i>=0;){if(t.getTaskByIndex(i)){n=i;break}i--}if(n>-1)return new t.$keyboardNavigation.TaskRow(t.getTaskByIndex(n).id)},fromDomElement:function(e){if(t.config.keyboard_navigation_cells)return null;var n=t.locate(e);return t.isTaskExists(n)?new t.$keyboardNavigation.TaskRow(n):null},getNode:function(){if(t.isTaskExists(this.taskId)&&t.isTaskVisible(this.taskId))return t.config.show_grid?t.$grid.querySelector(".gantt_row["+t.config.task_attribute+"='"+this.taskId+"']"):t.getTaskNode(this.taskId)},focus:function(e){if(!e){var n,i,r=t.getTaskPosition(t.getTask(this.taskId)),a=t.getTaskHeight(this.taskId),o=t.getScrollState();n=t.$task?t.$task.offsetWidth:o.inner_width,i=t.$grid_data||t.$task_data?(t.$grid_data||t.$task_data).offsetHeight:o.inner_height,r.top<o.y||r.top+a>o.y+i?t.scrollTo(null,r.top-5*a):t.config.scroll_on_click&&t.config.show_chart&&(r.left>o.x+n?t.scrollTo(r.left-t.config.task_scroll_offset):r.left+r.width<o.x&&t.scrollTo(r.left+r.width-t.config.task_scroll_offset))}t.$keyboardNavigation.KeyNavNode.prototype.focus.apply(this,[e]),function(){var e=t.$ui.getView("grid"),n=parseInt(e.$grid.scrollLeft),i=parseInt(e.$grid_data.scrollTop),r=e.$config.scrollX;if(r&&e.$config.scrollable){var a=t.$ui.getView(r);a&&a.scrollTo(n,i)}var o=e.$config.scrollY;if(o){var s=t.$ui.getView(o);s&&s.scrollTo(n,i)}}()},keys:{pagedown:function(){t.getVisibleTaskCount()&&this.moveTo(new t.$keyboardNavigation.TaskRow(t.getTaskByIndex(t.getVisibleTaskCount()-1).id))},pageup:function(){t.getVisibleTaskCount()&&this.moveTo(new t.$keyboardNavigation.TaskRow(t.getTaskByIndex(0).id))},up:function(){var e=null,n=t.getPrev(this.taskId);e=t.isTaskExists(n)?new t.$keyboardNavigation.TaskRow(n):new t.$keyboardNavigation.HeaderCell,this.moveTo(e)},down:function(){var e=t.getNext(this.taskId);t.isTaskExists(e)&&this.moveTo(new t.$keyboardNavigation.TaskRow(e))},"shift+down":function(){t.hasChild(this.taskId)&&!t.getTask(this.taskId).$open&&t.open(this.taskId)},"shift+up":function(){t.hasChild(this.taskId)&&t.getTask(this.taskId).$open&&t.close(this.taskId)},"shift+right":function(){if(!t.isReadonly(this)){var e=t.getPrevSibling(this.taskId);if(t.isTaskExists(e)&&!t.isChildOf(this.taskId,e))t.getTask(e).$open=!0,!1!==t.moveTask(this.taskId,-1,e)&&t.updateTask(this.taskId)}},"shift+left":function(){if(!t.isReadonly(this)){var e=t.getParent(this.taskId);if(t.isTaskExists(e))!1!==t.moveTask(this.taskId,t.getTaskIndex(e)+1,t.getParent(e))&&t.updateTask(this.taskId)}},space:function(e){t.isSelectedTask(this.taskId)?t.unselectTask(this.taskId):t.selectTask(this.taskId)},"ctrl+left":function(e){t.close(this.taskId)},"ctrl+right":function(e){t.open(this.taskId)},delete:function(e){t.isReadonly(this)||t.$click.buttons.delete(this.taskId)},enter:function(){t.isReadonly(this)||t.showLightbox(this.taskId)},"ctrl+enter":function(){t.isReadonly(this)||t.createTask({},this.taskId)}}}),t.$keyboardNavigation.TaskRow.prototype.bindAll(t.$keyboardNavigation.TaskRow.prototype.keys)}},function(t,e,n){t.exports=function(t){var e=n(1);t.$keyboardNavigation.HeaderCell=function(t){this.index=t||0},t.$keyboardNavigation.HeaderCell.prototype=t._compose(t.$keyboardNavigation.KeyNavNode,{_handlers:null,isValid:function(){return!(!t.config.show_grid&&t.getVisibleTaskCount())&&(!!t.getGridColumns()[this.index]||!t.getVisibleTaskCount())},fallback:function(){if(!t.config.show_grid)return t.getVisibleTaskCount()?new t.$keyboardNavigation.TaskRow:null;for(var e=t.getGridColumns(),n=this.index;n>=0&&!e[n];)n--;return e[n]?new t.$keyboardNavigation.HeaderCell(n):null},fromDomElement:function(n){var i=e.locateClassName(n,"gantt_grid_head_cell");if(i){for(var r=0;i&&i.previousSibling;)i=i.previousSibling,r+=1;return new t.$keyboardNavigation.HeaderCell(r)}return null},getNode:function(){return t.$grid_scale.childNodes[this.index]},keys:{left:function(){this.index>0&&this.moveTo(new t.$keyboardNavigation.HeaderCell(this.index-1))},right:function(){var e=t.getGridColumns();this.index<e.length-1&&this.moveTo(new t.$keyboardNavigation.HeaderCell(this.index+1))},down:function(){var e,n=t.getChildren(t.config.root_id);t.isTaskExists(n[0])&&(e=n[0]),e&&(t.config.keyboard_navigation_cells?this.moveTo(new t.$keyboardNavigation.TaskCell(e,this.index)):this.moveTo(new t.$keyboardNavigation.TaskRow(e)))},end:function(){var e=t.getGridColumns();this.moveTo(new t.$keyboardNavigation.HeaderCell(e.length-1))},home:function(){this.moveTo(new t.$keyboardNavigation.HeaderCell(0))},"enter, space":function(){e.getActiveElement().click()},"ctrl+enter":function(){t.isReadonly(this)||t.createTask({},this.taskId)}}}),t.$keyboardNavigation.HeaderCell.prototype.bindAll(t.$keyboardNavigation.HeaderCell.prototype.keys)}},function(t,e){t.exports=function(t){t.$keyboardNavigation.KeyNavNode=function(){},t.$keyboardNavigation.KeyNavNode.prototype=t._compose(t.$keyboardNavigation.EventHandler,{isValid:function(){return!0},fallback:function(){return null},moveTo:function(e){t.$keyboardNavigation.dispatcher.setActiveNode(e)},compareTo:function(t){if(!t)return!1;for(var e in this){if(!!this[e]!=!!t[e])return!1;var n=!(!this[e]||!this[e].toString),i=!(!t[e]||!t[e].toString);if(i!=n)return!1;if(i&&n){if(t[e].toString()!=this[e].toString())return!1}else if(t[e]!=this[e])return!1}return!0},getNode:function(){},focus:function(){var e=this.getNode();if(e){var n=t.$keyboardNavigation.facade;!1!==n.callEvent("onBeforeFocus",[e])&&e&&(e.setAttribute("tabindex","-1"),e.$eventAttached||(e.$eventAttached=!0,t.event(e,"focus",function(t){return t.preventDefault(),!1},!1)),e.focus&&e.focus(),n.callEvent("onFocus",[this.getNode()]))}},blur:function(){var e=this.getNode();e&&(t.$keyboardNavigation.facade.callEvent("onBlur",[e]),e.setAttribute("tabindex","-1"))}})}},function(t,e){t.exports=function(t){t.$keyboardNavigation.GanttNode=function(){},t.$keyboardNavigation.GanttNode.prototype=t._compose(t.$keyboardNavigation.EventHandler,{focus:function(){t.focus()},blur:function(){},isEnabled:function(){return t.$container.hasAttribute("tabindex")},scrollHorizontal:function(e){var n=t.dateFromPos(t.getScrollState().x),i=t.getScale(),r=e<0?-i.step:i.step;n=t.date.add(n,r,i.unit),t.scrollTo(t.posFromDate(n))},scrollVertical:function(e){var n=t.getScrollState().y,i=t.config.row_height;t.scrollTo(null,n+(e<0?-1:1)*i)},keys:{"alt+left":function(t){this.scrollHorizontal(-1)},"alt+right":function(t){this.scrollHorizontal(1)},"alt+up":function(t){this.scrollVertical(-1)},"alt+down":function(t){this.scrollVertical(1)},"ctrl+z":function(){t.undo&&t.undo()},"ctrl+r":function(){t.redo&&t.redo()}}}),t.$keyboardNavigation.GanttNode.prototype.bindAll(t.$keyboardNavigation.GanttNode.prototype.keys)}},function(t,e,n){t.exports=function(t){!function(){var e=n(1);t.$keyboardNavigation.getFocusableNodes=e.getFocusableNodes,t.$keyboardNavigation.trapFocus=function(n,i){if(9!=i.keyCode)return!1;for(var r=t.$keyboardNavigation.getFocusableNodes(n),a=e.getActiveElement(),o=-1,s=0;s<r.length;s++)if(r[s]==a){o=s;break}if(i.shiftKey){if(o<=0){var l=r[r.length-1];if(l)return l.focus(),i.preventDefault(),!0}}else if(o>=r.length-1){var c=r[0];if(c)return c.focus(),i.preventDefault(),!0}return!1}}()}},function(t,e){t.exports=function(t){t.$keyboardNavigation.EventHandler={_handlers:null,findHandler:function(e){this._handlers||(this._handlers={});var n=t.$keyboardNavigation.shortcuts.getHash(e);return this._handlers[n]},doAction:function(e,n){var i=this.findHandler(e);if(i){if(!1===t.$keyboardNavigation.facade.callEvent("onBeforeAction",[e,n]))return;i.call(this,n),n.preventDefault?n.preventDefault():n.returnValue=!1}},bind:function(e,n){this._handlers||(this._handlers={});for(var i=t.$keyboardNavigation.shortcuts,r=i.parse(e),a=0;a<r.length;a++)this._handlers[i.getHash(r[a])]=n},unbind:function(e){for(var n=t.$keyboardNavigation.shortcuts,i=n.parse(e),r=0;r<i.length;r++)this._handlers[n.getHash(i[r])]&&delete this._handlers[n.getHash(i[r])]},bindAll:function(t){for(var e in t)this.bind(e,t[e])},initKeys:function(){this._handlers||(this._handlers={}),this.keys&&this.bindAll(this.keys)}}}},function(t,e){t.exports=function(t){t.$keyboardNavigation.shortcuts={createCommand:function(){return{modifiers:{shift:!1,alt:!1,ctrl:!1,meta:!1},keyCode:null}},parse:function(t){for(var e=[],n=this.getExpressions(this.trim(t)),i=0;i<n.length;i++){for(var r=this.getWords(n[i]),a=this.createCommand(),o=0;o<r.length;o++)this.commandKeys[r[o]]?a.modifiers[r[o]]=!0:this.specialKeys[r[o]]?a.keyCode=this.specialKeys[r[o]]:a.keyCode=r[o].charCodeAt(0);e.push(a)}return e},getCommandFromEvent:function(t){var e=this.createCommand();e.modifiers.shift=!!t.shiftKey,e.modifiers.alt=!!t.altKey,e.modifiers.ctrl=!!t.ctrlKey,e.modifiers.meta=!!t.metaKey,e.keyCode=t.which||t.keyCode,e.keyCode>=96&&e.keyCode<=105&&(e.keyCode-=48);var n=String.fromCharCode(e.keyCode);return n&&(e.keyCode=n.toLowerCase().charCodeAt(0)),e},getHashFromEvent:function(t){return this.getHash(this.getCommandFromEvent(t))},getHash:function(t){var e=[];for(var n in t.modifiers)t.modifiers[n]&&e.push(n);return e.push(t.keyCode),e.join(this.junctionChar)},getExpressions:function(t){return t.split(this.junctionChar)},getWords:function(t){return t.split(this.combinationChar)},trim:function(t){return t.replace(/\s/g,"")},junctionChar:",",combinationChar:"+",commandKeys:{shift:16,alt:18,ctrl:17,meta:!0},specialKeys:{backspace:8,tab:9,enter:13,esc:27,space:32,up:38,down:40,left:37,right:39,home:36,end:35,pageup:33,pagedown:34,delete:46,insert:45,plus:107,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123}}}},function(t,e,n){t.exports=function(t){var e=n(4);!function(t){t.config.keyboard_navigation=!0,t.config.keyboard_navigation_cells=!1,t.$keyboardNavigation={},t._compose=function(){for(var t=Array.prototype.slice.call(arguments,0),e={},n=0;n<t.length;n++){var i=t[n];for(var r in"function"==typeof i&&(i=new i),i)e[r]=i[r]}return e},n(243)(t),n(242)(t),n(241)(t),n(240)(t),n(239)(t),n(238)(t),n(237)(t),n(236)(t),n(235)(t),n(234)(t);var i=n(1);!function(){var n=t.$keyboardNavigation.dispatcher;n.isTaskFocused=function(e){var i=n.activeNode;return(i instanceof t.$keyboardNavigation.TaskRow||i instanceof t.$keyboardNavigation.TaskCell)&&i.taskId==e};var r=function(e){if(t.config.keyboard_navigation&&(t.config.keyboard_navigation_cells||!s(e)))return n.keyDownHandler(e)},a=function(e){if(n.$preventDefault)return e.preventDefault(),t.$container.blur(),!1;n.awaitsFocus()||n.focusGlobalNode()},o=function(){if(n.isEnabled()){var t=n.getActiveNode();if(t){var e,i,r=t.getNode();r&&r.parentNode&&(e=r.parentNode.scrollTop,i=r.parentNode.scrollLeft),t.focus(!0),r&&r.parentNode&&(r.parentNode.scrollTop=e,r.parentNode.scrollLeft=i)}}};function s(t){return!!i.closest(t.target,".gantt_grid_editor_placeholder")}function l(e){if(!t.config.keyboard_navigation)return!0;if(!t.config.keyboard_navigation_cells&&s(e))return!0;var r,a=n.fromDomElement(e);a&&(n.activeNode instanceof t.$keyboardNavigation.TaskCell&&i.isChildOf(e.target,t.$task)&&(a=new t.$keyboardNavigation.TaskCell(a.taskId,n.activeNode.columnIndex)),r=a),r?n.isEnabled()?n.delay(function(){n.setActiveNode(r)}):n.activeNode=r:(n.$preventDefault=!0,setTimeout(function(){n.$preventDefault=!1},300))}t.attachEvent("onDataRender",function(){t.config.keyboard_navigation&&o()}),t.attachEvent("onGanttRender",function(){t.eventRemove(t.$root,"keydown",r),t.eventRemove(t.$container,"focus",a),t.eventRemove(t.$container,"mousedown",l),t.config.keyboard_navigation?(t.event(t.$root,"keydown",r),t.event(t.$container,"focus",a),t.event(t.$container,"mousedown",l),t.$container.setAttribute("tabindex","0")):t.$container.removeAttribute("tabindex")});var c=t.attachEvent("onGanttReady",function(){if(t.detachEvent(c),t.$data.tasksStore.attachEvent("onStoreUpdated",function(e){if(t.config.keyboard_navigation&&n.isEnabled()){var i=n.getActiveNode();i&&i.taskId==e&&o()}}),t._smart_render){var e=t._smart_render._redrawTasks;t._smart_render._redrawTasks=function(i,r){if(t.config.keyboard_navigation&&n.isEnabled()){var a=n.getActiveNode();if(a&&void 0!==a.taskId){for(var o=!1,s=0;s<r.length;s++)if(r[s].id==a.taskId&&r[s].start_date){o=!0;break}o||r.push(t.getTask(a.taskId))}}return e.apply(this,arguments)}}});t.attachEvent("onAfterTaskAdd",function(e,i){if(!t.config.keyboard_navigation)return!0;if(n.isEnabled()){var r=0,a=n.activeNode;a instanceof t.$keyboardNavigation.TaskCell&&(r=a.columnIndex);var o=t.config.keyboard_navigation_cells?t.$keyboardNavigation.TaskCell:t.$keyboardNavigation.TaskRow;n.setActiveNode(new o(e,r))}}),t.attachEvent("onTaskIdChange",function(e,i){if(!t.config.keyboard_navigation)return!0;var r=n.activeNode;return n.isTaskFocused(e)&&(r.taskId=i),!0});var u=setInterval(function(){t.config.keyboard_navigation&&(n.isEnabled()||n.enable())},500);function d(e){var n={gantt:t.$keyboardNavigation.GanttNode,headerCell:t.$keyboardNavigation.HeaderCell,taskRow:t.$keyboardNavigation.TaskRow,taskCell:t.$keyboardNavigation.TaskCell};return n[e]||n.gantt}function h(e){for(var n=t.getGridColumns(),i=0;i<n.length;i++)if(n[i].name==e)return i;return 0}t.attachEvent("onDestroy",function(){clearInterval(u)});var f={};e(f),t.mixin(f,{addShortcut:function(t,e,n){var i=d(n);i&&i.prototype.bind(t,e)},getShortcutHandler:function(e,n){var i=t.$keyboardNavigation.shortcuts.parse(e);if(i.length)return f.getCommandHandler(i[0],n)},getCommandHandler:function(t,e){var n=d(e);if(n&&t)return n.prototype.findHandler(t)},removeShortcut:function(t,e){var n=d(e);n&&n.prototype.unbind(t)},focus:function(t){var e,i=t?t.type:null,r=d(i);switch(i){case"taskCell":e=new r(t.id,h(t.column));break;case"taskRow":e=new r(t.id);break;case"headerCell":e=new r(h(t.column))}n.delay(function(){e?n.setActiveNode(e):(n.enable(),n.getActiveNode()?n.awaitsFocus()||n.enable():n.setDefaultNode())})},getActiveNode:function(){if(n.isEnabled()){var e=n.getActiveNode(),i=function(e){return e instanceof t.$keyboardNavigation.GanttNode?"gantt":e instanceof t.$keyboardNavigation.HeaderCell?"headerCell":e instanceof t.$keyboardNavigation.TaskRow?"taskRow":e instanceof t.$keyboardNavigation.TaskCell?"taskCell":null}(e),r=t.getGridColumns();switch(i){case"taskCell":return{type:"taskCell",id:e.taskId,column:r[e.columnIndex].name};case"taskRow":return{type:"taskRow",id:e.taskId};case"headerCell":return{type:"headerCell",column:r[e.index].name}}}return null}}),t.$keyboardNavigation.facade=f,t.ext.keyboardNavigation=f,t.focus=function(){f.focus()},t.addShortcut=f.addShortcut,t.getShortcutHandler=f.getShortcutHandler,t.removeShortcut=f.removeShortcut}()}(t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){function e(){var t=document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement;return!(!t||t!==document.body)}t.$services.getService("state").registerProvider("fullscreen",function(){return{fullscreen:e()}});var n={overflow:null,padding:null,paddingTop:null,paddingRight:null,paddingBottom:null,paddingLeft:null},i={width:null,height:null,top:null,left:null,position:null,zIndex:null,modified:!1},r=null;function a(t,e){e.width=t.width,e.height=t.height,e.top=t.top,e.left=t.left,e.position=t.position,e.zIndex=t.zIndex}var o=!1;function s(){var s;t.$container&&(e()?o&&(s="onExpand",function(){var e=t.ext.fullscreen.getFullscreenElement(),o=document.body;a(e.style,i),n={overflow:o.style.overflow,padding:o.style.padding?o.style.padding:null,paddingTop:o.style.paddingTop?o.style.paddingTop:null,paddingRight:o.style.paddingRight?o.style.paddingRight:null,paddingBottom:o.style.paddingBottom?o.style.paddingBottom:null,paddingLeft:o.style.paddingLeft?o.style.paddingLeft:null},o.style.padding&&(o.style.padding="0"),o.style.paddingTop&&(o.style.paddingTop="0"),o.style.paddingRight&&(o.style.paddingRight="0"),o.style.paddingBottom&&(o.style.paddingBottom="0"),o.style.paddingLeft&&(o.style.paddingLeft="0"),o.style.overflow="hidden",e.style.width="100vw",e.style.height="100vh",e.style.top="0px",e.style.left="0px",e.style.position="absolute",e.style.zIndex=1,i.modified=!0,r=function(t){for(var e=t.parentNode,n=[];e&&e.style;)n.push({element:e,originalPositioning:e.style.position}),e.style.position="static",e=e.parentNode;return n}(e)}()):o&&(o=!1,s="onCollapse",function(){var e=t.ext.fullscreen.getFullscreenElement(),o=document.body;i.modified&&(n.padding&&(o.style.padding=n.padding),n.paddingTop&&(o.style.paddingTop=n.paddingTop),n.paddingRight&&(o.style.paddingRight=n.paddingRight),n.paddingBottom&&(o.style.paddingBottom=n.paddingBottom),n.paddingLeft&&(o.style.paddingLeft=n.paddingLeft),o.style.overflow=n.overflow,n={overflow:null,padding:null,paddingTop:null,paddingRight:null,paddingBottom:null,paddingLeft:null},a(i,e.style),i.modified=!1),function(t){t.forEach(function(t){t.element.style.position=t.originalPositioning})}(r),r=null}()),setTimeout(function(){t.render()}),setTimeout(function(){t.callEvent(s,[t.ext.fullscreen.getFullscreenElement()])}))}function l(){return!(t.$container&&t.ext.fullscreen.getFullscreenElement()&&(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled||((console.warning||console.log)("The `fullscreen` feature not being allowed, or full-screen mode not being supported"),0)))}t.ext.fullscreen={expand:function(){if(!l()&&!e()&&t.callEvent("onBeforeExpand",[this.getFullscreenElement()])){o=!0;var n=document.body,i=n.webkitRequestFullscreen?[Element.ALLOW_KEYBOARD_INPUT]:[],r=n.msRequestFullscreen||n.mozRequestFullScreen||n.webkitRequestFullscreen||n.requestFullscreen;r&&r.apply(n,i)}},collapse:function(){if(!l()&&e()&&t.callEvent("onBeforeCollapse",[this.getFullscreenElement()])){var n=document.msExitFullscreen||document.mozCancelFullScreen||document.webkitExitFullscreen||document.exitFullscreen;n&&n.apply(document)}},toggle:function(){l()||(e()?this.collapse():this.expand())},getFullscreenElement:function(){return t.$root}},t.expand=function(){t.ext.fullscreen.expand()},t.collapse=function(){t.ext.fullscreen.collapse()},t.attachEvent("onGanttReady",function(){t.event(document,"webkitfullscreenchange",s),t.event(document,"mozfullscreenchange",s),t.event(document,"MSFullscreenChange",s),t.event(document,"fullscreenChange",s),t.event(document,"fullscreenchange",s)})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t){var e=this;this._mouseDown=!1,this._calculateDirectionVector=function(){if(e._trace.length>=10){for(var t=e._trace.slice(e._trace.length-10),n=[],i=1;i<t.length;i++)n.push({x:t[i].x-t[i-1].x,y:t[i].y-t[i-1].y});var r={x:0,y:0};return n.forEach(function(t){r.x+=t.x,r.y+=t.y}),{magnitude:Math.sqrt(r.x*r.x+r.y*r.y),angleDegrees:180*Math.atan2(Math.abs(r.y),Math.abs(r.x))/Math.PI}}return null},this._applyDndReadyStyles=function(){e._timeline.$task.classList.add("gantt_timeline_move_available")},this._clearDndReadyStyles=function(){e._timeline.$task.classList.remove("gantt_timeline_move_available")},this._getScrollPosition=function(t){var n=e._gantt;return{x:n.$ui.getView(t.$config.scrollX).getScrollState().position,y:n.$ui.getView(t.$config.scrollY).getScrollState().position}},this._countNewScrollPosition=function(t){var n=e._calculateDirectionVector(),i=e._startPoint.x-t.x,r=e._startPoint.y-t.y;return n&&(n.angleDegrees<15?r=0:n.angleDegrees>75&&(i=0)),{x:e._scrollState.x+i,y:e._scrollState.y+r}},this._setScrollPosition=function(t,n){var i=e._gantt;requestAnimationFrame(function(){i.$ui.getView(t.$config.scrollX).scroll(n.x),i.$ui.getView(t.$config.scrollY).scroll(n.y)})},this._stopDrag=function(t){var n=e._gantt;if(e._trace=[],n.$root.classList.remove("gantt_noselect"),void 0!==e._originalReadonly&&(n.config.readonly=e._originalReadonly),void 0!==e._originAutoscroll&&(n.config.autoscroll=e._originAutoscroll),n.config.drag_timeline){var i=n.config.drag_timeline.useKey;if(i&&!0!==t[i])return}e._mouseDown=!1},this._startDrag=function(t){var n=e._gantt;e._originAutoscroll=n.config.autoscroll,n.config.autoscroll=!1,n.$root.classList.add("gantt_noselect"),e._originalReadonly=n.config.readonly,n.config.readonly=!0,e._trace=[],e._mouseDown=!0;var i=e._getScrollPosition(e._timeline),r=i.x,a=i.y;e._scrollState={x:r,y:a},e._startPoint={x:t.clientX,y:t.clientY},e._trace.push(e._startPoint)},this._gantt=t,this._domEvents=t._createDomEventScope(),this._trace=[]}return t.create=function(e){return new t(e)},t.prototype.destructor=function(){this._domEvents.detachAll()},t.prototype.attach=function(t){var e=this;this._timeline=t;var n=this._gantt;this._domEvents.attach(t.$task,"mousedown",function(t){if(n.config.drag_timeline){var i=n.config.drag_timeline,r=i.useKey,a=i.ignore;if(!1!==i.enabled){var o=".gantt_task_line, .gantt_task_link";void 0!==a&&(o=a instanceof Array?a.join(", "):a),o&&n.utils.dom.closest(t.target,o)||r&&!0!==t[r]||e._startDrag(t)}}}),this._domEvents.attach(document,"keydown",function(t){if(n.config.drag_timeline){var i=n.config.drag_timeline.useKey;i&&!0===t[i]&&e._applyDndReadyStyles()}}),this._domEvents.attach(document,"keyup",function(t){if(n.config.drag_timeline){var i=n.config.drag_timeline.useKey;i&&!1===t[i]&&(e._clearDndReadyStyles(),e._stopDrag(t))}}),this._domEvents.attach(document,"mouseup",function(t){e._stopDrag(t)}),this._domEvents.attach(n.$root,"mouseup",function(t){e._stopDrag(t)}),this._domEvents.attach(document,"mouseleave",function(t){e._stopDrag(t)}),this._domEvents.attach(n.$root,"mouseleave",function(t){e._stopDrag(t)}),this._domEvents.attach(n.$root,"mousemove",function(i){if(n.config.drag_timeline){var r=n.config.drag_timeline.useKey;if((!r||!0===i[r])&&!0===e._mouseDown){e._trace.push({x:i.clientX,y:i.clientY});var a=e._countNewScrollPosition({x:i.clientX,y:i.clientY});e._setScrollPosition(t,a),e._scrollState=a,e._startPoint={x:i.clientX,y:i.clientY}}}})},t}();e.EventsManager=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(246);e.default=function(t){t.ext||(t.ext={}),t.ext.dragTimeline={create:function(){return i.EventsManager.create(t)}},t.config.drag_timeline={enabled:!0}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(4),r=n(2),a=function(){function t(t,e,n){var a=this;this._el=document.createElement("div"),this.defaultRender=function(t,e){a._el||(a._el=document.createElement("div"));var n=a._el,i=Math.min(t.relative.top,e.relative.top),r=Math.max(t.relative.top,e.relative.top),o=Math.min(t.relative.left,e.relative.left),s=Math.max(t.relative.left,e.relative.left);if(a._singleRow){var l=a._getTaskPositionByTop(a._startPoint.relative.top);n.style.height=l.height+"px",n.style.top=l.top+"px"}else n.style.height=Math.abs(r-i)+"px",n.style.top=i+"px";return n.style.width=Math.abs(s-o)+"px",n.style.left=o+"px",n},this._gantt=e,this._view=n,this._viewPort=t.viewPort,this._el.classList.add(t.className),"function"==typeof t.callback&&(this._callback=t.callback),this.render=function(){var e;(e=t.render?t.render(a._startPoint,a._endPoint):a.defaultRender(a._startPoint,a._endPoint))!==a._el&&(a._el&&a._el.parentNode&&a._el.parentNode.removeChild(a._el),a._el=e),""!==t.className&&a._el.classList.add(t.className),a.draw()},r.isEventable(this._viewPort)||i(this._viewPort),this._singleRow=t.singleRow,this._useRequestAnimationFrame=t.useRequestAnimationFrame}return t.prototype.draw=function(){var t=this;if(this._useRequestAnimationFrame)return requestAnimationFrame(function(){t._viewPort.appendChild(t.getElement())});this._viewPort.appendChild(this.getElement())},t.prototype.clear=function(){var t=this;if(this._useRequestAnimationFrame)return requestAnimationFrame(function(){t._el.parentNode&&t._viewPort.removeChild(t._el)});this._el.parentNode&&this._viewPort.removeChild(this._el)},t.prototype.getElement=function(){return this._el},t.prototype.getViewPort=function(){return this._viewPort},t.prototype.setStart=function(t){var e=this._gantt;this._startPoint=t,this._startDate=e.dateFromPos(this._startPoint.relative.left),this._viewPort.callEvent("onBeforeDrag",[this._startPoint])},t.prototype.setEnd=function(t){var e=this._gantt;if(this._endPoint=t,this._singleRow){var n=this._getTaskPositionByTop(this._startPoint.relative.top);this._endPoint.relative.top=n.top}this._endDate=e.dateFromPos(this._endPoint.relative.left),this._startPoint.relative.left>this._endPoint.relative.left&&(this._positionPoint={relative:{left:this._endPoint.relative.left,top:this._positionPoint.relative.top},absolute:{left:this._endPoint.absolute.left,top:this._positionPoint.absolute.top}}),this._startPoint.relative.top>this._endPoint.relative.top&&(this._positionPoint={relative:{left:this._positionPoint.relative.left,top:this._endPoint.relative.top},absolute:{left:this._positionPoint.absolute.left,top:this._endPoint.absolute.top}}),this._viewPort.callEvent("onDrag",[this._startPoint,this._endPoint])},t.prototype.setPosition=function(t){this._positionPoint=t},t.prototype.dragEnd=function(t){var e,n=this._gantt;t.relative.left<0&&(t.relative.left=0),this._viewPort.callEvent("onBeforeDragEnd",[this._startPoint,t]),this.setEnd(t),this._endDate=this._endDate||n.getState().max_date,this._startDate.valueOf()>this._endDate.valueOf()&&(e=[this._endDate,this._startDate],this._startDate=e[0],this._endDate=e[1]),this.clear();var i=n.getTaskByTime(this._startDate,this._endDate),r=this._getTasksByTop(this._startPoint.relative.top,this._endPoint.relative.top);this._viewPort.callEvent("onDragEnd",[this._startPoint,this._endPoint]),this._callback&&this._callback(this._startPoint,this._endPoint,this._startDate,this._endDate,i,r)},t.prototype.getInBounds=function(){return this._singleRow},t.prototype._getTasksByTop=function(t,e){var n=this._gantt,i=t,r=e;t>e&&(i=e,r=t);for(var a=this._getTaskPositionByTop(i).index,o=this._getTaskPositionByTop(r).index,s=[],l=a;l<=o;l++){n.getTaskByIndex(l)&&s.push(n.getTaskByIndex(l))}return s},t.prototype._getTaskPositionByTop=function(t){var e=this._gantt,n=this._view,i=n.getItemIndexByTopPosition(t),r=e.getTaskByIndex(i);if(r){var a=n.getItemHeight(r.id);return{top:n.getItemTop(r.id)||0,height:a||0,index:i}}var o=n.getTotalHeight();return{top:t>o?o:0,height:e.config.row_height,index:t>o?e.getTaskCount():0}},t}();e.SelectedRegion=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),r=function(){function t(t){this._mouseDown=!1,this._gantt=t,this._domEvents=t._createDomEventScope()}return t.prototype.attach=function(t,e){var n=this,r=this._gantt,a=t.getViewPort();this._originPosition=window.getComputedStyle(a).display,this._restoreOriginPosition=function(){a.style.position=n._originPosition},"static"===this._originPosition&&(a.style.position="relative");var o=r.$services.getService("state");o.registerProvider("clickDrag",function(){return{autoscroll:!1}});var s=null;this._domEvents.attach(a,"mousedown",function(i){s=null,r.utils.dom.closest(i.target,".gantt_task_line, .gantt_task_link")||(o.registerProvider("clickDrag",function(){return{autoscroll:n._mouseDown}}),e&&!0!==i[e]||(s=n._getCoordinates(i,t)))});var l=i.getRootNode(r.$root)||document.body;this._domEvents.attach(l,"mouseup",function(i){if(s=null,(!e||!0===i[e])&&!0===n._mouseDown){n._mouseDown=!1;var r=n._getCoordinates(i,t);t.dragEnd(r)}}),this._domEvents.attach(a,"mousemove",function(i){if(!e||!0===i[e]){var a=null;if(!n._mouseDown&&s)return a=n._getCoordinates(i,t),void(Math.abs(s.relative.left-a.relative.left)>5&&s&&(n._mouseDown=!0,t.setStart(r.copy(s)),t.setPosition(r.copy(s)),t.setEnd(r.copy(s)),s=null));!0===n._mouseDown&&(a=n._getCoordinates(i,t),t.setEnd(a),t.render())}})},t.prototype.detach=function(){var t=this._gantt;this._domEvents.detachAll(),this._restoreOriginPosition&&this._restoreOriginPosition(),t.$services.getService("state").unregisterProvider("clickDrag")},t.prototype.destructor=function(){this.detach()},t.prototype._getCoordinates=function(t,e){var n=e.getViewPort(),i=n.getBoundingClientRect(),r=t.clientX,a=t.clientY;return{absolute:{left:r,top:a},relative:{left:r-i.left+n.scrollLeft,top:a-i.top+n.scrollTop}}},t}();e.EventsManager=r},function(t,e,n){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var r in e=arguments[n])Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}).apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var r=n(249),a=n(248);e.default=function(t){t.ext||(t.ext={});var e={className:"gantt_click_drag_rect",useRequestAnimationFrame:!0,callback:void 0,singleRow:!1},n=new r.EventsManager(t);t.ext.clickDrag=n,t.attachEvent("onGanttReady",function(){var n=i({viewPort:t.$task_data},e);if(t.config.click_drag){var r=t.config.click_drag;n.render=r.render||e.render,n.className=r.className||e.className,n.callback=r.callback||e.callback,n.viewPort=r.viewPort||t.$task_data,n.useRequestAnimationFrame=void 0===r.useRequestAnimationFrame?e.useRequestAnimationFrame:r.useRequestAnimationFrame,n.singleRow=void 0===r.singleRow?e.singleRow:r.singleRow;var o=t.$ui.getView("timeline"),s=new a.SelectedRegion(n,t,o);t.ext.clickDrag.attach(s,r.useKey)}}),t.attachEvent("onDestroy",function(){n.destructor()})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(250),r=n(247),a=n(245),o=n(244),s=n(233),l=n(232),c=n(231),u=n(229),d=n(226);e.default={click_drag:i.default,drag_timeline:r.default,fullscreen:a.default,keyboard_navigation:o,quick_info:c.default,tooltip:u.default,undo:d.default,marker:s,multiselect:l}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(251),r=n(223),a=n(15).gantt=r(i.default);e.gantt=a,e.default=a}])}); //# sourceMappingURL=dhtmlxgantt.js.map
t
webpack-runtime-b50d2edb9b6efb43f77a.js
!function(e){function t(t){for(var r,c,s=t[0],u=t[1],i=t[2],f=0,l=[];f<s.length;f++)c=s[f],Object.prototype.hasOwnProperty.call(o,c)&&o[c]&&l.push(o[c][0]),o[c]=0;for(r in u)Object.prototype.hasOwnProperty.call(u,r)&&(e[r]=u[r]);for(p&&p(t);l.length;)l.shift()();return a.push.apply(a,i||[]),n()}function
(){for(var e,t=0;t<a.length;t++){for(var n=a[t],r=!0,s=1;s<n.length;s++){var u=n[s];0!==o[u]&&(r=!1)}r&&(a.splice(t--,1),e=c(c.s=n[0]))}return e}var r={},o={1:0},a=[];function c(t){if(r[t])return r[t].exports;var n=r[t]={i:t,l:!1,exports:{}};return e[t].call(n.exports,n,n.exports,c),n.l=!0,n.exports}c.e=function(e){var t=[],n=o[e];if(0!==n)if(n)t.push(n[2]);else{var r=new Promise((function(t,r){n=o[e]=[t,r]}));t.push(n[2]=r);var a,s=document.createElement("script");s.charset="utf-8",s.timeout=120,c.nc&&s.setAttribute("nonce",c.nc),s.src=function(e){return c.p+""+({0:"1c6c460d2798f625d7d33655e99bbbc462724012",3:"component---cache-caches-gatsby-plugin-offline-app-shell-js",4:"component---src-pages-404-js",5:"component---src-pages-index-js",6:"component---src-pages-pensieve-index-js",7:"component---src-pages-pensieve-tags-js",8:"component---src-templates-post-js",9:"component---src-templates-tag-js"}[e]||e)+"-"+{0:"218ce543bae0bbba20f3",3:"16703ee5599528db9f93",4:"08f90ad8b2905e1368d6",5:"3f15a2c77c5d479923e7",6:"d537248b7ab279c944ad",7:"f66729dadd6ee9ea0abd",8:"2888aa4839c28a682fa7",9:"690b295c568c7f3ac936"}[e]+".js"}(e);var u=new Error;a=function(t){s.onerror=s.onload=null,clearTimeout(i);var n=o[e];if(0!==n){if(n){var r=t&&("load"===t.type?"missing":t.type),a=t&&t.target&&t.target.src;u.message="Loading chunk "+e+" failed.\n("+r+": "+a+")",u.name="ChunkLoadError",u.type=r,u.request=a,n[1](u)}o[e]=void 0}};var i=setTimeout((function(){a({type:"timeout",target:s})}),12e4);s.onerror=s.onload=a,document.head.appendChild(s)}return Promise.all(t)},c.m=e,c.c=r,c.d=function(e,t,n){c.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},c.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.t=function(e,t){if(1&t&&(e=c(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(c.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)c.d(n,r,function(t){return e[t]}.bind(null,r));return n},c.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return c.d(t,"a",t),t},c.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},c.p="/",c.oe=function(e){throw console.error(e),e};var s=window.webpackJsonp=window.webpackJsonp||[],u=s.push.bind(s);s.push=t,s=s.slice();for(var i=0;i<s.length;i++)t(s[i]);var p=u;n()}([]); //# sourceMappingURL=webpack-runtime-b50d2edb9b6efb43f77a.js.map
n
serializers.py
# kombu v4 will come out with the following commit in: # https://github.com/celery/kombu/commit/010aae8ccf16ad2fa5a9c3d6f3b84b21e1c1677a # which does the same thing, but this also allows us to not have to enable # insecure serializers from datetime import datetime import msgpack import six from kombu.serialization import register DATE_FORMAT = '%Y%m%dT%H:%M:%S.%f' MESSAGE_CONTENT_TYPE = 'application/x-unicode-msgpack-with-dates' MESSAGE_CONTENT_ENCODING = 'binary' def decode_datetime(obj): if b'__datetime__' in obj: # This must have been produced by python2. obj = datetime.strptime(obj[b'as_str'].decode('utf-8'), DATE_FORMAT) elif '__datetime__' in obj: as_str = obj['as_str'] # We are not done yet!! Just because the keys are unicode, doesn't mean that the # values are!! if six.PY3 and isinstance(as_str, six.binary_type): as_str = as_str.decode('utf-8') obj = datetime.strptime(as_str, DATE_FORMAT) return obj def encode_datetime(obj): if isinstance(obj, datetime): # We want to return a dict that can be parsed later. # The dict should __always__ have unicode output. if six.PY3: as_str = obj.strftime(DATE_FORMAT) elif six.PY2: # We are in python2! But we want to output unicode.unicode_literals will take care # of the keys, but strftime returns a bytestring in python2. as_bytes = obj.strftime(DATE_FORMAT) as_str = as_bytes.decode('utf-8') return {'__datetime__': True, 'as_str': as_str} return obj def pack(s): return msgpack.packb( s, use_bin_type=True, unicode_errors='ignore', default=encode_datetime, ) def unpack(s): return msgpack.unpackb( s, encoding='utf-8', unicode_errors='ignore', object_hook=decode_datetime, ) register( 'unicode-msgpack-with-dates', pack,
# This is around for compatibility reasons (so that we're able to decode any messages # that are already in queues, with the old/non-date-aware content_type). register( 'unicode-msgpack', pack, unpack, content_type='application/x-unicode-msgpack', content_encoding='binary', )
unpack, content_type=MESSAGE_CONTENT_TYPE, content_encoding=MESSAGE_CONTENT_ENCODING, )
scalar.rs
use super::Filter; use crate::compare::ScalarCompare; use once_cell::sync::Lazy; use prisma_models::{ModelProjection, PrismaListValue, PrismaValue, ScalarFieldRef}; use std::{collections::BTreeSet, env, sync::Arc}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ScalarProjection { Single(ScalarFieldRef), Compound(Vec<ScalarFieldRef>), } #[derive(Debug, Clone, PartialEq, Eq, Hash)] /// Filtering with a scalar value. From a GraphQL point of view this is in the /// head of the query: /// /// ```graphql /// findManyUser(where: { id: 5 }) /// ```` /// /// This translates to a projection of one column `id` with a condition where /// the column value equals `5`. pub struct ScalarFilter { pub projection: ScalarProjection, pub condition: ScalarCondition, pub mode: QueryMode, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum QueryMode { Default, Insensitive, } /// Number of allowed elements in query's `IN` or `NOT IN` statement. /// Certain databases error out if querying with too many items. For test /// purposes, this value can be set with the `QUERY_BATCH_SIZE` environment /// value to a smaller number. static BATCH_SIZE: Lazy<usize> = Lazy::new(|| match env::var("QUERY_BATCH_SIZE") { Ok(size) => size.parse().unwrap_or(5000), Err(_) => 5000, }); impl ScalarFilter { /// The number of values in the filter. `IN` and `NOT IN` may contain more /// than one. pub fn len(&self) -> usize { match self.condition { ScalarCondition::In(ref l) => l.len(), ScalarCondition::NotIn(ref l) => l.len(), _ => 1, } } /// If `true`, the filter can be split into smaller filters executed in /// separate queries. pub fn can_batch(&self) -> bool { self.len() > *BATCH_SIZE } /// If possible, converts the filter into multiple smaller filters. pub fn batched(self) -> Vec<ScalarFilter> { fn inner(mut list: PrismaListValue) -> Vec<PrismaListValue> { let dedup_list: BTreeSet<_> = list.drain(..).collect(); let mut batches = Vec::with_capacity(list.len() % *BATCH_SIZE + 1); batches.push(Vec::with_capacity(*BATCH_SIZE)); for (idx, item) in dedup_list.into_iter().enumerate() { if idx != 0 && idx % *BATCH_SIZE == 0 { batches.push(Vec::with_capacity(*BATCH_SIZE)); } batches.last_mut().unwrap().push(item); } batches } let mode = self.mode.clone(); match self.condition { ScalarCondition::In(list) => { let projection = self.projection; inner(list) .into_iter() .map(|batch| ScalarFilter { projection: projection.clone(), condition: ScalarCondition::In(batch), mode: mode.clone(), }) .collect() } ScalarCondition::NotIn(list) => { let projection = self.projection; inner(list) .into_iter() .map(|batch| ScalarFilter { projection: projection.clone(), condition: ScalarCondition::NotIn(batch), mode: mode.clone(), }) .collect() } _ => vec![self], } } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ScalarCondition { Equals(PrismaValue), NotEquals(PrismaValue), Contains(PrismaValue), NotContains(PrismaValue), StartsWith(PrismaValue), NotStartsWith(PrismaValue), EndsWith(PrismaValue), NotEndsWith(PrismaValue), LessThan(PrismaValue), LessThanOrEquals(PrismaValue), GreaterThan(PrismaValue), GreaterThanOrEquals(PrismaValue), In(PrismaListValue), NotIn(PrismaListValue), } impl ScalarCompare for ScalarFieldRef { /// Field is in a given value fn is_in<T>(&self, values: Vec<T>) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::In(values.into_iter().map(|i| i.into()).collect()), mode: QueryMode::Default, }) } /// Field is not in a given value fn not_in<T>(&self, values: Vec<T>) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::NotIn(values.into_iter().map(|i| i.into()).collect()), mode: QueryMode::Default, }) } /// Field equals the given value. fn equals<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::Equals(val.into()), mode: QueryMode::Default, }) } /// Field does not equal the given value. fn not_equals<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::NotEquals(val.into()), mode: QueryMode::Default, }) } /// Field contains the given value. fn contains<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::Contains(val.into()), mode: QueryMode::Default, }) } /// Field does not contain the given value. fn not_contains<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::NotContains(val.into()), mode: QueryMode::Default, }) } /// Field starts with the given value. fn starts_with<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::StartsWith(val.into()), mode: QueryMode::Default, }) } /// Field does not start with the given value. fn not_starts_with<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::NotStartsWith(val.into()), mode: QueryMode::Default, }) } /// Field ends with the given value. fn ends_with<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::EndsWith(val.into()), mode: QueryMode::Default, }) } /// Field does not end with the given value. fn not_ends_with<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::NotEndsWith(val.into()), mode: QueryMode::Default, }) } /// Field is less than the given value. fn less_than<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::LessThan(val.into()), mode: QueryMode::Default, }) } /// Field is less than or equals the given value. fn less_than_or_equals<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::LessThanOrEquals(val.into()), mode: QueryMode::Default, }) } /// Field is greater than the given value. fn greater_than<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::GreaterThan(val.into()), mode: QueryMode::Default, }) } /// Field is greater than or equals the given value. fn greater_than_or_equals<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Single(Arc::clone(self)), condition: ScalarCondition::GreaterThanOrEquals(val.into()), mode: QueryMode::Default, }) } } impl ScalarCompare for ModelProjection { /// Field is in a given value fn is_in<T>(&self, values: Vec<T>) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::In(values.into_iter().map(|i| i.into()).collect()), mode: QueryMode::Default, }) } /// Field is not in a given value fn not_in<T>(&self, values: Vec<T>) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::NotIn(values.into_iter().map(|i| i.into()).collect()), mode: QueryMode::Default, }) } /// Field equals the given value. fn equals<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::Equals(val.into()), mode: QueryMode::Default, }) } /// Field does not equal the given value. fn not_equals<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::NotEquals(val.into()), mode: QueryMode::Default, }) } /// Field contains the given value. fn contains<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::Contains(val.into()), mode: QueryMode::Default, }) } /// Field does not contain the given value. fn not_contains<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::NotContains(val.into()), mode: QueryMode::Default, }) } /// Field starts with the given value. fn starts_with<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::StartsWith(val.into()), mode: QueryMode::Default, }) } /// Field does not start with the given value. fn not_starts_with<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::NotStartsWith(val.into()), mode: QueryMode::Default, }) } /// Field ends with the given value. fn
<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::EndsWith(val.into()), mode: QueryMode::Default, }) } /// Field does not end with the given value. fn not_ends_with<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::NotEndsWith(val.into()), mode: QueryMode::Default, }) } /// Field is less than the given value. fn less_than<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::LessThan(val.into()), mode: QueryMode::Default, }) } /// Field is less than or equals the given value. fn less_than_or_equals<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::LessThanOrEquals(val.into()), mode: QueryMode::Default, }) } /// Field is greater than the given value. fn greater_than<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::GreaterThan(val.into()), mode: QueryMode::Default, }) } /// Field is greater than or equals the given value. fn greater_than_or_equals<T>(&self, val: T) -> Filter where T: Into<PrismaValue>, { Filter::from(ScalarFilter { projection: ScalarProjection::Compound(self.scalar_fields().collect()), condition: ScalarCondition::GreaterThanOrEquals(val.into()), mode: QueryMode::Default, }) } }
ends_with
keying_material.rs
// // Copyright 2021 The Project Oak 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. // use crate::report::{AttestationInfo, Report}; use anyhow::{anyhow, Context}; use serde::{Deserialize, Serialize}; const KEYING_MATERIAL_PURPOSE: &str = "TLSAttestationV1"; const KEYING_MATERIAL_CLIENT_LABEL: &str = "EXPERIMENTAL Google Confidential Computing Client Attestation 1.0"; const KEYING_MATERIAL_SERVER_LABEL: &str = "EXPERIMENTAL Google Confidential Computing Server Attestation 1.0"; const KEYING_MATERIAL_LENGTH: usize = 128; // TODO(#2048): Implement multiple assertion types and assertion negotiation. const ASSERTION_TYPE: &str = "amd_sev_snp_report"; /// Assertion used for remote attestation. #[derive(Serialize, Deserialize)] pub struct Assertion { attestation_info: AttestationInfo, } impl Assertion { /// Generates assertion by putting `keying_material` into a TEE report and attaching /// `tee_certificate` used to verify the correctness of the TEE report. pub fn generate( tee_certificate: &[u8], keying_material: KeyingMaterial, ) -> anyhow::Result<Self> { let serialized_keying_material = serde_json::to_string(&keying_material) .context("Couldn't serialize keying material")?; let tee_report = Report::new(serialized_keying_material.as_bytes()); let attestation_info = AttestationInfo { report: tee_report, certificate: tee_certificate.to_vec(), }; Ok(Self { attestation_info }) } /// Verify remote attestation assertion by verifying the TEE report and checking that it /// contains `expected_keying_material`. pub fn verify(&self, expected_keying_material: &KeyingMaterial) -> anyhow::Result<()> { self.attestation_info .verify() .context("Incorrect attestation info")?; let serialized_expected_keying_material = serde_json::to_string(expected_keying_material) .context("Couldn't serialize keying material")?; if serialized_expected_keying_material.as_bytes() == self.attestation_info.report.data { Ok(()) } else { Err(anyhow!("Incorrect keying material")) } } pub fn from_string(input: &str) -> anyhow::Result<Self> { serde_json::from_str(input).context("Couldn't deserialize assertion") } pub fn to_string(&self) -> anyhow::Result<String> { serde_json::to_string(&self).context("Couldn't serialize assertion") } } /// Value uniquely derived from the TLS master secret that is shared by both participants of the TLS /// session. Used to bind remote attestation to each TLS session independently. /// https://tools.ietf.org/html/rfc5705 #[derive(Clone, Serialize, Deserialize, PartialEq)] pub struct KeyingMaterial { /// Value used to disambiguate the proper use of the `KeyingMaterial`. purpose: String, /// Pseudo-random value that is uniquely exported for an individual TLS session. value: Vec<u8>, } impl KeyingMaterial { /// Exports `KeyingMaterial` for a given TLS `session`. /// https://tools.ietf.org/html/rfc5705#section-4 fn export( // TLS session used to export `KeyingMaterial` from. session: &dyn rustls::Session, // Label value that is needed to distinguish between application level protocols that rely // on `KeyingMaterial`. label: &str, // Context value that is used to derive separate `KeyingMaterial` for different assertion // types. assertion_type: &str, ) -> anyhow::Result<Self> { let mut buffer = vec![0; KEYING_MATERIAL_LENGTH]; session .export_keying_material( &mut buffer, label.as_bytes(), Some(assertion_type.as_bytes()), ) .context("Couldn't export keying material")?; Ok(Self { // Purpose value is used to disambiguate the proper use of the `KeyingMaterial`. In this // case the usage is remote attestation via TLS. purpose: KEYING_MATERIAL_PURPOSE.to_string(), value: buffer, }) } } /// Convenience structure for exporting keying material with client and server labels. #[derive(Clone)] pub struct
{ pub client_keying_material: KeyingMaterial, pub server_keying_material: KeyingMaterial, } impl KeyingMaterialBundle { pub fn export(session: &dyn rustls::Session) -> anyhow::Result<Self> { Ok(Self { client_keying_material: KeyingMaterial::export( session, KEYING_MATERIAL_CLIENT_LABEL, ASSERTION_TYPE, )?, server_keying_material: KeyingMaterial::export( session, KEYING_MATERIAL_SERVER_LABEL, ASSERTION_TYPE, )?, }) } }
KeyingMaterialBundle
mod.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module defines physical storage schema for LedgerInfoWithSignatures structure. //! //! Serialized LedgerInfoWithSignatures identified by version. //! ```text //! |<--key-->|<---------------value------------->| //! | version | ledger_info_with_signatures bytes | //! ``` //! //! `Version` is serialized in big endian so that records in RocksDB will be in order of it's //! numeric value. use crate::schema::ensure_slice_len_eq; use byteorder::{BigEndian, ReadBytesExt}; use failure::prelude::*; use proto_conv::{FromProtoBytes, IntoProtoBytes}; use schemadb::{ define_schema, schema::{KeyCodec, ValueCodec}, DEFAULT_CF_NAME, }; use std::mem::size_of; use types::{ledger_info::LedgerInfoWithSignatures, transaction::Version}; define_schema!( LedgerInfoSchema, Version, LedgerInfoWithSignatures, DEFAULT_CF_NAME ); impl KeyCodec<LedgerInfoSchema> for Version { fn encode_key(&self) -> Result<Vec<u8>> { Ok(self.to_be_bytes().to_vec()) } fn decode_key(data: &[u8]) -> Result<Self> { ensure_slice_len_eq(data, size_of::<Version>())?; Ok((&data[..]).read_u64::<BigEndian>()?) } } impl ValueCodec<LedgerInfoSchema> for LedgerInfoWithSignatures { fn
(&self) -> Result<Vec<u8>> { self.clone().into_proto_bytes() } fn decode_value(data: &[u8]) -> Result<Self> { Self::from_proto_bytes(data) } } #[cfg(test)] mod test;
encode_value
benchmark.py
import os from collections import defaultdict from traceback import print_exc from typing import List, Dict, Any, Optional, Tuple, Type import numpy as np from modnet.preprocessing import MODData from modnet.models import MODNetModel from modnet.utils import LOG from modnet.hyper_opt import FitGenetic MATBENCH_SEED = 18012019 def matbench_kfold_splits(data: MODData, n_splits=5, classification=False): """Return the pre-defined k-fold splits to use when reporting matbench results. Arguments: data: The featurized MODData. """ if classification: from sklearn.model_selection import StratifiedKFold as KFold else: from sklearn.model_selection import KFold kf = KFold(n_splits=n_splits, shuffle=True, random_state=MATBENCH_SEED) kf_splits = kf.split(data.df_featurized, y=data.df_targets) return kf_splits def matbench_benchmark( data: MODData, target: List[str], target_weights: Dict[str, float], fit_settings: Optional[Dict[str, Any]] = None, ga_settings: Optional[Dict[str, float]] = None, classification: bool = False, model_type: Type[MODNetModel] = MODNetModel, save_folds: bool = False, save_models: bool = False, hp_optimization: bool = True, hp_strategy: str = "fit_preset", inner_feat_selection: bool = True, use_precomputed_cross_nmi: bool = True, presets: Optional[List[dict]] = None, fast: bool = False, n_jobs: Optional[int] = None, nested: bool = False, **model_init_kwargs, ) -> dict: """Train and cross-validate a model against Matbench data splits, optionally performing hyperparameter optimisation. Arguments: data: The entire dataset as a `MODData`. target: The list of target names to train on. target_weights: The target weights to use for the `MODNetModel`. fit_settings: Any settings to pass to `model.fit(...)` directly (typically when not performing hyperparameter optimisation). classification: Whether all tasks are classification rather than regression. model_type: The type of the model to create and benchmark. save_folds: Whether to save dataframes with pre-processed fold data (e.g. feature selection). save_models: Whether to pickle all trained models according to their fold index and performance. hp_optimization: Whether to perform hyperparameter optimisation. hp_strategy: Which optimization strategy to choose. Use either \"fit_preset\" or \"ga\". inner_feat_selection: Whether to perform split-level feature selection or try to use pre-computed values. use_precomputed_cross_nmi: Whether to use the precmputed cross NMI from the Materials Project dataset, or recompute per fold. presets: Override the built-in hyperparameter grid with these presets. fast: Whether to perform debug training, i.e. reduced presets and epochs, for the fit_preset strategy. n_jobs: Try to parallelize the inner fit_preset over this number of processes. Maxes out at number_of_presets*nested_folds nested: Whether to perform nested CV for hyperparameter optimisation. **model_init_kwargs: Additional arguments to pass to the model on creation. Returns: A dictionary containing all the results from the training, broken down by model and by fold. """ if hp_optimization: if hp_strategy not in ["fit_preset", "ga"]: raise RuntimeError( f'{hp_strategy} not supported. Choose from "fit_genetic" or "ga".' ) if fit_settings is None: fit_settings = {} if not fit_settings.get("n_feat"): nf = len(data.df_featurized.columns) fit_settings["n_feat"] = nf if not fit_settings.get("num_neurons"): # Pass dummy network fit_settings["num_neurons"] = [[4], [4], [4], [4]] if ga_settings is None: ga_settings = { "size_pop": 20, "num_generations": 10, "early_stopping": 4, "refit": False, } fold_data = [] results = defaultdict(list) for ind, (train, test) in enumerate( matbench_kfold_splits(data, classification=classification) ): train_data, test_data = data.split((train, test)) if inner_feat_selection: path = "folds/train_moddata_f{}".format(ind + 1) if os.path.isfile(path): train_data = MODData.load(path) else: train_data.feature_selection( n=-1, use_precomputed_cross_nmi=use_precomputed_cross_nmi, n_jobs=n_jobs, ) os.makedirs("folds", exist_ok=True) train_data.save(path) fold_data.append((train_data, test_data)) args = (target, target_weights, fit_settings, ga_settings) model_kwargs = { "model_type": model_type, "hp_optimization": hp_optimization, "fast": fast, "classification": classification, "save_folds": save_folds, "presets": presets, "hp_strategy": hp_strategy, "save_models": save_models, "nested": nested, "n_jobs": n_jobs, } model_kwargs.update(model_init_kwargs) fold_results = [] for fold in enumerate(fold_data): fold_results.append(train_fold(fold, *args, **model_kwargs)) for fold in fold_results: for key in fold: results[key].append(fold[key]) return results def
( fold: Tuple[int, Tuple[MODData, MODData]], target: List[str], target_weights: Dict[str, float], fit_settings: Dict[str, Any], ga_settings: Dict[str, float], model_type: Type[MODNetModel] = MODNetModel, presets=None, hp_optimization=True, hp_strategy="fit_preset", classification=False, save_folds=False, fast=False, save_models=False, nested=False, n_jobs=None, **model_kwargs, ) -> dict: """Train one fold of a CV. Unless stated, all arguments have the same meaning as in `matbench_benchmark(...)`. Arguments: fold: A tuple containing the fold index, and another tuple of the training MODData and test MODData. Returns: A dictionary summarising the fold results. """ fold_ind, (train_data, test_data) = fold results = {} multi_target = bool(len(target) - 1) # If not performing hp_optimization, load model init settings from fit_settings model_settings = {} if not hp_optimization: model_settings = { "num_neurons": fit_settings["num_neurons"], "num_classes": fit_settings.get("num_classes"), "act": fit_settings.get("act"), "out_act": fit_settings.get("out_act", "linear"), "n_feat": fit_settings["n_feat"], } model_settings.update(model_kwargs) if classification: model_settings["num_classes"] = {t: 2 for t in target_weights} model = model_type(target, target_weights, **model_settings) if hp_optimization: if hp_strategy == "fit_preset": ( models, val_losses, best_learning_curve, learning_curves, best_presets, ) = model.fit_preset( train_data, presets=presets, fast=fast, classification=classification, nested=nested, n_jobs=n_jobs, ) results["nested_losses"] = val_losses results["nested_learning_curves"] = learning_curves results["best_learning_curves"] = best_learning_curve results["best_presets"] = best_presets elif hp_strategy == "ga": ga = FitGenetic(train_data) model = ga.run( size_pop=ga_settings["size_pop"], num_generations=ga_settings["num_generations"], nested=nested, n_jobs=n_jobs, early_stopping=ga_settings["early_stopping"], refit=ga_settings["refit"], fast=fast, ) if save_models: for ind, nested_model in enumerate(models): score = val_losses[ind] nested_model.save(f"results/nested_model_{fold_ind}_{ind}_{score:3.3f}") model.save(f"results/best_model_{fold_ind}_{score:3.3f}") else: if fit_settings["increase_bs"]: model.fit( train_data, lr=fit_settings["lr"], epochs=fit_settings["epochs"], batch_size=fit_settings["batch_size"], loss=fit_settings["loss"], ) model.fit( train_data, lr=fit_settings["lr"] / 7, epochs=fit_settings["epochs"] // 2, batch_size=fit_settings["batch_size"] * 2, loss=fit_settings["loss"], ) else: model.fit(train_data, **fit_settings) try: predict_kwargs = {} if classification: predict_kwargs["return_prob"] = True if model.can_return_uncertainty: predict_kwargs["return_unc"] = True pred_results = model.predict(test_data, **predict_kwargs) if isinstance(pred_results, tuple): predictions, stds = pred_results else: predictions = pred_results stds = None targets = test_data.df_targets if classification: from sklearn.metrics import roc_auc_score from sklearn.preprocessing import OneHotEncoder y_true = OneHotEncoder().fit_transform(targets.values).toarray() score = roc_auc_score(y_true, predictions.values) pred_bool = model.predict(test_data, return_prob=False) LOG.info(f"ROC-AUC: {score}") errors = targets - pred_bool elif multi_target: errors = targets - predictions score = np.mean(np.abs(errors.values), axis=0) else: errors = targets - predictions score = np.mean(np.abs(errors.values)) except Exception: print_exc() print("Something went wrong benchmarking this model.") predictions = None errors = None score = None if save_folds: opt_feat = train_data.optimal_features[: fit_settings["n_feat"]] df_train = train_data.df_featurized df_train = df_train[opt_feat] df_train.to_csv("folds/train_f{}.csv".format(ind + 1)) df_test = test_data.df_featurized df_test = df_test[opt_feat] errors.columns = [x + "_error" for x in errors.columns] df_test = df_test.join(errors) df_test.to_csv("folds/test_f{}.csv".format(ind + 1)) results["predictions"] = predictions if stds is not None: results["stds"] = stds results["targets"] = targets results["errors"] = errors results["scores"] = score results["model"] = model return results
train_fold
vtable_comparison.rs
// Copyright Kani Contributors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Test relation comparison for vtable fat pointers fail due to unstable behavior. use std::rc::Rc; trait Dummy {} impl Dummy for u8 {} struct TestData { #[allow(dead_code)] array: Rc<[u8; 10]>, smaller_ptr: *const dyn Dummy, bigger_ptr: *const dyn Dummy, } fn
() -> TestData { let array = Rc::new([0u8; 10]); TestData { array: array.clone(), smaller_ptr: &array[0], bigger_ptr: &array[5] } } #[kani::proof] fn check_lt() { let data = setup(); assert!(data.smaller_ptr < data.bigger_ptr); } #[kani::proof] fn check_le() { let data = setup(); assert!(data.smaller_ptr <= data.bigger_ptr); } #[kani::proof] fn check_gt() { let data = setup(); assert!(data.bigger_ptr > data.smaller_ptr); } #[kani::proof] fn check_ge() { let data = setup(); assert!(data.bigger_ptr >= data.smaller_ptr); } #[kani::proof] fn check_ne() { let data = setup(); assert!(data.bigger_ptr != data.smaller_ptr); } #[kani::proof] fn check_eq() { let data = setup(); assert!(!(data.bigger_ptr == data.smaller_ptr)); }
setup
model_apm_stats_query_row_type.go
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-Present Datadog, Inc. */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package datadog import ( "encoding/json" "fmt" ) // ApmStatsQueryRowType The level of detail for the request. type ApmStatsQueryRowType string // List of ApmStatsQueryRowType const ( APMSTATSQUERYROWTYPE_SERVICE ApmStatsQueryRowType = "service" APMSTATSQUERYROWTYPE_RESOURCE ApmStatsQueryRowType = "resource" APMSTATSQUERYROWTYPE_SPAN ApmStatsQueryRowType = "span" ) var allowedApmStatsQueryRowTypeEnumValues = []ApmStatsQueryRowType{ "service", "resource", "span", } func (w *ApmStatsQueryRowType) GetAllowedValues() []ApmStatsQueryRowType { return allowedApmStatsQueryRowTypeEnumValues } func (v *ApmStatsQueryRowType) UnmarshalJSON(src []byte) error { var value string err := json.Unmarshal(src, &value) if err != nil { return err } ev, err := NewApmStatsQueryRowTypeFromValue(value) if err != nil { return err } *v = *ev return nil } // NewApmStatsQueryRowTypeFromValue returns a pointer to a valid ApmStatsQueryRowType // for the value passed as argument, or an error if the value passed is not allowed by the enum func NewApmStatsQueryRowTypeFromValue(v string) (*ApmStatsQueryRowType, error)
// IsValid return true if the value is valid for the enum, false otherwise func (v ApmStatsQueryRowType) IsValid() bool { for _, existing := range allowedApmStatsQueryRowTypeEnumValues { if existing == v { return true } } return false } // Ptr returns reference to ApmStatsQueryRowType value func (v ApmStatsQueryRowType) Ptr() *ApmStatsQueryRowType { return &v } type NullableApmStatsQueryRowType struct { value *ApmStatsQueryRowType isSet bool } func (v NullableApmStatsQueryRowType) Get() *ApmStatsQueryRowType { return v.value } func (v *NullableApmStatsQueryRowType) Set(val *ApmStatsQueryRowType) { v.value = val v.isSet = true } func (v NullableApmStatsQueryRowType) IsSet() bool { return v.isSet } func (v *NullableApmStatsQueryRowType) Unset() { v.value = nil v.isSet = false } func NewNullableApmStatsQueryRowType(val *ApmStatsQueryRowType) *NullableApmStatsQueryRowType { return &NullableApmStatsQueryRowType{value: val, isSet: true} } func (v NullableApmStatsQueryRowType) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableApmStatsQueryRowType) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
{ ev := ApmStatsQueryRowType(v) if ev.IsValid() { return &ev, nil } else { return nil, fmt.Errorf("invalid value '%v' for ApmStatsQueryRowType: valid values are %v", v, allowedApmStatsQueryRowTypeEnumValues) } }
World.ts
import { isClient } from '../../common/functions/isClient' import { Action } from '../../networking/interfaces/Action' import { defineQuery, getComponent, hasComponent, MappedComponent } from '../functions/ComponentFunctions' import { createEntity } from '../functions/EntityFunctions' import { SystemFactoryType, SystemModuleType } from '../functions/SystemFunctions' import { Entity } from './Entity' import { System } from './System' import { Engine } from './Engine' import * as bitecs from 'bitecs' import { AvatarComponent } from '../../avatar/components/AvatarComponent' import { NetworkObjectComponent } from '../../networking/components/NetworkObjectComponent' import { Physics } from '../../physics/classes/Physics' import { HostUserId, UserId } from '@xrengine/common/src/interfaces/UserId' import { NetworkId } from '@xrengine/common/src/interfaces/NetworkId' import { NetworkClient } from '../../networking/interfaces/NetworkClient' import { SystemUpdateType } from '../functions/SystemUpdateType' import { WorldStateInterface } from '../../networking/schema/networkSchema' type SystemInstanceType = { name: string; type: SystemUpdateType; execute: System } type RemoveIndex<T> = { [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K] } export const CreateWorld = Symbol('CreateWorld') export class World { private constructor() { bitecs.createWorld(this) Engine.worlds.push(this) this.worldEntity = createEntity(this) this.localClientEntity = isClient ? (createEntity(this) as Entity) : (NaN as Entity) if (!Engine.defaultWorld) Engine.defaultWorld = this } static [CreateWorld] = () => new World() sceneMetadata = undefined as string | undefined worldMetadata = {} as { [key: string]: string } delta = NaN elapsedTime = NaN fixedDelta = NaN fixedElapsedTime = NaN fixedTick = -1 _removedComponents = new Map<Entity, Set<MappedComponent<any, any>>>() _pipeline = [] as SystemModuleType<any>[] physics = new Physics() entities = [] as Entity[] portalEntities = [] as Entity[] isInPortal = false /** Connected clients */ clients = new Map() as Map<UserId, NetworkClient>
/** Incoming actions */ incomingActions = new Set<Required<Action>>() /** Delayed actions */ delayedActions = new Set<Required<Action>>() /** Outgoing actions */ outgoingActions = new Set<Action>() outgoingNetworkState: WorldStateInterface previousNetworkState: WorldStateInterface /** * Check if this user is hosting the world. */ get isHosting() { return Engine.userId === this.hostId } /** * The UserId of the host */ hostId = 'server' as HostUserId /** * The world entity (always exists, and always has eid 0) */ worldEntity: Entity /** * The local client entity */ localClientEntity: Entity /** * Systems that run only once every frame. * Ideal for cosmetic updates (e.g., particles), animation, rendering, etc. */ freeSystems = [] as SystemInstanceType[] /** * Systems that run once for every fixed time interval (in simulation time). * Ideal for game logic, ai logic, simulation logic, etc. */ fixedSystems = [] as SystemInstanceType[] /** * Custom systems injected into this world */ injectedSystems = { [SystemUpdateType.UPDATE]: [], [SystemUpdateType.FIXED_EARLY]: [], [SystemUpdateType.FIXED]: [], [SystemUpdateType.FIXED_LATE]: [], [SystemUpdateType.PRE_RENDER]: [], [SystemUpdateType.POST_RENDER]: [] } as { [pipeline: string]: SystemInstanceType[] } /** * Entities mapped by name */ namedEntities = new Map<string, Entity>() /** * Network object query */ networkObjectQuery = defineQuery([NetworkObjectComponent]) /** * Get the network objects owned by a given user * @param userId */ getOwnedNetworkObjects(userId: UserId) { return this.networkObjectQuery(this).filter((eid) => getComponent(eid, NetworkObjectComponent).userId === userId) } /** * Get a network object by NetworkId * @returns */ getNetworkObject(networkId: NetworkId) { return this.networkObjectQuery(this).find( (eid) => getComponent(eid, NetworkObjectComponent).networkId === networkId )! } /** * Get the user avatar entity (the network object w/ an Avatar component) * @param userId * @returns */ getUserAvatarEntity(userId: UserId) { return this.getOwnedNetworkObjects(userId).find((eid) => { return hasComponent(eid, AvatarComponent, this) })! } /** * Action receptors */ receptors = new Array<(action: Action) => void>() /** * Execute systems on this world * * @param delta * @param elapsedTime */ execute(delta: number, elapsedTime: number) { this.delta = delta this.elapsedTime = elapsedTime for (const system of this.freeSystems) system.execute() for (const [entity, components] of this._removedComponents) { for (const c of components) c.delete(entity) } this._removedComponents.clear() } async initSystems() { const loadSystem = async (s: SystemFactoryType<any>) => { const system = await s.systemModule.default(this, s.args) return { name: s.systemModule.default.name, type: s.type, execute: () => { try { system() } catch (e) { console.error(e) } } } as SystemInstanceType } const systemModule = await Promise.all( this._pipeline.map(async (s) => { return { args: s.args, type: s.type, systemModule: await s.systemModulePromise } }) ) const systems = await Promise.all(systemModule.map(loadSystem)) systems.forEach((s) => console.log(`${s.type} ${s.name}`)) this.freeSystems = systems.filter((s) => { return !s.type.includes('FIXED') }) this.fixedSystems = systems.filter((s) => { return s.type.includes('FIXED') }) console.log('[World]: All systems initialized!') } } export function createWorld() { console.log('Creating world') return World[CreateWorld]() }
test.rs
use super::{args, get}; use clap::{App, Arg, ArgMatches, SubCommand}; use elba::{ cli::build, util::{config::Config, error::Result}, }; use failure::{format_err, ResultExt}; use std::env::current_dir; pub fn cli() -> App<'static, 'static> { SubCommand::with_name("test") .about("Runs the tests of the root package") .args(&args::backends()) .arg(args::build_threads()) .arg(args::offline()) .arg(args::debug_log()) .arg( Arg::with_name("test-threads") .long("test-threads") .takes_value(true) .number_of_values(1) .help("The number of threads to use to simultaneously run test binaries"), ) .arg( Arg::with_name("targets") .multiple(true) .help("The names of the tests to run (all tests are run if unspecified)"), ) .arg(args::idris_opts()) } pub fn exec(c: &mut Config, args: &ArgMatches) -> Result<String> { let project = current_dir().context(format_err!( "couldn't get current dir; doesn't exist or no permissions..." ))?; let ctx = get::build_ctx(c, args); // This is where our default codegen backend is set let backend = get::backends(c, args); let targets = args .values_of("targets") .map(|x| x.collect()) .unwrap_or_else(|| vec![]); let test_threads = args .value_of("test-threads") .and_then(|x| x.parse::<u32>().ok()) .unwrap_or(1); build::test(&ctx, &project, &targets, &backend, test_threads)
}
ConsolePrintActor.go
package printmessage import ( "fmt" "log" "github.com/heckdevice/goactorframework-corelib" "github.com/heckdevice/goactorframework-examples/samples/common" ) const ( // ActorType - actor type for this actor ActorType = "PrintActor" ) // InitActor - Initialises this actor by registering its different message handlers and spawing the actor using the Default actor system func InitActor() { printActor := core.Actor{ActorType: ActorType} err := core.GetDefaultActorSystem().RegisterActor(&printActor, common.ConsolePrint, consolePrint) if err != nil { log.Panic(fmt.Sprintf("Error while registering actor %v. Details : %v", printActor.ActorType, err.Error())) } go printActor.SpawnActor() } func consolePrint(message core.Message)
{ fmt.Print(fmt.Sprintf("Got Message %v", message)) }
FavPage_20210727141537.js
import axios from 'axios' import React, { Component } from 'react' import ApiFavData from './ApiFavData' export class FavPage extends Component { constructor() { super() this.state = { favData: [], showFavData: false } } componentDidMount = () => { axios.get("http://localhost:8001/fav-list").then(res => { this.setState({ favData: res.data, showFavData: true } )
} deleteFav =(id)=>{ axios.delete() } render() { return ( <> {this.state.showFavData && this.state.favData.map((item, i) => { return ( <ApiFavData key={i} favData={item} /> ) })} </> ) } } export default FavPage
})
test_fabs42_detached_award_financial_assistance_1.py
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'fabs42_detached_award_financial_assistance_1' def test_column_headers(database): expected_subset = {'row_number', 'place_of_performance_forei', 'place_of_perform_country_c', 'record_type', 'uniqueid_AssistanceTransactionUniqueKey'} actual = set(query_columns(_FILE, database)) assert expected_subset == actual def
(database): """ Test PrimaryPlaceOfPerformanceForeignLocationDescription is required for foreign places of performance (i.e., when PrimaryPlaceOfPerformanceCountryCode does not equal USA) for record type 2. This test shouldn't care about content when country_code is USA (that is for another validation). """ det_award_1 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei='description', place_of_perform_country_c='UK', record_type=2, correction_delete_indicatr='') det_award_2 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei='description', place_of_perform_country_c='USA', record_type=2, correction_delete_indicatr=None) det_award_3 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei=None, place_of_perform_country_c='USA', record_type=2, correction_delete_indicatr='c') det_award_4 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei='', place_of_perform_country_c='UsA', record_type=2, correction_delete_indicatr='C') det_award_5 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei='', place_of_perform_country_c='UK', record_type=1, correction_delete_indicatr='') det_award_6 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei=None, place_of_perform_country_c='UK', record_type=1, correction_delete_indicatr='') # Ignore correction delete indicator of D det_award_7 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei='', place_of_perform_country_c='UK', record_type=2, correction_delete_indicatr='d') errors = number_of_errors(_FILE, database, models=[det_award_1, det_award_2, det_award_3, det_award_4, det_award_5, det_award_6, det_award_7]) assert errors == 0 def test_failure(database): """ Test failure PrimaryPlaceOfPerformanceForeignLocationDescription is required for foreign places of performance (i.e., when PrimaryPlaceOfPerformanceCountryCode does not equal USA) for record type 2. """ det_award_1 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei='', place_of_perform_country_c='UK', record_type=2, correction_delete_indicatr='') det_award_2 = DetachedAwardFinancialAssistanceFactory(place_of_performance_forei=None, place_of_perform_country_c='UK', record_type=2, correction_delete_indicatr='c') errors = number_of_errors(_FILE, database, models=[det_award_1, det_award_2]) assert errors == 2
test_success
object-lifetime-default-elision.rs
// Test various cases where the old rules under lifetime elision // yield slightly different results than the new rules. #![allow(dead_code)] trait SomeTrait { fn dummy(&self) { } } struct SomeStruct<'a> { r: Box<dyn SomeTrait+'a> } fn deref<T>(ss: &T) -> T { // produces the type of a deref without worrying about whether a // move out would actually be legal loop { } } fn load0<'a>(ss: &'a Box<dyn SomeTrait>) -> Box<dyn SomeTrait> { // Under old rules, the fully elaborated types of input/output were: // // for<'a,'b> fn(&'a Box<SomeTrait+'b>) -> Box<SomeTrait+'a> // // Under new rules the result is: // // for<'a> fn(&'a Box<SomeTrait+'static>) -> Box<SomeTrait+'static> // // Therefore, no type error. deref(ss) } fn load1(ss: &dyn SomeTrait) -> &dyn SomeTrait { // Under old rules, the fully elaborated types of input/output were: // // for<'a,'b> fn(&'a (SomeTrait+'b)) -> &'a (SomeTrait+'a) //
// Under new rules the result is: // // for<'a> fn(&'a (SomeTrait+'a)) -> &'a (SomeTrait+'a) // // In both cases, returning `ss` is legal. ss } fn load2<'a>(ss: &'a dyn SomeTrait) -> &dyn SomeTrait { // Same as `load1` but with an explicit name thrown in for fun. ss } fn load3<'a,'b>(ss: &'a dyn SomeTrait) -> &'b dyn SomeTrait { // Under old rules, the fully elaborated types of input/output were: // // for<'a,'b,'c>fn(&'a (SomeTrait+'c)) -> &'b (SomeTrait+'a) // // Based on the input/output types, the compiler could infer that // 'c : 'a // 'b : 'a // must hold, and therefore it permitted `&'a (Sometrait+'c)` to be // coerced to `&'b (SomeTrait+'a)`. // // Under the newer defaults, though, we get: // // for<'a,'b> fn(&'a (SomeTrait+'a)) -> &'b (SomeTrait+'b) // // which fails to type check. ss //~^ ERROR lifetime may not live long enough } fn main() { }
create-shorter-dto.ts
import { InputType, OmitType } from "@nestjs/graphql"; import { ShorterEntity } from "../entities/shorter.entity"; @InputType() export class
extends OmitType(ShorterEntity, ["id"], InputType) {}
CreateShorterDto
main.go
package main import "github.com/k-yomo/pubsub_cli/cmd" func main()
{ cmd.Exec() }
floats_arm64.go
// Copyright 2022 gorse Project 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 floats import ( "unsafe" ) func init() { impl = neon{} } type neon struct{} func (neon) MulConstAddTo(a []float32, b float32, c []float32) { vmul_const_add_to(unsafe.Pointer(&a[0]), unsafe.Pointer(&b), unsafe.Pointer(&c[0]), unsafe.Pointer(uintptr(len(a)))) } func (neon) MulConstTo(a []float32, b float32, c []float32) { vmul_const_to(unsafe.Pointer(&a[0]), unsafe.Pointer(&b), unsafe.Pointer(&c[0]), unsafe.Pointer(uintptr(len(a)))) }
} func (neon) MulConst(a []float32, b float32) { vmul_const(unsafe.Pointer(&a[0]), unsafe.Pointer(&b), unsafe.Pointer(uintptr(len(a)))) } func (neon) Dot(a, b []float32) float32 { var ret float32 vdot(unsafe.Pointer(&a[0]), unsafe.Pointer(&b[0]), unsafe.Pointer(uintptr(len(a))), unsafe.Pointer(&ret)) return ret } //go:noescape func vmul_const_add_to(a, b, c, n unsafe.Pointer) //go:noescape func vmul_const_to(a, b, c, n unsafe.Pointer) //go:noescape func vmul_const(a, b, n unsafe.Pointer) //go:noescape func vmul_to(a, b, c, n unsafe.Pointer) //go:noescape func vdot(a, b, n, ret unsafe.Pointer)
func (neon) MulTo(a, b, c []float32) { vmul_to(unsafe.Pointer(&a[0]), unsafe.Pointer(&b[0]), unsafe.Pointer(&c[0]), unsafe.Pointer(uintptr(len(a))))
download.rs
//! Downloads a Habitat package from a [depot](../depot). //! //! # Examples //! //! ```bash //! $ hab pkg download core/redis //! ``` //! //! Will download `core/redis` package and all its transitive dependencies from a custom depot: //! //! ```bash //! $ hab pkg download -u http://depot.co:9633 -t x86-64_linux --download-directory download core/redis/3.0.1 //! ``` //! //! This would download the `3.0.1` version of redis for linux and all //! of its transitive dependencies, and the accompanying signing keys //! to a directory 'download' //! //! The most common usage will have a file containing newline separated list of package //! identifiers. //! //! # Internals //! //! * Resolve the list of partial artifact identifiers to fully qualified idents //! * Gather the TDEPS of the list (done concurrently with the above step) //! * Download the artifact //! * Verify it is un-altered //! * Fetch the signing keys use std::{collections::HashSet, fs::DirBuilder, path::{Path, PathBuf}, time::Duration}; use crate::{api_client::{self, BoxedClient, Client, Error::APIError, Package}, common::Error as CommonError, hcore::{crypto::{artifact, keys::parse_name_with_rev, SigKeyPair}, fs::cache_root_path, package::{PackageArchive, PackageIdent, PackageTarget}, ChannelIdent, Error as CoreError}}; use reqwest::StatusCode; use retry::{delay, retry}; use crate::error::{Error, Result}; use habitat_common::ui::{Glyph, Status, UIWriter}; pub const RETRIES: usize = 5; pub const RETRY_WAIT: Duration = Duration::from_millis(3000); /// Download a Habitat package. /// /// If an `PackageIdent` is given, we retrieve the package from the specified Builder /// `url`. Providing a fully-qualified identifer will result in that exact package being downloaded /// (regardless of `channel`). Providing a partially-qualified identifier will result in the /// installation of latest appropriate release from the given `channel`. /// /// Any dependencies of will be retrieved from Builder (if they're not already downloaded locally). /// /// At the end of this function, the specified package and all its /// dependencies will be downloaded on the system in the /// <download_path>/artifacts directory. Any signing keys will also be /// downloaded and put in the <download_path/keys> directory. /// Also, in the future we may want to accept an alternate builder to 'filter' what we pull down by /// That would greatly optimize the 'sync' to on prem builder case, as we could point to that /// and only fetch what we don't already have. #[allow(clippy::too_many_arguments)] pub fn start<U>(ui: &mut U, url: &str, channel: &ChannelIdent, product: &str, version: &str, idents: Vec<PackageIdent>, target: PackageTarget, download_path: Option<&PathBuf>, token: Option<&str>, verify: bool) -> Result<()> where U: UIWriter { debug!("Starting download with url: {}, channel: {}, product: {}, version: {}, target: {}, \ download_path: {:?}, token: {:?}, verify: {}, ident_count: {}", url, channel, product, version, target, download_path, token, verify, idents.len()); let download_path_default = &cache_root_path::<PathBuf>(None); // Satisfy E0716 let download_path_expanded = download_path.unwrap_or(download_path_default).as_ref(); debug!("Using download_path {:?} expanded to {:?}", download_path, download_path_expanded); if idents.is_empty() { ui.fatal("No package identifers provided. Specify identifiers on the command line, or \ via a input file")?; return Err(CommonError::MissingCLIInputError(String::from("No package identifiers \ found")).into()); } // We deliberately use None to specify the default path as this is used for cert paths, which // we don't want to override. let api_client = Client::new(url, product, version, None)?; let task = DownloadTask { idents, target, url, api_client, token, channel, download_path: download_path_expanded, verify }; let download_count = task.execute(ui)?; debug!("Expanded package count: {}", download_count); Ok(()) } struct DownloadTask<'a> { idents: Vec<PackageIdent>, target: PackageTarget, url: &'a str, api_client: BoxedClient, token: Option<&'a str>, channel: &'a ChannelIdent, download_path: &'a Path, verify: bool, } impl<'a> DownloadTask<'a> { fn execute<T>(&self, ui: &mut T) -> Result<usize> where T: UIWriter { // This was written intentionally with an eye towards data parallelism // Any or all of these phases should naturally fit a fork-join model ui.begin(format!("Resolving dependencies for {} package idents", self.idents.len()))?; ui.begin(format!("Using channel {} from {}", self.channel, self.url))?; ui.begin(format!("Using target {}", self.target))?; ui.begin(format!("Storing in download directory {:?} ", self.download_path))?; self.verify_and_prepare_download_directory(ui)?; // Phase 1: Expand to fully qualified deps and TDEPS let expanded_idents = self.expand_sources(ui)?; // Phase 2: Download artifacts let downloaded_artifacts = self.download_artifacts(ui, &expanded_idents)?; Ok(downloaded_artifacts.len()) } // For each source, use the builder/depot to expand it to a fully qualifed form // The same call gives us the TDEPS, add those as well. fn expand_sources<T>(&self, ui: &mut T) -> Result<HashSet<(PackageIdent, PackageTarget)>> where T: UIWriter { let mut expanded_packages = Vec::<Package>::new(); let mut expanded_idents = HashSet::<(PackageIdent, PackageTarget)>::new(); // This loop should be easy to convert to a parallel map. for ident in &self.idents { let package = self.determine_latest_from_ident(ui, &ident.clone(), self.target)?; expanded_packages.push(package); } // Collect all the expanded deps into one structure // Done separately because it's not as easy to parallelize for package in expanded_packages { for ident in package.tdeps { expanded_idents.insert((ident.clone(), self.target)); } expanded_idents.insert((package.ident.clone(), self.target)); } ui.status(Status::Found, format!("{} artifacts", expanded_idents.len()))?; Ok(expanded_idents) } fn download_artifacts<T>(&self, ui: &mut T, expanded_idents: &HashSet<(PackageIdent, PackageTarget)>) -> Result<Vec<PackageArchive>> where T: UIWriter { let mut downloaded_artifacts = Vec::<PackageArchive>::new(); ui.status(Status::Downloading, format!("Downloading {} artifacts (and their signing keys)", expanded_idents.len()))?; for (ident, target) in expanded_idents { let archive: PackageArchive = match self.get_downloaded_archive(ui, ident, *target) { Ok(v) => v, Err(e) => { // Is this the right status? Or should this be a debug message? debug!("Error fetching archive {} for {}: {:?}", ident, *target, e); ui.status(Status::Missing, format!("Error fetching archive {} for {}", ident, *target))?; return Err(e); } }; downloaded_artifacts.push(archive); } Ok(downloaded_artifacts) } fn determine_latest_from_ident<T>(&self, ui: &mut T, ident: &PackageIdent, target: PackageTarget) -> Result<Package> where T: UIWriter { // Unlike in the install command, we always hit the online // depot; our purpose is to sync with latest, and falling back // to a local package would defeat that. Find the latest // package in the proper channel from Builder API, ui.status(Status::Determining, format!("latest version of {}", ident))?; match self.fetch_latest_package_in_channel_for(ident, target, self.channel, self.token) { Ok(latest_package) => { ui.status(Status::Using, format!("{}", latest_package.ident))?; Ok(latest_package) } Err(Error::APIClient(APIError(StatusCode::NOT_FOUND, _))) => { // In install we attempt to recommend a channel to look in. That's a bit of a // heavyweight process, and probably a bad idea in the context of // what's a normally a batch process. It might be OK to fall back to // the stable channel, but for now, error. ui.warn(format!("No packages matching ident {} for {} exist in the '{}' \ channel. Check the package ident, target, channel and Builder \ url ({}) for correctness", ident, target, self.channel, self.url))?; Err(CommonError::PackageNotFound(format!("{} for {} in channel {}", ident, target, self.channel)).into()) } Err(e) => { debug!("Error fetching ident {} for target {}: {:?}", ident, target, e); ui.warn(format!("Error fetching ident {} for target {}", ident, target))?; Err(e) } } } // This function and its sibling get_cached_artifact in // install.rs deserve to be refactored to eke out commonality. /// This ensures the identified package is in the local download directory, /// verifies it, and returns a handle to the package's metadata. fn get_downloaded_archive<T>(&self, ui: &mut T, ident: &PackageIdent, target: PackageTarget) -> Result<PackageArchive> where T: UIWriter { let fetch_artifact = || self.fetch_artifact(ui, ident, target); if self.downloaded_artifact_path(ident, target).is_file() { debug!("Found {} in download directory, skipping remote download", ident); ui.status(Status::Custom(Glyph::Elipses, String::from("Using cached")), format!("{}", ident))?; } else if let Err(err) = retry(delay::Fixed::from(RETRY_WAIT).take(RETRIES), fetch_artifact) { return Err(CommonError::DownloadFailed(format!("We tried {} times but could not \ download {} for {}. Last error \ was: {}", RETRIES, ident, target, err)).into()); } // At this point the artifact is in the download directory... let mut artifact = PackageArchive::new(self.downloaded_artifact_path(ident, target)); self.fetch_keys_and_verify_artifact(ui, ident, target, &mut artifact)?; Ok(artifact) } // This function and its sibling in install.rs deserve to be refactored to eke out commonality. /// Retrieve the identified package from the depot, ensuring that /// the artifact is downloaded. fn fetch_artifact<T>(&self, ui: &mut T, ident: &PackageIdent, target: PackageTarget) -> Result<()> where T: UIWriter
fn fetch_origin_key<T>(&self, ui: &mut T, name_with_rev: &str, token: Option<&str>) -> Result<()> where T: UIWriter { let (name, rev) = parse_name_with_rev(&name_with_rev)?; self.api_client.fetch_origin_key(&name, &rev, token, &self.path_for_keys(), ui.progress())?; Ok(()) } fn fetch_keys_and_verify_artifact<T>(&self, ui: &mut T, ident: &PackageIdent, target: PackageTarget, artifact: &mut PackageArchive) -> Result<()> where T: UIWriter { // We need to look at the artifact to know the signing keys to fetch // Once we have them, it's the natural time to verify. // Otherwise, it might make sense to take this fetch out of the verification code. let signer = artifact::artifact_signer(&artifact.path)?; if SigKeyPair::get_public_key_path(&signer, &self.path_for_keys()).is_err() { ui.status(Status::Downloading, format!("public key for signer {:?}", signer))?; self.fetch_origin_key(ui, &signer, self.token)?; } if self.verify { ui.status(Status::Verifying, artifact.ident()?)?; artifact.verify(&self.path_for_keys())?; debug!("Verified {} for {} signed by {}", ident, target, &signer); } Ok(()) } // This function and its sibling in install.rs deserve to be refactored to eke out commonality. /// Returns the path to the location this package would exist at in /// the local package cache. It does not mean that the package is /// actually *in* the package download directory, though. fn downloaded_artifact_path(&self, ident: &PackageIdent, target: PackageTarget) -> PathBuf { self.path_for_artifact() .join(ident.archive_name_with_target(target).unwrap()) } fn fetch_latest_package_in_channel_for(&self, ident: &PackageIdent, target: PackageTarget, channel: &ChannelIdent, token: Option<&str>) -> Result<Package> { self.api_client .show_package_metadata((&ident, target), channel, token) .map_err(Error::from) } /// The cache_*_path functions in fs don't let you override a path base with Some(base) /// So we have to build our own paths. fn path_for_keys(&self) -> PathBuf { self.download_path.join("keys") } fn path_for_artifact(&self) -> PathBuf { self.download_path.join("artifacts") } /// Sanity check the download directory tree. The errors from the api around permissions are /// opaque; this validates the directory in advance to help provide useful feedback. fn verify_and_prepare_download_directory<T>(&self, ui: &mut T) -> Result<()> where T: UIWriter { let system_paths = [self.download_path, &self.path_for_keys(), &self.path_for_artifact()]; ui.status(Status::Verifying, format!("the download directory \"{}\"", self.download_path.display()))?; let mut builder = DirBuilder::new(); builder.recursive(true); // Create directories if they don't exist for dir in &system_paths { builder.create(dir).map_err(|_| { mk_perm_error(format!("Can't create directory {:?} needed \ for download", dir)) })? } // Check permissions of directories: for dir in &system_paths { let metadata = std::fs::metadata(dir)?; if !metadata.is_dir() { return Err(mk_perm_error(format!("{} isn't a directory, needed for \ download", dir.display()))); } if metadata.permissions().readonly() { return Err(mk_perm_error(format!("{} isn't writeable, needed for \ download", dir.display()))); } } Ok(()) } } fn mk_perm_error(msg: String) -> Error { CoreError::PermissionFailed(msg).into() }
{ ui.status(Status::Downloading, format!("{}", ident))?; match self.api_client.fetch_package((ident, target), self.token, &self.path_for_artifact(), ui.progress()) { Ok(_) => Ok(()), Err(api_client::Error::APIError(StatusCode::NOT_IMPLEMENTED, _)) => { println!("Host platform or architecture not supported by the targeted depot; \ skipping."); Ok(()) } Err(e) => Err(e.into()), } }
networkservice.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: networkservice.proto package networkservice import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" empty "github.com/golang/protobuf/ptypes/empty" connection "github.com/networkservicemesh/networkservicemesh/controlplane/api/connection" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type NetworkServiceRequest struct { Connection *connection.Connection `protobuf:"bytes,1,opt,name=connection,proto3" json:"connection,omitempty"` MechanismPreferences []*connection.Mechanism `protobuf:"bytes,2,rep,name=mechanism_preferences,json=mechanismPreferences,proto3" json:"mechanism_preferences,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NetworkServiceRequest) Reset() { *m = NetworkServiceRequest{} } func (m *NetworkServiceRequest) String() string { return proto.CompactTextString(m) } func (*NetworkServiceRequest) ProtoMessage() {} func (*NetworkServiceRequest) Descriptor() ([]byte, []int) { return fileDescriptor_361e8247d5a9945c, []int{0} } func (m *NetworkServiceRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NetworkServiceRequest.Unmarshal(m, b) } func (m *NetworkServiceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NetworkServiceRequest.Marshal(b, m, deterministic) } func (m *NetworkServiceRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_NetworkServiceRequest.Merge(m, src) } func (m *NetworkServiceRequest) XXX_Size() int { return xxx_messageInfo_NetworkServiceRequest.Size(m) } func (m *NetworkServiceRequest) XXX_DiscardUnknown() { xxx_messageInfo_NetworkServiceRequest.DiscardUnknown(m) } var xxx_messageInfo_NetworkServiceRequest proto.InternalMessageInfo func (m *NetworkServiceRequest) GetConnection() *connection.Connection { if m != nil { return m.Connection } return nil } func (m *NetworkServiceRequest) GetMechanismPreferences() []*connection.Mechanism { if m != nil { return m.MechanismPreferences } return nil } func init() { proto.RegisterType((*NetworkServiceRequest)(nil), "networkservice.NetworkServiceRequest") } func init()
var fileDescriptor_361e8247d5a9945c = []byte{ // 268 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0x5f, 0x4b, 0xc3, 0x30, 0x14, 0xc5, 0xa9, 0xa2, 0x42, 0x06, 0x43, 0xc2, 0x3a, 0x4a, 0x9f, 0x86, 0x20, 0xec, 0x29, 0x85, 0x0a, 0xfa, 0xee, 0x10, 0x44, 0x50, 0xa4, 0xbe, 0x09, 0x22, 0x6d, 0xb8, 0x6b, 0x83, 0x4d, 0x6e, 0x4c, 0x52, 0x65, 0x9f, 0xc3, 0x47, 0xbf, 0xac, 0xcc, 0xec, 0x4f, 0x3a, 0xb6, 0x97, 0x72, 0x39, 0xf7, 0xdc, 0x5f, 0x4f, 0xee, 0x25, 0x23, 0x05, 0xee, 0x1b, 0xcd, 0x87, 0x05, 0xf3, 0x25, 0x38, 0x30, 0x6d, 0xd0, 0x21, 0x1d, 0xf6, 0xd5, 0xf4, 0xad, 0x16, 0xae, 0xe9, 0x2a, 0xc6, 0x51, 0x66, 0xfd, 0x96, 0x04, 0xdb, 0xec, 0x93, 0x38, 0x2a, 0x67, 0xb0, 0xd5, 0x6d, 0xa9, 0x20, 0x2b, 0xb5, 0x58, 0x0a, 0x0a, 0xb8, 0x13, 0xa8, 0x82, 0xd2, 0xff, 0x2e, 0x4d, 0xb4, 0x5b, 0x68, 0xb0, 0x19, 0x48, 0xed, 0x16, 0xfe, 0xeb, 0x3b, 0x17, 0xbf, 0x11, 0x89, 0x9f, 0x3c, 0xfd, 0xc5, 0xd3, 0x0b, 0xf8, 0xec, 0xc0, 0x3a, 0x7a, 0x4d, 0xc8, 0x96, 0x93, 0x44, 0x93, 0x68, 0x3a, 0xc8, 0xc7, 0x2c, 0x40, 0xcf, 0x36, 0x65, 0x11, 0x38, 0xe9, 0x03, 0x89, 0x25, 0xf0, 0xa6, 0x54, 0xc2, 0xca, 0x77, 0x6d, 0x60, 0x0e, 0x06, 0x14, 0x07, 0x9b, 0x1c, 0x4d, 0x8e, 0xa7, 0x83, 0x3c, 0x0e, 0x11, 0x8f, 0x6b, 0x63, 0x31, 0xda, 0xcc, 0x3c, 0x6f, 0x47, 0xf2, 0x9f, 0x88, 0x0c, 0xfb, 0xe9, 0xe8, 0x3d, 0x39, 0x5b, 0x27, 0xbc, 0x64, 0x3b, 0xbb, 0xdd, 0xfb, 0x90, 0xf4, 0x40, 0x68, 0x7a, 0x43, 0x4e, 0x66, 0x2d, 0x5a, 0xa0, 0x07, 0x0c, 0xe9, 0x98, 0xd5, 0x88, 0x75, 0xbb, 0xba, 0x59, 0xd5, 0xcd, 0xd9, 0xdd, 0x72, 0x73, 0xb7, 0xe7, 0xaf, 0x3b, 0xe7, 0xab, 0x4e, 0xff, 0x1d, 0x57, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x2d, 0x6f, 0xf7, 0xed, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // NetworkServiceClient is the client API for NetworkService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type NetworkServiceClient interface { Request(ctx context.Context, in *NetworkServiceRequest, opts ...grpc.CallOption) (*connection.Connection, error) Close(ctx context.Context, in *connection.Connection, opts ...grpc.CallOption) (*empty.Empty, error) } type networkServiceClient struct { cc grpc.ClientConnInterface } func NewNetworkServiceClient(cc grpc.ClientConnInterface) NetworkServiceClient { return &networkServiceClient{cc} } func (c *networkServiceClient) Request(ctx context.Context, in *NetworkServiceRequest, opts ...grpc.CallOption) (*connection.Connection, error) { out := new(connection.Connection) err := c.cc.Invoke(ctx, "/networkservice.NetworkService/Request", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *networkServiceClient) Close(ctx context.Context, in *connection.Connection, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/networkservice.NetworkService/Close", in, out, opts...) if err != nil { return nil, err } return out, nil } // NetworkServiceServer is the server API for NetworkService service. type NetworkServiceServer interface { Request(context.Context, *NetworkServiceRequest) (*connection.Connection, error) Close(context.Context, *connection.Connection) (*empty.Empty, error) } // UnimplementedNetworkServiceServer can be embedded to have forward compatible implementations. type UnimplementedNetworkServiceServer struct { } func (*UnimplementedNetworkServiceServer) Request(ctx context.Context, req *NetworkServiceRequest) (*connection.Connection, error) { return nil, status.Errorf(codes.Unimplemented, "method Request not implemented") } func (*UnimplementedNetworkServiceServer) Close(ctx context.Context, req *connection.Connection) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Close not implemented") } func RegisterNetworkServiceServer(s *grpc.Server, srv NetworkServiceServer) { s.RegisterService(&_NetworkService_serviceDesc, srv) } func _NetworkService_Request_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(NetworkServiceRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(NetworkServiceServer).Request(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/networkservice.NetworkService/Request", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(NetworkServiceServer).Request(ctx, req.(*NetworkServiceRequest)) } return interceptor(ctx, in, info, handler) } func _NetworkService_Close_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(connection.Connection) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(NetworkServiceServer).Close(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/networkservice.NetworkService/Close", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(NetworkServiceServer).Close(ctx, req.(*connection.Connection)) } return interceptor(ctx, in, info, handler) } var _NetworkService_serviceDesc = grpc.ServiceDesc{ ServiceName: "networkservice.NetworkService", HandlerType: (*NetworkServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Request", Handler: _NetworkService_Request_Handler, }, { MethodName: "Close", Handler: _NetworkService_Close_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "networkservice.proto", }
{ proto.RegisterFile("networkservice.proto", fileDescriptor_361e8247d5a9945c) }
dns_services_gen.go
// Copyright 2017-2021 The Usacloud 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. // Code generated by 'github.com/sacloud/usacloud/tools/gen-commands'; DO NOT EDIT package services import ( service "github.com/sacloud/libsacloud/v2/helper/service/dns" "github.com/sacloud/usacloud/pkg/cli" "github.com/sacloud/usacloud/pkg/cmd/conv" ) func init()
{ setDefaultServiceFunc("dns", "list", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) req := &service.FindRequest{} if err := conv.ConvertTo(parameter, req); err != nil { return nil, err } if err := req.Validate(); err != nil { return nil, err } res, err := svc.FindWithContext(ctx, req) if err != nil { return nil, err } var results []interface{} for _, v := range res { results = append(results, v) } return results, nil }, ) setDefaultListAllFunc("dns", "list", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) res, err := svc.FindWithContext(ctx, &service.FindRequest{}) if err != nil { return nil, err } var results []interface{} for _, v := range res { results = append(results, v) } return results, nil }, ) setDefaultServiceFunc("dns", "create", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) req := &service.CreateRequest{} if err := conv.ConvertTo(parameter, req); err != nil { return nil, err } if err := req.Validate(); err != nil { return nil, err } res, err := svc.CreateWithContext(ctx, req) if err != nil { return nil, err } return []interface{}{res}, nil }, ) setDefaultListAllFunc("dns", "create", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) res, err := svc.FindWithContext(ctx, &service.FindRequest{}) if err != nil { return nil, err } var results []interface{} for _, v := range res { results = append(results, v) } return results, nil }, ) setDefaultServiceFunc("dns", "read", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) req := &service.ReadRequest{} if err := conv.ConvertTo(parameter, req); err != nil { return nil, err } if err := req.Validate(); err != nil { return nil, err } res, err := svc.ReadWithContext(ctx, req) if err != nil { return nil, err } return []interface{}{res}, nil }, ) setDefaultListAllFunc("dns", "read", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) res, err := svc.FindWithContext(ctx, &service.FindRequest{}) if err != nil { return nil, err } var results []interface{} for _, v := range res { results = append(results, v) } return results, nil }, ) setDefaultServiceFunc("dns", "update", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) req := &service.UpdateRequest{} if err := conv.ConvertTo(parameter, req); err != nil { return nil, err } if err := req.Validate(); err != nil { return nil, err } res, err := svc.UpdateWithContext(ctx, req) if err != nil { return nil, err } return []interface{}{res}, nil }, ) setDefaultListAllFunc("dns", "update", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) res, err := svc.FindWithContext(ctx, &service.FindRequest{}) if err != nil { return nil, err } var results []interface{} for _, v := range res { results = append(results, v) } return results, nil }, ) setDefaultServiceFunc("dns", "delete", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) req := &service.DeleteRequest{} if err := conv.ConvertTo(parameter, req); err != nil { return nil, err } if err := req.Validate(); err != nil { return nil, err } err := svc.DeleteWithContext(ctx, req) if err != nil { return nil, err } return nil, nil }, ) setDefaultListAllFunc("dns", "delete", func(ctx cli.Context, parameter interface{}) ([]interface{}, error) { svc := service.New(ctx.Client()) res, err := svc.FindWithContext(ctx, &service.FindRequest{}) if err != nil { return nil, err } var results []interface{} for _, v := range res { results = append(results, v) } return results, nil }, ) }
download_manager.py
from ftplib import FTP import popen2, time, sys directory = sys.argv[1] filename = sys.argv[2] download_dir = sys.argv[3] host = sys.argv[4] size_ftp = sys.argv[5] path_to_cvs = sys.argv[6] '''this commands needs to be redirected to /dev/null or it won't work, also can't read out from this for debugging b/c process will wait''' command = "python " + path_to_cvs + "/download_remote.py " + directory + " " + filename + " " + download_dir + " " + host + " >& /dev/null" print command e = popen2.Popen4(command,1) #output = e.fromchild.readlines() #errors = e.childerr.read() #print output #print errors downloaded = 'no' import time for j in range(600): time.sleep(1) print e.poll(), e.pid, j #break time cycle if completed from glob import glob file_there = glob(download_dir + "/" + directory + "/" + filename) print file_there downloaded = 'not' downloading = 'not' if len(file_there) > 0: import os stats = os.stat(download_dir + "/" + directory + "/" + filename)
size = stats[6] #print int(size_ftp), int(size), filename if int(size_ftp) == int(size): import os import signal os.kill(e.pid,signal.SIGKILL) os.system("kill -9 " + str(e.pid)) downloaded = 'yes' if e.poll() != -1: import os os.system("mv " + download_dir + "/" + directory + "/tmp" + host + filename + " " + download_dir + "/" + directory + "/" + filename) break if e.poll() != -1: import os os.system("rm " + download_dir + directory + "/tmp" + host + filename) break #kill if download times out and delete image if j == 598: import os import signal os.kill(e.pid,signal.SIGKILL) os.system("kill -9 " + str(e.pid)) os.system("rm " + download_dir + directory + "/tmp" + host + filename)
last_time = stats[-1]
cli.rs
use crate::CoreResult; use clap::ArgMatches; use itertools::Itertools; use migration_connector::*; use quaint::prelude::SqlFamily; use sql_migration_connector::SqlMigrationConnector; use std::collections::HashMap; use thiserror::Error; use url::Url; #[derive(Debug, Error)] pub enum CliError { #[error("Known error: {:?}", error)] Known { error: user_facing_errors::KnownError, exit_code: i32, }, #[error("{}", error)] Unknown { error: migration_connector::ErrorKind, exit_code: i32, }, #[error("No command defined")] NoCommandDefined, #[error("Unknown error occured: {0}")] Other(String), } impl CliError { pub fn exit_code(&self) -> i32 { match self { CliError::Known { exit_code, .. } => *exit_code, CliError::Unknown { exit_code, .. } => *exit_code, _ => 255, } } /// The errors spec error code, if applicable #[cfg(test)] fn error_code(&self) -> Option<&str> {
} => Some(error_code), _ => None, } } } pub fn exit_code(error_kind: &migration_connector::ErrorKind) -> i32 { match error_kind { ErrorKind::DatabaseDoesNotExist { .. } => 1, ErrorKind::DatabaseAccessDenied { .. } => 2, ErrorKind::AuthenticationFailed { .. } => 3, ErrorKind::ConnectTimeout | ErrorKind::Timeout => 4, ErrorKind::DatabaseAlreadyExists { .. } => 5, ErrorKind::TlsError { .. } => 6, _ => 255, } } impl From<ConnectorError> for CliError { fn from(e: ConnectorError) -> Self { let ConnectorError { user_facing_error, kind: error_kind, } = e; let exit_code = exit_code(&error_kind); match user_facing_error { Some(error) => CliError::Known { error, exit_code }, None => CliError::Unknown { error: error_kind, exit_code, }, } } } impl From<crate::Error> for CliError { fn from(e: crate::Error) -> Self { match e { crate::Error::ConnectorError(e) => e.into(), e => Self::Other(format!("{}", e)), } } } pub async fn run(matches: &ArgMatches<'_>, datasource: &str) -> Result<String, CliError> { if matches.is_present("can_connect_to_database") { create_conn(datasource, false).await?; Ok("Connection successful".into()) } else if matches.is_present("create_database") { let (db_name, conn) = create_conn(datasource, true).await?; conn.create_database(&db_name).await?; Ok(format!("Database '{}' created successfully.", db_name)) } else { Err(CliError::NoCommandDefined) } } fn fetch_db_name(url: &Url, default: &str) -> String { let result = match url.path_segments() { Some(mut segments) => segments.next().unwrap_or(default), None => default, }; String::from(result) } async fn create_conn(datasource: &str, admin_mode: bool) -> CoreResult<(String, Box<SqlMigrationConnector>)> { let mut url = Url::parse(datasource).expect("Invalid url in the datasource"); let sql_family = SqlFamily::from_scheme(url.scheme()); match sql_family { Some(SqlFamily::Sqlite) => { let inner = SqlMigrationConnector::new(datasource, "sqlite").await?; Ok((String::new(), Box::new(inner))) } Some(SqlFamily::Postgres) => { let db_name = fetch_db_name(&url, "postgres"); let connector = if admin_mode { create_postgres_admin_conn(url).await? } else { SqlMigrationConnector::new(url.as_str(), "postgres").await? }; Ok((db_name, Box::new(connector))) } Some(SqlFamily::Mysql) => { let db_name = fetch_db_name(&url, "mysql"); if admin_mode { url.set_path(""); } let inner = SqlMigrationConnector::new(url.as_str(), "mysql").await?; Ok((db_name, Box::new(inner))) } None => unimplemented!("Connector {} is not supported yet", url.scheme()), } } /// Try to connect as an admin to a postgres database. We try to pick a default database from which /// we can create another database. async fn create_postgres_admin_conn(mut url: Url) -> CoreResult<SqlMigrationConnector> { let candidate_default_databases = &["postgres", "template1"]; let mut params: HashMap<String, String> = url.query_pairs().into_owned().collect(); params.remove("schema"); let params = params.into_iter().map(|(k, v)| format!("{}={}", k, v)).join("&"); url.set_query(Some(&params)); let mut connector = None; for database_name in candidate_default_databases { url.set_path(database_name); match SqlMigrationConnector::new(url.as_str(), "postgresql").await { // If the database does not exist, try the next one. Err(err) => match &err.kind { migration_connector::ErrorKind::DatabaseDoesNotExist { .. } => (), _other_outcome => { connector = Some(Err(err)); break; } }, // If the outcome is anything else, use this. other_outcome => { connector = Some(other_outcome); break; } } } let connector = connector .ok_or_else(|| { ConnectorError::from_kind(ErrorKind::DatabaseCreationFailed { explanation: "Prisma could not connect to a default database (`postgres` or `template1`), it cannot create the specified database.".to_owned() }) })??; Ok(connector) } pub fn clap_app() -> clap::App<'static, 'static> { use clap::{App, Arg, SubCommand}; App::new("Prisma Migration Engine") .version(env!("CARGO_PKG_VERSION")) .arg( Arg::with_name("datamodel_location") .short("d") .long("datamodel") .value_name("FILE") .help("Path to the datamodel.") .takes_value(true) .required(false), ) .arg( Arg::with_name("single_cmd") .short("s") .long("single_cmd") .help("Run only a single command, then exit") .takes_value(false) .required(false), ) .arg( Arg::with_name("version") .long("version") .help("Prints the server commit ID") .takes_value(false) .required(false), ) .subcommand( SubCommand::with_name("cli") .about("Doesn't start a server, but allows running specific commands against Prisma.") .arg( Arg::with_name("datasource") .long("datasource") .short("d") .help("The connection string to the database") .takes_value(true) .required(true), ) .arg( Arg::with_name("can_connect_to_database") .long("can_connect_to_database") .help("Does the database connection string work") .takes_value(false) .required(false), ) .arg( Arg::with_name("create_database") .long("create_database") .help("Create an empty database defined in the configuration string.") .takes_value(false) .required(false), ), ) } pub fn render_error(cli_error: CliError) -> user_facing_errors::Error { use user_facing_errors::UnknownError; match cli_error { CliError::Known { error, .. } => error.into(), other => UnknownError { message: format!("{}", other), backtrace: None, } .into(), } } #[cfg(test)] mod tests { use super::CliError; use clap::ArgMatches; use once_cell::sync::Lazy; use quaint::{prelude::*, single::Quaint}; static TEST_ASYNC_RUNTIME: Lazy<std::sync::Mutex<tokio::runtime::Runtime>> = Lazy::new(|| { std::sync::Mutex::new(tokio::runtime::Runtime::new().expect("failed to start tokio test runtime")) }); fn run_sync(matches: &ArgMatches<'_>, datasource: &str) -> Result<String, CliError> { let mut rt = TEST_ASYNC_RUNTIME.lock().unwrap(); rt.block_on(super::run(matches, datasource)) } async fn run(args: &[&str], datasource: &str) -> Result<String, CliError> { let mut complete_args = vec!["me", "cli", "--datasource", datasource]; complete_args.extend(args); let matches = super::clap_app().get_matches_from(complete_args); super::run(&matches.subcommand_matches("cli").unwrap(), datasource).await } fn with_cli<F>(matches: Vec<&str>, f: F) -> Result<(), Box<dyn std::any::Any + Send + 'static>> where F: FnOnce(&clap::ArgMatches) -> () + std::panic::UnwindSafe, { let matches = clap::App::new("cli") .arg( clap::Arg::with_name("can_connect_to_database") .long("can_connect_to_database") .takes_value(false) .required(false), ) .arg( clap::Arg::with_name("create_database") .long("create_database") .help("Create an empty database defined in the configuration string.") .takes_value(false) .required(false), ) .get_matches_from(matches); std::panic::catch_unwind(|| f(&matches)) } fn postgres_url(db: Option<&str>) -> String { postgres_url_with_scheme(db, "postgresql") } fn postgres_url_with_scheme(db: Option<&str>, scheme: &str) -> String { match std::env::var("IS_BUILDKITE") { Ok(_) => format!( "{scheme}://postgres:prisma@test-db-postgres-10:5432/{db_name}", scheme = scheme, db_name = db.unwrap_or("postgres") ), _ => format!( "{scheme}://postgres:[email protected]:5432/{db_name}?schema=migration-engine", scheme = scheme, db_name = db.unwrap_or("postgres") ), } } fn mysql_url(db: Option<&str>) -> String { match std::env::var("IS_BUILDKITE") { Ok(_) => format!("mysql://root:prisma@test-db-mysql-5-7:3306/{}", db.unwrap_or("")), _ => format!("mysql://root:[email protected]:3306/{}", db.unwrap_or("")), } } #[test] fn test_with_missing_command() { with_cli(vec!["cli"], |matches| { assert_eq!( "No command defined", &run_sync(&matches, &mysql_url(None)).unwrap_err().to_string() ); }) .unwrap(); } #[test] fn test_connecting_with_a_working_mysql_connection_string() { with_cli(vec!["cli", "--can_connect_to_database"], |matches| { assert_eq!( String::from("Connection successful"), run_sync(&matches, &mysql_url(None)).unwrap() ) }) .unwrap(); } #[test] fn test_connecting_with_a_non_working_mysql_connection_string() { let dm = mysql_url(Some("this_does_not_exist")); with_cli(vec!["cli", "--can_connect_to_database"], |matches| { assert_eq!("P1003", run_sync(&matches, &dm).unwrap_err().error_code().unwrap()); }) .unwrap(); } #[test] fn test_connecting_with_a_working_psql_connection_string() { with_cli(vec!["cli", "--can_connect_to_database"], |matches| { assert_eq!( String::from("Connection successful"), run_sync(&matches, &postgres_url(None)).unwrap() ); }) .unwrap(); } #[test] fn test_connecting_with_a_working_psql_connection_string_with_postgres_scheme() { with_cli(vec!["cli", "--can_connect_to_database"], |matches| { assert_eq!( String::from("Connection successful"), run_sync(&matches, &postgres_url_with_scheme(None, "postgres")).unwrap() ); }) .unwrap(); } #[test] fn test_connecting_with_a_non_working_psql_connection_string() { let dm = postgres_url(Some("this_does_not_exist")); with_cli(vec!["cli", "--can_connect_to_database"], |matches| { assert_eq!("P1003", run_sync(&matches, &dm).unwrap_err().error_code().unwrap()); }) .unwrap(); } #[tokio::test] async fn test_create_mysql_database() { let url = mysql_url(Some("this_should_exist")); let res = run(&["--create_database"], &url).await; assert_eq!( "Database 'this_should_exist' created successfully.", res.as_ref().unwrap() ); if let Ok(_) = res { let res = run(&["--can_connect_to_database"], &url).await; assert_eq!("Connection successful", res.as_ref().unwrap()); { let uri = mysql_url(None); let conn = Quaint::new(&uri).await.unwrap(); conn.execute_raw("DROP DATABASE `this_should_exist`", &[]) .await .unwrap(); } res.unwrap(); } else { res.unwrap(); } } #[tokio::test] async fn test_create_psql_database() { let url = postgres_url(Some("this_should_exist")); let res = run(&["--create_database"], &url).await; assert_eq!( "Database 'this_should_exist' created successfully.", res.as_ref().unwrap() ); if let Ok(_) = res { let res = run(&["--can_connect_to_database"], &url).await; assert_eq!("Connection successful", res.as_ref().unwrap()); { let uri = postgres_url(None); let conn = Quaint::new(&uri).await.unwrap(); conn.execute_raw("DROP DATABASE \"this_should_exist\"", &[]) .await .unwrap(); } res.unwrap(); } } #[test] fn test_fetch_db_name() { let url: url::Url = "postgresql://postgres:[email protected]:5432/pgres?schema=test_schema" .parse() .unwrap(); let db_name = super::fetch_db_name(&url, "postgres"); assert_eq!(db_name, "pgres"); } #[test] fn test_fetch_db_name_with_postgres_scheme() { let url: url::Url = "postgres://postgres:[email protected]:5432/pgres?schema=test_schema" .parse() .unwrap(); let db_name = super::fetch_db_name(&url, "postgres"); assert_eq!(db_name, "pgres"); } }
match self { CliError::Known { error: user_facing_errors::KnownError { error_code, .. }, ..
main.py
class Solution:
def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: res = [] x, y = toBeRemoved for interval in intervals: l, h = interval if l <= x <= h <= y: res.append([l, x]) elif x <= l <= y <= h: res.append([y, h]) elif l <= x <= y <= h: res.append([l, x]) res.append([y, h]) elif x <= l <= h <= y: continue else: res.append([l, h]) return res
integrationtestharness.go
/* Copyright 2017 The Kubernetes 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 testutils import ( "io/ioutil" "os" "path" "path/filepath" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/route53" "github.com/gophercloud/gophercloud/openstack/compute/v2/flavors" "github.com/gophercloud/gophercloud/openstack/dns/v2/zones" "github.com/gophercloud/gophercloud/openstack/imageservice/v2/images" "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/external" "github.com/gophercloud/gophercloud/openstack/networking/v2/networks" "github.com/gophercloud/gophercloud/openstack/networking/v2/subnets" "k8s.io/klog/v2" kopsroot "k8s.io/kops" "k8s.io/kops/cloudmock/aws/mockautoscaling" "k8s.io/kops/cloudmock/aws/mockec2" "k8s.io/kops/cloudmock/aws/mockelb" "k8s.io/kops/cloudmock/aws/mockelbv2" "k8s.io/kops/cloudmock/aws/mockiam" "k8s.io/kops/cloudmock/aws/mockroute53" "k8s.io/kops/cloudmock/openstack/mockblockstorage" "k8s.io/kops/cloudmock/openstack/mockcompute" "k8s.io/kops/cloudmock/openstack/mockdns" "k8s.io/kops/cloudmock/openstack/mockimage" "k8s.io/kops/cloudmock/openstack/mockloadbalancer" "k8s.io/kops/cloudmock/openstack/mocknetworking" "k8s.io/kops/pkg/apis/kops" "k8s.io/kops/pkg/pki" "k8s.io/kops/upup/pkg/fi" "k8s.io/kops/upup/pkg/fi/cloudup/awsup" "k8s.io/kops/upup/pkg/fi/cloudup/gce" "k8s.io/kops/upup/pkg/fi/cloudup/openstack" "k8s.io/kops/util/pkg/vfs" ) type IntegrationTestHarness struct { TempDir string T *testing.T // The original kops DefaultChannelBase value, restored on Close originalDefaultChannelBase string // originalKopsVersion is the original kops.Version value, restored on Close originalKopsVersion string // originalPKIDefaultPrivateKeySize is the saved pki.DefaultPrivateKeySize value, restored on Close originalPKIDefaultPrivateKeySize int } func NewIntegrationTestHarness(t *testing.T) *IntegrationTestHarness { h := &IntegrationTestHarness{} tempDir, err := ioutil.TempDir("", "test") if err != nil { t.Fatalf("failed to create temp dir: %v", err) } h.TempDir = tempDir vfs.Context.ResetMemfsContext(true) // Generate much smaller keys, as this is often the bottleneck for tests h.originalPKIDefaultPrivateKeySize = pki.DefaultPrivateKeySize pki.DefaultPrivateKeySize = 512 // Replace the default channel path with a local filesystem path, so we don't try to retrieve it from a server {
t.Fatalf("error resolving stable channel path: %v", err) } channelPath += "/" h.originalDefaultChannelBase = kops.DefaultChannelBase // Make sure any platform-specific separators that aren't /, are converted to / for use in a file: protocol URL kops.DefaultChannelBase = "file://" + filepath.ToSlash(channelPath) } return h } func (h *IntegrationTestHarness) Close() { if h.TempDir != "" { if os.Getenv("KEEP_TEMP_DIR") != "" { klog.Infof("NOT removing temp directory, because KEEP_TEMP_DIR is set: %s", h.TempDir) } else { err := os.RemoveAll(h.TempDir) if err != nil { h.T.Fatalf("failed to remove temp dir %q: %v", h.TempDir, err) } } } if h.originalKopsVersion != "" { kopsroot.Version = h.originalKopsVersion } if h.originalDefaultChannelBase != "" { kops.DefaultChannelBase = h.originalDefaultChannelBase } if h.originalPKIDefaultPrivateKeySize != 0 { pki.DefaultPrivateKeySize = h.originalPKIDefaultPrivateKeySize } } func (h *IntegrationTestHarness) SetupMockAWS() *awsup.MockAWSCloud { cloud := awsup.InstallMockAWSCloud("us-test-1", "abc") mockEC2 := &mockec2.MockEC2{} cloud.MockEC2 = mockEC2 mockRoute53 := &mockroute53.MockRoute53{} cloud.MockRoute53 = mockRoute53 mockELB := &mockelb.MockELB{} cloud.MockELB = mockELB mockELBV2 := &mockelbv2.MockELBV2{} cloud.MockELBV2 = mockELBV2 mockIAM := &mockiam.MockIAM{} cloud.MockIAM = mockIAM mockAutoscaling := &mockautoscaling.MockAutoscaling{} cloud.MockAutoscaling = mockAutoscaling mockRoute53.MockCreateZone(&route53.HostedZone{ Id: aws.String("/hostedzone/Z1AFAKE1ZON3YO"), Name: aws.String("example.com."), Config: &route53.HostedZoneConfig{ PrivateZone: aws.Bool(false), }, }, nil) mockRoute53.MockCreateZone(&route53.HostedZone{ Id: aws.String("/hostedzone/Z2AFAKE1ZON3NO"), Name: aws.String("internal.example.com."), Config: &route53.HostedZoneConfig{ PrivateZone: aws.Bool(true), }, }, []*route53.VPC{{ VPCId: aws.String("vpc-23456789"), }}) mockRoute53.MockCreateZone(&route53.HostedZone{ Id: aws.String("/hostedzone/Z3AFAKE1ZOMORE"), Name: aws.String("private.example.com."), Config: &route53.HostedZoneConfig{ PrivateZone: aws.Bool(true), }, }, []*route53.VPC{{ VPCId: aws.String("vpc-12345678"), }}) mockEC2.Images = append(mockEC2.Images, &ec2.Image{ CreationDate: aws.String("2016-10-21T20:07:19.000Z"), ImageId: aws.String("ami-12345678"), Name: aws.String("k8s-1.4-debian-jessie-amd64-hvm-ebs-2016-10-21"), OwnerId: aws.String(awsup.WellKnownAccountKopeio), RootDeviceName: aws.String("/dev/xvda"), }) mockEC2.Images = append(mockEC2.Images, &ec2.Image{ CreationDate: aws.String("2017-01-09T17:08:27.000Z"), ImageId: aws.String("ami-15000000"), Name: aws.String("k8s-1.5-debian-jessie-amd64-hvm-ebs-2017-01-09"), OwnerId: aws.String(awsup.WellKnownAccountKopeio), RootDeviceName: aws.String("/dev/xvda"), }) mockEC2.Images = append(mockEC2.Images, &ec2.Image{ CreationDate: aws.String("2019-08-06T00:00:00.000Z"), ImageId: aws.String("ami-11400000"), Name: aws.String("k8s-1.14-debian-stretch-amd64-hvm-ebs-2019-08-16"), OwnerId: aws.String(awsup.WellKnownAccountKopeio), RootDeviceName: aws.String("/dev/xvda"), }) mockEC2.CreateVpcWithId(&ec2.CreateVpcInput{ CidrBlock: aws.String("172.20.0.0/16"), }, "vpc-12345678") mockEC2.CreateInternetGateway(&ec2.CreateInternetGatewayInput{}) mockEC2.AttachInternetGateway(&ec2.AttachInternetGatewayInput{ InternetGatewayId: aws.String("igw-1"), VpcId: aws.String("vpc-12345678"), }) mockEC2.CreateRouteTableWithId(&ec2.CreateRouteTableInput{ VpcId: aws.String("vpc-12345678"), }, "rtb-12345678") mockEC2.CreateSubnetWithId(&ec2.CreateSubnetInput{ VpcId: aws.String("vpc-12345678"), AvailabilityZone: aws.String("us-test-1a"), CidrBlock: aws.String("172.20.32.0/19"), }, "subnet-12345678") mockEC2.AssociateRouteTable(&ec2.AssociateRouteTableInput{ RouteTableId: aws.String("rtb-12345678"), SubnetId: aws.String("subnet-12345678"), }) mockEC2.CreateSubnetWithId(&ec2.CreateSubnetInput{ VpcId: aws.String("vpc-12345678"), AvailabilityZone: aws.String("us-test-1a"), CidrBlock: aws.String("172.20.4.0/22"), }, "subnet-abcdef") mockEC2.CreateSubnetWithId(&ec2.CreateSubnetInput{ VpcId: aws.String("vpc-12345678"), AvailabilityZone: aws.String("us-test-1b"), CidrBlock: aws.String("172.20.8.0/22"), }, "subnet-b2345678") mockEC2.AssociateRouteTable(&ec2.AssociateRouteTableInput{ RouteTableId: aws.String("rtb-12345678"), SubnetId: aws.String("subnet-abcdef"), }) mockEC2.AllocateAddressWithId(&ec2.AllocateAddressInput{ Address: aws.String("123.45.67.8"), }, "eipalloc-12345678") mockEC2.CreateNatGatewayWithId(&ec2.CreateNatGatewayInput{ SubnetId: aws.String("subnet-12345678"), AllocationId: aws.String("eipalloc-12345678"), }, "nat-a2345678") mockEC2.AllocateAddressWithId(&ec2.AllocateAddressInput{ Address: aws.String("2.22.22.22"), }, "eipalloc-b2345678") mockEC2.CreateNatGatewayWithId(&ec2.CreateNatGatewayInput{ SubnetId: aws.String("subnet-b2345678"), AllocationId: aws.String("eipalloc-b2345678"), }, "nat-b2345678") return cloud } // SetupMockGCE configures a mock GCE cloud provider func (h *IntegrationTestHarness) SetupMockGCE() { gce.InstallMockGCECloud("us-test1", "testproject") } func (h *IntegrationTestHarness) SetupMockOpenstack() *openstack.MockCloud { c := openstack.InstallMockOpenstackCloud("us-test1") c.MockCinderClient = mockblockstorage.CreateClient() c.MockNeutronClient = mocknetworking.CreateClient() c.MockLBClient = mockloadbalancer.CreateClient() c.MockNovaClient = mockcompute.CreateClient(c.MockNeutronClient.ServiceClient()) c.MockDNSClient = mockdns.CreateClient() c.MockImageClient = mockimage.CreateClient() extNetworkName := "external" networkCreateOpts := networks.CreateOpts{ Name: extNetworkName, AdminStateUp: fi.Bool(true), } extNetwork := external.CreateOptsExt{ CreateOptsBuilder: networkCreateOpts, External: fi.Bool(true), } c.CreateNetwork(extNetwork) c.SetExternalNetwork(&extNetworkName) extSubnetName := "external" extSubnet := subnets.CreateOpts{ Name: extSubnetName, NetworkID: extNetworkName, EnableDHCP: fi.Bool(true), CIDR: "172.20.0.0/22", } c.CreateSubnet(extSubnet) c.SetExternalSubnet(fi.String(extSubnetName)) c.SetLBFloatingSubnet(fi.String(extSubnetName)) images.Create(c.MockImageClient.ServiceClient(), images.CreateOpts{ Name: "Ubuntu-20.04", MinDisk: 12, }) flavors.Create(c.MockNovaClient.ServiceClient(), flavors.CreateOpts{ Name: "n1-standard-2", RAM: 8192, VCPUs: 4, Disk: fi.Int(16), }) flavors.Create(c.MockNovaClient.ServiceClient(), flavors.CreateOpts{ Name: "n1-standard-1", RAM: 8192, VCPUs: 4, Disk: fi.Int(16), }) zones.Create(c.MockDNSClient.ServiceClient(), zones.CreateOpts{ Name: "minimal-openstack.k8s.local", }) return c } // MockKopsVersion will set the kops version to the specified value, until Close is called func (h *IntegrationTestHarness) MockKopsVersion(version string) { if h.originalKopsVersion != "" { h.T.Fatalf("MockKopsVersion called twice (%s and %s)", version, h.originalKopsVersion) } h.originalKopsVersion = kopsroot.Version kopsroot.Version = version }
channelPath, err := filepath.Abs(path.Join("../../channels/")) if err != nil {
templates.ts
export type TemplateFileContext = { dbType: string, apiSecret: string, projectName: string, dockerVersion: string, driverEnvVariables?: string[], }; export type Template = { scripts: Record<string, string>, files: Record<string, (ctx: TemplateFileContext) => string>, dependencies?: string[], devDependencies?: string[], }; const indexJs = `const CubejsServer = require('@cubejs-backend/server'); const server = new CubejsServer(); server.listen().then(({ version, port }) => { console.log(\`🚀 Cube.js server (\${version}) is listening on \${port}\`); }).catch(e => { console.error('Fatal error during server start: '); console.error(e.stack || e); }); `; const handlerJs = `module.exports = require('@cubejs-backend/serverless'); `; // Shared environment variables, across all DB types const sharedDotEnvVars = env => `CUBEJS_DEV_MODE=true CUBEJS_DB_TYPE=${env.dbType} CUBEJS_API_SECRET=${env.apiSecret} CUBEJS_EXTERNAL_DEFAULT=true CUBEJS_SCHEDULED_REFRESH_DEFAULT=true`; const defaultDotEnvVars = env => `# Cube.js environment variables: https://cube.dev/docs/reference/environment-variables ${sharedDotEnvVars(env)} CUBEJS_WEB_SOCKETS=true`; const athenaDotEnvVars = env => `# Cube.js environment variables: https://cube.dev/docs/reference/environment-variables CUBEJS_AWS_KEY=<YOUR ATHENA AWS KEY HERE> CUBEJS_AWS_SECRET=<YOUR ATHENA SECRET KEY HERE> CUBEJS_AWS_REGION=<AWS REGION STRING, e.g. us-east-1> # You can find the Athena S3 Output location here: https://docs.aws.amazon.com/athena/latest/ug/querying.html CUBEJS_AWS_S3_OUTPUT_LOCATION=<S3 OUTPUT LOCATION> CUBEJS_JDBC_DRIVER=athena ${sharedDotEnvVars(env)}`; const mongobiDotEnvVars = env => `${defaultDotEnvVars(env)} #CUBEJS_DB_SSL=<SSL_PROFILE> #CUBEJS_DB_SSL_CA=<SSL_CA> #CUBEJS_DB_SSL_CERT=<SSL_CERT> #CUBEJS_DB_SSL_CIPHERS=<SSL_CIPHERS> #CUBEJS_DB_SSL_PASSPHRASE=<SSL_PASSPHRASE> #CUBEJS_DB_SSL_REJECT_UNAUTHORIZED=<SSL_REJECT_UNAUTHORIZED>`; const dotEnv = env => { if (env.driverEnvVariables) { const envVars = env.driverEnvVariables.map(v => `${v}=<${v.replace('CUBEJS', 'YOUR')}>`).join('\n'); return `${envVars}\n${sharedDotEnvVars(env)}`; } return { athena: athenaDotEnvVars(env), mongobi: mongobiDotEnvVars(env) }[env.dbType] || defaultDotEnvVars(env); }; const gitIgnore = `.env node_modules .cubestore upstream `; const serverlessYml = env => `service: ${env.projectName} provider: name: aws runtime: nodejs12.x iamRoleStatements: - Effect: "Allow" Action: - "sns:*" # Athena permissions # - "athena:*" # - "s3:*" # - "glue:*" Resource: '*' # When you uncomment vpc please make sure lambda has access to internet: https://medium.com/@philippholly/aws-lambda-enable-outgoing-internet-access-within-vpc-8dd250e11e12 # vpc: # securityGroupIds: # - sg-12345678901234567 # Your DB and Redis security groups here # subnetIds: # - subnet-12345678901234567 # Put here subnet with access to your DB, Redis and internet. For internet access 0.0.0.0/0 should be routed through NAT only for this subnet! environment: CUBEJS_DB_HOST: <YOUR_DB_HOST_HERE> CUBEJS_DB_NAME: <YOUR_DB_NAME_HERE> CUBEJS_DB_USER: <YOUR_DB_USER_HERE> CUBEJS_DB_PASS: <YOUR_DB_PASS_HERE> CUBEJS_DB_PORT: <YOUR_DB_PORT_HERE> CUBEJS_REDIS_URL: <YOUR_REDIS_URL_HERE> CUBEJS_DB_TYPE: ${env.dbType} CUBEJS_API_SECRET: ${env.apiSecret} CUBEJS_APP: "\${self:service.name}-\${self:provider.stage}" NODE_ENV: production AWS_ACCOUNT_ID: Fn::Join: - "" - - Ref: "AWS::AccountId" functions: cubejs: handler: index.api timeout: 30
path: / method: GET - http: path: /{proxy+} method: ANY cors: origin: '*' headers: - Content-Type - Authorization - X-Request-Id - X-Amz-Date - X-Amz-Security-Token - X-Api-Key cubejsProcess: handler: index.process timeout: 630 events: - sns: "\${self:service.name}-\${self:provider.stage}-process" plugins: - serverless-express `; const serverlessGoogleYml = env => `service: ${env.projectName} # NOTE: Don't put the word "google" in here provider: name: google stage: dev runtime: nodejs12 region: us-central1 project: <YOUR_GOOGLE_PROJECT_ID_HERE> # The GCF credentials can be a little tricky to set up. Luckily we've documented this for you here: # https://serverless.com/framework/docs/providers/google/guide/credentials/ # # the path to the credentials file needs to be absolute credentials: </path/to/service/account/keyfile.json> environment: CUBEJS_DB_TYPE: ${env.dbType} CUBEJS_DB_HOST: <YOUR_DB_HOST_HERE> CUBEJS_DB_NAME: <YOUR_DB_NAME_HERE> CUBEJS_DB_USER: <YOUR_DB_USER_HERE> CUBEJS_DB_PASS: <YOUR_DB_PASS_HERE> CUBEJS_DB_PORT: <YOUR_DB_PORT_HERE> CUBEJS_DB_BQ_PROJECT_ID: "\${self:provider.project}" CUBEJS_REDIS_URL: <YOUR_REDIS_URL_HERE> CUBEJS_API_SECRET: ${env.apiSecret} CUBEJS_APP: "\${self:service.name}-\${self:provider.stage}" CUBEJS_SERVERLESS_PLATFORM: "\${self:provider.name}" plugins: - serverless-google-cloudfunctions - serverless-express # needs more granular excluding in production as only the serverless provider npm # package should be excluded (and not the whole node_modules directory) package: exclude: - node_modules/** - .gitignore - .git/** functions: cubejs: handler: api events: - http: ANY cubejsProcess: handler: process events: - event: eventType: providers/cloud.pubsub/eventTypes/topic.publish resource: "projects/\${self:provider.project}/topics/\${self:service.name}-\${self:provider.stage}-process" `; const ordersJs = `cube(\`Orders\`, { sql: \` select 1 as id, 100 as amount, 'new' status UNION ALL select 2 as id, 200 as amount, 'new' status UNION ALL select 3 as id, 300 as amount, 'processed' status UNION ALL select 4 as id, 500 as amount, 'processed' status UNION ALL select 5 as id, 600 as amount, 'shipped' status \`, preAggregations: { // Pre-Aggregations definitions go here // Learn more here: https://cube.dev/docs/caching/pre-aggregations/getting-started }, measures: { count: { type: \`count\` }, totalAmount: { sql: \`amount\`, type: \`sum\` } }, dimensions: { status: { sql: \`status\`, type: \`string\` } } }); `; const cubeJs = `// Cube.js configuration options: https://cube.dev/docs/config module.exports = { }; `; const dockerCompose = (ctx: TemplateFileContext) => ` version: '2.2' services: cube: image: cubejs/cube:${ctx.dockerVersion} ports: # It's better to use random port binding for 4000/3000 ports # without it you will not able to start multiple projects inside docker # - 4000 # - 3000 # 4000 is a port for Cube.js API - 4000:4000 # 3000 is a port for Playground web-server - 3000:3000 env_file: .env volumes: - .:/cube/conf # We ignore Cube.js deps, because they are built-in inside the official Docker image - .empty:/cube/conf/node_modules/@cubejs-backend/ `; const templates: Record<string, Template> = { docker: { scripts: { dev: 'cubejs-server', }, files: { 'cube.js': () => cubeJs, 'docker-compose.yml': dockerCompose, '.env': dotEnv, '.gitignore': () => gitIgnore, 'schema/Orders.js': () => ordersJs } }, express: { scripts: { dev: 'node index.js', }, files: { 'index.js': () => indexJs, '.env': dotEnv, '.gitignore': () => gitIgnore, 'schema/Orders.js': () => ordersJs } }, serverless: { scripts: { dev: 'cubejs-dev-server', }, files: { 'index.js': () => handlerJs, 'serverless.yml': serverlessYml, '.env': dotEnv, '.gitignore': () => gitIgnore, 'schema/Orders.js': () => ordersJs }, dependencies: ['@cubejs-backend/serverless', '@cubejs-backend/serverless-aws'] }, 'serverless-google': { scripts: { dev: 'cubejs-dev-server', }, files: { 'index.js': () => handlerJs, 'serverless.yml': serverlessGoogleYml, '.env': dotEnv, '.gitignore': () => gitIgnore, 'schema/Orders.js': () => ordersJs }, dependencies: ['@cubejs-backend/serverless', '@cubejs-backend/serverless-google'], devDependencies: ['serverless-google-cloudfunctions'] } }; export default templates;
events: - http:
issue-19121.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a partially specified trait object with unspecified associated // type does not ICE. #![feature(associated_types)] trait Foo { type A; } fn bar(x: &Foo) {} // FIXME(#19482) -- `Foo` should specify `A`, but this is not // currently enforced except at object creation pub fn main()
{}
toolbox.py
# -*- coding: utf-8 -*- import functools import os from anima.env.mayaEnv.animation import Animation from anima.env.mayaEnv.general import General from anima.env.mayaEnv.modeling import Modeling from anima.env.mayaEnv.previs import Previs from anima.env.mayaEnv.reference import Reference from anima.env.mayaEnv.render import Render from anima.env.mayaEnv.rigging import Rigging import pymel.core as pm import maya.mel as mel from anima.env.mayaEnv import auxiliary, camera_tools __last_commands__ = [] # list of dictionaries __last_tab__ = 'ANIMA_TOOLBOX_LAST_TAB_INDEX' __commands__ = [] def repeater(index): """repeats the last command with the given index """ global __last_commands__ try: call_data = __last_commands__[index] return call_data[0](*call_data[1], **call_data[2]) except IndexError: return None def repeat_last(call_data): """own implementation of pm.repeatLast """ global __last_commands__ index = len(__last_commands__) callable_ = call_data[0] args = call_data[1] kwargs = call_data[2] command = \ 'print \\"\\";python(\\\"from anima.env.mayaEnv.toolbox import ' \ 'repeater; repeater(%s);\\\");' % index repeat_last_command = 'repeatLast -ac "%(command)s" -acl "%(label)s";' % { 'command': command, 'label': callable_.__name__ } print(repeat_last_command) pm.mel.eval(repeat_last_command) __last_commands__.append(call_data) # also call the callable callable_(*args, **kwargs) def repeated_callback(callable_, *args, **kwargs): """Adds the given callable to the last commands list and adds a caller to the pm.repeatLast """ return pm.Callback( repeat_last, [callable_, args, kwargs] ) class Color(object): """a simple color class """ colors = [ (1.000, 0.500, 0.666), (1.000, 0.833, 0.500), (0.666, 1.000, 0.500), (0.500, 1.000, 0.833), (0.500, 0.666, 1.000), (0.833, 0.500, 1.000) ] def __init__(self, index=0): self.index = index self.max_colors = len(self.colors) def change(self): """updates the index to the next one """ self.index = int((self.index + 1) % self.max_colors) def reset(self): """resets the color index """ self.index = 0 @property def color(self): """returns the current color values """ return self.colors[self.index] def filter_tools(search_text): """filters toolbox :param str search_text: The search_text """ for command in __commands__: uitype = command.type() if uitype == 'button': label = command.getLabel() if search_text.lower() not in label.lower(): command.setVisible(False) else: command.setVisible(True) elif uitype == 'rowLayout': # get the children children = command.children() matched_children = False for c in children: c_uitype = c.type() if c_uitype in ['button', 'staticText'] and \ search_text in c.getLabel().lower(): matched_children = True break if not matched_children: command.setVisible(False) else: command.setVisible(True) def UI(): # window setup width = 260 height = 650 row_spacing = 3 color = Color() # init the __commands LUT global __commands__ __commands__ = [] if pm.dockControl("toolbox_dockControl", q=True, ex=True): pm.deleteUI("toolbox_dockControl") window_name = "toolbox_window" if pm.window(window_name, q=True, ex=True): pm.deleteUI(window_name, wnd=True) toolbox_window = pm.window( window_name, wh=(width, height), title="Anima ToolBox" ) # the layout that holds the tabs main_form_layout = pm.formLayout( 'main_form_layout', nd=100, parent=toolbox_window ) search_field = pm.textField( 'search_text_field', tcc=filter_tools, placeholderText='Search...', parent=main_form_layout ) main_tab_layout = pm.tabLayout( 'main_tab_layout', scr=True, cr=True, parent=main_form_layout ) # attach the main_tab_layout to main_form_layout pm.formLayout( main_form_layout, edit=True, attachForm=[ (search_field, "top", 0), (search_field, "left", 0), (search_field, "right", 0), # (main_tab_layout, "top", 0), (main_tab_layout, "bottom", 0), (main_tab_layout, "left", 0), (main_tab_layout, "right", 0) ], attachNone=[ (search_field, "bottom") ], attachControl=[ (main_tab_layout, "top", 0, search_field) ] ) with main_tab_layout: # ----- GENERAL ------ general_column_layout = pm.columnLayout( 'general_column_layout', adj=True, cal="center", rs=row_spacing ) with general_column_layout: color.change() pm.button( 'open_version_button', l="Open Version", c=repeated_callback(General.version_dialog, mode=1), ann="Open Version", bgc=color.color ) pm.button( 'save_as_version_button', l="Save As Version", c=repeated_callback(General.version_dialog, mode=0), ann="Save As Version", bgc=color.color ) color.change() pm.button( 'selectionManager_button', l="Selection Manager", c=repeated_callback(General.selection_manager), ann="Selection Manager", bgc=color.color ) color.change() pm.button( 'publishChecker_button', l="Publish Checker", c=repeated_callback(General.publish_checker), ann="Publish Checker", bgc=color.color ) color.change() pm.button( 'rename_unique_button', l='Rename Unique', c=repeated_callback(General.rename_unique), ann=General.rename_unique.__doc__, bgc=color.color ) pm.button( 'removeColonFromNames_button', l="remove colon(:) from node names", c=repeated_callback(General.remove_colon_from_names), ann="removes the colon (:) character from all " "selected object names", bgc=color.color ) pm.button( 'removePastedFromNames_button', l="remove \"pasted_\" from node names", c=repeated_callback(General.remove_pasted), ann="removes the \"passed__\" from all selected " "object names", bgc=color.color ) color.change() pm.button( 'togglePolyMeshes_button', l="toggle polymesh visibility", c=repeated_callback(General.toggle_poly_meshes), ann="toggles the polymesh display in the active model " "panel", bgc=color.color ) color.change() pm.button( 'selectSetMembers_button', l="select set members", c=repeated_callback(General.select_set_members), ann="selects the selected set members in correct " "order", bgc=color.color ) color.change() pm.button( 'delete_unused_intermediate_shapes_button', l='Delete Unused Intermediate Shape Nodes', c=repeated_callback(General.delete_unused_intermediate_shapes), ann='Deletes unused (no connection) intermediate shape nodes', bgc=color.color ) color.change() pm.button( 'export_transform_info_button', l='Export Transform Info', c=repeated_callback(General.export_transform_info), ann='exports transform info', bgc=color.color ) pm.button( 'import_transform_info_button', l='Import Transform Info', c=repeated_callback(General.import_transform_info), ann='imports transform info', bgc=color.color ) color.change() pm.button( 'export_global_transform_info_button', l='Export Global Transform Info', c=repeated_callback(General.export_transform_info, True), ann='exports global transform info', bgc=color.color ) pm.button( 'import_global_transform_info_button', l='Import Global Transform Info', c=repeated_callback(General.import_transform_info, True), ann='imports global transform info', bgc=color.color ) color.change() pm.button( 'export_component_transform_info_button', l='Export Component Transform Info', c=repeated_callback(General.export_component_transform_info), ann='exports component transform info', bgc=color.color ) pm.button( 'import_component_transform_info_button', l='Import Component Transform Info', c=repeated_callback(General.import_component_transform_info), ann='imports component transform info', bgc=color.color ) color.change() pm.button( 'import_rsproxy_data_from_houdini_button', l='Import RSProxy Data From Houdini', c=repeated_callback(General.rsproxy_data_importer), ann=General.rsproxy_data_importer.__doc__, bgc=color.color ) color.change() pm.button( 'generate_thumbnail_button', l='Generate Thumbnail', c=repeated_callback(General.generate_thumbnail), ann='Generates thumbnail for current scene', bgc=color.color ) color.change() pm.button( 'cleanup_light_cameras_button', l='Cleanup Light Cameras', c=repeated_callback(General.cleanup_light_cameras), ann=General.cleanup_light_cameras.__doc__, bgc=color.color ) color.change() from anima.env.mayaEnv.general import unknown_plugin_cleaner_ui pm.button( 'cleanup_plugins_button', l='Cleanup Unknown Plugins', c=repeated_callback(unknown_plugin_cleaner_ui), ann=unknown_plugin_cleaner_ui.__doc__, bgc=color.color ) color.change() pm.button( 'unshape_parent_node_button', l='Unshape Parent Nodes', c=repeated_callback(General.unshape_parent_nodes), ann=General.unshape_parent_nodes.__doc__, bgc=color.color ) # store commands __commands__.extend(general_column_layout.children()) # ----- REFERENCE ------ reference_columnLayout = pm.columnLayout( 'reference_columnLayout', adj=True, cal="center", rs=row_spacing) with reference_columnLayout: color.reset() pm.text(l='===== Reference Tools =====') pm.button( 'nsDelete_button', l="nsDelete", c=repeated_callback(General.namespace_deleter), ann=General.namespace_deleter.__doc__, bgc=color.color ) color.change() pm.button( 'duplicate_selected_reference_button', l='Duplicate Selected Reference', c=repeated_callback(Reference.duplicate_selected_reference), ann='Duplicates the selected reference', bgc=color.color ) color.change() pm.button( 'select_reference_in_reference_editor_button', l='Select Reference In Reference Editor', c=repeated_callback( Reference.select_reference_in_reference_editor ), ann=Reference.select_reference_in_reference_editor.__doc__, bgc=color.color ) color.change() pm.button( 'get_selected_reference_path_button', l='Get Selected Reference Path', c=repeated_callback(Reference.get_selected_reference_path), ann='Prints the selected reference full path', bgc=color.color ) pm.button( 'open_selected_reference_button', l='Open Selected Reference in New Maya', c=repeated_callback(Reference.open_reference_in_new_maya), ann='Opens the selected reference in new Maya ' 'instance', bgc=color.color ) color.change() pm.button( 'publish_model_as_look_dev_button', l='Model -> LookDev', c=repeated_callback(Reference.publish_model_as_look_dev), ann='References the current Model scene to the LookDev scene ' 'of the same task, creates the LookDev scene if ' 'necessary, also reopens the current model scene.', bgc=color.color ) color.change() pm.button( 'fix_reference_namespace_button', l='Fix Reference Namespace', c=repeated_callback(Reference.fix_reference_namespace), ann='Fixes old style reference namespaces with new one, ' 'creates new versions if necessary.', bgc=color.color ) color.change() pm.button( 'fix_reference_paths_button', l='Fix Reference Paths', c=repeated_callback(Reference.fix_reference_paths), ann='Fixes reference paths deeply, so they will use' '$REPO env var.', bgc=color.color ) pm.button( 'fix_student_license_on_references_button', l='Fix Student License Error On References', c=repeated_callback( Reference.fix_student_license_on_references ), ann=Reference.fix_student_license.__doc__, bgc=color.color ) pm.button( 'fix_student_license_on_files_button', l='Fix Student License Error On Selected Files', c=repeated_callback( Reference.fix_student_license_on_selected_file ), ann=Reference.fix_student_license.__doc__, bgc=color.color ) color.change() pm.button( 'archive_button', l='Archive Current Scene', c=repeated_callback(Reference.archive_current_scene), ann='Creates a ZIP file containing the current scene and its' 'references in a flat Maya default project folder ' 'structure', bgc=color.color ) pm.button( 'bind_to_original_button', l='Bind To Original', c=repeated_callback(Reference.bind_to_original), ann='Binds the current local references to the ones on the ' 'repository', bgc=color.color ) pm.button( 'unload_selected_references_button', l='Unload Selected References', c=repeated_callback(Reference.unload_selected_references), ann='Unloads the highest references that is related with the selected objects', bgc=color.color ) pm.button( 'unload_unselected_references_button', l='Unload UnSelected References', c=repeated_callback(Reference.unload_unselected_references), ann='Unloads any references that is not related with the ' 'selected objects', bgc=color.color ) color.change() pm.button( 'remove_selected_references_button', l='Remove Selected References', c=repeated_callback(Reference.remove_selected_references), ann='Removes the highest references that is related with the selected objects', bgc=color.color ) color.change() pm.text(l='===== Representation Tools =====') with pm.rowLayout(nc=2, adj=1): pm.checkBoxGrp( 'generate_repr_types_checkbox_grp', l='Reprs', numberOfCheckBoxes=3, labelArray3=['GPU', 'ASS', 'RS'], cl4=['left', 'left', 'left', 'left'], cw4=[51, 50, 50, 50], valueArray3=[1, 1, 1] ) pm.checkBox( 'generate_repr_skip_existing_checkBox', l='Skip existing Reprs.', value=0 ) pm.button( 'generate_repr_of_all_references_button', l='Deep Generate Repr Of All References', c=repeated_callback( Reference.generate_repr_of_all_references_caller ), ann='Deeply generates desired Representations of all ' 'references of this scene', bgc=color.color ) pm.button( 'generate_repr_of_scene_button', l='Generate Repr Of This Scene', c=repeated_callback(Reference.generate_repr_of_scene_caller), ann='Generates desired Representations of this scene', bgc=color.color ) color.change() with pm.rowLayout(nc=2, adj=1): pm.radioButtonGrp( 'repr_apply_to_radio_button_grp', l='Apply To', # ad3=1, labelArray2=['Selected', 'All References'], numberOfRadioButtons=2, cl3=['left', 'left', 'left'], cw3=[50, 65, 65], sl=1 ) pm.button( 'to_base_button', l='To Base', c=repeated_callback(Reference.to_base), ann='Convert selected to Base representation', bgc=color.color ) pm.button( 'to_gpu_button', l='To GPU', c=repeated_callback(Reference.to_gpu), ann='Convert selected to GPU representation', bgc=color.color ) pm.button( 'to_ass_button', l='To ASS', c=repeated_callback(Reference.to_ass), ann='Convert selected to ASS representation', bgc=color.color ) pm.button( 'to_rs_button', l='To RS', c=repeated_callback(Reference.to_rs), ann='Convert selected to RS representation', bgc=color.color ) color.change() pm.button( 'update_alembic_references_button', l='Update Alembic References', c=repeated_callback(auxiliary.update_alembic_references), ann=auxiliary.update_alembic_references.__doc__, bgc=color.color ) # store commands __commands__.extend(reference_columnLayout.children()) # ----- MODELING ------ modeling_column_layout = pm.columnLayout( 'modeling_column_layout', adj=True, cal="center", rs=row_spacing) with modeling_column_layout: color.reset() pm.button('toggleFaceNormalDisplay_button', l="toggle face normal display", c=repeated_callback( pm.runtime.ToggleFaceNormalDisplay), ann="toggles face normal display", bgc=color.color) pm.button('reverseNormals_button', l="reverse normals", c=repeated_callback(Modeling.reverse_normals), ann="reverse normals", bgc=color.color) pm.button('fixNormals_button', l="fix normals", c=repeated_callback(Modeling.fix_normals), ann="applies setToFace then conform and then " "soften edge to all selected objects", bgc=color.color) color.change() pm.button( 'oyHierarchyInstancer_button', l="hierarchy_instancer on selected", c=repeated_callback(Modeling.hierarchy_instancer), ann="hierarchy_instancer on selected", bgc=color.color ) color.change() pm.button( 'relax_verts_button', l="Relax Vertices", c=repeated_callback(Modeling.relax_vertices), ann="opens relax_vertices", bgc=color.color ) with pm.rowLayout(nc=4, adj=1): def smooth_edges_callback(): iteration = pm.intSliderGrp( "smooth_edges_iteration_intField", q=1, v=1 ) Modeling.smooth_edges(iteration=iteration) pm.button( 'smooth_edges_button', l="Smooth Edges", c=repeated_callback(smooth_edges_callback), ann=Modeling.smooth_edges.__doc__, bgc=color.color ) pm.intSliderGrp( 'smooth_edges_iteration_intField', v=100, min=0, max=100 ) color.change() pm.button( 'create_curve_from_mesh_edges_button', l="Curve From Mesh Edges", c=repeated_callback(Modeling.create_curve_from_mesh_edges), ann="Creates a curve from selected mesh edges", bgc=color.color ) color.change() pm.button( 'vertex_aligned_locator_button', l="Vertex Aligned Locator", c=repeated_callback(Modeling.vertex_aligned_locator), ann="Creates an aligned locator from selected vertices", bgc=color.color ) color.change() with pm.rowLayout(nc=8, rat=(1, "both", 0), adj=1): pm.text('set_pivot_text', l='Set Pivot', bgc=color.color) pm.button( 'center_button', l="C", c=repeated_callback( Modeling.set_pivot, 0 ), bgc=(0.8, 0.8, 0.8) ) pm.button( 'minus_X_button', l="-X", c=repeated_callback( Modeling.set_pivot, 1 ), bgc=(1.000, 0.500, 0.666) ) pm.button( 'plus_X_button', l="+X", c=repeated_callback( Modeling.set_pivot, 2 ), bgc=(1.000, 0.500, 0.666) ) pm.button( 'minus_Y_button', l="-Y", c=repeated_callback( Modeling.set_pivot, 3 ), bgc=(0.666, 1.000, 0.500) ) pm.button( 'plus_Y_button', l="+Y", c=repeated_callback( Modeling.set_pivot, 4 ), bgc=(0.666, 1.000, 0.500) ) pm.button( 'minus_Z_button', l="-X", c=repeated_callback( Modeling.set_pivot, 5 ), bgc=(0.500, 0.666, 1.000) ) pm.button( 'plus_Z_button', l="+X", c=repeated_callback( Modeling.set_pivot, 6 ), bgc=(0.500, 0.666, 1.000) ) color.change() with pm.rowLayout(nc=7, rat=(1, "both", 0), adj=1): pm.text(l='Text. Res', bgc=color.color) pm.button( l="128", c=repeated_callback( Modeling.set_texture_res, 128 ), bgc=Color.colors[0] ) pm.button( l="256", c=repeated_callback( Modeling.set_texture_res, 256 ), bgc=Color.colors[1] ) pm.button( l="512", c=repeated_callback( Modeling.set_texture_res, 512 ), bgc=Color.colors[2] ) pm.button( l="1024", c=repeated_callback( Modeling.set_texture_res, 1024 ), bgc=Color.colors[3] ) pm.button( l='2048', c=repeated_callback( Modeling.set_texture_res, 2048 ), bgc=Color.colors[4] ) pm.button( l='4096', c=repeated_callback( Modeling.set_texture_res, 4096 ), bgc=Color.colors[5] ) pm.text(l='========== UV Tools =============') color.change() pm.button( 'fix_uvsets_button', l="Fix UVSets (DiffuseUV -> map1)", c=repeated_callback(Modeling.fix_uvsets), ann=Modeling.fix_uvsets, bgc=color.color ) color.change() pm.button( 'select_zero_uv_area_faces_button', l="Filter Zero UV Area Faces", c=repeated_callback(Modeling.select_zero_uv_area_faces), ann="Selects faces with zero uv area", bgc=color.color ) color.change() pm.button( 'create_auto_uvmap_button', l='Create Auto UVMap', c=repeated_callback(Modeling.create_auto_uvmap), ann=Modeling.create_auto_uvmap.__doc__, bgc=color.color ) with pm.rowLayout(nc=6, adj=1): def transfer_uvs_button_callback(*args, **kwargs): label_lut = { 'W': 0, 'L': 1, 'UV': 2, 'C': 3, 'T': 4 } sample_space = label_lut[ pm.radioCollection( 'transfer_uvs_radio_collection', q=1, sl=1 ) ] Modeling.transfer_uvs(sample_space=sample_space) pm.button('transfer_uvs_button', l="Transfer UVs", c=repeated_callback(transfer_uvs_button_callback), ann="Transfers UVs from one group to other, use it" "for LookDev -> Alembic", bgc=color.color) pm.radioCollection('transfer_uvs_radio_collection') button_with = 40 pm.radioButton( 'W', w=button_with, al='left', ann='World' ) pm.radioButton( 'L', w=button_with, al='left', ann='Local' ) pm.radioButton( 'UV', w=button_with, al='left', ann='UV' ) pm.radioButton( 'C', w=button_with, al='left', ann='Component', sl=1 ) pm.radioButton( 'T', w=button_with, al='left', ann='Topology' ) color.change() pm.text(l='======= Manipulator Tools =======') pm.button('set_to_point_button', l="Set To Point", c=repeated_callback(pm.mel.eval, "manipMoveOrient 1;"), ann="Set manipulator to the point", bgc=color.color) pm.button('set_to_edge_button', l="Set To Edge", c=repeated_callback(pm.mel.eval, "manipMoveOrient 2;"), ann="Set manipulator to the edge", bgc=color.color) pm.button('set_to_face_button', l="Set To Face", c=repeated_callback(pm.mel.eval, "manipMoveOrient 3;"), ann="Set manipulator to the face", bgc=color.color) color.change() pm.button('create_bbox_from_selection_button', l="Create BBOX from selection", c=repeated_callback(Modeling.bbox_from_selection), ann=Modeling.bbox_from_selection.__doc__, bgc=color.color) # store commands __commands__.extend(modeling_column_layout.children()) # ----- RIGGING ------ rigging_columnLayout = pm.columnLayout( 'rigging_columnLayout', adj=True, cal="center", rs=row_spacing ) with rigging_columnLayout: color.reset() pm.button( 'create_joints_on_curve_ui_button', l="Create Joints On Curve UI", c=repeated_callback(Rigging.create_joints_on_curve_ui), ann=Rigging.create_joints_on_curve_ui.__doc__, bgc=color.color ) pm.button( 'mirror_transformation_button', l="Mirror Transformation", c=repeated_callback(Rigging.mirror_transformation), ann=Rigging.mirror_transformation.__doc__, bgc=color.color ) color.change() pm.button( 'IKFKLimbRigger_button', l="IK/FK Limb Rigger", c=repeated_callback(Rigging.ik_fk_limb_rigger), ann=Rigging.ik_fk_limb_rigger.__doc__, bgc=color.color ) with pm.rowLayout(nc=2, adj=1): def ik_fk_limb_rigger_callback(): subdivision = pm.intField('bendy_ik_fk_subdivision_count_field', q=1, v=1) Rigging.bendy_ik_fk_limb_rigger(subdivision=subdivision) pm.button( 'bendy_ik_fk_limb_rigger_button', l='IK/FK Limb Rigger (Bendy)', c=repeated_callback(ik_fk_limb_rigger_callback), ann=Rigging.bendy_ik_fk_limb_rigger.__doc__, bgc=color.color ) pm.intField('bendy_ik_fk_subdivision_count_field', min=0, v=2) pm.button( 'ReverseFootRigger_button', l="Reverse Foot Rigger", c=repeated_callback(Rigging.reverse_foot_rigger), ann=Rigging.reverse_foot_rigger.__doc__, bgc=color.color ) pm.button( 'squashStretchBendRigger_button', l="Squash/Stretch/Bend Rigger", c=repeated_callback(Rigging.squash_stretch_bend_rigger), ann=Rigging.squash_stretch_bend_rigger.__doc__, bgc=color.color ) pm.button( 'setupStretchySplineIKCurve_button', l="setup stretchy splineIK curve", c=repeated_callback(Rigging.setup_stretchy_spline_ik_curve), ann="connects necessary nodes to calculate arcLength " "change in percent", bgc=color.color ) pm.button( 'selectJointsDeformingTheObject_button', l="select joints deforming the object", c=repeated_callback(Rigging.select_joints_deforming_object), ann="select joints that deform the object", bgc=color.color ) color.change() pm.button( 'create_axial_correction_group_button', l="Create Axial Correction Groups", c=repeated_callback(Rigging.axial_correction_group), ann=Rigging.axial_correction_group.__doc__, bgc=color.color ) pm.button( 'create_zv_parent_compatible_groups_button', l="Create ZV Parent Compatible Groups", c=repeated_callback(Rigging.create_zv_parent_compatible_groups), ann=Rigging.axial_correction_group.__doc__, bgc=color.color ) color.change() pm.button( 'setClustersToAbsolute_button', l="set selected clusters to absolute", c=repeated_callback(Rigging.set_clusters_relative_state, 0), ann="set Clusters to Absolute", bgc=color.color ) pm.button( 'setClustersToRelative_button', l="set selected clusters to relative", c=repeated_callback( Rigging.set_clusters_relative_state, 1 ), ann="set Clusters to Relative", bgc=color.color ) color.change() pm.button( 'addControllerShape_button', l="add controller shape", c=repeated_callback(Rigging.add_controller_shape), ann="add the shape in the selected joint", bgc=color.color ) pm.button( 'replaceControllerShape_button', l="replace controller shape", c=repeated_callback(Rigging.replace_controller_shape), ann="replaces the shape in the selected joint", bgc=color.color ) color.change() def pin_controller_callback(color, *args): """Creates Pin Controller on the selected Vertex """ from anima.env.mayaEnv import rigging vertex = pm.ls(sl=1)[0] pc = rigging.PinController() pc.color = color pc.pin_to_vertex = vertex pc.setup() # TODO: Give the user the ability of selecting custom colors with pm.rowLayout(nc=4, adj=1): pm.text(l="Pin Controller") pm.button('pin_controller_red_button', l="R", c=repeated_callback(pin_controller_callback, [1, 0, 0]), ann=pin_controller_callback.__doc__, bgc=[1, 0, 0]) pm.button('pin_controller_green_button', l="G", c=repeated_callback(pin_controller_callback, [0, 1, 0]), ann=pin_controller_callback.__doc__, bgc=[0, 1, 0]) pm.button('pin_controller_blue_button', l="B", c=repeated_callback(pin_controller_callback, [0, 0, 1]), ann=pin_controller_callback.__doc__, bgc=[0, 0, 1]) pm.button('rivet_button', l="create rivet", c=repeated_callback(mel.eval, 'rivet'), ann="create rivet", bgc=color.color) pm.button('oyAutoRivet_button', l="auto rivet", c=repeated_callback(mel.eval, 'oyAutoRivet'), ann="auto rivet", bgc=color.color) pm.button( 'oyAutoRivetFollicle_button', l="auto rivet (Follicle)", c=repeated_callback(auxiliary.auto_rivet), ann="creates a rivet setup by using hair follicles", bgc=color.color ) pm.button( 'rivet_per_face_button', l="rivet per face (Follicle)", c=repeated_callback(auxiliary.rivet_per_face), ann="creates a rivet setup per selected face by using hair " "follicles", bgc=color.color ) pm.button('create_hair_from_curves_button', l="Create Hair From Curves", c=repeated_callback(auxiliary.hair_from_curves), ann="creates hair from curves", bgc=color.color) color.change() pm.button('artPaintSkinWeightsTool_button', l="paint weights tool", c=repeated_callback(mel.eval, 'ArtPaintSkinWeightsTool'), ann="paint weights tool", bgc=color.color) def skin_tools_ui_caller(*args):
pm.button('skin_tools_button', l="Skin Tools", c=skin_tools_ui_caller, ann="skin tools", bgc=color.color) pm.button('oyFixBoundJoint_button', l="fix_bound_joint", c=repeated_callback(Rigging.fix_bound_joint), ann="fix_bound_joint", bgc=color.color) pm.button('toggle_local_rotation_axes_button', l="Toggle Local Rotation Axes", c=repeated_callback(General.toggle_attributes, "displayLocalAxis"), ann="Toggle Local Rotation Axes", bgc=color.color) pm.button('toggle_display_rotate_pivot_button', l="Toggle Display Rotate Pivot", c=repeated_callback(General.toggle_attributes, "displayRotatePivot"), ann="Toggle Display Rotate Pivot", bgc=color.color) pm.button('seroBlendController_button', l="seroBlendController", c=repeated_callback(mel.eval, 'seroBlendController'), ann="seroBlendController", bgc=color.color) pm.button('align_to_pole_vector_button', l="Align To Pole Vector", c=repeated_callback(auxiliary.align_to_pole_vector), ann="align to pole vector", bgc=color.color) color.change() pm.button('oyResetCharSet_button', l="oyResetCharSet", c=repeated_callback(mel.eval, 'oyResetCharSet'), ann="reset char set", bgc=color.color) pm.button('export_blend_connections_button', l="Export blend connections", c=repeated_callback(auxiliary.export_blend_connections), ann="export blend connections", bgc=color.color) color.change() pm.button('createFollicles_button', l="create follicles", c=repeated_callback(Rigging.create_follicles), ann="create follicles", bgc=color.color) color.change() pm.button('oyResetTweaks_button', l="reset tweaks", c=repeated_callback(Rigging.reset_tweaks), ann="reset tweaks", bgc=color.color) color.change() def add_cacheable_attribute_callback(): """add <b>cacheable</b> attribute to the selected nodes """ for node in pm.selected(): Rigging.add_cacheable_attribute(node) pm.button('add_cacheable_attr_button', l="add `cacheable` attribute", c=repeated_callback(add_cacheable_attribute_callback), ann=add_cacheable_attribute_callback.__doc__, bgc=color.color) # store commands __commands__.extend(rigging_columnLayout.children()) # ----- RENDER ------ render_columnLayout = pm.columnLayout( 'render_columnLayout', adj=True, cal="center", rs=row_spacing ) with render_columnLayout: color.reset() color.change() pm.button( 'update_render_settings_button', l="Update Render Settings", c=repeated_callback(Render.update_render_settings), ann=Render.update_render_settings.__doc__, bgc=color.color ) color.change() pm.button( 'delete_render_layers_button', l="Delete Render Layers", c=repeated_callback(Render.delete_render_layers), ann=Render.delete_render_layers.__doc__, bgc=color.color ) pm.button( 'delete_display_layers_button', l="Delete Display Layers", c=repeated_callback(Render.delete_display_layers), ann=Render.delete_display_layers.__doc__, bgc=color.color ) pm.button( 'delete_render_and_display_layers_button', l="Delete Render and Display Layers", c=repeated_callback(Render.delete_render_and_display_layers), ann=Render.delete_render_and_display_layers.__doc__, bgc=color.color ) color.change() pm.button( 'delete_unused_shading_nodes_button', l="Delete Unused Shading Nodes", c=repeated_callback(Render.delete_unused_shading_nodes), ann=Render.delete_unused_shading_nodes.__doc__, bgc=color.color ) color.change() pm.button( 'duplicate_input_graph_button', l="Duplicate Input Graph", c=repeated_callback(Render.duplicate_input_graph), ann=Render.duplicate_input_graph.__doc__, bgc=color.color ) pm.button( 'duplicate_with_connections_button', l="Duplicate With Connections To Network", c=repeated_callback(Render.duplicate_with_connections), ann=Render.duplicate_with_connections.__doc__, bgc=color.color ) color.change() pm.text(l='=========== RedShift Tools ===========') pm.button( 'generate_rs_from_selection_button', l='Generate RSProxy From Selection', c=repeated_callback(Render.generate_rsproxy_from_selection), ann=Render.generate_rsproxy_from_selection.__doc__, bgc=color.color ) pm.button( 'generate_rs_from_selection_per_selection_button', l='Generate RSProxy From Selection (Per Selection)', c=repeated_callback(Render.generate_rsproxy_from_selection, True), ann=Render.generate_rsproxy_from_selection.__doc__, bgc=color.color ) pm.button( 'set_rsproxy_to_bbox_button', l='RSProxy -> Bounding Box', c=repeated_callback(Render.rsproxy_to_bounding_box), ann=Render.rsproxy_to_bounding_box.__doc__, bgc=color.color ) pm.button( 'set_rsproxy_to_preview_mesh_button', l='RSProxy -> Preview Mesh', c=repeated_callback(Render.rsproxy_to_preview_mesh), ann=Render.rsproxy_to_preview_mesh.__doc__, bgc=color.color ) color.change() pm.text(l='===== RedShift IC + IPC Bake =====') pm.button( 'redshift_ic_ipc_bake_button', l="Do Bake", c=repeated_callback(Render.redshift_ic_ipc_bake), ann=Render.redshift_ic_ipc_bake.__doc__, bgc=color.color ) pm.button( 'redshift_ic_ipc_bake_restore_button', l="Restore Settings", c=repeated_callback(Render.redshift_ic_ipc_bake_restore), ann=Render.redshift_ic_ipc_bake_restore.__doc__, bgc=color.color ) pm.text(l='======================================') color.change() pm.button( 'submit_afanasy_button', l="Afanasy Job Submitter", c=repeated_callback(Render.afanasy_job_submitter), ann=Render.afanasy_job_submitter.__doc__, bgc=color.color ) color.change() pm.button( 'open_node_in_browser_button', l="Open node in browser", c=repeated_callback(Render.open_node_in_browser), ann="Open node in browser", bgc=color.color ) color.change() pm.button('auto_convert_to_redshift_button', l="Auto Convert Scene To RedShift (BETA)", c=repeated_callback(Render.auto_convert_to_redshift), ann="Automatically converts the scene from Arnold to " "Redshift, including materials and lights", bgc=color.color) pm.button('convert_nodes_to_redshift_button', l="Convert Selected To RedShift (BETA)", c=repeated_callback(Render.convert_nodes_to_redshift), ann="Automatically converts the selected node from " "Arnold to Redshift", bgc=color.color) def set_shape_attribute_wrapper(attr_name, value): """a wrapper function for set_shape_attribute """ apply_to_hierarchy = pm.checkBox( apply_to_hierarchy_checkBox, q=True, v=True ) disable_undo = pm.checkBox( disable_undo_queue_check_box, q=True, v=True ) Render.set_shape_attribute( attr_name, value, apply_to_hierarchy, disable_undo ) with pm.rowLayout(nc=3, rat=(1, "both", 0), adj=1): pm.text('renderThumbnailUpdate_text', l="renderThumbnailUpdate", bgc=color.color) pm.button('set_renderThumbnailUpdate_ON_button', l="ON", c=repeated_callback(pm.renderThumbnailUpdate, 1), bgc=(0, 1, 0)) pm.button('set_renderThumbnailUpdate_OFF_button', l="OFF", c=repeated_callback(pm.renderThumbnailUpdate, 0), bgc=(1, 0, 0)) color.change() pm.button('replaceShadersWithLast_button', l="replace shaders with last", c=repeated_callback(Render.replace_shaders_with_last), ann="replace shaders with last", bgc=color.color) color.change() pm.button('createTextureRefObject_button', l="create texture ref. object", c=repeated_callback(Render.create_texture_ref_object), ann="create texture ref. object", bgc=color.color) pm.text(l='========== Texture Tools =============') color.change() pm.button('assign_substance_textures_button', l="Assign Substance Textures", c=repeated_callback(Render.assign_substance_textures), ann=Render.assign_substance_textures.__doc__, bgc=color.color) color.change() pm.button('normalize_texture_paths_button', l="Normalize Texture Paths (remove $)", c=repeated_callback(Render.normalize_texture_paths), ann=Render.normalize_texture_paths.__doc__, bgc=color.color) pm.button('unnormalize_texture_paths_button', l="Unnormalize Texture Paths (add $)", c=repeated_callback(Render.unnormalize_texture_paths), ann=Render.unnormalize_texture_paths.__doc__, bgc=color.color) color.change() pm.button('assign_random_material_color_button', l="Assign Material with Random Color", c=repeated_callback(Render.assign_random_material_color), ann=Render.assign_random_material_color.__doc__, bgc=color.color) pm.button('randomize_material_color_button', l="Randomize Material Color", c=repeated_callback(Render.randomize_material_color), ann=Render.randomize_material_color.__doc__, bgc=color.color) color.change() pm.button('import_image_as_plane_button', l="Import Image as Plane", c=repeated_callback(Render.import_image_as_plane), ann=Render.import_image_as_plane.__doc__, bgc=color.color) pm.text(l='============ Camera Tools ============') color.change() pm.button( 'CameraFilmOffsetTool_button', l="Camera Film Offset Tool", c=repeated_callback( camera_tools.camera_film_offset_tool ), ann="Camera Film Offset Tool", bgc=color.color ) def camera_focus_plane_tool_callback(): """callback for the camera_focus_plane_tool """ camera = pm.ls(sl=1)[0] camera_tools.camera_focus_plane_tool(camera) pm.button( 'CameraFocusPlaneTool_button', l="Camera Focus Plane Tool", c=repeated_callback(camera_focus_plane_tool_callback), ann="Camera Film Offset Tool", bgc=color.color ) pm.button( 'lock_tracked_camera_channels_button', l="Lock Tracked Camera Channels", c=repeated_callback(camera_tools.lock_tracked_camera_channels), ann=camera_tools.lock_tracked_camera_channels.__doc__, bgc=color.color ) color.change() pm.text(l='===== Vertigo =====') pm.button('vertigo_setup_look_at_button', l="Setup -> Look At", c=repeated_callback(Render.vertigo_setup_look_at), ann="Setup Look At", bgc=color.color) pm.button('vertigo_setup_vertigo_button', l="Setup -> Vertigo", c=repeated_callback(Render.vertigo_setup_vertigo), ann="Setup Vertigo", bgc=color.color) pm.button('vertigo_delete_button', l="Delete", c=repeated_callback(Render.vertigo_delete), ann="Delete", bgc=color.color) pm.text(l='===================') pm.button('oyTracker2Null_button', l="oyTracker2Null", c=repeated_callback(mel.eval, 'oyTracker2Null'), ann="Tracker2Null", bgc=color.color) with pm.rowLayout(nc=3, adj=1): def import_3dequalizer_points_callback(): """callback for Import 3DEqualizer points """ cam_width = pm.intField('import_3DEqualizer_points_width_int_field', q=1, v=1) cam_height = pm.intField('import_3DEqualizer_points_height_int_field', q=1, v=1) camera_tools.import_3dequalizer_points(cam_width, cam_height) pm.button( 'import_3DEqualizer_points_button', l="Import 3DEqualizer Points", c=repeated_callback(import_3dequalizer_points_callback), ann=camera_tools.import_3dequalizer_points.__doc__, bgc=color.color ) pm.intField('import_3DEqualizer_points_width_int_field', min=1, v=1920) pm.intField('import_3DEqualizer_points_height_int_field', min=1, v=1080) pm.text(l='===================') color.change() pm.button('reloadFileTextures_button', l="reload file textures", c=repeated_callback(Render.reload_file_textures), ann="reload file textures", bgc=color.color) color.change() pm.button('transfer_shaders_button', l="Transfer Shaders", c=repeated_callback(Render.transfer_shaders), ann="Transfers shaders from one group to other, use it" "for LookDev -> Alembic", bgc=color.color) color.change() pm.button('fitPlacementToUV_button', l="fit placement to UV", c=repeated_callback(Render.fit_placement_to_UV), ann="fit placement to UV", bgc=color.color) pm.button( 'connect_placement2d_to_file_texture_button', l='Connect Placement2D to File Texture', c=repeated_callback(Render.connect_placement2d_to_file), ann=Render.connect_placement2d_to_file.__doc__, bgc=color.color ) color.change() with pm.rowLayout(nc=2, adj=1): def enable_subdiv_callback(): max_tess = pm.intField('enable_subdiv_int_field', q=1, v=1) Render.enable_subdiv_on_selected( max_subdiv=max_tess, fixed_tes=False ) pm.button( 'enable_subdiv_on_selected_objects_button', l='Enable Subdiv (Adaptive)', c=repeated_callback(enable_subdiv_callback), ann='Enables Arnold/RedShift Subdiv (catclark) on ' 'selected objects', bgc=color.color ) pm.intField('enable_subdiv_int_field', min=0, v=3) with pm.rowLayout(nc=2, adj=1): def fixed_tess_callback(): max_tess = pm.intField('fixed_tess_int_field', q=1, v=1) Render.enable_subdiv_on_selected( fixed_tes=True, max_subdiv=max_tess ) pm.button( 'enable_fixed_subdiv_on_selected_objects_button', l='Enable Subdiv (Fixed Tes.)', c=repeated_callback(fixed_tess_callback), ann='Enables Arnold/RedShift Subdiv (catclark) on selected ' 'objects with fixed tessellation', bgc=color.color ) pm.intField('fixed_tess_int_field', min=0, v=1) pm.button( 'disable_subdiv_on_selected_objects_button', l='Disable Subdiv', c=repeated_callback(Render.disable_subdiv_on_selected), ann=Render.disable_subdiv.__doc__, bgc=color.color ) color.change() pm.button( 'export_shader_data_button', l='Export Shader Attributes', c=repeated_callback(Render.export_shader_attributes), ann=Render.export_shader_attributes.__doc__, bgc=color.color ) pm.button( 'import_shader_data_button', l='Import Shader Attributes', c=repeated_callback(Render.import_shader_attributes), ann=Render.import_shader_attributes.__doc__, bgc=color.color ) color.change() pm.button( 'export_shader_to_houdini_button', l='Export Shader Assignments To Houdini', c=repeated_callback(Render.export_shader_assignments_to_houdini), ann=Render.export_shader_assignments_to_houdini.__doc__, bgc=color.color ) color.change() pm.button( 'create_eye_shader_and_controls_button', l='Create Eye Shader and Controls', c=repeated_callback(Render.create_eye_shader_and_controls), ann='Creates eye shaders and controls for the selected eyes', bgc=color.color ) pm.button( 'setup_outer_eye_render_attributes_button', l='Setup Outer Eye Render Attributes', c=repeated_callback(Render.setup_outer_eye_render_attributes), ann=Render.setup_outer_eye_render_attributes.__doc__, bgc=color.color ) pm.button( 'setup_window_glass_render_attributes_button', l='Setup **Window Glass** Render Attributes', c=repeated_callback(Render.setup_window_glass_render_attributes), ann=Render.setup_window_glass_render_attributes.__doc__, bgc=color.color ) pm.button( 'setup_dummy_window_light_button', l='Setup/Update **Dummy Window** Light Plane', c=repeated_callback(Render.dummy_window_light_plane), ann=Render.dummy_window_light_plane.__doc__, bgc=color.color ) color.change() pm.button( 'create_generic_tooth_shader_button', l='Create Generic TOOTH Shader', c=repeated_callback(Render.create_generic_tooth_shader), ann=Render.create_generic_gum_shader.__doc__, bgc=color.color ) pm.button( 'create_generic_gum_shader_button', l='Create Generic GUM Shader', c=repeated_callback(Render.create_generic_gum_shader), ann=Render.create_generic_gum_shader.__doc__, bgc=color.color ) pm.button( 'create_generic_tongue_shader_button', l='Create Generic TONGUE Shader', c=repeated_callback(Render.create_generic_tongue_shader), ann=Render.create_generic_tongue_shader.__doc__, bgc=color.color ) color.change() pm.button('convert_to_ai_image_button', l="To aiImage", c=repeated_callback( Render.convert_file_node_to_ai_image_node), ann="Converts the selected File (file texture) nodes to " "aiImage nodes, also connects the place2dTexture " "node if necessary", bgc=color.color) color.change() pm.button('to_bbox_button', l="aiStandIn To BBox", c=repeated_callback(Render.standin_to_bbox), ann="Convert selected stand ins to bbox", bgc=color.color) pm.button('to_polywire_button', l="aiStandIn To Polywire", c=repeated_callback(Render.standin_to_polywire), ann="Convert selected stand ins to polywire", bgc=color.color) color.change() with pm.rowLayout(nc=3, adj=3, bgc=color.color): min_range_field = pm.floatField( minValue=1000, maxValue=50000, step=1, pre=0, value=3500, w=50, bgc=color.color, ann='Min Value' ) max_range_field = pm.floatField( minValue=1000, maxValue=50000, step=1, pre=0, value=6500, w=50, bgc=color.color, ann='Max Value' ) pm.button( ann="Randomize Color Temperature", l="Randomize Color Temp.", w=70, c=repeated_callback( Render.randomize_light_color_temp, min_range_field, max_range_field ), bgc=color.color ) with pm.rowLayout(nc=3, adj=3, bgc=color.color): min_range_field = pm.floatField( minValue=0, maxValue=200, step=0.1, pre=1, value=10, w=50, bgc=color.color, ann='Min Value' ) max_range_field = pm.floatField( minValue=0, maxValue=200, step=0.1, pre=1, value=20, w=50, bgc=color.color, ann='Max Value' ) pm.button( ann="Randomize Exposure", l="Randomize Exposure", w=70, c=repeated_callback( Render.randomize_light_intensity, min_range_field, max_range_field ), bgc=color.color ) color.change() pm.button( ann="Create Reflection Curve", l="Reflection Curve", c=repeated_callback( Render.generate_reflection_curve ), bgc=color.color ) color.change() pm.button( ann="Import GPU Content", l="Import GPU Content", c=repeated_callback( Render.import_gpu_content ), bgc=color.color ) color.change() with pm.rowLayout(nc=3, adj=3, bgc=color.color): source_driver_field = pm.textField( text='S:', w=50, bgc=color.color, ann='Source Driver' ) target_driver_field = pm.textField( text='L:', w=50, bgc=color.color, ann='Target Driver' ) pm.button( ann="Move Cache Files to Another Location", l="Move Cache Files", w=70, c=repeated_callback( Render.move_cache_files_wrapper, source_driver_field, target_driver_field ), bgc=color.color ) # store commands __commands__.extend(render_columnLayout.children()) # ----- PREVIS ------ previs_columnLayout = pm.columnLayout( 'previs_columnLayout', adj=True, cal="center", rs=row_spacing ) with previs_columnLayout: color.reset() pm.button('split_camera_button', l="Split Camera", c=repeated_callback(Previs.split_camera), ann=Previs.split_camera.__doc__, bgc=color.color) color.change() pm.button('shots_from_camera_button', l="Shots From Camera", c=repeated_callback(Previs.shots_from_cams), ann=Previs.shots_from_cams.__doc__, bgc=color.color) color.change() pm.button('auto_rename_shots_button', l="Auto Rename Shots", c=repeated_callback(Previs.auto_rename_shots), ann=Previs.auto_rename_shots.__doc__, bgc=color.color) color.change() pm.button('save_previs_to_shots_button', l="Save Previs To Shots", c=repeated_callback(Previs.save_previs_to_shots), ann=Previs.save_previs_to_shots.__doc__, bgc=color.color) color.change() pm.button('very_nice_camera_rig_button', l="Create a Very Nice Camera Rig", c=repeated_callback(camera_tools.very_nice_camera_rig), ann=camera_tools.very_nice_camera_rig.__doc__, bgc=color.color) # store commands __commands__.extend(previs_columnLayout.children()) # ----- ANIMATION ------ animation_columnLayout = pm.columnLayout( 'animation_columnLayout', adj=True, cal="center", rs=row_spacing ) with animation_columnLayout: color.reset() color.change() from anima.env.mayaEnv import picker pm.text(l='===== Object Picker =====') pm.button('picker_setParent_button', l="Set Parent", c=repeated_callback(picker.set_parent), ann="Set Parent", bgc=color.color) pm.button('picker_releaseObject_button', l="Release", c=repeated_callback(picker.release_object), ann="Release Object", bgc=color.color) pm.button('picker_editKeyframes_button', l="Edit Keyframes", c=repeated_callback(picker.edit_keyframes), ann="Edit Keyframes", bgc=color.color) pm.button('picker_fixJump_button', l="Fix Jump", c=repeated_callback(picker.fix_jump), ann="Fix Jump", bgc=color.color) pm.button('picker_explodeSetup_button', l="Explode", c=repeated_callback(picker.explode_setup), ann="Explode Setup", bgc=color.color) color.change() from anima.env.mayaEnv import pivot_switcher pm.text(l='===== Pivot Switcher =====') pm.button('oyPivotSwitcher_setupPivot_button', l="Setup", c=repeated_callback(pivot_switcher.setup_pivot), ann="Setup Pivot", bgc=color.color) pm.button('oyPivotSwitcher_switchPivot_button', l="Switch", c=repeated_callback(pivot_switcher.switch_pivot), ann="Switch Pivot", bgc=color.color) pm.button('oyPivotSwitcher_togglePivot_button', l="Toggle", c=repeated_callback(pivot_switcher.toggle_pivot), ann="Toggle Pivot", bgc=color.color) color.change() pm.text(l='===== Alembic Tools =====') pm.button('bake_all_constraints_button', l="Bake All Constraints", c=repeated_callback(Animation.bake_all_constraints), ann=Animation.bake_all_constraints.__doc__, bgc=color.color) pm.button('bake_alembic_animations_button', l="Bake Alembic Animations", c=repeated_callback(Animation.bake_alembic_animations), ann=Animation.bake_alembic_animations.__doc__, bgc=color.color) rowLayout = pm.rowLayout(nc=2, adj=1, bgc=color.color) with rowLayout: pm.button( 'abc_from_selected_button', l='From Selected', c=repeated_callback(Animation.create_alembic_command), ann='Creates Alembic Cache from selected nodes', bgc=color.color ) from_top_node_checkBox = pm.checkBox( 'from_top_node_checkBox', l="Top Node", value=True, bgc=color.color ) # pm.button( # 'abc_from_source_to_target_button', # l='Source -> Target', # c=repeated_callback(Animation.copy_alembic_data), # ann='Copy Alembic Data from Source to Target by the matching ' # 'node names', # bgc=color.color # ) # rowLayout = pm.rowLayout(nc=2, adj=1, bgc=color.color) pm.text(l='===== EXPORT =====') with pm.rowLayout(nc=3, adj=3): pm.checkBoxGrp( 'export_alembic_of_nodes_checkbox_grp', l='Alembic Options', numberOfCheckBoxes=2, labelArray2=['Isolate', 'Unload Refs'], cl3=['left', 'left', 'left'], cw3=[100, 60, 60], valueArray2=[1, 1] ) pm.intFieldGrp( 'export_alembic_of_nodes_handles_int_slider_grp', l='Handles', el='frames', nf=1, adj=2, cw3=[65, 1, 20], v1=1, ) def export_alembic_callback_with_options(func): """calls the function with the parameters from the ui :param func: :return: """ isolate, unload_refs = pm.checkBoxGrp( 'export_alembic_of_nodes_checkbox_grp', q=1, valueArray2=1 ) handles = pm.intFieldGrp('export_alembic_of_nodes_handles_int_slider_grp', q=1, v1=1) func(isolate=isolate, unload_refs=unload_refs, handles=handles) pm.button( 'export_alembic_of_selected_cacheable_nodes_button', l='Selected Cacheable Nodes', c=repeated_callback(export_alembic_callback_with_options, auxiliary.export_alembic_of_selected_cacheable_nodes), ann=auxiliary.export_alembic_of_selected_cacheable_nodes.__doc__.split('\n')[0], bgc=color.color ) pm.button( 'export_alembic_of_all_cacheable_nodes_button', l='ALL Cacheable Nodes', c=repeated_callback(export_alembic_callback_with_options, auxiliary.export_alembic_of_all_cacheable_nodes), ann=auxiliary.export_alembic_of_all_cacheable_nodes.__doc__.split('\n')[0], bgc=color.color ) pm.button( 'export_alembic_on_farm_button', l='Export Alembic On Farm', c=repeated_callback(Animation.export_alembics_on_farm), ann=Animation.export_alembics_on_farm.__doc__.split('\n')[0], bgc=color.color ) pm.text(l='===== Playblast Tools =====') color.change() pm.button( 'playblast_on_farm_button', l='PLayblast On Farm', c=repeated_callback(Animation.playblast_on_farm), ann=Animation.playblast_on_farm.__doc__.split('\n')[0], bgc=color.color ) pm.text(l='===== Exporters =====') color.change() rowLayout = pm.rowLayout(nc=3, adj=3, bgc=color.color) with rowLayout: start = int(pm.playbackOptions(q=1, minTime=1)) end = int(pm.playbackOptions(q=1, maxTime=1)) startButtonField = pm.textField( text=start, w=50, bgc=color.color, ann='start frame' ) endButtonField = pm.textField( text=end, w=50, bgc=color.color, ann='end frame' ) pm.button(ann="Exports maya camera to nuke", l="cam2chan", w=70, c=repeated_callback( Animation.cam_2_chan, startButtonField, endButtonField ), bgc=color.color) pm.text(l='===== Component Animation =====') color.change() smooth_selected_keyframes_text_fbg = pm.textFieldButtonGrp( 'smooth_selected_keyframes_text_fbg_button', bl="Smooth Selected Keyframes", adj=2, tx=1, cw=(1, 40), ann="select keyframes in graph editor to smooth", bgc=color.color ) def smooth_selected_keyframes_text_fbg_callback(): iteration = int( pm.textFieldButtonGrp( "smooth_selected_keyframes_text_fbg_button", q=1, tx=1 ) ) Animation.smooth_selected_keyframes(iteration) pm.textFieldButtonGrp( smooth_selected_keyframes_text_fbg, e=1, bc=repeated_callback( smooth_selected_keyframes_text_fbg_callback ) ) smooth_component_anim = pm.textFieldButtonGrp( 'oySmoothComponentAnimation_button', bl="Smooth Component Animation", adj=2, tx=1, cw=(1, 40), ann="select components to smooth", bgc=color.color ) pm.textFieldButtonGrp( smooth_component_anim, e=1, bc=repeated_callback( Animation.smooth_component_animation, smooth_component_anim ) ) color.change() pm.button( 'bake_component_animation_button', l='Bake component animation to Locator', c=repeated_callback(Animation.bake_component_animation), ann='Creates a locator at the center of selected components ' 'and moves it with the components along the current ' 'frame range', bgc=color.color ) pm.button( 'create_follicle_button', l='Attach Follicle', c=repeated_callback(Animation.attach_follicle), ann='Attaches a follicle in the selected components', bgc=color.color ) pm.button( 'equalize_node_speed_button', l='Equalize Node Speed', c=repeated_callback(Animation.equalize_node_speed), ann=Animation.equalize_node_speed.__doc__, bgc=color.color ) pm.text(l='===== Generic Tools =====') color.change() pm.button( 'set_range_from_shot_node_button', l='Range From Shot', c=repeated_callback(Animation.set_range_from_shot), ann='Sets the playback range from the shot node in the scene', bgc=color.color ) color.change() pm.button( 'delete_base_anim_layer_button', l='Delete Base Anim Layer', c=repeated_callback(Animation.delete_base_anim_layer), ann=Animation.delete_base_anim_layer.__doc__, bgc=color.color ) # store commands __commands__.extend(animation_columnLayout.children()) # Obsolete obsolete_columnLayout = pm.columnLayout( 'obsolete_columnLayout', adj=True, cal="center", ann="Obsolete", rs=row_spacing ) with obsolete_columnLayout: color.reset() pm.button('addMiLabel_button', l="add miLabel to selected", c=repeated_callback(Render.add_miLabel), ann="add miLabel to selected", bgc=color.color) color.change() pm.button('connectFacingRatioToVCoord_button', l="connect facingRatio to vCoord", c=repeated_callback( Render.connect_facingRatio_to_vCoord), ann="connect facingRatio to vCoord", bgc=color.color) color.change() with pm.rowLayout(nc=3, rat=(1, "both", 0), adj=1): pm.text('miFinalGatherCast_text', l="miFinalGatherCast", bgc=color.color) pm.button('set_miFinalGatherCast_ON_button', l="ON", c=repeated_callback( set_shape_attribute_wrapper, "miFinalGatherCast", 1 ), bgc=(0, 1, 0)) pm.button('set_miFinalGatherCast_OFF_button', l="OFF", c=repeated_callback( set_shape_attribute_wrapper, "miFinalGatherCast", 0 ), bgc=(1, 0, 0)) with pm.rowLayout(nc=3, rat=(1, "both", 0), adj=1): pm.text('miFinalGatherReceive_text', l="miFinalGatherReceive", bgc=color.color) pm.button('set_miFinalGatherReceive_ON_button', l="ON", c=repeated_callback( set_shape_attribute_wrapper, "miFinalGatherReceive", 1 ), bgc=(0, 1, 0)) pm.button('set_miFinalGatherReceive_OFF_button', l="OFF", c=repeated_callback( set_shape_attribute_wrapper, "miFinalGatherReceive", 0 ), bgc=(1, 0, 0)) with pm.rowLayout(nc=3, rat=(1, "both", 0), adj=1): pm.text('miFinalGatherHide_text', l="miFinalGatherHide", bgc=color.color) pm.button('set_miFinalGatherHide_ON_button', l="ON", c=repeated_callback(Render.set_finalGatherHide, 1), bgc=(0, 1, 0)) pm.button('set_miFinalGatherHide_OFF_button', l="OFF", c=repeated_callback(Render.set_finalGatherHide, 0), bgc=(1, 0, 0)) color.change() pm.button('convertToMRTexture_button', l="use mib_texture_filter_lookup", c=repeated_callback( Render.use_mib_texture_filter_lookup), ann=( "adds an mib_texture_filter_lookup node in \n" + "between the file nodes and their outputs, to \n" + "get a sharper look output from the texture file"), bgc=color.color) pm.button('convertToLinear_button', l="convert to Linear texture", c=repeated_callback(Render.convert_to_linear), ann="convert to Linear texture", bgc=color.color) pm.button('useImageSequence_button', l="use image sequence for \nmentalrayTexture", c=repeated_callback(Render.use_image_sequence), ann="use image sequence for \nmentalrayTexture", bgc=color.color) color.change() pm.button('oyAddToSelectedContainer_button', l="add to selected container", c=repeated_callback(Render.add_to_selected_container), ann="add to selected container", bgc=color.color) pm.button('oyRemoveFromContainer_button', l="remove from selected container", c=repeated_callback(Render.remove_from_container), ann="remove from selected container", bgc=color.color) color.change() pm.button('oySmedgeRenderSlicer_button', l="oySmedgeRenderSlicer", c=repeated_callback(mel.eval, 'oySmedgeRenderSlicer'), ann="SmedgeRenderSlicer", bgc=color.color) color.change() pm.button( 'exponentialSmooth_button', l="exponential smooth", c=repeated_callback(Modeling.polySmoothFace, 0), ann="applies exponential smooth to selected objects", bgc=color.color ) pm.button( 'linearSmooth_button', l="linear smooth", c=repeated_callback(Modeling.polySmoothFace, 1), ann="applies linear smooth to selected objects", bgc=color.color ) pm.button( 'deActivateSmooth_button', l="deActivate smooth", c=repeated_callback(Modeling.activate_deActivate_smooth, 1), ann="deActivates all polySmoothFace nodes in the " "scene", bgc=color.color ) pm.button( 'activateSmooth_button', l="activate smooth", c=repeated_callback(Modeling.activate_deActivate_smooth, 0), ann="activates all deActivated polySmoothFace nodes " "in the scene", bgc=color.color ) pm.button( 'deleteSmooth_button', l="delete smooth", c=repeated_callback(Modeling.delete_smooth), ann="deletes all the polySmoothFace nodes from the " "scene", bgc=color.color ) pm.button( 'deleteSmoothOnSelected_button', l="delete smooth on selected", c=repeated_callback(Modeling.delete_smooth_on_selected), ann="deletes selected polySmoothFace nodes from scene", bgc=color.color ) color.change() pm.button( 'deleteAllSound_button', l="delete all sound", c=repeated_callback(General.delete_all_sound), ann="delete all sound", bgc=color.color ) pm.button( 'displayHandlesOfSelectedObjects_button', l="toggle handles of selected objects", c=repeated_callback( General.toggle_attributes, "displayHandle" ), ann="select objects to toggle handle", bgc=color.color ) color.change() pm.button( 'referenceSelectedObjects_button', l="reference selected objects", c=repeated_callback( General.reference_selected_objects ), ann="sets objects display override to reference", bgc=color.color ) pm.button( 'dereferenceSelectedObjects_button', l="de-reference selected objects", c=repeated_callback( General.dereference_selected_objects ), ann="sets objects display override to reference", bgc=color.color ) color.change() pm.button( 'oyDeReferencer_button', l="dereferencer", c=repeated_callback(General.dereferencer), ann="sets all objects display override to normal", bgc=color.color ) color.change() enable_matte_row_layout = pm.rowLayout(nc=6, adj=1) with enable_matte_row_layout: pm.text( l='Enable Arnold Matte', ) pm.button( l='Default', c=repeated_callback(Render.enable_matte, 0), ann='Enables Arnold Matte on selected objects with <b>No Color</b>', bgc=color.color ) pm.button( l='R', c=repeated_callback(Render.enable_matte, 1), ann='Enables Arnold Matte on selected objects with <b>Red</b>', bgc=[1, 0, 0] ) pm.button( l='G', c=repeated_callback(Render.enable_matte, 2), ann='Enables Arnold Matte on selected objects with <b>Green</b>', bgc=[0, 1, 0] ) pm.button( l='B', c=repeated_callback(Render.enable_matte, 3), ann='Enables Arnold Matte on selected objects with <b>Blue</b>', bgc=[0, 0, 1] ) pm.button( l='A', c=repeated_callback(Render.enable_matte, 4), ann='Enables Arnold Matte on selected objects with <b>Alpha</b>', bgc=[0.5, 0.5, 0.5] ) color.change() pm.button( 'fix_render_layer_out_adjustment_errors_button', l="fixRenderLayerOutAdjustmentErrors", c='pm.mel.eval("fixRenderLayerOutAdjustmentErrors();")', ann="fixRenderLayerOutAdjustmentErrors", bgc=color.color ) pm.separator() color.change() with pm.rowLayout(nc=2, adj=2): apply_to_hierarchy_checkBox = pm.checkBox( 'apply_to_hierarchy_checkBox', l="Apply to Hierarchy", value=True, bgc=color.color ) disable_undo_queue_check_box = pm.checkBox( 'disable_undo_queue_checkBox', l="Disable Undo", value=False, bgc=color.color ) attr_names = [ 'castsShadows', 'receiveShadows', 'motionBlur', 'primaryVisibility', 'visibleInReflections', 'visibleInRefractions', 'aiSelfShadows', 'aiOpaque', 'aiVisibleInDiffuse', 'aiVisibleInGlossy', 'aiMatte', 'overrideShaders' ] for attr_name in attr_names: with pm.rowLayout(nc=4, rat=(1, "both", 0), adj=1): pm.text('%s_text' % attr_name, l=attr_name, bgc=color.color) pm.button( 'set_%s_ON_button' % attr_name, l="ON", c=repeated_callback( set_shape_attribute_wrapper, attr_name, 1, ), bgc=(0, 1, 0) ) pm.button( 'set_%s_OFF_button' % attr_name, l="OFF", c=repeated_callback( set_shape_attribute_wrapper, attr_name, 0 ), bgc=(1, 0, 0) ) pm.button( 'set_%s_REMOVE_button' % attr_name, l="REM", ann='Remove Override', c=repeated_callback( set_shape_attribute_wrapper, attr_name, -1 ), bgc=(0, 0.5, 1) ) pm.separator() color.change() pm.button( l='Setup Z-Layer', c=repeated_callback(Render.create_z_layer), ann=Render.create_z_layer.__doc__, bgc=color.color ) pm.button( l='Setup EA Matte', c=repeated_callback(Render.create_ea_matte), ann=Render.create_ea_matte.__doc__, bgc=color.color ) color.change() pm.text(l='===== BarnDoor Simulator =====') pm.button( 'barn_door_simulator_setup_button', l='Setup', c=repeated_callback(Render.barndoor_simulator_setup), ann='Creates a arnold barn door simulator to the selected ' 'light', bgc=color.color ) pm.button( 'barn_door_simulator_unsetup_button', l='Un-Setup', c=repeated_callback(Render.barndoor_simulator_unsetup), ann='Removes the barn door simulator nodes from the selected ' 'light', bgc=color.color ) pm.button( 'fix_barndoors_button', l='Fix BarnDoors', c=repeated_callback(Render.fix_barndoors), ann=Render.fix_barndoors.__doc__, bgc=color.color ) color.change() pm.button( 'ai_skin_sss_to_ai_skin_button', l='aiSkinSSS --> aiSkin', c=repeated_callback(Render.convert_aiSkinSSS_to_aiSkin), ann=Render.convert_aiSkinSSS_to_aiSkin.__doc__, bgc=color.color ) pm.button( 'normalize_sss_weights_button', l='Normalize SSS Weights', c=repeated_callback(Render.normalize_sss_weights), ann=Render.normalize_sss_weights.__doc__, bgc=color.color ) # store commands __commands__.extend(obsolete_columnLayout.children()) pm.tabLayout( main_tab_layout, edit=True, tabLabel=[ (general_column_layout, "Gen"), (reference_columnLayout, "Ref"), (modeling_column_layout, "Mod"), (rigging_columnLayout, "Rig"), (render_columnLayout, "Ren"), (previs_columnLayout, "Prev"), (animation_columnLayout, "Ani"), (obsolete_columnLayout, "Obs") ], cc=functools.partial(store_tab_index, main_tab_layout) ) dock_control = pm.dockControl( "toolbox_dockControl", l='toolbox', content=toolbox_window, area="left", allowedArea=["left", "right"], width=width ) # switch to last tab last_tab_index = get_last_tab_index() if last_tab_index: pm.tabLayout( main_tab_layout, e=1, sti=last_tab_index ) def store_tab_index(tab_layout): val = pm.tabLayout(tab_layout, q=1, sti=1) os.environ[__last_tab__] = str(val) def get_last_tab_index(): """returns the last tab index from settings """ return int(os.environ.get(__last_tab__, 0))
from anima.env.mayaEnv.rigging import SkinToolsUI st = SkinToolsUI() st.ui()
execute.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = execute; var _ErrorHandler = require('../utils/ErrorHandler'); var _utilities = require('../helpers/utilities'); /** * * Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. * The executed script is assumed to be synchronous and the result of evaluating the script is returned to * the client. * * The script argument defines the script to execute in the form of a function body. The value returned by * that function will be returned to the client. The function will be invoked with the provided args array * and the values may be accessed via the arguments object in the order specified. * * Arguments may be any JSON-primitive, array, or JSON object. JSON objects that define a WebElement * reference will be converted to the corresponding DOM element. Likewise, any WebElements in the script
* <example> :execute.js it('should inject javascript on the page', function () { var result = browser.execute(function(a, b, c, d) { // browser context - you may not access client or console return a + b + c + d; }, 1, 2, 3, 4) // node.js context - client and console are available console.log(result.value); // outputs: 10 }); * </example> * * @param {String|Function} script The script to execute. * @param {*} [argument1,...,argumentN] script arguments * * @return {*} The script result. * * @see https://w3c.github.io/webdriver/webdriver-spec.html#dfn-execute-script * @type protocol * */ function execute() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var script = args.shift(); /*! * parameter check */ if (typeof script !== 'string' && typeof script !== 'function') { throw new _ErrorHandler.ProtocolError('number or type of arguments don\'t agree with execute protocol command'); } /*! * instances started as multibrowserinstance can't getting called with * a function parameter, therefor we need to check if it starts with "function () {" */ if (typeof script === 'function' || this.inMultibrowserMode && script.indexOf('function (') === 0) { script = `return (${script}).apply(null, arguments)`; } return this.requestHandler.create('/session/:sessionId/execute', { script, args }).catch(function (err) { /** * jsonwire command not supported try webdriver endpoint * Note: MicrosoftWebDriver returns "UnknownError" when receiving * a jsonwire command in W3C Mode * https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/19917561/ */ if ((0, _utilities.isUnknownCommand)(err) || (0, _utilities.isUnknownError)(err)) { return _this.requestHandler.create('/session/:sessionId/execute/sync', { script, args }); } throw err; }); } module.exports = exports['default'];
* result will be returned to the client as WebElement JSON objects. *
video-caption.js
/** * @license Copyright 2017 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. */ 'use strict'; /** * @fileoverview Ensures `<video>` elements have closed captions. * See base class in axe-audit.js for audit() implementation. */ const AxeAudit = require('./axe-audit'); class VideoCaption extends AxeAudit { /** * @return {!AuditMeta} */ static get meta() { return { category: 'Accessibility', name: 'video-caption', description: '`<video>` elements contain a `<track>` element with `[kind="captions"]`.', failureDescription: '`<video>` elements do not contain a `<track>` element ' + 'with `[kind="captions"]`.', helpText: 'When a video provides a caption it is easier for deaf and hearing impaired ' +
requiredArtifacts: ['Accessibility'] }; } } module.exports = VideoCaption;
'users to access its information. ' + '[Learn more](https://dequeuniversity.com/rules/axe/2.2/video-caption?application=lighthouse).',
selected.js
import { ACTIONS } from '../utils/constants'; export function
(data) { return { type: ACTIONS.SET_SELECTED_APPLICATION, data }; }
setSelectedApplication
jobs.go
package oracle import ( "context" "encoding/gob" "fmt" "time" "github.com/centrifuge/go-centrifuge/config" "github.com/centrifuge/go-centrifuge/contextutil" "github.com/centrifuge/go-centrifuge/ethereum" "github.com/centrifuge/go-centrifuge/identity" "github.com/centrifuge/go-centrifuge/jobs" "github.com/centrifuge/go-centrifuge/nft" "github.com/centrifuge/gocelery/v2" "github.com/ethereum/go-ethereum/common" ) func init()
const oraclePushJob = "Push to Oracle" // PushToOracleJob pushes nft value to oracle // args are as follows // did, oracleAddr, tokenID, fingerprint, value type PushToOracleJob struct { jobs.Base accountsSrv config.Service identityService identity.Service ethClient ethereum.Client } // New returns a new PushToOracleJob instance func (p *PushToOracleJob) New() gocelery.Runner { np := &PushToOracleJob{ accountsSrv: p.accountsSrv, identityService: p.identityService, ethClient: p.ethClient, } np.Base = jobs.NewBase(np.getTasks()) return np } func (p *PushToOracleJob) getTasks() map[string]jobs.Task { return map[string]jobs.Task{ "push_to_oracle": { RunnerFunc: func(args []interface{}, overrides map[string]interface{}) (result interface{}, err error) { did := args[0].(identity.DID) acc, err := p.accountsSrv.GetAccount(did[:]) if err != nil { return nil, fmt.Errorf("failed to get account: %w", err) } ctx := contextutil.WithAccount(context.Background(), acc) oracleAddr := args[1].(common.Address) // to tokenId *big.Int, bytes32, bytes32 txn, err := p.identityService.ExecuteAsync(ctx, oracleAddr, updateABI, "update", args[2:]...) if err != nil { return nil, fmt.Errorf("failed to send oracle txn: %w", err) } log.Infof("Sent nft details to oracle[%s] with txn[%s]", oracleAddr, txn.Hash()) overrides["eth_txn"] = txn.Hash() return nil, nil }, Next: "wait_for_txn", }, "wait_for_txn": { RunnerFunc: func(args []interface{}, overrides map[string]interface{}) (result interface{}, err error) { txn := overrides["eth_txn"].(common.Hash) _, err = ethereum.IsTxnSuccessful(context.Background(), p.ethClient, txn) if err != nil { return nil, err } log.Infof("Document value successfully pushed to Oracle with TX hash: %v\n", txn.Hex()) return nil, nil }, }, } } func initOraclePushJob( dispatcher jobs.Dispatcher, did identity.DID, oracleAddr common.Address, tokenID nft.TokenID, fp, value [32]byte) (gocelery.JobID, error) { job := gocelery.NewRunnerJob( oraclePushJob, oraclePushJob, "push_to_oracle", []interface{}{did, oracleAddr, tokenID.BigInt(), fp, value}, make(map[string]interface{}), time.Time{}) _, err := dispatcher.Dispatch(did, job) return job.ID, err }
{ gob.Register([32]byte{}) }
testnet.ts
import { switchToClusterFromEnv } from 'src/lib/cluster' import { failIfVmBased } from 'src/lib/env-utils' import { isCelotoolHelmDryRun, resetAndUpgradeHelmChart, upgradeHelmChart, upgradeStaticIPs, } from 'src/lib/helm_deploy' import { uploadEnvFileToGoogleStorage, uploadGenesisBlockToGoogleStorage, uploadTestnetStaticNodesToGoogleStorage, } from 'src/lib/testnet-utils' import yargs from 'yargs' import { UpgradeArgv } from '../../deploy/upgrade' export const command = 'testnet' export const describe = 'upgrade an existing deploy of the testnet package' type TestnetArgv = UpgradeArgv & { reset: boolean useExistingGenesis: boolean } export const builder = (argv: yargs.Argv) => { return argv .option('reset', { describe: 'deletes any chain data in persistent volume claims', default: false, type: 'boolean', }) .option('useExistingGenesis', { type: 'boolean', description: 'Instead of generating a new genesis, use an existing genesis in GCS', default: false, }) } export const handler = async (argv: TestnetArgv) => {
failIfVmBased() await switchToClusterFromEnv() await upgradeStaticIPs(argv.celoEnv) if (argv.reset === true) { await resetAndUpgradeHelmChart(argv.celoEnv, argv.useExistingGenesis) if (!argv.useExistingGenesis) { await uploadGenesisBlockToGoogleStorage(argv.celoEnv) } } else { await upgradeHelmChart(argv.celoEnv, argv.useExistingGenesis) } if (!isCelotoolHelmDryRun()) { await uploadTestnetStaticNodesToGoogleStorage(argv.celoEnv) await uploadEnvFileToGoogleStorage(argv.celoEnv) } }
main.py
from scrape_utils import retrieveWebpage from sportsreview_importer import retrieveLinks, bulkDownloadData, collateData def saveSportReviewWebpage(): baseURL = 'https://www.sportsbookreviewsonline.com/scoresoddsarchives/nba/nbaoddsarchives.htm' saveFile = 'data/sportsbookreview_nba_odds_archive.html' element = '/html/body/table[2]/tbody/tr[1]/td[2]/table/tbody/tr[2]/td/ul/li[1]/a' retrieveWebpage(baseURL, saveFile, element) def retrieveSportsReviewLinks(): webpage = 'data/sportsbookreview_nba_odds_archive.html' base = 'https://www.sportsbookreviewsonline.com/scoresoddsarchives/nba/'
def bulkDownloadAllDataFile(): saveFile = 'data/sportsbookreview_downloadable_archive_links.json' bulkDownloadData(saveFile) def collateDownloadedData(): saveFile = 'data/sportsbookreview_downloadable_archive_links.json' collateData(saveFile) def main(): # saveSportReviewWebpage() # retrieveSportsReviewLinks() # bulkDownloadAllDataFile() collateDownloadedData() if __name__ == "__main__": main()
saveFile = 'data/sportsbookreview_downloadable_archive_links.json' retrieveLinks(webpage, base, saveFile)
endpointUtils.js
/** * Copyright (c) WSO2 Inc. (http://wso2.com) 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. */ import cloneDeep from 'lodash.clonedeep'; /** * Utility method to get the endpoint property name based on the given endpoint type and category. * * @param {string} type The type of the endpoint (load_balance/ failover) * @param {string} category The endpoint category (production/ sandbox) * @return {string} The property name of the endpoints. */ function
(type, category) { if (type !== 'failover') { return category; } else { return category === 'sandbox_endpoints' ? 'sandbox_failovers' : 'production_failovers'; } } /** * Merge the loadbalance/ failover endpoints to single object. * * @param {object} endpointConfig The endpoint config object * @return {object} {production: [], sandbox: []} * */ function mergeEndpoints(endpointConfig) { const type = endpointConfig.endpoint_type; if (type === 'load_balance') { return { production: endpointConfig.production_endpoints, sandbox: endpointConfig.sandbox_endpoints }; } else if (type === 'failover') { const prodEps = [endpointConfig.production_endpoints].concat(endpointConfig.production_failovers); const sandboxEps = [endpointConfig.sandbox_endpoints].concat(endpointConfig.sandbox_failovers); return { production: prodEps, sandbox: sandboxEps }; } return { production: [endpointConfig.production_endpoints], sandbox: [endpointConfig.sandbox_endpoints] }; } /** * Method to get the endpoints templates based on the selected endpoint type (loadbalance/ failover) and whether is * http or address endpoint. * * @param {string} endpointType The endpoint type * @param {bool} isAddressEndpoint Whether the endpoint is soap or not. * @param {object} currentEndpointConfig The existing endpoint information. * @return {object} A endpoint template object. * */ function getEndpointTemplateByType(endpointType, isAddressEndpoint, currentEndpointConfig) { const tmpEndpointConfig = {}; if (endpointType === 'failover') { tmpEndpointConfig.endpoint_type = endpointType; tmpEndpointConfig.production_failovers = currentEndpointConfig.production_failovers ? currentEndpointConfig.production_failovers : []; tmpEndpointConfig.sandbox_failovers = currentEndpointConfig.sandbox_failovers ? currentEndpointConfig.sandbox_failovers : []; tmpEndpointConfig.production_endpoints = Array.isArray(currentEndpointConfig.production_endpoints) ? currentEndpointConfig.production_endpoints[0] : currentEndpointConfig.production_endpoints; tmpEndpointConfig.sandbox_endpoints = Array.isArray(currentEndpointConfig.sandbox_endpoints) ? currentEndpointConfig.sandbox_endpoints[0] : currentEndpointConfig.sandbox_endpoints; tmpEndpointConfig.failOver = true; } else if (endpointType === 'load_balance') { tmpEndpointConfig.endpoint_type = endpointType; tmpEndpointConfig.algoClassName = 'org.apache.synapse.endpoints.algorithms.RoundRobin'; tmpEndpointConfig.algoCombo = 'org.apache.synapse.endpoints.algorithms.RoundRobin'; tmpEndpointConfig.sessionManagement = ''; tmpEndpointConfig.sessionTimeOut = ''; if (currentEndpointConfig.production_endpoints) { tmpEndpointConfig.production_endpoints = Array.isArray(currentEndpointConfig.production_endpoints) ? currentEndpointConfig.production_endpoints : [currentEndpointConfig.production_endpoints]; } if (currentEndpointConfig.sandbox_endpoints) { tmpEndpointConfig.sandbox_endpoints = Array.isArray(currentEndpointConfig.sandbox_endpoints) ? currentEndpointConfig.sandbox_endpoints : [currentEndpointConfig.sandbox_endpoints]; } tmpEndpointConfig.failOver = false; } else { tmpEndpointConfig.endpoint_type = isAddressEndpoint === true ? 'address' : 'http'; tmpEndpointConfig.production_endpoints = Array.isArray(currentEndpointConfig.production_endpoints) ? currentEndpointConfig.production_endpoints[0] : currentEndpointConfig.production_endpoints; tmpEndpointConfig.sandbox_endpoints = Array.isArray(currentEndpointConfig.sandbox_endpoints) ? currentEndpointConfig.sandbox_endpoints[0] : currentEndpointConfig.sandbox_endpoints; tmpEndpointConfig.failOver = false; } return tmpEndpointConfig; } /** * Returns all the endpoints as a list. * * @param {object} endpointConfig The endpoint config object from the api. * @return {array} The list of endpoints. * */ function endpointsToList(endpointConfig) { const config = cloneDeep(endpointConfig); const endpoints = []; if (Array.isArray(config.production_endpoints)) { endpoints.push(...config.production_endpoints); } else { endpoints.push(config.production_endpoints); } if (Array.isArray(config.sandbox_endpoints)) { endpoints.push(...config.sandbox_endpoints); } else { endpoints.push(config.sandbox_endpoints); } if (config.endpoint_type === 'failover') { if (config.sandbox_failovers) { endpoints.push(...config.sandbox_failovers); } if (config.production_failovers) { endpoints.push(...config.production_failovers); } } return endpoints; } /** * Returns an endpoint config object template based on the implementation method. * Eg: Managed, Prototyped. * * @param {string} implementationType The endpoint implementation type. * @return {object} The endpoint template. * */ function getEndpointConfigByImpl(implementationType) { const tmpEndpointConfig = {}; if (implementationType === 'PROTOTYPED') { tmpEndpointConfig.endpoint_type = 'http'; tmpEndpointConfig.implementation_status = 'prototyped'; tmpEndpointConfig.production_endpoints = { config: null, url: 'http://localhost' }; tmpEndpointConfig.sandbox_endpoints = { config: null, url: 'http://localhost' }; } else { tmpEndpointConfig.endpoint_type = 'http'; tmpEndpointConfig.production_endpoints = { url: '' }; tmpEndpointConfig.sandbox_endpoints = { url: '' }; tmpEndpointConfig.failOver = false; } return tmpEndpointConfig; } /** * Get the endpoint config based on the selected endpoint type. * Supported endpoint types: * 1. http * 2. address * 3. prototyped * 4. awslambda * 5. default (Dynamic) * * @param {string} endpointType The selected endpoint type. * @return {endpointConfig} Endpoint config object. * */ function createEndpointConfig(endpointType) { const tmpEndpointConfig = {}; switch (endpointType) { case 'http': tmpEndpointConfig.endpoint_type = 'http'; tmpEndpointConfig.failOver = false; break; case 'address': tmpEndpointConfig.endpoint_type = 'address'; tmpEndpointConfig.failOver = false; break; case 'prototyped': tmpEndpointConfig.implementation_status = 'prototyped'; tmpEndpointConfig.endpoint_type = 'http'; tmpEndpointConfig.production_endpoints = { config: null, url: 'http://localhost' }; tmpEndpointConfig.sandbox_endpoints = { config: null, url: 'http://localhost' }; break; case 'awslambda': tmpEndpointConfig.endpoint_type = 'awslambda'; tmpEndpointConfig.access_method = 'role-supplied'; tmpEndpointConfig.amznAccessKey = ''; tmpEndpointConfig.amznSecretKey = ''; tmpEndpointConfig.amznRegion = ''; break; default: tmpEndpointConfig.endpoint_type = 'default'; tmpEndpointConfig.production_endpoints = { url: 'default' }; tmpEndpointConfig.sandbox_endpoints = { url: 'default' }; tmpEndpointConfig.failOver = false; break; } return tmpEndpointConfig; } /** * Get the endpoint template based on endpoint type. * * @param {string} type: Endpoint type (HTTP/ Address) * @return {object} Endpoint Template * */ function getEndpointTemplate(type) { if (type === 'address') { return { url: '', endpoint_type: 'address', template_not_supported: false }; } return { url: '', template_not_supported: false }; } export { getEndpointTypeProperty, mergeEndpoints, getEndpointTemplateByType, endpointsToList, getEndpointConfigByImpl, createEndpointConfig, getEndpointTemplate, };
getEndpointTypeProperty
Navbar.js
import React from 'react'; import './Navbar.css'; function
(props) { return ( <nav className='navbar'> <ul className='navbar__nav'>{props.children}</ul> </nav> ) } export default Navbar
Navbar
tor_src_lib_fs_dir.go
// go-libtor - Self-contained Tor from Go // Copyright (c) 2018 Péter Szilágyi. All rights reserved. package libtor /* #define BUILDDIR "" #include <src/lib/fs/dir.c>
*/ import "C"
views.py
from urllib.parse import urlencode from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import SuccessURLAllowedHostsMixin from django.shortcuts import redirect from django.urls import reverse, reverse_lazy from django.utils.http import is_safe_url from django.utils.translation import gettext_lazy as _ from django.views.generic import FormView, TemplateView from mtp_common.auth.api_client import get_api_session from mtp_common.views import SettingsView from security import confirmed_prisons_flag, provided_job_info_flag from settings.forms import ConfirmPrisonForm, ChangePrisonForm, ALL_PRISONS_CODE, JobInformationForm from security.models import EmailNotifications from security.utils import save_user_flags, can_skip_confirming_prisons, has_provided_job_information class NomsOpsSettingsView(SettingsView):
class ConfirmPrisonsView(FormView): title = _('Confirm your prisons') template_name = 'settings/confirm-prisons.html' form_class = ConfirmPrisonForm success_url = reverse_lazy('confirm_prisons_confirmation') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_prisons'] = ','.join([ p['nomis_id'] for p in self.request.user.user_data['prisons'] ] if self.request.user.user_data.get('prisons') else ['ALL']) selected_prisons = self.request.GET.getlist('prisons') if not selected_prisons: selected_prisons = [ p['nomis_id'] for p in self.request.user.user_data['prisons'] ] if not selected_prisons: selected_prisons = [ALL_PRISONS_CODE] query_dict = self.request.GET.copy() query_dict['prisons'] = selected_prisons context['change_prison_query'] = urlencode(query_dict, doseq=True) self.request.cannot_navigate_away = not can_skip_confirming_prisons(self.request.user) return context def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): form.save() save_user_flags(self.request, confirmed_prisons_flag) return redirect(self.get_success_url()) def get_success_url(self): if 'next' in self.request.GET: return '{path}?{query}'.format( path=self.success_url, query=urlencode({'next': self.request.GET['next']}) ) return self.success_url class ChangePrisonsView(SuccessURLAllowedHostsMixin, FormView): title = _('Change prisons') template_name = 'settings/confirm-prisons-change.html' form_class = ChangePrisonForm def get_success_url(self): """ Returns the REDIRECT_FIELD_NAME value in GET if it exists and it's valid or the url to the settings page otherwise. """ if REDIRECT_FIELD_NAME in self.request.GET: next_page = self.request.GET[REDIRECT_FIELD_NAME] url_is_safe = is_safe_url( url=next_page, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) if url_is_safe: return next_page return reverse('settings') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data_attrs'] = { 'data-autocomplete-error-empty': _('Type a prison name'), 'data-autocomplete-error-summary': _('There was a problem'), 'data-event-category': 'PrisonConfirmation', } context['current_prisons'] = ','.join([ p['nomis_id'] for p in self.request.user.user_data['prisons'] ] if self.request.user.user_data.get('prisons') else ['ALL']) return context def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): form.save() save_user_flags(self.request, confirmed_prisons_flag) return redirect(self.get_success_url()) class AddOrRemovePrisonsView(ChangePrisonsView): title = _('Add or remove prisons') template_name = 'settings/confirm-prisons-change.html' form_class = ChangePrisonForm success_url = reverse_lazy('confirm_prisons') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.request.cannot_navigate_away = not can_skip_confirming_prisons(self.request.user) return context def form_valid(self, form): return redirect('{path}?{query}'.format( path=self.get_success_url(), query=form.get_confirmation_query_string() )) class ConfirmPrisonsConfirmationView(TemplateView): title = _('Your prisons have been saved') template_name = 'settings/confirm-prisons-confirmation.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['prisons'] = self.request.user_prisons return context class JobInformationView(SuccessURLAllowedHostsMixin, FormView): title = _('Help us improve this service') template_name = 'settings/job-information.html' form_class = JobInformationForm def dispatch(self, request, *args, **kwargs): request.cannot_navigate_away = True return super().dispatch(request, *args, **kwargs) def get_success_url(self): if REDIRECT_FIELD_NAME in self.request.GET: next_page = self.request.GET[REDIRECT_FIELD_NAME] url_is_safe = is_safe_url( url=next_page, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) if url_is_safe: return next_page return reverse('security:dashboard') def form_valid(self, form): if has_provided_job_information(self.request.user): return redirect(self.get_success_url()) session = get_api_session(self.request) session.post('/job-information/', json={'title': form.cleaned_data['job_title_or_other'], 'prison_estate': form.cleaned_data['prison_estate'], 'tasks': form.cleaned_data['tasks']}) save_user_flags(self.request, provided_job_info_flag) return super().form_valid(form)
template_name = 'settings/settings.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.can_access_security: session = get_api_session(self.request) email_preferences = session.get('/emailpreferences/').json() context['email_notifications'] = email_preferences['frequency'] != EmailNotifications.never return context def post(self, *args, **kwargs): if self.request.can_access_security and 'email_notifications' in self.request.POST: session = get_api_session(self.request) if self.request.POST['email_notifications'] == 'True': session.post('/emailpreferences/', json={'frequency': EmailNotifications.daily}) else: session.post('/emailpreferences/', json={'frequency': EmailNotifications.never}) return redirect(reverse_lazy('settings'))
parse.ts
/** * @module std */ import { flatbuffers } from './internal/flatbuffers'; import { __std } from './internal/__std_generated'; import { sendRequest } from './internal/deferred'; import Format = __std.Format; export function parse(input: string, format?: Format): any { const builder = new flatbuffers.Builder(512); const inputOffset = builder.createString(input); __std.ParseArgs.startParseArgs(builder); __std.ParseArgs.addChars(builder, inputOffset); if (format !== undefined) { __std.ParseArgs.addFormat(builder, format); } const argsOffset = __std.ParseArgs.endParseArgs(builder); __std.Message.startMessage(builder); __std.Message.addArgsType(builder, __std.Args.ParseArgs); __std.Message.addArgs(builder, argsOffset); builder.finish(__std.Message.endMessage(builder)); const buf = sendRequest(builder.asArrayBuffer()); const data = new flatbuffers.ByteBuffer(new Uint8Array(buf)); const resp = __std.ParseUnparseResponse.getRootAsParseUnparseResponse(data); switch (resp.retvalType()) { case __std.ParseUnparseRetval.Error: { const err = new __std.Error(); resp.retval(err); throw new Error(err.message()); } case __std.ParseUnparseRetval.ParseUnparseData: { const val = new __std.ParseUnparseData(); resp.retval(val); return JSON.parse(val.data()); } default: throw new Error('Response type was not set'); } }
__std.UnparseArgs.startUnparseArgs(builder); __std.UnparseArgs.addObject(builder, inputOffset); if (format !== undefined) { __std.UnparseArgs.addFormat(builder, format); } const argsOffset = __std.UnparseArgs.endUnparseArgs(builder); __std.Message.startMessage(builder); __std.Message.addArgsType(builder, __std.Args.UnparseArgs); __std.Message.addArgs(builder, argsOffset); builder.finish(__std.Message.endMessage(builder)); const buf = sendRequest(builder.asArrayBuffer()); const data = new flatbuffers.ByteBuffer(new Uint8Array(buf)); const resp = __std.ParseUnparseResponse.getRootAsParseUnparseResponse(data); switch (resp.retvalType()) { case __std.ParseUnparseRetval.Error: { const err = new __std.Error(); resp.retval(err); throw new Error(err.message()); } case __std.ParseUnparseRetval.ParseUnparseData: { const val = new __std.ParseUnparseData(); resp.retval(val); return val.data(); } default: throw new Error('Response type was not set'); } }
export function stringify(obj: any, format?: Format): string { const builder = new flatbuffers.Builder(512); const inputOffset = builder.createString(JSON.stringify(obj));
win2019_cuda11_installer.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """Dependency installer for Windows""" __author__ = 'Pedro Larroy, Chance Bair, Joe Evans' __version__ = '0.4' import argparse import errno import logging import os import psutil import shutil import subprocess import urllib import stat import tempfile import zipfile from time import sleep from urllib.error import HTTPError import logging from subprocess import check_output, check_call, call import re import sys import urllib.request import contextlib import glob import ssl ssl._create_default_https_context = ssl._create_unverified_context log = logging.getLogger(__name__) DEPS = { 'openblas': 'https://windows-post-install.s3-us-west-2.amazonaws.com/OpenBLAS-windows-v0_2_19.zip', 'opencv': 'https://windows-post-install.s3-us-west-2.amazonaws.com/opencv-windows-4.1.2-vc14_vc15.zip', 'cudnn7': 'https://windows-post-install.s3-us-west-2.amazonaws.com/cudnn-10.2-windows10-x64-v7.6.5.32.zip', 'cudnn8': 'https://windows-post-install.s3-us-west-2.amazonaws.com/cudnn-11.0-windows-x64-v8.0.3.33.zip', 'perl': 'http://strawberryperl.com/download/5.30.1.1/strawberry-perl-5.30.1.1-64bit.msi', 'clang': 'https://github.com/llvm/llvm-project/releases/download/llvmorg-9.0.1/LLVM-9.0.1-win64.exe', } DEFAULT_SUBPROCESS_TIMEOUT = 3600 @contextlib.contextmanager def remember_cwd(): ''' Restore current directory when exiting context ''' curdir = os.getcwd() try: yield finally: os.chdir(curdir) def retry(target_exception, tries=4, delay_s=1, backoff=2): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param target_exception: the exception to check. may be a tuple of exceptions to check :type target_exception: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay_s: initial delay between retries in seconds :type delay_s: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int """ import time from functools import wraps def decorated_retry(f): @wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay_s while mtries > 1: try: return f(*args, **kwargs) except target_exception as e: logging.warning("Exception: %s, Retrying in %d seconds...", str(e), mdelay) time.sleep(mdelay) mtries -= 1 mdelay *= backoff return f(*args, **kwargs) return f_retry # true decorator return decorated_retry @retry((ValueError, OSError, HTTPError), tries=5, delay_s=2, backoff=5) def download(url, dest=None, progress=False) -> str: from urllib.request import urlopen from urllib.parse import (urlparse, urlunparse) import progressbar import http.client class ProgressCB(): def __init__(self): self.pbar = None def __call__(self, block_num, block_size, total_size): if not self.pbar and total_size > 0: self.pbar = progressbar.bar.ProgressBar(max_value=total_size) downloaded = block_num * block_size if self.pbar: if downloaded < total_size: self.pbar.update(downloaded) else: self.pbar.finish() if dest and os.path.isdir(dest): local_file = os.path.split(urlparse(url).path)[1] local_path = os.path.normpath(os.path.join(dest, local_file)) else: local_path = dest with urlopen(url) as c: content_length = c.getheader('content-length') length = int(content_length) if content_length and isinstance(c, http.client.HTTPResponse) else None if length and local_path and os.path.exists(local_path) and os.stat(local_path).st_size == length: log.debug(f"download('{url}'): Already downloaded.") return local_path log.debug(f"download({url}, {local_path}): downloading {length} bytes") if local_path: with tempfile.NamedTemporaryFile(delete=False) as tmpfd: urllib.request.urlretrieve(url, filename=tmpfd.name, reporthook=ProgressCB() if progress else None) shutil.move(tmpfd.name, local_path) else: (local_path, _) = urllib.request.urlretrieve(url, reporthook=ProgressCB()) log.debug(f"download({url}, {local_path}'): done.") return local_path # Takes arguments and runs command on host. Shell is disabled by default. # TODO: Move timeout to args def run_command(*args, shell=False, timeout=DEFAULT_SUBPROCESS_TIMEOUT, **kwargs): try: logging.info("Issuing command: {}".format(args)) res = subprocess.check_output(*args, shell=shell, timeout=timeout).decode("utf-8").replace("\r\n", "\n") logging.info("Output: {}".format(res)) except subprocess.CalledProcessError as e: raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) return res # Copies source directory recursively to destination. def copy(src, dest): try: shutil.copytree(src, dest) logging.info("Moved {} to {}".format(src, dest)) except OSError as e: # If the error was caused because the source wasn't a directory if e.errno == errno.ENOTDIR: shutil.copy(src, dest) logging.info("Moved {} to {}".format(src, dest)) else: raise RuntimeError("copy return with error: {}".format(e)) # Workaround for windows readonly attribute error def on_rm_error(func, path, exc_info): # path contains the path of the file that couldn't be removed # let's just assume that it's read-only and unlink it.
def reboot_system(): logging.info("Rebooting system now...") run_command("shutdown -r -t 5") exit(0) def shutdown_system(): logging.info("Shutting down system now...") # wait 20 sec so we can capture the install logs run_command("shutdown -s -t 20") exit(0) def install_vs(): if os.path.exists("C:\\Program Files (x86)\\Microsoft Visual Studio\\2019"): logging.info("MSVS already installed, skipping.") return False # Visual Studio 2019 # Components: https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community?view=vs-2019#visual-studio-core-editor-included-with-visual-studio-community-2019 logging.info("Installing Visual Studio 2019...") vs_file_path = download('https://windows-post-install.s3-us-west-2.amazonaws.com/vs_community__1246179388.1585201415.exe') run_command("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(vs_file_path, vs_file_path.split('\\')[-1]), shell=True) vs_file_path = vs_file_path + '.exe' logging.info("Installing VisualStudio 2019.....") ret = call(vs_file_path + ' --add Microsoft.VisualStudio.Workload.ManagedDesktop' ' --add Microsoft.VisualStudio.Workload.NetCoreTools' ' --add Microsoft.VisualStudio.Workload.NetWeb' ' --add Microsoft.VisualStudio.Workload.Node' ' --add Microsoft.VisualStudio.Workload.Office' ' --add Microsoft.VisualStudio.Component.TypeScript.2.0' ' --add Microsoft.VisualStudio.Component.TestTools.WebLoadTest' ' --add Component.GitHub.VisualStudio' ' --add Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core' ' --add Microsoft.VisualStudio.Component.Static.Analysis.Tools' ' --add Microsoft.VisualStudio.Component.VC.CMake.Project' ' --add Microsoft.VisualStudio.Component.VC.140' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.Desktop' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.UWP' ' --add Microsoft.VisualStudio.Component.Windows10SDK.18362.UWP.Native' ' --add Microsoft.VisualStudio.ComponentGroup.Windows10SDK.18362' ' --add Microsoft.VisualStudio.Component.Windows10SDK.16299' ' --wait' ' --passive' ' --norestart' ) if ret == 3010 or ret == 0: # 3010 is restart required logging.info("VS install successful.") else: raise RuntimeError("VS failed to install, exit status {}".format(ret)) # Workaround for --wait sometimes ignoring the subprocesses doing component installs def vs_still_installing(): return {'vs_installer.exe', 'vs_installershell.exe', 'vs_setup_bootstrapper.exe'} & set(map(lambda process: process.name(), psutil.process_iter())) timer = 0 while vs_still_installing() and timer < DEFAULT_SUBPROCESS_TIMEOUT: logging.warning("VS installers still running for %d s", timer) if timer % 60 == 0: logging.info("Waiting for Visual Studio to install for the last {} seconds".format(str(timer))) sleep(1) timer += 1 if vs_still_installing(): logging.warning("VS install still running after timeout (%d)", DEFAULT_SUBPROCESS_TIMEOUT) else: logging.info("Visual studio install complete.") return True def install_perl(): if os.path.exists("C:\\Strawberry\\perl\\bin\\perl.exe"): logging.info("Perl already installed, skipping.") return False logging.info("Installing Perl") with tempfile.TemporaryDirectory() as tmpdir: perl_file_path = download(DEPS['perl'], tmpdir) check_call(['msiexec ', '/n', '/passive', '/i', perl_file_path]) logging.info("Perl install complete") return True def install_clang(): if os.path.exists("C:\\Program Files\\LLVM"): logging.info("Clang already installed, skipping.") return False logging.info("Installing Clang") with tempfile.TemporaryDirectory() as tmpdir: clang_file_path = download(DEPS['clang'], tmpdir) run_command(clang_file_path + " /S /D=C:\\Program Files\\LLVM") logging.info("Clang install complete") return True def install_openblas(): if os.path.exists("C:\\Program Files\\OpenBLAS-windows-v0_2_19"): logging.info("OpenBLAS already installed, skipping.") return False logging.info("Installing OpenBLAS") local_file = download(DEPS['openblas']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall("C:\\Program Files") run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name OpenBLAS_HOME -Value 'C:\\Program Files\\OpenBLAS-windows-v0_2_19'") logging.info("Openblas Install complete") return True def install_mkl(): if os.path.exists("C:\\Program Files (x86)\\IntelSWTools"): logging.info("Intel MKL already installed, skipping.") return False logging.info("Installing MKL 2019.3.203...") file_path = download("http://registrationcenter-download.intel.com/akdlm/irc_nas/tec/15247/w_mkl_2019.3.203.exe") run_command("{} --silent --remove-extracted-files yes --a install -output=C:\mkl-install-log.txt -eula=accept".format(file_path)) logging.info("MKL Install complete") return True def install_opencv(): if os.path.exists("C:\\Program Files\\opencv"): logging.info("OpenCV already installed, skipping.") return False logging.info("Installing OpenCV") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['opencv']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) copy(f'{tmpdir}\\opencv\\build', r'c:\Program Files\opencv') run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name OpenCV_DIR -Value 'C:\\Program Files\\opencv'") logging.info("OpenCV install complete") return True def install_cudnn7(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin\\cudnn64_7.dll"): logging.info("cuDNN7 already installed, skipping.") return False # cuDNN logging.info("Installing cuDNN7") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['cudnn7']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) for f in glob.glob(tmpdir+"\\cuda\\bin\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin") for f in glob.glob(tmpdir+"\\cuda\\include\\*.h"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\include") for f in glob.glob(tmpdir+"\\cuda\\lib\\x64\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\lib\\x64") logging.info("cuDNN7 install complete") return True def install_cudnn8(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin\\cudnn64_8.dll"): logging.info("cuDNN7 already installed, skipping.") return False # cuDNN logging.info("Installing cuDNN8") with tempfile.TemporaryDirectory() as tmpdir: local_file = download(DEPS['cudnn8']) with zipfile.ZipFile(local_file, 'r') as zip: zip.extractall(tmpdir) for f in glob.glob(tmpdir+"\\cuda\\bin\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin") for f in glob.glob(tmpdir+"\\cuda\\include\\*.h"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\include") for f in glob.glob(tmpdir+"\\cuda\\lib\\x64\\*"): copy(f, "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\lib\\x64") logging.info("cuDNN8 install complete") return True def instance_family(): return urllib.request.urlopen('http://instance-data/latest/meta-data/instance-type').read().decode().split('.')[0] CUDA_COMPONENTS=[ 'nvcc', 'cublas', 'cublas_dev', 'cudart', 'cufft', 'cufft_dev', 'curand', 'curand_dev', 'cusolver', 'cusolver_dev', 'cusparse', 'cusparse_dev', 'npp', 'npp_dev', 'nvrtc', 'nvrtc_dev', 'nvml_dev' ] def install_cuda110(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.0\\bin"): logging.info("CUDA 11.0 already installed, skipping.") return False logging.info("Downloadinng CUDA 11.0...") cuda_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/11.0.3/network_installers/cuda_11.0.3_win10_network.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(cuda_file_path, cuda_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename file failed") cuda_file_path = cuda_file_path + '.exe' logging.info("Installing CUDA 11.0...") check_call(cuda_file_path + ' -s') #check_call(cuda_file_path + ' -s ' + " ".join([p + "_11.0" for p in CUDA_COMPONENTS])) logging.info("Done installing CUDA 11.0.") return True def install_cuda102(): if os.path.exists("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin"): logging.info("CUDA 10.2 already installed, skipping.") return False logging.info("Downloading CUDA 10.2...") cuda_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/10.2/Prod/network_installers/cuda_10.2.89_win10_network.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(cuda_file_path, cuda_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename file failed") cuda_file_path = cuda_file_path + '.exe' logging.info("Installing CUDA 10.2...") check_call(cuda_file_path + ' -s') #check_call(cuda_file_path + ' -s ' + " ".join([p + "_10.2" for p in CUDA_COMPONENTS])) logging.info("Downloading CUDA 10.2 patch...") patch_file_path = download( 'http://developer.download.nvidia.com/compute/cuda/10.2/Prod/patches/1/cuda_10.2.1_win10.exe') try: check_call("PowerShell Rename-Item -Path {} -NewName \"{}.exe\"".format(patch_file_path, patch_file_path.split('\\')[-1]), shell=True) except subprocess.CalledProcessError as e: logging.exception("Rename patch failed") patch_file_path = patch_file_path + '.exe' logging.info("Installing CUDA patch...") check_call(patch_file_path + ' -s ') logging.info("Done installing CUDA 10.2 and patches.") return True def schedule_aws_userdata(): logging.info("Scheduling AWS init so userdata will run on next boot...") run_command("PowerShell C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Scripts\\InitializeInstance.ps1 -Schedule") def add_paths(): # TODO: Add python paths (python -> C:\\Python37\\python.exe, python2 -> C:\\Python27\\python.exe) logging.info("Adding Windows Kits to PATH...") current_path = run_command( "PowerShell (Get-Itemproperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name Path).Path") current_path = current_path.rstrip() logging.debug("current_path: {}".format(current_path)) new_path = current_path + \ ";C:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.16299.0\\x86;C:\\Program Files\\OpenBLAS-windows-v0_2_19\\bin;C:\\Program Files\\LLVM\\bin;C:\\Program Files\\opencv\\bin;C:\\Program Files\\opencv\\x64\\vc15\\bin" logging.debug("new_path: {}".format(new_path)) run_command("PowerShell Set-ItemProperty -path 'hklm:\\system\\currentcontrolset\\control\\session manager\\environment' -Name Path -Value '" + new_path + "'") def script_name() -> str: """:returns: script name with leading paths removed""" return os.path.split(sys.argv[0])[1] def remove_install_task(): logging.info("Removing stage2 startup task...") run_command("PowerShell Unregister-ScheduledTask -TaskName 'Stage2Install' -Confirm:$false") def main(): logging.getLogger().setLevel(os.environ.get('LOGLEVEL', logging.DEBUG)) logging.basicConfig(filename="C:\\install.log", format='{}: %(asctime)sZ %(levelname)s %(message)s'.format(script_name())) # install all necessary software and reboot after some components # for CUDA, the last version you install will be the default, based on PATH variable if install_cuda110(): reboot_system() install_cudnn8() #if install_cuda102(): # reboot_system() #install_cudnn7() if install_vs(): reboot_system() install_openblas() install_mkl() install_opencv() install_perl() install_clang() add_paths() remove_install_task() schedule_aws_userdata() shutdown_system() if __name__ == "__main__": exit(main())
os.chmod(path, stat.S_IWRITE) os.unlink(path)
IconArrowSwap_size_all.tsx
import * as React from 'react'; function
(props: React.SVGProps<SVGSVGElement>) { return ( <svg viewBox="0 0 24 24" {...props}> <path d="M13.7197 2.46967C14.0126 2.17678 14.4874 2.17678 14.7803 2.46967L19.2803 6.96967C19.5732 7.26256 19.5732 7.73744 19.2803 8.03033L14.7803 12.5303C14.4874 12.8232 14.0126 12.8232 13.7197 12.5303C13.4268 12.2374 13.4268 11.7626 13.7197 11.4697L16.9393 8.25H5.25C4.83579 8.25 4.5 7.91421 4.5 7.5C4.5 7.08579 4.83579 6.75 5.25 6.75H16.9393L13.7197 3.53033C13.4268 3.23744 13.4268 2.76256 13.7197 2.46967Z" /> <path d="M7.06066 17.25L10.2803 20.4697C10.5732 20.7626 10.5732 21.2374 10.2803 21.5303C9.98744 21.8232 9.51256 21.8232 9.21967 21.5303L4.71967 17.0303C4.42678 16.7374 4.42678 16.2626 4.71967 15.9697L9.21967 11.4697C9.51256 11.1768 9.98744 11.1768 10.2803 11.4697C10.5732 11.7626 10.5732 12.2374 10.2803 12.5303L7.06066 15.75H18.75C19.1642 15.75 19.5 16.0858 19.5 16.5C19.5 16.9142 19.1642 17.25 18.75 17.25H7.06066Z" /> </svg> ); } export default IconArrowSwapSizeAll;
IconArrowSwapSizeAll
api_op_PutScalingPolicy.go
// Code generated by smithy-go-codegen DO NOT EDIT. package applicationautoscaling import ( "context" 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/applicationautoscaling/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Creates or updates a scaling policy for an Application Auto Scaling scalable // target. Each scalable target is identified by a service namespace, resource ID, // and scalable dimension. A scaling policy applies to the scalable target // identified by those three attributes. You cannot create a scaling policy until // you have registered the resource as a scalable target. Multiple scaling policies // can be in force at the same time for the same scalable target. You can have one // or more target tracking scaling policies, one or more step scaling policies, or // both. However, there is a chance that multiple policies could conflict, // instructing the scalable target to scale out or in at the same time. Application // Auto Scaling gives precedence to the policy that provides the largest capacity // for both scale out and scale in. For example, if one policy increases capacity // by 3, another policy increases capacity by 200 percent, and the current capacity // is 10, Application Auto Scaling uses the policy with the highest calculated // capacity (200% of 10 = 20) and scales out to 30. We recommend caution, however, // when using target tracking scaling policies with step scaling policies because // conflicts between these policies can cause undesirable behavior. For example, if // the step scaling policy initiates a scale-in activity before the target tracking // policy is ready to scale in, the scale-in activity will not be blocked. After // the scale-in activity completes, the target tracking policy could instruct the // scalable target to scale out again. For more information, see Target tracking // scaling policies // (https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html) // and Step scaling policies // (https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html) // in the Application Auto Scaling User Guide. If a scalable target is // deregistered, the scalable target is no longer available to execute scaling // policies. Any scaling policies that were specified for the scalable target are // deleted. func (c *Client) PutScalingPolicy(ctx context.Context, params *PutScalingPolicyInput, optFns ...func(*Options)) (*PutScalingPolicyOutput, error) { if params == nil { params = &PutScalingPolicyInput{} } result, metadata, err := c.invokeOperation(ctx, "PutScalingPolicy", params, optFns, c.addOperationPutScalingPolicyMiddlewares) if err != nil { return nil, err } out := result.(*PutScalingPolicyOutput) out.ResultMetadata = metadata return out, nil } type PutScalingPolicyInput struct { // The name of the scaling policy. // // This member is required. PolicyName *string // The identifier of the resource associated with the scaling policy. This string // consists of the resource type and unique identifier. // // * ECS service - The // resource type is service and the unique identifier is the cluster name and // service name. Example: service/default/sample-webapp. // // * Spot Fleet request - // The resource type is spot-fleet-request and the unique identifier is the Spot // Fleet request ID. Example: // spot-fleet-request/sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE. // // * EMR cluster - // The resource type is instancegroup and the unique identifier is the cluster ID // and instance group ID. Example: // instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0. // // * AppStream 2.0 fleet - The // resource type is fleet and the unique identifier is the fleet name. Example: // fleet/sample-fleet. // // * DynamoDB table - The resource type is table and the // unique identifier is the table name. Example: table/my-table. // // * DynamoDB global // secondary index - The resource type is index and the unique identifier is the // index name. Example: table/my-table/index/my-table-index. // // * Aurora DB cluster - // The resource type is cluster and the unique identifier is the cluster name. // Example: cluster:my-db-cluster. // // * Amazon SageMaker endpoint variant - The // resource type is variant and the unique identifier is the resource ID. Example: // endpoint/my-end-point/variant/KMeansClustering. // // * Custom resources are not // supported with a resource type. This parameter must specify the OutputValue from // the CloudFormation template stack used to access the resources. The unique // identifier is defined by the service provider. More information is available in // our GitHub repository // (https://github.com/aws/aws-auto-scaling-custom-resource). // // * Amazon Comprehend // document classification endpoint - The resource type and unique identifier are // specified using the endpoint ARN. Example: // arn:aws:comprehend:us-west-2:123456789012:document-classifier-endpoint/EXAMPLE. // // * // Amazon Comprehend entity recognizer endpoint - The resource type and unique // identifier are specified using the endpoint ARN. Example: // arn:aws:comprehend:us-west-2:123456789012:entity-recognizer-endpoint/EXAMPLE. // // * // Lambda provisioned concurrency - The resource type is function and the unique // identifier is the function name with a function version or alias name suffix // that is not $LATEST. Example: function:my-function:prod or // function:my-function:1. // // * Amazon Keyspaces table - The resource type is table // and the unique identifier is the table name. Example: // keyspace/mykeyspace/table/mytable. // // * Amazon MSK cluster - The resource type and // unique identifier are specified using the cluster ARN. Example: // arn:aws:kafka:us-east-1:123456789012:cluster/demo-cluster-1/6357e0b2-0e6a-4b86-a0b4-70df934c2e31-5. // // This member is required. ResourceId *string // The scalable dimension. This string consists of the service namespace, resource // type, and scaling property. // // * ecs:service:DesiredCount - The desired task count // of an ECS service. // // * ec2:spot-fleet-request:TargetCapacity - The target // capacity of a Spot Fleet request. // // * // elasticmapreduce:instancegroup:InstanceCount - The instance count of an EMR // Instance Group. // // * appstream:fleet:DesiredCapacity - The desired capacity of an // AppStream 2.0 fleet. // // * dynamodb:table:ReadCapacityUnits - The provisioned read // capacity for a DynamoDB table. // // * dynamodb:table:WriteCapacityUnits - The // provisioned write capacity for a DynamoDB table. // // * // dynamodb:index:ReadCapacityUnits - The provisioned read capacity for a DynamoDB // global secondary index. // // * dynamodb:index:WriteCapacityUnits - The provisioned // write capacity for a DynamoDB global secondary index. // // * // rds:cluster:ReadReplicaCount - The count of Aurora Replicas in an Aurora DB // cluster. Available for Aurora MySQL-compatible edition and Aurora // PostgreSQL-compatible edition. // // * sagemaker:variant:DesiredInstanceCount - The // number of EC2 instances for an Amazon SageMaker model endpoint variant. // // * // custom-resource:ResourceType:Property - The scalable dimension for a custom // resource provided by your own application or service. // // * // comprehend:document-classifier-endpoint:DesiredInferenceUnits - The number of // inference units for an Amazon Comprehend document classification endpoint. // // * // comprehend:entity-recognizer-endpoint:DesiredInferenceUnits - The number of // inference units for an Amazon Comprehend entity recognizer endpoint. // // * // lambda:function:ProvisionedConcurrency - The provisioned concurrency for a // Lambda function. // // * cassandra:table:ReadCapacityUnits - The provisioned read // capacity for an Amazon Keyspaces table. // // * cassandra:table:WriteCapacityUnits - // The provisioned write capacity for an Amazon Keyspaces table. // // * // kafka:broker-storage:VolumeSize - The provisioned volume size (in GiB) for // brokers in an Amazon MSK cluster. // // This member is required. ScalableDimension types.ScalableDimension // The namespace of the AWS service that provides the resource. For a resource // provided by your own application or service, use custom-resource instead. // // This member is required. ServiceNamespace types.ServiceNamespace // The policy type. This parameter is required if you are creating a scaling // policy. The following policy types are supported: TargetTrackingScaling—Not // supported for Amazon EMR StepScaling—Not supported for DynamoDB, Amazon // Comprehend, Lambda, Amazon Keyspaces (for Apache Cassandra), or Amazon MSK. For // more information, see Target tracking scaling policies // (https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html) // and Step scaling policies // (https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html) // in the Application Auto Scaling User Guide. PolicyType types.PolicyType // A step scaling policy. This parameter is required if you are creating a policy // and the policy type is StepScaling. StepScalingPolicyConfiguration *types.StepScalingPolicyConfiguration // A target tracking scaling policy. Includes support for predefined or customized // metrics. This parameter is required if you are creating a policy and the policy // type is TargetTrackingScaling. TargetTrackingScalingPolicyConfiguration *types.TargetTrackingScalingPolicyConfiguration } type PutScalingPolicyOutput struct { // The Amazon Resource Name (ARN) of the resulting scaling policy. // // This member is required. PolicyARN *string // The CloudWatch alarms created for the target tracking scaling policy. Alarms []types.Alarm // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func (c *Client) addOperationPutScalingPolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutScalingPolicy{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutScalingPolicy{}, middleware.After) if err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } 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.AddRawResponseToMetadata(stack); err != nil { return err } if err = awsmiddleware.AddRecordResponseTiming(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 = addOpPutScalingPolicyValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutScalingPolicy(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 {
func newServiceMetadataMiddleware_opPutScalingPolicy(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "application-autoscaling", OperationName: "PutScalingPolicy", } }
return err } return nil }
precache-manifest.c78b0984798b61e469ab5d6abe51041b.js
self.__precacheManifest = [ { "revision": "c2d2420ec4230fd9f5c1", "url": "/static/css/main.33b6586e.chunk.css"
"revision": "c2d2420ec4230fd9f5c1", "url": "/static/js/main.c2d2420e.chunk.js" }, { "revision": "fdfcfda2d9b1bf31db52", "url": "/static/js/runtime~main.fdfcfda2.js" }, { "revision": "d16a266844ec01aafc8a", "url": "/static/js/2.d16a2668.chunk.js" }, { "revision": "5d5d9eefa31e5e13a6610d9fa7a283bb", "url": "/static/media/logo.5d5d9eef.svg" }, { "revision": "a8cb197126268a6550d5cd61fb4152ef", "url": "/index.html" } ];
}, {
varstack_pillar.py
# -*- coding: utf-8 -*- ''' Use `Varstack <https://github.com/conversis/varstack>`_ data as a Pillar source Configuring Varstack ==================== Using varstack in Salt is fairly simple. Just put the following into the config file of your master: .. code-block:: yaml ext_pillar: - varstack: /etc/varstack.yaml Varstack will then use /etc/varstack.yaml to determine which configuration data to return as pillar information. From there you can take a look at the `README <https://github.com/conversis/varstack/blob/master/README.md>`_ of varstack on how this file is evaluated. ''' from __future__ import absolute_import # Import python libs import logging HAS_VARSTACK = False try: import varstack HAS_VARSTACK = True except ImportError: pass # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'varstack' def __virtual__(): if not HAS_VARSTACK: return False return __virtualname__ def
(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 conf): ''' Parse varstack data and return the result ''' vs = varstack.Varstack(config_filename=conf) return vs.evaluate(__grains__)
ext_pillar
gep.rs
use SafeWrapper; use ir::{User, Instruction, Value, Type}; use sys; /// An instruction which can read elements from a pointer. pub struct
<'ctx>(Instruction<'ctx>); impl<'ctx> GetElementPtrInst<'ctx> { /// Creates a new GEP instruction. pub fn new(pointee_ty: &Type, pointer: &Value, indices: &[&Value]) -> Self { GetElementPtrInst::new_generic(pointee_ty, pointer, indices, false) } /// Creates a new in-bounds GEP instruction. pub fn inbounds(pointee_ty: &Type, pointer: &Value, indices: &[&Value]) -> Self { GetElementPtrInst::new_generic(pointee_ty, pointer, indices, true) } /// Creates a new GEP instruction. pub fn new_generic(pointee_ty: &Type, pointer: &Value, indices: &[&Value], in_bounds: bool) -> Self { let indices: Vec<_> = indices.iter().map(|i| i.inner()).collect(); unsafe { let inner = sys::LLVMRustCreateGetElementPtrInst(pointee_ty.inner(), pointer.inner(), &indices, in_bounds); wrap_value!(inner => User => Instruction => GetElementPtrInst) } } } impl_subtype!(GetElementPtrInst => Instruction);
GetElementPtrInst
push_to_listen_again.go
/* * DialMyCalls API * * The DialMyCalls API * * OpenAPI spec version: 2.0.1 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License");
* 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 dialmycalls type PushToListenAgain struct { // The add-on type. Option: listen Type_ string `json:"type,omitempty"` // Add a generic add-on message. AddMessage Object `json:"add_message,omitempty"` }
* you may not use this file except in compliance with the License. * You may obtain a copy of the License at *
function.py
""" There are three types of functions implemented in SymPy: 1) defined functions (in the sense that they can be evaluated) like exp or sin; they have a name and a body: f = exp 2) undefined function which have a name but no body. Undefined functions can be defined using a Function class as follows: f = Function('f') (the result will be a Function instance) 3) anonymous function (or lambda function) which have a body (defined with dummy variables) but have no name: f = Lambda(x, exp(x)*x) f = Lambda((x, y), exp(x)*y) The fourth type of functions are composites, like (sin + cos)(x); these work in SymPy core, but are not yet part of SymPy. Examples ======== >>> import sympy >>> f = sympy.Function("f") >>> from sympy.abc import x >>> f(x) f(x) >>> print(sympy.srepr(f(x).func)) Function('f') >>> f(x).args (x,) """ from typing import Any, Dict as tDict, Optional, Set as tSet, Tuple as tTuple, Union as tUnion from collections.abc import Iterable from .add import Add from .assumptions import ManagedProperties from .basic import Basic, _atomic from .cache import cacheit from .containers import Tuple, Dict from .decorators import _sympifyit from .expr import Expr, AtomicExpr from .logic import fuzzy_and, fuzzy_or, fuzzy_not, FuzzyBool from .mul import Mul from .numbers import Rational, Float, Integer from .operations import LatticeOp from .parameters import global_parameters from .rules import Transform from .singleton import S from .sympify import sympify from .sorting import default_sort_key, ordered from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) from sympy.utilities.iterables import (has_dups, sift, iterable, is_sequence, uniq, topological_sort) from sympy.utilities.lambdify import MPMATH_TRANSLATIONS from sympy.utilities.misc import as_int, filldedent, func_name import mpmath from mpmath.libmp.libmpf import prec_to_dps import inspect from collections import Counter def _coeff_isneg(a): """Return True if the leading Number is negative. Examples ======== >>> from sympy.core.function import _coeff_isneg >>> from sympy import S, Symbol, oo, pi >>> _coeff_isneg(-3*pi) True >>> _coeff_isneg(S(3)) False >>> _coeff_isneg(-oo) True >>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1 False For matrix expressions: >>> from sympy import MatrixSymbol, sqrt >>> A = MatrixSymbol("A", 3, 3) >>> _coeff_isneg(-sqrt(2)*A) True >>> _coeff_isneg(sqrt(2)*A) False """ if a.is_MatMul: a = a.args[0] if a.is_Mul: a = a.args[0] return a.is_Number and a.is_extended_negative class PoleError(Exception): pass class ArgumentIndexError(ValueError): def __str__(self): return ("Invalid operation with argument number %s for Function %s" % (self.args[1], self.args[0])) class BadSignatureError(TypeError): '''Raised when a Lambda is created with an invalid signature''' pass class BadArgumentsError(TypeError): '''Raised when a Lambda is called with an incorrect number of arguments''' pass # Python 3 version that does not raise a Deprecation warning def arity(cls): """Return the arity of the function if it is known, else None. Explanation =========== When default values are specified for some arguments, they are optional and the arity is reported as a tuple of possible values. Examples ======== >>> from sympy import arity, log >>> arity(lambda x: x) 1 >>> arity(log) (1, 2) >>> arity(lambda *x: sum(x)) is None True """ eval_ = getattr(cls, 'eval', cls) parameters = inspect.signature(eval_).parameters.items() if [p for _, p in parameters if p.kind == p.VAR_POSITIONAL]: return p_or_k = [p for _, p in parameters if p.kind == p.POSITIONAL_OR_KEYWORD] # how many have no default and how many have a default value no, yes = map(len, sift(p_or_k, lambda p:p.default == p.empty, binary=True)) return no if not yes else tuple(range(no, no + yes + 1)) class FunctionClass(ManagedProperties): """ Base class for function classes. FunctionClass is a subclass of type. Use Function('<function name>' [ , signature ]) to create undefined function classes. """ _new = type.__new__ def __init__(cls, *args, **kwargs): # honor kwarg value or class-defined value before using # the number of arguments in the eval function (if present) nargs = kwargs.pop('nargs', cls.__dict__.get('nargs', arity(cls))) if nargs is None and 'nargs' not in cls.__dict__: for supcls in cls.__mro__: if hasattr(supcls, '_nargs'): nargs = supcls._nargs break else: continue # Canonicalize nargs here; change to set in nargs. if is_sequence(nargs): if not nargs: raise ValueError(filldedent(''' Incorrectly specified nargs as %s: if there are no arguments, it should be `nargs = 0`; if there are any number of arguments, it should be `nargs = None`''' % str(nargs))) nargs = tuple(ordered(set(nargs))) elif nargs is not None: nargs = (as_int(nargs),) cls._nargs = nargs super().__init__(*args, **kwargs) @property def __signature__(self): """ Allow Python 3's inspect.signature to give a useful signature for Function subclasses. """ # Python 3 only, but backports (like the one in IPython) still might # call this. try: from inspect import signature except ImportError: return None # TODO: Look at nargs return signature(self.eval) @property def free_symbols(self): return set() @property def xreplace(self): # Function needs args so we define a property that returns # a function that takes args...and then use that function # to return the right value return lambda rule, **_: rule.get(self, self) @property def nargs(self): """Return a set of the allowed number of arguments for the function. Examples ======== >>> from sympy import Function >>> f = Function('f') If the function can take any number of arguments, the set of whole numbers is returned: >>> Function('f').nargs Naturals0 If the function was initialized to accept one or more arguments, a corresponding set will be returned: >>> Function('f', nargs=1).nargs {1} >>> Function('f', nargs=(2, 1)).nargs {1, 2} The undefined function, after application, also has the nargs attribute; the actual number of arguments is always available by checking the ``args`` attribute: >>> f = Function('f') >>> f(1).nargs Naturals0 >>> len(f(1).args) 1 """ from sympy.sets.sets import FiniteSet # XXX it would be nice to handle this in __init__ but there are import # problems with trying to import FiniteSet there return FiniteSet(*self._nargs) if self._nargs else S.Naturals0 def __repr__(cls): return cls.__name__ class Application(Basic, metaclass=FunctionClass): """ Base class for applied functions. Explanation =========== Instances of Application represent the result of applying an application of any type to any object. """ is_Function = True @cacheit def __new__(cls, *args, **options): from sympy.sets.fancysets import Naturals0 from sympy.sets.sets import FiniteSet args = list(map(sympify, args)) evaluate = options.pop('evaluate', global_parameters.evaluate) # WildFunction (and anything else like it) may have nargs defined # and we throw that value away here options.pop('nargs', None) if options: raise ValueError("Unknown options: %s" % options) if evaluate: evaluated = cls.eval(*args) if evaluated is not None: return evaluated obj = super().__new__(cls, *args, **options) # make nargs uniform here sentinel = object() objnargs = getattr(obj, "nargs", sentinel) if objnargs is not sentinel: # things passing through here: # - functions subclassed from Function (e.g. myfunc(1).nargs) # - functions like cos(1).nargs # - AppliedUndef with given nargs like Function('f', nargs=1)(1).nargs # Canonicalize nargs here if is_sequence(objnargs): nargs = tuple(ordered(set(objnargs))) elif objnargs is not None: nargs = (as_int(objnargs),) else: nargs = None else: # things passing through here: # - WildFunction('f').nargs # - AppliedUndef with no nargs like Function('f')(1).nargs nargs = obj._nargs # note the underscore here # convert to FiniteSet obj.nargs = FiniteSet(*nargs) if nargs else Naturals0() return obj @classmethod def eval(cls, *args): """ Returns a canonical form of cls applied to arguments args. Explanation =========== The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None. Examples of eval() for the function "sign" --------------------------------------------- .. code-block:: python @classmethod def eval(cls, arg): if arg is S.NaN: return S.NaN if arg.is_zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, Mul): coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One: return cls(coeff) * cls(terms) """ return @property def func(self): return self.__class__ def _eval_subs(self, old, new): if (old.is_Function and new.is_Function and callable(old) and callable(new) and old == self.func and len(self.args) in new.nargs): return new(*[i._subs(old, new) for i in self.args]) class Function(Application, Expr): """ Base class for applied mathematical functions. It also serves as a constructor for undefined function classes. Examples ======== First example shows how to use Function as a constructor for undefined function classes: >>> from sympy import Function, Symbol >>> x = Symbol('x') >>> f = Function('f') >>> g = Function('g')(x) >>> f f >>> f(x) f(x) >>> g g(x) >>> f(x).diff(x) Derivative(f(x), x) >>> g.diff(x) Derivative(g(x), x) Assumptions can be passed to Function, and if function is initialized with a Symbol, the function inherits the name and assumptions associated with the Symbol: >>> f_real = Function('f', real=True) >>> f_real(x).is_real True >>> f_real_inherit = Function(Symbol('f', real=True)) >>> f_real_inherit(x).is_real True Note that assumptions on a function are unrelated to the assumptions on the variable it is called on. If you want to add a relationship, subclass Function and define the appropriate ``_eval_is_assumption`` methods. In the following example Function is used as a base class for ``my_func`` that represents a mathematical function *my_func*. Suppose that it is well known, that *my_func(0)* is *1* and *my_func* at infinity goes to *0*, so we want those two simplifications to occur automatically. Suppose also that *my_func(x)* is real exactly when *x* is real. Here is an implementation that honours those requirements: >>> from sympy import Function, S, oo, I, sin >>> class my_func(Function): ... ... @classmethod ... def eval(cls, x): ... if x.is_Number: ... if x.is_zero: ... return S.One ... elif x is S.Infinity: ... return S.Zero ... ... def _eval_is_real(self): ... return self.args[0].is_real ... >>> x = S('x') >>> my_func(0) + sin(0) 1 >>> my_func(oo) 0 >>> my_func(3.54).n() # Not yet implemented for my_func. my_func(3.54) >>> my_func(I).is_real False In order for ``my_func`` to become useful, several other methods would need to be implemented. See source code of some of the already implemented functions for more complete examples. Also, if the function can take more than one argument, then ``nargs`` must be defined, e.g. if ``my_func`` can take one or two arguments then, >>> class my_func(Function): ... nargs = (1, 2) ... >>> """ @property def _diff_wrt(self): return False @cacheit def __new__(cls, *args, **options): # Handle calls like Function('f') if cls is Function: return UndefinedFunction(*args, **options) n = len(args) if n not in cls.nargs: # XXX: exception message must be in exactly this format to # make it work with NumPy's functions like vectorize(). See, # for example, https://github.com/numpy/numpy/issues/1697. # The ideal solution would be just to attach metadata to # the exception and change NumPy to take advantage of this. temp = ('%(name)s takes %(qual)s %(args)s ' 'argument%(plural)s (%(given)s given)') raise TypeError(temp % { 'name': cls, 'qual': 'exactly' if len(cls.nargs) == 1 else 'at least', 'args': min(cls.nargs), 'plural': 's'*(min(cls.nargs) != 1), 'given': n}) evaluate = options.get('evaluate', global_parameters.evaluate) result = super().__new__(cls, *args, **options) if evaluate and isinstance(result, cls) and result.args: pr2 = min(cls._should_evalf(a) for a in result.args) if pr2 > 0: pr = max(cls._should_evalf(a) for a in result.args) result = result.evalf(prec_to_dps(pr)) return result @classmethod def _should_evalf(cls, arg): """ Decide if the function should automatically evalf(). Explanation =========== By default (in this implementation), this happens if (and only if) the ARG is a floating point number. This function is used by __new__. Returns the precision to evalf to, or -1 if it shouldn't evalf. """ if arg.is_Float: return arg._prec if not arg.is_Add: return -1 from .evalf import pure_complex m = pure_complex(arg) if m is None or not (m[0].is_Float or m[1].is_Float): return -1 l = [i._prec for i in m if i.is_Float] l.append(-1) return max(l) @classmethod def class_key(cls): from sympy.sets.fancysets import Naturals0 funcs = { 'exp': 10, 'log': 11, 'sin': 20, 'cos': 21, 'tan': 22, 'cot': 23, 'sinh': 30, 'cosh': 31, 'tanh': 32, 'coth': 33, 'conjugate': 40, 're': 41, 'im': 42, 'arg': 43, } name = cls.__name__ try: i = funcs[name] except KeyError: i = 0 if isinstance(cls.nargs, Naturals0) else 10000 return 4, i, name def _eval_evalf(self, prec): def _get_mpmath_func(fname): """Lookup mpmath function based on name""" if isinstance(self, AppliedUndef): # Shouldn't lookup in mpmath but might have ._imp_ return None if not hasattr(mpmath, fname): fname = MPMATH_TRANSLATIONS.get(fname, None) if fname is None: return None return getattr(mpmath, fname) _eval_mpmath = getattr(self, '_eval_mpmath', None) if _eval_mpmath is None: func = _get_mpmath_func(self.func.__name__) args = self.args else: func, args = _eval_mpmath() # Fall-back evaluation if func is None: imp = getattr(self, '_imp_', None) if imp is None: return None try: return Float(imp(*[i.evalf(prec) for i in self.args]), prec) except (TypeError, ValueError): return None # Convert all args to mpf or mpc # Convert the arguments to *higher* precision than requested for the # final result. # XXX + 5 is a guess, it is similar to what is used in evalf.py. Should # we be more intelligent about it? try: args = [arg._to_mpmath(prec + 5) for arg in args] def bad(m): from mpmath import mpf, mpc # the precision of an mpf value is the last element # if that is 1 (and m[1] is not 1 which would indicate a # power of 2), then the eval failed; so check that none of # the arguments failed to compute to a finite precision. # Note: An mpc value has two parts, the re and imag tuple; # check each of those parts, too. Anything else is allowed to # pass if isinstance(m, mpf): m = m._mpf_ return m[1] !=1 and m[-1] == 1 elif isinstance(m, mpc): m, n = m._mpc_ return m[1] !=1 and m[-1] == 1 and \ n[1] !=1 and n[-1] == 1 else: return False if any(bad(a) for a in args): raise ValueError # one or more args failed to compute with significance except ValueError: return with mpmath.workprec(prec): v = func(*args) return Expr._from_mpmath(v, prec) def _eval_derivative(self, s): # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s) i = 0 l = [] for a in self.args: i += 1 da = a.diff(s) if da.is_zero: continue try: df = self.fdiff(i) except ArgumentIndexError: df = Function.fdiff(self, i) l.append(df * da) return Add(*l) def _eval_is_commutative(self): return fuzzy_and(a.is_commutative for a in self.args) def _eval_is_meromorphic(self, x, a): if not self.args: return True if any(arg.has(x) for arg in self.args[1:]): return False arg = self.args[0] if not arg._eval_is_meromorphic(x, a): return None return fuzzy_not(type(self).is_singular(arg.subs(x, a))) _singularities = None # type: tUnion[FuzzyBool, tTuple[Expr, ...]] @classmethod def is_singular(cls, a): """ Tests whether the argument is an essential singularity or a branch point, or the functions is non-holomorphic. """ ss = cls._singularities if ss in (True, None, False): return ss return fuzzy_or(a.is_infinite if s is S.ComplexInfinity else (a - s).is_zero for s in ss) def as_base_exp(self): """ Returns the method as the 2-tuple (base, exponent). """ return self, S.One def _eval_aseries(self, n, args0, x, logx): """ Compute an asymptotic expansion around args0, in terms of self.args. This function is only used internally by _eval_nseries and should not be called directly; derived classes can overwrite this to implement asymptotic expansions. """ raise PoleError(filldedent(''' Asymptotic expansion of %s around %s is not implemented.''' % (type(self), args0))) def _eval_nseries(self, x, n, logx, cdir=0): """ This function does compute series for multivariate functions, but the expansion is always in terms of *one* variable. Examples ======== >>> from sympy import atan2 >>> from sympy.abc import x, y >>> atan2(x, y).series(x, n=2) atan2(0, y) + x/y + O(x**2) >>> atan2(x, y).series(y, n=2) -y/x + atan2(x, 0) + O(y**2) This function also computes asymptotic expansions, if necessary and possible: >>> from sympy import loggamma >>> loggamma(1/x)._eval_nseries(x,0,None) -1/x - log(x)/x + log(x)/2 + O(1) """ from .symbol import uniquely_named_symbol from sympy.series.order import Order from sympy.sets.sets import FiniteSet args = self.args args0 = [t.limit(x, 0) for t in args] if any(t.is_finite is False for t in args0): from .numbers import oo, zoo, nan # XXX could use t.as_leading_term(x) here but it's a little # slower a = [t.compute_leading_term(x, logx=logx) for t in args] a0 = [t.limit(x, 0) for t in a] if any(t.has(oo, -oo, zoo, nan) for t in a0): return self._eval_aseries(n, args0, x, logx) # Careful: the argument goes to oo, but only logarithmically so. We # are supposed to do a power series expansion "around the # logarithmic term". e.g. # f(1+x+log(x)) # -> f(1+logx) + x*f'(1+logx) + O(x**2) # where 'logx' is given in the argument a = [t._eval_nseries(x, n, logx) for t in args] z = [r - r0 for (r, r0) in zip(a, a0)] p = [Dummy() for _ in z] q = [] v = None for ai, zi, pi in zip(a0, z, p): if zi.has(x): if v is not None: raise NotImplementedError q.append(ai + pi) v = pi else: q.append(ai) e1 = self.func(*q) if v is None: return e1 s = e1._eval_nseries(v, n, logx) o = s.getO() s = s.removeO() s = s.subs(v, zi).expand() + Order(o.expr.subs(v, zi), x) return s if (self.func.nargs is S.Naturals0 or (self.func.nargs == FiniteSet(1) and args0[0]) or any(c > 1 for c in self.func.nargs)): e = self e1 = e.expand() if e == e1: #for example when e = sin(x+1) or e = sin(cos(x)) #let's try the general algorithm if len(e.args) == 1: # issue 14411 e = e.func(e.args[0].cancel()) term = e.subs(x, S.Zero) if term.is_finite is False or term is S.NaN: raise PoleError("Cannot expand %s around 0" % (self)) series = term fact = S.One _x = uniquely_named_symbol('xi', self) e = e.subs(x, _x) for i in range(n - 1): i += 1 fact *= Rational(i) e = e.diff(_x) subs = e.subs(_x, S.Zero) if subs is S.NaN: # try to evaluate a limit if we have to subs = e.limit(_x, S.Zero) if subs.is_finite is False: raise PoleError("Cannot expand %s around 0" % (self)) term = subs*(x**i)/fact term = term.expand() series += term return series + Order(x**n, x) return e1.nseries(x, n=n, logx=logx) arg = self.args[0] l = [] g = None # try to predict a number of terms needed nterms = n + 2 cf = Order(arg.as_leading_term(x), x).getn() if cf != 0: nterms = (n/cf).ceiling() for i in range(nterms): g = self.taylor_term(i, arg, g) g = g.nseries(x, n=n, logx=logx) l.append(g) return Add(*l) + Order(x**n, x) def fdiff(self, argindex=1): """ Returns the first derivative of the function. """ if not (1 <= argindex <= len(self.args)): raise ArgumentIndexError(self, argindex) ix = argindex - 1 A = self.args[ix] if A._diff_wrt: if len(self.args) == 1 or not A.is_Symbol: return _derivative_dispatch(self, A) for i, v in enumerate(self.args): if i != ix and A in v.free_symbols: # it can't be in any other argument's free symbols # issue 8510 break else: return _derivative_dispatch(self, A) # See issue 4624 and issue 4719, 5600 and 8510 D = Dummy('xi_%i' % argindex, dummy_index=hash(A)) args = self.args[:ix] + (D,) + self.args[ix + 1:] return Subs(Derivative(self.func(*args), D), D, A) def _eval_as_leading_term(self, x, logx=None, cdir=0): """Stub that should be overridden by new Functions to return the first non-zero term in a series if ever an x-dependent argument whose leading term vanishes as x -> 0 might be encountered. See, for example, cos._eval_as_leading_term. """ from sympy.series.order import Order args = [a.as_leading_term(x, logx=logx) for a in self.args] o = Order(1, x) if any(x in a.free_symbols and o.contains(a) for a in args): # Whereas x and any finite number are contained in O(1, x), # expressions like 1/x are not. If any arg simplified to a # vanishing expression as x -> 0 (like x or x**2, but not # 3, 1/x, etc...) then the _eval_as_leading_term is needed # to supply the first non-zero term of the series, # # e.g. expression leading term # ---------- ------------ # cos(1/x) cos(1/x) # cos(cos(x)) cos(1) # cos(x) 1 <- _eval_as_leading_term needed # sin(x) x <- _eval_as_leading_term needed # raise NotImplementedError( '%s has no _eval_as_leading_term routine' % self.func) else: return self.func(*args) class AppliedUndef(Function): """ Base class for expressions resulting from the application of an undefined function. """ is_number = False def __new__(cls, *args, **options): args = list(map(sympify, args)) u = [a.name for a in args if isinstance(a, UndefinedFunction)] if u: raise TypeError('Invalid argument: expecting an expression, not UndefinedFunction%s: %s' % ( 's'*(len(u) > 1), ', '.join(u))) obj = super().__new__(cls, *args, **options) return obj def _eval_as_leading_term(self, x, logx=None, cdir=0): return self @property def _diff_wrt(self): """ Allow derivatives wrt to undefined functions. Examples ======== >>> from sympy import Function, Symbol >>> f = Function('f') >>> x = Symbol('x') >>> f(x)._diff_wrt True >>> f(x).diff(x) Derivative(f(x), x) """ return True class UndefSageHelper: """ Helper to facilitate Sage conversion. """ def __get__(self, ins, typ): import sage.all as sage if ins is None: return lambda: sage.function(typ.__name__) else: args = [arg._sage_() for arg in ins.args] return lambda : sage.function(ins.__class__.__name__)(*args) _undef_sage_helper = UndefSageHelper() class UndefinedFunction(FunctionClass): """ The (meta)class of undefined functions. """ def __new__(mcl, name, bases=(AppliedUndef,), __dict__=None, **kwargs): from .symbol import _filter_assumptions # Allow Function('f', real=True) # and/or Function(Symbol('f', real=True)) assumptions, kwargs = _filter_assumptions(kwargs) if isinstance(name, Symbol): assumptions = name._merge(assumptions) name = name.name elif not isinstance(name, str): raise TypeError('expecting string or Symbol for name') else: commutative = assumptions.get('commutative', None) assumptions = Symbol(name, **assumptions).assumptions0 if commutative is None: assumptions.pop('commutative') __dict__ = __dict__ or {} # put the `is_*` for into __dict__ __dict__.update({'is_%s' % k: v for k, v in assumptions.items()}) # You can add other attributes, although they do have to be hashable # (but seriously, if you want to add anything other than assumptions, # just subclass Function) __dict__.update(kwargs) # add back the sanitized assumptions without the is_ prefix kwargs.update(assumptions) # Save these for __eq__ __dict__.update({'_kwargs': kwargs}) # do this for pickling __dict__['__module__'] = None obj = super().__new__(mcl, name, bases, __dict__) obj.name = name obj._sage_ = _undef_sage_helper return obj def __instancecheck__(cls, instance): return cls in type(instance).__mro__ _kwargs = {} # type: tDict[str, Optional[bool]] def __hash__(self): return hash((self.class_key(), frozenset(self._kwargs.items()))) def __eq__(self, other): return (isinstance(other, self.__class__) and self.class_key() == other.class_key() and self._kwargs == other._kwargs) def __ne__(self, other): return not self == other @property def _diff_wrt(self): return False # XXX: The type: ignore on WildFunction is because mypy complains: # # sympy/core/function.py:939: error: Cannot determine type of 'sort_key' in # base class 'Expr' # # Somehow this is because of the @cacheit decorator but it is not clear how to # fix it. class WildFunction(Function, AtomicExpr): # type: ignore """ A WildFunction function matches any function (with its arguments). Examples ======== >>> from sympy import WildFunction, Function, cos >>> from sympy.abc import x, y >>> F = WildFunction('F') >>> f = Function('f') >>> F.nargs Naturals0 >>> x.match(F) >>> F.match(F) {F_: F_} >>> f(x).match(F) {F_: f(x)} >>> cos(x).match(F) {F_: cos(x)} >>> f(x, y).match(F) {F_: f(x, y)} To match functions with a given number of arguments, set ``nargs`` to the desired value at instantiation: >>> F = WildFunction('F', nargs=2) >>> F.nargs {2} >>> f(x).match(F) >>> f(x, y).match(F) {F_: f(x, y)} To match functions with a range of arguments, set ``nargs`` to a tuple containing the desired number of arguments, e.g. if ``nargs = (1, 2)`` then functions with 1 or 2 arguments will be matched. >>> F = WildFunction('F', nargs=(1, 2)) >>> F.nargs {1, 2} >>> f(x).match(F) {F_: f(x)} >>> f(x, y).match(F) {F_: f(x, y)} >>> f(x, y, 1).match(F) """ # XXX: What is this class attribute used for? include = set() # type: tSet[Any] def __init__(cls, name, **assumptions): from sympy.sets.sets import Set, FiniteSet cls.name = name nargs = assumptions.pop('nargs', S.Naturals0) if not isinstance(nargs, Set): # Canonicalize nargs here. See also FunctionClass. if is_sequence(nargs): nargs = tuple(ordered(set(nargs))) elif nargs is not None: nargs = (as_int(nargs),) nargs = FiniteSet(*nargs) cls.nargs = nargs def matches(self, expr, repl_dict=None, old=False): if not isinstance(expr, (AppliedUndef, Function)): return None if len(expr.args) not in self.nargs: return None if repl_dict is None: repl_dict = dict() else: repl_dict = repl_dict.copy() repl_dict[self] = expr return repl_dict class Derivative(Expr): """ Carries out differentiation of the given expression with respect to symbols. Examples ======== >>> from sympy import Derivative, Function, symbols, Subs >>> from sympy.abc import x, y >>> f, g = symbols('f g', cls=Function) >>> Derivative(x**2, x, evaluate=True) 2*x Denesting of derivatives retains the ordering of variables: >>> Derivative(Derivative(f(x, y), y), x) Derivative(f(x, y), y, x) Contiguously identical symbols are merged into a tuple giving the symbol and the count: >>> Derivative(f(x), x, x, y, x) Derivative(f(x), (x, 2), y, x) If the derivative cannot be performed, and evaluate is True, the order of the variables of differentiation will be made canonical: >>> Derivative(f(x, y), y, x, evaluate=True) Derivative(f(x, y), x, y) Derivatives with respect to undefined functions can be calculated: >>> Derivative(f(x)**2, f(x), evaluate=True) 2*f(x) Such derivatives will show up when the chain rule is used to evalulate a derivative: >>> f(g(x)).diff(x) Derivative(f(g(x)), g(x))*Derivative(g(x), x) Substitution is used to represent derivatives of functions with arguments that are not symbols or functions: >>> f(2*x + 3).diff(x) == 2*Subs(f(y).diff(y), y, 2*x + 3) True Notes ===== Simplification of high-order derivatives: Because there can be a significant amount of simplification that can be done when multiple differentiations are performed, results will be automatically simplified in a fairly conservative fashion unless the keyword ``simplify`` is set to False. >>> from sympy import sqrt, diff, Function, symbols >>> from sympy.abc import x, y, z >>> f, g = symbols('f,g', cls=Function) >>> e = sqrt((x + 1)**2 + x) >>> diff(e, (x, 5), simplify=False).count_ops() 136 >>> diff(e, (x, 5)).count_ops() 30 Ordering of variables: If evaluate is set to True and the expression cannot be evaluated, the list of differentiation symbols will be sorted, that is, the expression is assumed to have continuous derivatives up to the order asked. Derivative wrt non-Symbols: For the most part, one may not differentiate wrt non-symbols. For example, we do not allow differentiation wrt `x*y` because there are multiple ways of structurally defining where x*y appears in an expression: a very strict definition would make (x*y*z).diff(x*y) == 0. Derivatives wrt defined functions (like cos(x)) are not allowed, either: >>> (x*y*z).diff(x*y) Traceback (most recent call last): ... ValueError: Can't calculate derivative wrt x*y. To make it easier to work with variational calculus, however, derivatives wrt AppliedUndef and Derivatives are allowed. For example, in the Euler-Lagrange method one may write F(t, u, v) where u = f(t) and v = f'(t). These variables can be written explicitly as functions of time:: >>> from sympy.abc import t >>> F = Function('F') >>> U = f(t) >>> V = U.diff(t) The derivative wrt f(t) can be obtained directly: >>> direct = F(t, U, V).diff(U) When differentiation wrt a non-Symbol is attempted, the non-Symbol is temporarily converted to a Symbol while the differentiation is performed and the same answer is obtained: >>> indirect = F(t, U, V).subs(U, x).diff(x).subs(x, U) >>> assert direct == indirect The implication of this non-symbol replacement is that all functions are treated as independent of other functions and the symbols are independent of the functions that contain them:: >>> x.diff(f(x)) 0 >>> g(x).diff(f(x)) 0 It also means that derivatives are assumed to depend only on the variables of differentiation, not on anything contained within the expression being differentiated:: >>> F = f(x) >>> Fx = F.diff(x) >>> Fx.diff(F) # derivative depends on x, not F 0 >>> Fxx = Fx.diff(x) >>> Fxx.diff(Fx) # derivative depends on x, not Fx 0 The last example can be made explicit by showing the replacement of Fx in Fxx with y: >>> Fxx.subs(Fx, y) Derivative(y, x) Since that in itself will evaluate to zero, differentiating wrt Fx will also be zero: >>> _.doit() 0 Replacing undefined functions with concrete expressions One must be careful to replace undefined functions with expressions that contain variables consistent with the function definition and the variables of differentiation or else insconsistent result will be obtained. Consider the following example: >>> eq = f(x)*g(y) >>> eq.subs(f(x), x*y).diff(x, y).doit() y*Derivative(g(y), y) + g(y) >>> eq.diff(x, y).subs(f(x), x*y).doit() y*Derivative(g(y), y) The results differ because `f(x)` was replaced with an expression that involved both variables of differentiation. In the abstract case, differentiation of `f(x)` by `y` is 0; in the concrete case, the presence of `y` made that derivative nonvanishing and produced the extra `g(y)` term. Defining differentiation for an object An object must define ._eval_derivative(symbol) method that returns the differentiation result. This function only needs to consider the non-trivial case where expr contains symbol and it should call the diff() method internally (not _eval_derivative); Derivative should be the only one to call _eval_derivative. Any class can allow derivatives to be taken with respect to itself (while indicating its scalar nature). See the docstring of Expr._diff_wrt. See Also ======== _sort_variable_count """ is_Derivative = True @property def _diff_wrt(self): """An expression may be differentiated wrt a Derivative if it is in elementary form. Examples ======== >>> from sympy import Function, Derivative, cos >>> from sympy.abc import x >>> f = Function('f') >>> Derivative(f(x), x)._diff_wrt True >>> Derivative(cos(x), x)._diff_wrt False >>> Derivative(x + 1, x)._diff_wrt False A Derivative might be an unevaluated form of what will not be a valid variable of differentiation if evaluated. For example, >>> Derivative(f(f(x)), x).doit() Derivative(f(x), x)*Derivative(f(f(x)), f(x)) Such an expression will present the same ambiguities as arise when dealing with any other product, like ``2*x``, so ``_diff_wrt`` is False: >>> Derivative(f(f(x)), x)._diff_wrt False """ return self.expr._diff_wrt and isinstance(self.doit(), Derivative) def __new__(cls, expr, *variables, **kwargs): expr = sympify(expr) symbols_or_none = getattr(expr, "free_symbols", None) has_symbol_set = isinstance(symbols_or_none, set) if not has_symbol_set: raise ValueError(filldedent(''' Since there are no variables in the expression %s, it cannot be differentiated.''' % expr)) # determine value for variables if it wasn't given if not variables: variables = expr.free_symbols if len(variables) != 1: if expr.is_number: return S.Zero if len(variables) == 0: raise ValueError(filldedent(''' Since there are no variables in the expression, the variable(s) of differentiation must be supplied to differentiate %s''' % expr)) else: raise ValueError(filldedent(''' Since there is more than one variable in the expression, the variable(s) of differentiation must be supplied to differentiate %s''' % expr)) # Split the list of variables into a list of the variables we are diff # wrt, where each element of the list has the form (s, count) where # s is the entity to diff wrt and count is the order of the # derivative. variable_count = [] array_likes = (tuple, list, Tuple) integer_likes = (int, Integer) from sympy.tensor.array import Array, NDimArray for i, v in enumerate(variables): if isinstance(v, integer_likes): if i == 0: raise ValueError("First variable cannot be a number: %i" % v) count = v prev, prevcount = variable_count[-1] if prevcount != 1: raise TypeError("tuple {} followed by number {}".format((prev, prevcount), v)) if count == 0: variable_count.pop() else: variable_count[-1] = Tuple(prev, count) else: if isinstance(v, array_likes): if len(v) == 0: # Ignore empty tuples: Derivative(expr, ... , (), ... ) continue if isinstance(v[0], array_likes): # Derive by array: Derivative(expr, ... , [[x, y, z]], ... ) if len(v) == 1: v = Array(v[0]) count = 1 else: v, count = v v = Array(v) else: v, count = v if count == 0: continue elif isinstance(v, UndefinedFunction): raise TypeError( "cannot differentiate wrt " "UndefinedFunction: %s" % v) else: count = 1 variable_count.append(Tuple(v, count)) # light evaluation of contiguous, identical # items: (x, 1), (x, 1) -> (x, 2) merged = [] for t in variable_count: v, c = t if c.is_negative: raise ValueError( 'order of differentiation must be nonnegative') if merged and merged[-1][0] == v: c += merged[-1][1] if not c: merged.pop() else: merged[-1] = Tuple(v, c) else: merged.append(t) variable_count = merged # sanity check of variables of differentation; we waited # until the counts were computed since some variables may # have been removed because the count was 0 for v, c in variable_count: # v must have _diff_wrt True if not v._diff_wrt: __ = '' # filler to make error message neater raise ValueError(filldedent(''' Can't calculate derivative wrt %s.%s''' % (v, __))) # We make a special case for 0th derivative, because there is no # good way to unambiguously print this. if len(variable_count) == 0: return expr evaluate = kwargs.get('evaluate', False) if evaluate: if isinstance(expr, Derivative): expr = expr.canonical variable_count = [ (v.canonical if isinstance(v, Derivative) else v, c) for v, c in variable_count] # Look for a quick exit if there are symbols that don't appear in # expression at all. Note, this cannot check non-symbols like # Derivatives as those can be created by intermediate # derivatives. zero = False free = expr.free_symbols from sympy.matrices.expressions.matexpr import MatrixExpr for v, c in variable_count: vfree = v.free_symbols if c.is_positive and vfree: if isinstance(v, AppliedUndef): # these match exactly since # x.diff(f(x)) == g(x).diff(f(x)) == 0 # and are not created by differentiation D = Dummy() if not expr.xreplace({v: D}).has(D): zero = True break elif isinstance(v, MatrixExpr): zero = False break elif isinstance(v, Symbol) and v not in free: zero = True break else: if not free & vfree: # e.g. v is IndexedBase or Matrix zero = True break if zero: return cls._get_zero_with_shape_like(expr) # make the order of symbols canonical #TODO: check if assumption of discontinuous derivatives exist variable_count = cls._sort_variable_count(variable_count) # denest if isinstance(expr, Derivative): variable_count = list(expr.variable_count) + variable_count expr = expr.expr return _derivative_dispatch(expr, *variable_count, **kwargs) # we return here if evaluate is False or if there is no # _eval_derivative method if not evaluate or not hasattr(expr, '_eval_derivative'): # return an unevaluated Derivative if evaluate and variable_count == [(expr, 1)] and expr.is_scalar: # special hack providing evaluation for classes # that have defined is_scalar=True but have no # _eval_derivative defined return S.One return Expr.__new__(cls, expr, *variable_count) # evaluate the derivative by calling _eval_derivative method # of expr for each variable # ------------------------------------------------------------- nderivs = 0 # how many derivatives were performed unhandled = [] from sympy.matrices.common import MatrixCommon for i, (v, count) in enumerate(variable_count): old_expr = expr old_v = None is_symbol = v.is_symbol or isinstance(v, (Iterable, Tuple, MatrixCommon, NDimArray)) if not is_symbol: old_v = v v = Dummy('xi') expr = expr.xreplace({old_v: v}) # Derivatives and UndefinedFunctions are independent # of all others clashing = not (isinstance(old_v, Derivative) or \ isinstance(old_v, AppliedUndef)) if v not in expr.free_symbols and not clashing: return expr.diff(v) # expr's version of 0 if not old_v.is_scalar and not hasattr( old_v, '_eval_derivative'): # special hack providing evaluation for classes # that have defined is_scalar=True but have no # _eval_derivative defined expr *= old_v.diff(old_v) obj = cls._dispatch_eval_derivative_n_times(expr, v, count) if obj is not None and obj.is_zero: return obj nderivs += count if old_v is not None: if obj is not None: # remove the dummy that was used obj = obj.subs(v, old_v) # restore expr expr = old_expr if obj is None: # we've already checked for quick-exit conditions # that give 0 so the remaining variables # are contained in the expression but the expression # did not compute a derivative so we stop taking # derivatives unhandled = variable_count[i:] break expr = obj # what we have so far can be made canonical expr = expr.replace( lambda x: isinstance(x, Derivative), lambda x: x.canonical) if unhandled: if isinstance(expr, Derivative): unhandled = list(expr.variable_count) + unhandled expr = expr.expr expr = Expr.__new__(cls, expr, *unhandled) if (nderivs > 1) == True and kwargs.get('simplify', True): from .exprtools import factor_terms from sympy.simplify.simplify import signsimp expr = factor_terms(signsimp(expr)) return expr @property def canonical(cls): return cls.func(cls.expr, *Derivative._sort_variable_count(cls.variable_count)) @classmethod def _sort_variable_count(cls, vc): """ Sort (variable, count) pairs into canonical order while retaining order of variables that do not commute during differentiation: * symbols and functions commute with each other * derivatives commute with each other * a derivative doesn't commute with anything it contains * any other object is not allowed to commute if it has free symbols in common with another object Examples ======== >>> from sympy import Derivative, Function, symbols >>> vsort = Derivative._sort_variable_count >>> x, y, z = symbols('x y z') >>> f, g, h = symbols('f g h', cls=Function) Contiguous items are collapsed into one pair: >>> vsort([(x, 1), (x, 1)]) [(x, 2)] >>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)]) [(y, 2), (f(x), 2)] Ordering is canonical. >>> def vsort0(*v): ... # docstring helper to ... # change vi -> (vi, 0), sort, and return vi vals ... return [i[0] for i in vsort([(i, 0) for i in v])] >>> vsort0(y, x) [x, y] >>> vsort0(g(y), g(x), f(y)) [f(y), g(x), g(y)] Symbols are sorted as far to the left as possible but never move to the left of a derivative having the same symbol in its variables; the same applies to AppliedUndef which are always sorted after Symbols: >>> dfx = f(x).diff(x) >>> assert vsort0(dfx, y) == [y, dfx] >>> assert vsort0(dfx, x) == [dfx, x] """ if not vc: return [] vc = list(vc) if len(vc) == 1: return [Tuple(*vc[0])] V = list(range(len(vc))) E = [] v = lambda i: vc[i][0] D = Dummy() def
(d, v, wrt=False): # return True if v should not come before d else False if d == v: return wrt if d.is_Symbol: return False if isinstance(d, Derivative): # a derivative blocks if any of it's variables contain # v; the wrt flag will return True for an exact match # and will cause an AppliedUndef to block if v is in # the arguments if any(_block(k, v, wrt=True) for k in d._wrt_variables): return True return False if not wrt and isinstance(d, AppliedUndef): return False if v.is_Symbol: return v in d.free_symbols if isinstance(v, AppliedUndef): return _block(d.xreplace({v: D}), D) return d.free_symbols & v.free_symbols for i in range(len(vc)): for j in range(i): if _block(v(j), v(i)): E.append((j,i)) # this is the default ordering to use in case of ties O = dict(zip(ordered(uniq([i for i, c in vc])), range(len(vc)))) ix = topological_sort((V, E), key=lambda i: O[v(i)]) # merge counts of contiguously identical items merged = [] for v, c in [vc[i] for i in ix]: if merged and merged[-1][0] == v: merged[-1][1] += c else: merged.append([v, c]) return [Tuple(*i) for i in merged] def _eval_is_commutative(self): return self.expr.is_commutative def _eval_derivative(self, v): # If v (the variable of differentiation) is not in # self.variables, we might be able to take the derivative. if v not in self._wrt_variables: dedv = self.expr.diff(v) if isinstance(dedv, Derivative): return dedv.func(dedv.expr, *(self.variable_count + dedv.variable_count)) # dedv (d(self.expr)/dv) could have simplified things such that the # derivative wrt things in self.variables can now be done. Thus, # we set evaluate=True to see if there are any other derivatives # that can be done. The most common case is when dedv is a simple # number so that the derivative wrt anything else will vanish. return self.func(dedv, *self.variables, evaluate=True) # In this case v was in self.variables so the derivative wrt v has # already been attempted and was not computed, either because it # couldn't be or evaluate=False originally. variable_count = list(self.variable_count) variable_count.append((v, 1)) return self.func(self.expr, *variable_count, evaluate=False) def doit(self, **hints): expr = self.expr if hints.get('deep', True): expr = expr.doit(**hints) hints['evaluate'] = True rv = self.func(expr, *self.variable_count, **hints) if rv!= self and rv.has(Derivative): rv = rv.doit(**hints) return rv @_sympifyit('z0', NotImplementedError) def doit_numerically(self, z0): """ Evaluate the derivative at z numerically. When we can represent derivatives at a point, this should be folded into the normal evalf. For now, we need a special method. """ if len(self.free_symbols) != 1 or len(self.variables) != 1: raise NotImplementedError('partials and higher order derivatives') z = list(self.free_symbols)[0] def eval(x): f0 = self.expr.subs(z, Expr._from_mpmath(x, prec=mpmath.mp.prec)) f0 = f0.evalf(prec_to_dps(mpmath.mp.prec)) return f0._to_mpmath(mpmath.mp.prec) return Expr._from_mpmath(mpmath.diff(eval, z0._to_mpmath(mpmath.mp.prec)), mpmath.mp.prec) @property def expr(self): return self._args[0] @property def _wrt_variables(self): # return the variables of differentiation without # respect to the type of count (int or symbolic) return [i[0] for i in self.variable_count] @property def variables(self): # TODO: deprecate? YES, make this 'enumerated_variables' and # name _wrt_variables as variables # TODO: support for `d^n`? rv = [] for v, count in self.variable_count: if not count.is_Integer: raise TypeError(filldedent(''' Cannot give expansion for symbolic count. If you just want a list of all variables of differentiation, use _wrt_variables.''')) rv.extend([v]*count) return tuple(rv) @property def variable_count(self): return self._args[1:] @property def derivative_count(self): return sum([count for _, count in self.variable_count], 0) @property def free_symbols(self): ret = self.expr.free_symbols # Add symbolic counts to free_symbols for _, count in self.variable_count: ret.update(count.free_symbols) return ret @property def kind(self): return self.args[0].kind def _eval_subs(self, old, new): # The substitution (old, new) cannot be done inside # Derivative(expr, vars) for a variety of reasons # as handled below. if old in self._wrt_variables: # first handle the counts expr = self.func(self.expr, *[(v, c.subs(old, new)) for v, c in self.variable_count]) if expr != self: return expr._eval_subs(old, new) # quick exit case if not getattr(new, '_diff_wrt', False): # case (0): new is not a valid variable of # differentiation if isinstance(old, Symbol): # don't introduce a new symbol if the old will do return Subs(self, old, new) else: xi = Dummy('xi') return Subs(self.xreplace({old: xi}), xi, new) # If both are Derivatives with the same expr, check if old is # equivalent to self or if old is a subderivative of self. if old.is_Derivative and old.expr == self.expr: if self.canonical == old.canonical: return new # collections.Counter doesn't have __le__ def _subset(a, b): return all((a[i] <= b[i]) == True for i in a) old_vars = Counter(dict(reversed(old.variable_count))) self_vars = Counter(dict(reversed(self.variable_count))) if _subset(old_vars, self_vars): return _derivative_dispatch(new, *(self_vars - old_vars).items()).canonical args = list(self.args) newargs = list(x._subs(old, new) for x in args) if args[0] == old: # complete replacement of self.expr # we already checked that the new is valid so we know # it won't be a problem should it appear in variables return _derivative_dispatch(*newargs) if newargs[0] != args[0]: # case (1) can't change expr by introducing something that is in # the _wrt_variables if it was already in the expr # e.g. # for Derivative(f(x, g(y)), y), x cannot be replaced with # anything that has y in it; for f(g(x), g(y)).diff(g(y)) # g(x) cannot be replaced with anything that has g(y) syms = {vi: Dummy() for vi in self._wrt_variables if not vi.is_Symbol} wrt = {syms.get(vi, vi) for vi in self._wrt_variables} forbidden = args[0].xreplace(syms).free_symbols & wrt nfree = new.xreplace(syms).free_symbols ofree = old.xreplace(syms).free_symbols if (nfree - ofree) & forbidden: return Subs(self, old, new) viter = ((i, j) for ((i, _), (j, _)) in zip(newargs[1:], args[1:])) if any(i != j for i, j in viter): # a wrt-variable change # case (2) can't change vars by introducing a variable # that is contained in expr, e.g. # for Derivative(f(z, g(h(x), y)), y), y cannot be changed to # x, h(x), or g(h(x), y) for a in _atomic(self.expr, recursive=True): for i in range(1, len(newargs)): vi, _ = newargs[i] if a == vi and vi != args[i][0]: return Subs(self, old, new) # more arg-wise checks vc = newargs[1:] oldv = self._wrt_variables newe = self.expr subs = [] for i, (vi, ci) in enumerate(vc): if not vi._diff_wrt: # case (3) invalid differentiation expression so # create a replacement dummy xi = Dummy('xi_%i' % i) # replace the old valid variable with the dummy # in the expression newe = newe.xreplace({oldv[i]: xi}) # and replace the bad variable with the dummy vc[i] = (xi, ci) # and record the dummy with the new (invalid) # differentiation expression subs.append((xi, vi)) if subs: # handle any residual substitution in the expression newe = newe._subs(old, new) # return the Subs-wrapped derivative return Subs(Derivative(newe, *vc), *zip(*subs)) # everything was ok return _derivative_dispatch(*newargs) def _eval_lseries(self, x, logx, cdir=0): dx = self.variables for term in self.expr.lseries(x, logx=logx, cdir=cdir): yield self.func(term, *dx) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.expr.nseries(x, n=n, logx=logx) o = arg.getO() dx = self.variables rv = [self.func(a, *dx) for a in Add.make_args(arg.removeO())] if o: rv.append(o/x) return Add(*rv) def _eval_as_leading_term(self, x, logx=None, cdir=0): series_gen = self.expr.lseries(x) d = S.Zero for leading_term in series_gen: d = diff(leading_term, *self.variables) if d != 0: break return d def as_finite_difference(self, points=1, x0=None, wrt=None): """ Expresses a Derivative instance as a finite difference. Parameters ========== points : sequence or coefficient, optional If sequence: discrete values (length >= order+1) of the independent variable used for generating the finite difference weights. If it is a coefficient, it will be used as the step-size for generating an equidistant sequence of length order+1 centered around ``x0``. Default: 1 (step-size 1) x0 : number or Symbol, optional the value of the independent variable (``wrt``) at which the derivative is to be approximated. Default: same as ``wrt``. wrt : Symbol, optional "with respect to" the variable for which the (partial) derivative is to be approximated for. If not provided it is required that the derivative is ordinary. Default: ``None``. Examples ======== >>> from sympy import symbols, Function, exp, sqrt, Symbol >>> x, h = symbols('x h') >>> f = Function('f') >>> f(x).diff(x).as_finite_difference() -f(x - 1/2) + f(x + 1/2) The default step size and number of points are 1 and ``order + 1`` respectively. We can change the step size by passing a symbol as a parameter: >>> f(x).diff(x).as_finite_difference(h) -f(-h/2 + x)/h + f(h/2 + x)/h We can also specify the discretized values to be used in a sequence: >>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h]) -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h) The algorithm is not restricted to use equidistant spacing, nor do we need to make the approximation around ``x0``, but we can get an expression estimating the derivative at an offset: >>> e, sq2 = exp(1), sqrt(2) >>> xl = [x-h, x+h, x+e*h] >>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2) # doctest: +ELLIPSIS 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/... To approximate ``Derivative`` around ``x0`` using a non-equidistant spacing step, the algorithm supports assignment of undefined functions to ``points``: >>> dx = Function('dx') >>> f(x).diff(x).as_finite_difference(points=dx(x), x0=x-h) -f(-h + x - dx(-h + x)/2)/dx(-h + x) + f(-h + x + dx(-h + x)/2)/dx(-h + x) Partial derivatives are also supported: >>> y = Symbol('y') >>> d2fdxdy=f(x,y).diff(x,y) >>> d2fdxdy.as_finite_difference(wrt=x) -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y) We can apply ``as_finite_difference`` to ``Derivative`` instances in compound expressions using ``replace``: >>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative, ... lambda arg: arg.as_finite_difference()) 42**(-f(x - 1/2) + f(x + 1/2)) + 1 See also ======== sympy.calculus.finite_diff.apply_finite_diff sympy.calculus.finite_diff.differentiate_finite sympy.calculus.finite_diff.finite_diff_weights """ from sympy.calculus.finite_diff import _as_finite_diff return _as_finite_diff(self, points, x0, wrt) @classmethod def _get_zero_with_shape_like(cls, expr): return S.Zero @classmethod def _dispatch_eval_derivative_n_times(cls, expr, v, count): # Evaluate the derivative `n` times. If # `_eval_derivative_n_times` is not overridden by the current # object, the default in `Basic` will call a loop over # `_eval_derivative`: return expr._eval_derivative_n_times(v, count) def _derivative_dispatch(expr, *variables, **kwargs): from sympy.matrices.common import MatrixCommon from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.tensor.array import NDimArray array_types = (MatrixCommon, MatrixExpr, NDimArray, list, tuple, Tuple) if isinstance(expr, array_types) or any(isinstance(i[0], array_types) if isinstance(i, (tuple, list, Tuple)) else isinstance(i, array_types) for i in variables): from sympy.tensor.array.array_derivatives import ArrayDerivative return ArrayDerivative(expr, *variables, **kwargs) return Derivative(expr, *variables, **kwargs) class Lambda(Expr): """ Lambda(x, expr) represents a lambda function similar to Python's 'lambda x: expr'. A function of several variables is written as Lambda((x, y, ...), expr). Examples ======== A simple example: >>> from sympy import Lambda >>> from sympy.abc import x >>> f = Lambda(x, x**2) >>> f(4) 16 For multivariate functions, use: >>> from sympy.abc import y, z, t >>> f2 = Lambda((x, y, z, t), x + y**z + t**z) >>> f2(1, 2, 3, 4) 73 It is also possible to unpack tuple arguments: >>> f = Lambda(((x, y), z), x + y + z) >>> f((1, 2), 3) 6 A handy shortcut for lots of arguments: >>> p = x, y, z >>> f = Lambda(p, x + y*z) >>> f(*p) x + y*z """ is_Function = True def __new__(cls, signature, expr): if iterable(signature) and not isinstance(signature, (tuple, Tuple)): sympy_deprecation_warning( """ Using a non-tuple iterable as the first argument to Lambda is deprecated. Use Lambda(tuple(args), expr) instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-non-tuple-lambda", ) signature = tuple(signature) sig = signature if iterable(signature) else (signature,) sig = sympify(sig) cls._check_signature(sig) if len(sig) == 1 and sig[0] == expr: return S.IdentityFunction return Expr.__new__(cls, sig, sympify(expr)) @classmethod def _check_signature(cls, sig): syms = set() def rcheck(args): for a in args: if a.is_symbol: if a in syms: raise BadSignatureError("Duplicate symbol %s" % a) syms.add(a) elif isinstance(a, Tuple): rcheck(a) else: raise BadSignatureError("Lambda signature should be only tuples" " and symbols, not %s" % a) if not isinstance(sig, Tuple): raise BadSignatureError("Lambda signature should be a tuple not %s" % sig) # Recurse through the signature: rcheck(sig) @property def signature(self): """The expected form of the arguments to be unpacked into variables""" return self._args[0] @property def expr(self): """The return value of the function""" return self._args[1] @property def variables(self): """The variables used in the internal representation of the function""" def _variables(args): if isinstance(args, Tuple): for arg in args: yield from _variables(arg) else: yield args return tuple(_variables(self.signature)) @property def nargs(self): from sympy.sets.sets import FiniteSet return FiniteSet(len(self.signature)) bound_symbols = variables @property def free_symbols(self): return self.expr.free_symbols - set(self.variables) def __call__(self, *args): n = len(args) if n not in self.nargs: # Lambda only ever has 1 value in nargs # XXX: exception message must be in exactly this format to # make it work with NumPy's functions like vectorize(). See, # for example, https://github.com/numpy/numpy/issues/1697. # The ideal solution would be just to attach metadata to # the exception and change NumPy to take advantage of this. ## XXX does this apply to Lambda? If not, remove this comment. temp = ('%(name)s takes exactly %(args)s ' 'argument%(plural)s (%(given)s given)') raise BadArgumentsError(temp % { 'name': self, 'args': list(self.nargs)[0], 'plural': 's'*(list(self.nargs)[0] != 1), 'given': n}) d = self._match_signature(self.signature, args) return self.expr.xreplace(d) def _match_signature(self, sig, args): symargmap = {} def rmatch(pars, args): for par, arg in zip(pars, args): if par.is_symbol: symargmap[par] = arg elif isinstance(par, Tuple): if not isinstance(arg, (tuple, Tuple)) or len(args) != len(pars): raise BadArgumentsError("Can't match %s and %s" % (args, pars)) rmatch(par, arg) rmatch(sig, args) return symargmap @property def is_identity(self): """Return ``True`` if this ``Lambda`` is an identity function. """ return self.signature == self.expr def _eval_evalf(self, prec): return self.func(self.args[0], self.args[1].evalf(n=prec_to_dps(prec))) class Subs(Expr): """ Represents unevaluated substitutions of an expression. ``Subs(expr, x, x0)`` represents the expression resulting from substituting x with x0 in expr. Parameters ========== expr : Expr An expression. x : tuple, variable A variable or list of distinct variables. x0 : tuple or list of tuples A point or list of evaluation points corresponding to those variables. Notes ===== ``Subs`` objects are generally useful to represent unevaluated derivatives calculated at a point. The variables may be expressions, but they are subjected to the limitations of subs(), so it is usually a good practice to use only symbols for variables, since in that case there can be no ambiguity. There's no automatic expansion - use the method .doit() to effect all possible substitutions of the object and also of objects inside the expression. When evaluating derivatives at a point that is not a symbol, a Subs object is returned. One is also able to calculate derivatives of Subs objects - in this case the expression is always expanded (for the unevaluated form, use Derivative()). Examples ======== >>> from sympy import Subs, Function, sin, cos >>> from sympy.abc import x, y, z >>> f = Function('f') Subs are created when a particular substitution cannot be made. The x in the derivative cannot be replaced with 0 because 0 is not a valid variables of differentiation: >>> f(x).diff(x).subs(x, 0) Subs(Derivative(f(x), x), x, 0) Once f is known, the derivative and evaluation at 0 can be done: >>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0) True Subs can also be created directly with one or more variables: >>> Subs(f(x)*sin(y) + z, (x, y), (0, 1)) Subs(z + f(x)*sin(y), (x, y), (0, 1)) >>> _.doit() z + f(0)*sin(1) Notes ===== In order to allow expressions to combine before doit is done, a representation of the Subs expression is used internally to make expressions that are superficially different compare the same: >>> a, b = Subs(x, x, 0), Subs(y, y, 0) >>> a + b 2*Subs(x, x, 0) This can lead to unexpected consequences when using methods like `has` that are cached: >>> s = Subs(x, x, 0) >>> s.has(x), s.has(y) (True, False) >>> ss = s.subs(x, y) >>> ss.has(x), ss.has(y) (True, False) >>> s, ss (Subs(x, x, 0), Subs(y, y, 0)) """ def __new__(cls, expr, variables, point, **assumptions): if not is_sequence(variables, Tuple): variables = [variables] variables = Tuple(*variables) if has_dups(variables): repeated = [str(v) for v, i in Counter(variables).items() if i > 1] __ = ', '.join(repeated) raise ValueError(filldedent(''' The following expressions appear more than once: %s ''' % __)) point = Tuple(*(point if is_sequence(point, Tuple) else [point])) if len(point) != len(variables): raise ValueError('Number of point values must be the same as ' 'the number of variables.') if not point: return sympify(expr) # denest if isinstance(expr, Subs): variables = expr.variables + variables point = expr.point + point expr = expr.expr else: expr = sympify(expr) # use symbols with names equal to the point value (with prepended _) # to give a variable-independent expression pre = "_" pts = sorted(set(point), key=default_sort_key) from sympy.printing.str import StrPrinter class CustomStrPrinter(StrPrinter): def _print_Dummy(self, expr): return str(expr) + str(expr.dummy_index) def mystr(expr, **settings): p = CustomStrPrinter(settings) return p.doprint(expr) while 1: s_pts = {p: Symbol(pre + mystr(p)) for p in pts} reps = [(v, s_pts[p]) for v, p in zip(variables, point)] # if any underscore-prepended symbol is already a free symbol # and is a variable with a different point value, then there # is a clash, e.g. _0 clashes in Subs(_0 + _1, (_0, _1), (1, 0)) # because the new symbol that would be created is _1 but _1 # is already mapped to 0 so __0 and __1 are used for the new # symbols if any(r in expr.free_symbols and r in variables and Symbol(pre + mystr(point[variables.index(r)])) != r for _, r in reps): pre += "_" continue break obj = Expr.__new__(cls, expr, Tuple(*variables), point) obj._expr = expr.xreplace(dict(reps)) return obj def _eval_is_commutative(self): return self.expr.is_commutative def doit(self, **hints): e, v, p = self.args # remove self mappings for i, (vi, pi) in enumerate(zip(v, p)): if vi == pi: v = v[:i] + v[i + 1:] p = p[:i] + p[i + 1:] if not v: return self.expr if isinstance(e, Derivative): # apply functions first, e.g. f -> cos undone = [] for i, vi in enumerate(v): if isinstance(vi, FunctionClass): e = e.subs(vi, p[i]) else: undone.append((vi, p[i])) if not isinstance(e, Derivative): e = e.doit() if isinstance(e, Derivative): # do Subs that aren't related to differentiation undone2 = [] D = Dummy() arg = e.args[0] for vi, pi in undone: if D not in e.xreplace({vi: D}).free_symbols: if arg.has(vi): e = e.subs(vi, pi) else: undone2.append((vi, pi)) undone = undone2 # differentiate wrt variables that are present wrt = [] D = Dummy() expr = e.expr free = expr.free_symbols for vi, ci in e.variable_count: if isinstance(vi, Symbol) and vi in free: expr = expr.diff((vi, ci)) elif D in expr.subs(vi, D).free_symbols: expr = expr.diff((vi, ci)) else: wrt.append((vi, ci)) # inject remaining subs rv = expr.subs(undone) # do remaining differentiation *in order given* for vc in wrt: rv = rv.diff(vc) else: # inject remaining subs rv = e.subs(undone) else: rv = e.doit(**hints).subs(list(zip(v, p))) if hints.get('deep', True) and rv != self: rv = rv.doit(**hints) return rv def evalf(self, prec=None, **options): return self.doit().evalf(prec, **options) n = evalf # type:ignore @property def variables(self): """The variables to be evaluated""" return self._args[1] bound_symbols = variables @property def expr(self): """The expression on which the substitution operates""" return self._args[0] @property def point(self): """The values for which the variables are to be substituted""" return self._args[2] @property def free_symbols(self): return (self.expr.free_symbols - set(self.variables) | set(self.point.free_symbols)) @property def expr_free_symbols(self): sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") # Don't show the warning twice from the recursive call with ignore_warnings(SymPyDeprecationWarning): return (self.expr.expr_free_symbols - set(self.variables) | set(self.point.expr_free_symbols)) def __eq__(self, other): if not isinstance(other, Subs): return False return self._hashable_content() == other._hashable_content() def __ne__(self, other): return not(self == other) def __hash__(self): return super().__hash__() def _hashable_content(self): return (self._expr.xreplace(self.canonical_variables), ) + tuple(ordered([(v, p) for v, p in zip(self.variables, self.point) if not self.expr.has(v)])) def _eval_subs(self, old, new): # Subs doit will do the variables in order; the semantics # of subs for Subs is have the following invariant for # Subs object foo: # foo.doit().subs(reps) == foo.subs(reps).doit() pt = list(self.point) if old in self.variables: if _atomic(new) == {new} and not any( i.has(new) for i in self.args): # the substitution is neutral return self.xreplace({old: new}) # any occurrence of old before this point will get # handled by replacements from here on i = self.variables.index(old) for j in range(i, len(self.variables)): pt[j] = pt[j]._subs(old, new) return self.func(self.expr, self.variables, pt) v = [i._subs(old, new) for i in self.variables] if v != list(self.variables): return self.func(self.expr, self.variables + (old,), pt + [new]) expr = self.expr._subs(old, new) pt = [i._subs(old, new) for i in self.point] return self.func(expr, v, pt) def _eval_derivative(self, s): # Apply the chain rule of the derivative on the substitution variables: f = self.expr vp = V, P = self.variables, self.point val = Add.fromiter(p.diff(s)*Subs(f.diff(v), *vp).doit() for v, p in zip(V, P)) # these are all the free symbols in the expr efree = f.free_symbols # some symbols like IndexedBase include themselves and args # as free symbols compound = {i for i in efree if len(i.free_symbols) > 1} # hide them and see what independent free symbols remain dums = {Dummy() for i in compound} masked = f.xreplace(dict(zip(compound, dums))) ifree = masked.free_symbols - dums # include the compound symbols free = ifree | compound # remove the variables already handled free -= set(V) # add back any free symbols of remaining compound symbols free |= {i for j in free & compound for i in j.free_symbols} # if symbols of s are in free then there is more to do if free & s.free_symbols: val += Subs(f.diff(s), self.variables, self.point).doit() return val def _eval_nseries(self, x, n, logx, cdir=0): if x in self.point: # x is the variable being substituted into apos = self.point.index(x) other = self.variables[apos] else: other = x arg = self.expr.nseries(other, n=n, logx=logx) o = arg.getO() terms = Add.make_args(arg.removeO()) rv = Add(*[self.func(a, *self.args[1:]) for a in terms]) if o: rv += o.subs(other, x) return rv def _eval_as_leading_term(self, x, logx=None, cdir=0): if x in self.point: ipos = self.point.index(x) xvar = self.variables[ipos] return self.expr.as_leading_term(xvar) if x in self.variables: # if `x` is a dummy variable, it means it won't exist after the # substitution has been performed: return self # The variable is independent of the substitution: return self.expr.as_leading_term(x) def diff(f, *symbols, **kwargs): """ Differentiate f with respect to symbols. Explanation =========== This is just a wrapper to unify .diff() and the Derivative class; its interface is similar to that of integrate(). You can use the same shortcuts for multiple variables as with Derivative. For example, diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative of f(x). You can pass evaluate=False to get an unevaluated Derivative class. Note that if there are 0 symbols (such as diff(f(x), x, 0), then the result will be the function (the zeroth derivative), even if evaluate=False. Examples ======== >>> from sympy import sin, cos, Function, diff >>> from sympy.abc import x, y >>> f = Function('f') >>> diff(sin(x), x) cos(x) >>> diff(f(x), x, x, x) Derivative(f(x), (x, 3)) >>> diff(f(x), x, 3) Derivative(f(x), (x, 3)) >>> diff(sin(x)*cos(y), x, 2, y, 2) sin(x)*cos(y) >>> type(diff(sin(x), x)) cos >>> type(diff(sin(x), x, evaluate=False)) <class 'sympy.core.function.Derivative'> >>> type(diff(sin(x), x, 0)) sin >>> type(diff(sin(x), x, 0, evaluate=False)) sin >>> diff(sin(x)) cos(x) >>> diff(sin(x*y)) Traceback (most recent call last): ... ValueError: specify differentiation variables to differentiate sin(x*y) Note that ``diff(sin(x))`` syntax is meant only for convenience in interactive sessions and should be avoided in library code. References ========== .. [1] http://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html See Also ======== Derivative idiff: computes the derivative implicitly """ if hasattr(f, 'diff'): return f.diff(*symbols, **kwargs) kwargs.setdefault('evaluate', True) return _derivative_dispatch(f, *symbols, **kwargs) def expand(e, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints): r""" Expand an expression using methods given as hints. Explanation =========== Hints evaluated unless explicitly set to False are: ``basic``, ``log``, ``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following hints are supported but not applied unless set to True: ``complex``, ``func``, and ``trig``. In addition, the following meta-hints are supported by some or all of the other hints: ``frac``, ``numer``, ``denom``, ``modulus``, and ``force``. ``deep`` is supported by all hints. Additionally, subclasses of Expr may define their own hints or meta-hints. The ``basic`` hint is used for any special rewriting of an object that should be done automatically (along with the other hints like ``mul``) when expand is called. This is a catch-all hint to handle any sort of expansion that may not be described by the existing hint names. To use this hint an object should override the ``_eval_expand_basic`` method. Objects may also define their own expand methods, which are not run by default. See the API section below. If ``deep`` is set to ``True`` (the default), things like arguments of functions are recursively expanded. Use ``deep=False`` to only expand on the top level. If the ``force`` hint is used, assumptions about variables will be ignored in making the expansion. Hints ===== These hints are run by default mul --- Distributes multiplication over addition: >>> from sympy import cos, exp, sin >>> from sympy.abc import x, y, z >>> (y*(x + z)).expand(mul=True) x*y + y*z multinomial ----------- Expand (x + y + ...)**n where n is a positive integer. >>> ((x + y + z)**2).expand(multinomial=True) x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2 power_exp --------- Expand addition in exponents into multiplied bases. >>> exp(x + y).expand(power_exp=True) exp(x)*exp(y) >>> (2**(x + y)).expand(power_exp=True) 2**x*2**y power_base ---------- Split powers of multiplied bases. This only happens by default if assumptions allow, or if the ``force`` meta-hint is used: >>> ((x*y)**z).expand(power_base=True) (x*y)**z >>> ((x*y)**z).expand(power_base=True, force=True) x**z*y**z >>> ((2*y)**z).expand(power_base=True) 2**z*y**z Note that in some cases where this expansion always holds, SymPy performs it automatically: >>> (x*y)**2 x**2*y**2 log --- Pull out power of an argument as a coefficient and split logs products into sums of logs. Note that these only work if the arguments of the log function have the proper assumptions--the arguments must be positive and the exponents must be real--or else the ``force`` hint must be True: >>> from sympy import log, symbols >>> log(x**2*y).expand(log=True) log(x**2*y) >>> log(x**2*y).expand(log=True, force=True) 2*log(x) + log(y) >>> x, y = symbols('x,y', positive=True) >>> log(x**2*y).expand(log=True) 2*log(x) + log(y) basic ----- This hint is intended primarily as a way for custom subclasses to enable expansion by default. These hints are not run by default: complex ------- Split an expression into real and imaginary parts. >>> x, y = symbols('x,y') >>> (x + y).expand(complex=True) re(x) + re(y) + I*im(x) + I*im(y) >>> cos(x).expand(complex=True) -I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x)) Note that this is just a wrapper around ``as_real_imag()``. Most objects that wish to redefine ``_eval_expand_complex()`` should consider redefining ``as_real_imag()`` instead. func ---- Expand other functions. >>> from sympy import gamma >>> gamma(x + 1).expand(func=True) x*gamma(x) trig ---- Do trigonometric expansions. >>> cos(x + y).expand(trig=True) -sin(x)*sin(y) + cos(x)*cos(y) >>> sin(2*x).expand(trig=True) 2*sin(x)*cos(x) Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)`` and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x) = 1`. The current implementation uses the form obtained from Chebyshev polynomials, but this may change. See `this MathWorld article <http://mathworld.wolfram.com/Multiple-AngleFormulas.html>`_ for more information. Notes ===== - You can shut off unwanted methods:: >>> (exp(x + y)*(x + y)).expand() x*exp(x)*exp(y) + y*exp(x)*exp(y) >>> (exp(x + y)*(x + y)).expand(power_exp=False) x*exp(x + y) + y*exp(x + y) >>> (exp(x + y)*(x + y)).expand(mul=False) (x + y)*exp(x)*exp(y) - Use deep=False to only expand on the top level:: >>> exp(x + exp(x + y)).expand() exp(x)*exp(exp(x)*exp(y)) >>> exp(x + exp(x + y)).expand(deep=False) exp(x)*exp(exp(x + y)) - Hints are applied in an arbitrary, but consistent order (in the current implementation, they are applied in alphabetical order, except multinomial comes before mul, but this may change). Because of this, some hints may prevent expansion by other hints if they are applied first. For example, ``mul`` may distribute multiplications and prevent ``log`` and ``power_base`` from expanding them. Also, if ``mul`` is applied before ``multinomial`, the expression might not be fully distributed. The solution is to use the various ``expand_hint`` helper functions or to use ``hint=False`` to this function to finely control which hints are applied. Here are some examples:: >>> from sympy import expand, expand_mul, expand_power_base >>> x, y, z = symbols('x,y,z', positive=True) >>> expand(log(x*(y + z))) log(x) + log(y + z) Here, we see that ``log`` was applied before ``mul``. To get the mul expanded form, either of the following will work:: >>> expand_mul(log(x*(y + z))) log(x*y + x*z) >>> expand(log(x*(y + z)), log=False) log(x*y + x*z) A similar thing can happen with the ``power_base`` hint:: >>> expand((x*(y + z))**x) (x*y + x*z)**x To get the ``power_base`` expanded form, either of the following will work:: >>> expand((x*(y + z))**x, mul=False) x**x*(y + z)**x >>> expand_power_base((x*(y + z))**x) x**x*(y + z)**x >>> expand((x + y)*y/x) y + y**2/x The parts of a rational expression can be targeted:: >>> expand((x + y)*y/x/(x + 1), frac=True) (x*y + y**2)/(x**2 + x) >>> expand((x + y)*y/x/(x + 1), numer=True) (x*y + y**2)/(x*(x + 1)) >>> expand((x + y)*y/x/(x + 1), denom=True) y*(x + y)/(x**2 + x) - The ``modulus`` meta-hint can be used to reduce the coefficients of an expression post-expansion:: >>> expand((3*x + 1)**2) 9*x**2 + 6*x + 1 >>> expand((3*x + 1)**2, modulus=5) 4*x**2 + x + 1 - Either ``expand()`` the function or ``.expand()`` the method can be used. Both are equivalent:: >>> expand((x + 1)**2) x**2 + 2*x + 1 >>> ((x + 1)**2).expand() x**2 + 2*x + 1 API === Objects can define their own expand hints by defining ``_eval_expand_hint()``. The function should take the form:: def _eval_expand_hint(self, **hints): # Only apply the method to the top-level expression ... See also the example below. Objects should define ``_eval_expand_hint()`` methods only if ``hint`` applies to that specific object. The generic ``_eval_expand_hint()`` method defined in Expr will handle the no-op case. Each hint should be responsible for expanding that hint only. Furthermore, the expansion should be applied to the top-level expression only. ``expand()`` takes care of the recursion that happens when ``deep=True``. You should only call ``_eval_expand_hint()`` methods directly if you are 100% sure that the object has the method, as otherwise you are liable to get unexpected ``AttributeError``s. Note, again, that you do not need to recursively apply the hint to args of your object: this is handled automatically by ``expand()``. ``_eval_expand_hint()`` should generally not be used at all outside of an ``_eval_expand_hint()`` method. If you want to apply a specific expansion from within another method, use the public ``expand()`` function, method, or ``expand_hint()`` functions. In order for expand to work, objects must be rebuildable by their args, i.e., ``obj.func(*obj.args) == obj`` must hold. Expand methods are passed ``**hints`` so that expand hints may use 'metahints'--hints that control how different expand methods are applied. For example, the ``force=True`` hint described above that causes ``expand(log=True)`` to ignore assumptions is such a metahint. The ``deep`` meta-hint is handled exclusively by ``expand()`` and is not passed to ``_eval_expand_hint()`` methods. Note that expansion hints should generally be methods that perform some kind of 'expansion'. For hints that simply rewrite an expression, use the .rewrite() API. Examples ======== >>> from sympy import Expr, sympify >>> class MyClass(Expr): ... def __new__(cls, *args): ... args = sympify(args) ... return Expr.__new__(cls, *args) ... ... def _eval_expand_double(self, *, force=False, **hints): ... ''' ... Doubles the args of MyClass. ... ... If there more than four args, doubling is not performed, ... unless force=True is also used (False by default). ... ''' ... if not force and len(self.args) > 4: ... return self ... return self.func(*(self.args + self.args)) ... >>> a = MyClass(1, 2, MyClass(3, 4)) >>> a MyClass(1, 2, MyClass(3, 4)) >>> a.expand(double=True) MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4)) >>> a.expand(double=True, deep=False) MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4)) >>> b = MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True) MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True, force=True) MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) See Also ======== expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig, expand_power_base, expand_power_exp, expand_func, sympy.simplify.hyperexpand.hyperexpand """ # don't modify this; modify the Expr.expand method hints['power_base'] = power_base hints['power_exp'] = power_exp hints['mul'] = mul hints['log'] = log hints['multinomial'] = multinomial hints['basic'] = basic return sympify(e).expand(deep=deep, modulus=modulus, **hints) # This is a special application of two hints def _mexpand(expr, recursive=False): # expand multinomials and then expand products; this may not always # be sufficient to give a fully expanded expression (see # test_issue_8247_8354 in test_arit) if expr is None: return was = None while was != expr: was, expr = expr, expand_mul(expand_multinomial(expr)) if not recursive: break return expr # These are simple wrappers around single hints. def expand_mul(expr, deep=True): """ Wrapper around expand that only uses the mul hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_mul, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2)) x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2) """ return sympify(expr).expand(deep=deep, mul=True, power_exp=False, power_base=False, basic=False, multinomial=False, log=False) def expand_multinomial(expr, deep=True): """ Wrapper around expand that only uses the multinomial hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_multinomial, exp >>> x, y = symbols('x y', positive=True) >>> expand_multinomial((x + exp(x + 1))**2) x**2 + 2*x*exp(x + 1) + exp(2*x + 2) """ return sympify(expr).expand(deep=deep, mul=False, power_exp=False, power_base=False, basic=False, multinomial=True, log=False) def expand_log(expr, deep=True, force=False, factor=False): """ Wrapper around expand that only uses the log hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_log, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_log(exp(x+y)*(x+y)*log(x*y**2)) (x + y)*(log(x) + 2*log(y))*exp(x + y) """ from sympy.functions.elementary.exponential import log if factor is False: def _handle(x): x1 = expand_mul(expand_log(x, deep=deep, force=force, factor=True)) if x1.count(log) <= x.count(log): return x1 return x expr = expr.replace( lambda x: x.is_Mul and all(any(isinstance(i, log) and i.args[0].is_Rational for i in Mul.make_args(j)) for j in x.as_numer_denom()), _handle) return sympify(expr).expand(deep=deep, log=True, mul=False, power_exp=False, power_base=False, multinomial=False, basic=False, force=force, factor=factor) def expand_func(expr, deep=True): """ Wrapper around expand that only uses the func hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_func, gamma >>> from sympy.abc import x >>> expand_func(gamma(x + 2)) x*(x + 1)*gamma(x) """ return sympify(expr).expand(deep=deep, func=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_trig(expr, deep=True): """ Wrapper around expand that only uses the trig hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_trig, sin >>> from sympy.abc import x, y >>> expand_trig(sin(x+y)*(x+y)) (x + y)*(sin(x)*cos(y) + sin(y)*cos(x)) """ return sympify(expr).expand(deep=deep, trig=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_complex(expr, deep=True): """ Wrapper around expand that only uses the complex hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_complex, exp, sqrt, I >>> from sympy.abc import z >>> expand_complex(exp(z)) I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z)) >>> expand_complex(sqrt(I)) sqrt(2)/2 + sqrt(2)*I/2 See Also ======== sympy.core.expr.Expr.as_real_imag """ return sympify(expr).expand(deep=deep, complex=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_power_base(expr, deep=True, force=False): """ Wrapper around expand that only uses the power_base hint. A wrapper to expand(power_base=True) which separates a power with a base that is a Mul into a product of powers, without performing any other expansions, provided that assumptions about the power's base and exponent allow. deep=False (default is True) will only apply to the top-level expression. force=True (default is False) will cause the expansion to ignore assumptions about the base and exponent. When False, the expansion will only happen if the base is non-negative or the exponent is an integer. >>> from sympy.abc import x, y, z >>> from sympy import expand_power_base, sin, cos, exp >>> (x*y)**2 x**2*y**2 >>> (2*x)**y (2*x)**y >>> expand_power_base(_) 2**y*x**y >>> expand_power_base((x*y)**z) (x*y)**z >>> expand_power_base((x*y)**z, force=True) x**z*y**z >>> expand_power_base(sin((x*y)**z), deep=False) sin((x*y)**z) >>> expand_power_base(sin((x*y)**z), force=True) sin(x**z*y**z) >>> expand_power_base((2*sin(x))**y + (2*cos(x))**y) 2**y*sin(x)**y + 2**y*cos(x)**y >>> expand_power_base((2*exp(y))**x) 2**x*exp(y)**x >>> expand_power_base((2*cos(x))**y) 2**y*cos(x)**y Notice that sums are left untouched. If this is not the desired behavior, apply full ``expand()`` to the expression: >>> expand_power_base(((x+y)*z)**2) z**2*(x + y)**2 >>> (((x+y)*z)**2).expand() x**2*z**2 + 2*x*y*z**2 + y**2*z**2 >>> expand_power_base((2*y)**(1+z)) 2**(z + 1)*y**(z + 1) >>> ((2*y)**(1+z)).expand() 2*2**z*y*y**z See Also ======== expand """ return sympify(expr).expand(deep=deep, log=False, mul=False, power_exp=False, power_base=True, multinomial=False, basic=False, force=force) def expand_power_exp(expr, deep=True): """ Wrapper around expand that only uses the power_exp hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_power_exp >>> from sympy.abc import x, y >>> expand_power_exp(x**(y + 2)) x**2*x**y """ return sympify(expr).expand(deep=deep, complex=False, basic=False, log=False, mul=False, power_exp=True, power_base=False, multinomial=False) def count_ops(expr, visual=False): """ Return a representation (integer or expression) of the operations in expr. Parameters ========== expr : Expr If expr is an iterable, the sum of the op counts of the items will be returned. visual : bool, optional If ``False`` (default) then the sum of the coefficients of the visual expression will be returned. If ``True`` then the number of each type of operation is shown with the core class types (or their virtual equivalent) multiplied by the number of times they occur. Examples ======== >>> from sympy.abc import a, b, x, y >>> from sympy import sin, count_ops Although there isn't a SUB object, minus signs are interpreted as either negations or subtractions: >>> (x - y).count_ops(visual=True) SUB >>> (-x).count_ops(visual=True) NEG Here, there are two Adds and a Pow: >>> (1 + a + b**2).count_ops(visual=True) 2*ADD + POW In the following, an Add, Mul, Pow and two functions: >>> (sin(x)*x + sin(x)**2).count_ops(visual=True) ADD + MUL + POW + 2*SIN for a total of 5: >>> (sin(x)*x + sin(x)**2).count_ops(visual=False) 5 Note that "what you type" is not always what you get. The expression 1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather than two DIVs: >>> (1/x/y).count_ops(visual=True) DIV + MUL The visual option can be used to demonstrate the difference in operations for expressions in different forms. Here, the Horner representation is compared with the expanded form of a polynomial: >>> eq=x*(1 + x*(2 + x*(3 + x))) >>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True) -MUL + 3*POW The count_ops function also handles iterables: >>> count_ops([x, sin(x), None, True, x + 2], visual=False) 2 >>> count_ops([x, sin(x), None, True, x + 2], visual=True) ADD + SIN >>> count_ops({x: sin(x), x + 2: y + 1}, visual=True) 2*ADD + SIN """ from .relational import Relational from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral from sympy.logic.boolalg import BooleanFunction from sympy.simplify.radsimp import fraction expr = sympify(expr) if isinstance(expr, Expr) and not expr.is_Relational: ops = [] args = [expr] NEG = Symbol('NEG') DIV = Symbol('DIV') SUB = Symbol('SUB') ADD = Symbol('ADD') EXP = Symbol('EXP') while args: a = args.pop() # if the following fails because the object is # not Basic type, then the object should be fixed # since it is the intention that all args of Basic # should themselves be Basic if a.is_Rational: #-1/3 = NEG + DIV if a is not S.One: if a.p < 0: ops.append(NEG) if a.q != 1: ops.append(DIV) continue elif a.is_Mul or a.is_MatMul: if _coeff_isneg(a): ops.append(NEG) if a.args[0] is S.NegativeOne: a = a.as_two_terms()[1] else: a = -a n, d = fraction(a) if n.is_Integer: ops.append(DIV) if n < 0: ops.append(NEG) args.append(d) continue # won't be -Mul but could be Add elif d is not S.One: if not d.is_Integer: args.append(d) ops.append(DIV) args.append(n) continue # could be -Mul elif a.is_Add or a.is_MatAdd: aargs = list(a.args) negs = 0 for i, ai in enumerate(aargs): if _coeff_isneg(ai): negs += 1 args.append(-ai) if i > 0: ops.append(SUB) else: args.append(ai) if i > 0: ops.append(ADD) if negs == len(aargs): # -x - y = NEG + SUB ops.append(NEG) elif _coeff_isneg(aargs[0]): # -x + y = SUB, but already recorded ADD ops.append(SUB - ADD) continue if a.is_Pow and a.exp is S.NegativeOne: ops.append(DIV) args.append(a.base) # won't be -Mul but could be Add continue if a == S.Exp1: ops.append(EXP) continue if a.is_Pow and a.base == S.Exp1: ops.append(EXP) args.append(a.exp) continue if a.is_Mul or isinstance(a, LatticeOp): o = Symbol(a.func.__name__.upper()) # count the args ops.append(o*(len(a.args) - 1)) elif a.args and ( a.is_Pow or a.is_Function or isinstance(a, Derivative) or isinstance(a, Integral) or isinstance(a, Sum)): # if it's not in the list above we don't # consider a.func something to count, e.g. # Tuple, MatrixSymbol, etc... if isinstance(a.func, UndefinedFunction): o = Symbol("FUNC_" + a.func.__name__.upper()) else: o = Symbol(a.func.__name__.upper()) ops.append(o) if not a.is_Symbol: args.extend(a.args) elif isinstance(expr, Dict): ops = [count_ops(k, visual=visual) + count_ops(v, visual=visual) for k, v in expr.items()] elif iterable(expr): ops = [count_ops(i, visual=visual) for i in expr] elif isinstance(expr, (Relational, BooleanFunction)): ops = [] for arg in expr.args: ops.append(count_ops(arg, visual=True)) o = Symbol(func_name(expr, short=True).upper()) ops.append(o) elif not isinstance(expr, Basic): ops = [] else: # it's Basic not isinstance(expr, Expr): if not isinstance(expr, Basic): raise TypeError("Invalid type of expr") else: ops = [] args = [expr] while args: a = args.pop() if a.args: o = Symbol(type(a).__name__.upper()) if a.is_Boolean: ops.append(o*(len(a.args)-1)) else: ops.append(o) args.extend(a.args) if not ops: if visual: return S.Zero return 0 ops = Add(*ops) if visual: return ops if ops.is_Number: return int(ops) return sum(int((a.args or [1])[0]) for a in Add.make_args(ops)) def nfloat(expr, n=15, exponent=False, dkeys=False): """Make all Rationals in expr Floats except those in exponents (unless the exponents flag is set to True) and those in undefined functions. When processing dictionaries, do not modify the keys unless ``dkeys=True``. Examples ======== >>> from sympy import nfloat, cos, pi, sqrt >>> from sympy.abc import x, y >>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y)) x**4 + 0.5*x + sqrt(y) + 1.5 >>> nfloat(x**4 + sqrt(y), exponent=True) x**4.0 + y**0.5 Container types are not modified: >>> type(nfloat((1, 2))) is tuple True """ from sympy.matrices.matrices import MatrixBase kw = dict(n=n, exponent=exponent, dkeys=dkeys) if isinstance(expr, MatrixBase): return expr.applyfunc(lambda e: nfloat(e, **kw)) # handling of iterable containers if iterable(expr, exclude=str): if isinstance(expr, (dict, Dict)): if dkeys: args = [tuple(map(lambda i: nfloat(i, **kw), a)) for a in expr.items()] else: args = [(k, nfloat(v, **kw)) for k, v in expr.items()] if isinstance(expr, dict): return type(expr)(args) else: return expr.func(*args) elif isinstance(expr, Basic): return expr.func(*[nfloat(a, **kw) for a in expr.args]) return type(expr)([nfloat(a, **kw) for a in expr]) rv = sympify(expr) if rv.is_Number: return Float(rv, n) elif rv.is_number: # evalf doesn't always set the precision rv = rv.n(n) if rv.is_Number: rv = Float(rv.n(n), n) else: pass # pure_complex(rv) is likely True return rv elif rv.is_Atom: return rv elif rv.is_Relational: args_nfloat = (nfloat(arg, **kw) for arg in rv.args) return rv.func(*args_nfloat) # watch out for RootOf instances that don't like to have # their exponents replaced with Dummies and also sometimes have # problems with evaluating at low precision (issue 6393) from sympy.polys.rootoftools import RootOf rv = rv.xreplace({ro: ro.n(n) for ro in rv.atoms(RootOf)}) from .power import Pow if not exponent: reps = [(p, Pow(p.base, Dummy())) for p in rv.atoms(Pow)] rv = rv.xreplace(dict(reps)) rv = rv.n(n) if not exponent: rv = rv.xreplace({d.exp: p.exp for p, d in reps}) else: # Pow._eval_evalf special cases Integer exponents so if # exponent is suppose to be handled we have to do so here rv = rv.xreplace(Transform( lambda x: Pow(x.base, Float(x.exp, n)), lambda x: x.is_Pow and x.exp.is_Integer)) return rv.xreplace(Transform( lambda x: x.func(*nfloat(x.args, n, exponent)), lambda x: isinstance(x, Function) and not isinstance(x, AppliedUndef))) from .symbol import Dummy, Symbol
_block
references_bingo.go
package source import (
"go/ast" "go/token" "go/types" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/internal/span" ) // SearchFunc search global package cache function type SearchFunc func(walkFunc WalkFunc) // References find references func References(ctx context.Context, search SearchFunc, f GoFile, pos token.Pos, includeDeclaration bool) ([]*ReferenceInfo, error) { file, err := f.GetAST(ctx, ParseFull) if err != nil { return nil, err } pkg, err := f.GetPackage(ctx) if err != nil { return nil, err } if pkg.IsIllTyped() { return nil, fmt.Errorf("package for %s is ill typed", f.URI()) } path, _ := astutil.PathEnclosingInterval(file, pos, pos) if path == nil { return nil, fmt.Errorf("cannot find node enclosing position") } var ident *ast.Ident firstNode := path[0] switch node := firstNode.(type) { case *ast.Ident: ident = node case *ast.FuncDecl: ident = node.Name default: return nil, fmt.Errorf("not support node %v", node) } // NOTICE: Code adapted from golang.org/x/tools/cmd/guru // referrers.go. obj := pkg.GetTypesInfo().ObjectOf(ident) if obj == nil { return nil, fmt.Errorf("references object %s not found", ident.Name) } if obj.Pkg() == nil { if _, builtin := obj.(*types.Builtin); !builtin { return nil, fmt.Errorf("no package found for object %s", obj) } } refs, err := findReferences(ctx, search, pkg, obj) if err != nil { // If we are canceled, cancel loop early return nil, err } if includeDeclaration { refs = append(refs, &ReferIdent{ ident: &ast.Ident{NamePos: obj.Pos(), Name: obj.Name()}, isDeclaration: false, }) } return refStreamAndCollect(pkg, f.FileSet(), obj, refs, 0), nil } // refStreamAndCollect returns all refs read in from chan until it is // closed. While it is reading, it will also occasionally stream out updates of // the refs received so far. func refStreamAndCollect(pkg Package, fset *token.FileSet, obj types.Object, refs []*ReferIdent, limit int) []*ReferenceInfo { if limit == 0 { // If we don't have a limit, just set it to a value we should never exceed limit = len(refs) } l := len(refs) if limit < l { l = limit } var refers []*ReferenceInfo for i := 0; i < l; i++ { n := refs[i] rng := span.NewRange(fset, n.ident.Pos(), n.ident.Pos()+token.Pos(len([]byte(n.ident.Name)))) refer := &ReferenceInfo{ Name: n.ident.Name, mappedRange: mappedRange{spanRange: rng}, ident: n.ident, obj: obj, pkg: pkg, isDeclaration: n.isDeclaration, } refers = append(refers, refer) } return refers } type ReferIdent struct { ident *ast.Ident isDeclaration bool } // findReferences will find all references to obj. It will only return // references from packages in pkg.Imports. func findReferences(ctx context.Context, search SearchFunc, pkg Package, queryObj types.Object) ([]*ReferIdent, error) { // Bail out early if the context is canceled var refs []*ReferIdent var defPkgPath string if queryObj.Pkg() != nil { defPkgPath = queryObj.Pkg().Path() } else { defPkgPath = builtinPackage } seen := map[string]bool{} f := func(pkg Package) bool { if ctx.Err() != nil { return true } if pkg.GetTypesInfo() == nil { return false } if !imported(pkg, defPkgPath, seen) { return false } for id, obj := range pkg.GetTypesInfo().Uses { if bingoSameObj(queryObj, obj) { refs = append(refs, &ReferIdent{ident: id, isDeclaration: false}) } } return false } f(pkg) search(f) return refs, nil } func imported(pkg Package, defPkgPath string, seen map[string]bool) bool { if defPkgPath == builtinPackage { return true } if seen[pkg.GetTypes().Path()] { return false } seen[pkg.GetTypes().Path()] = true if pkg.GetTypes().Path() == defPkgPath { return true } for _, ip := range pkg.GetTypes().Imports() { if ip.Path() == defPkgPath { return true } } return false } // same reports whether x and y are identical, or both are PkgNames // that import the same Package. func bingoSameObj(x, y types.Object) bool { if x == y { return true } if x.Pkg() != nil && y.Pkg() != nil && x.Pkg().Path() == y.Pkg().Path() && x.Name() == y.Name() && x.Exported() && y.Exported() && x.Type().String() == y.Type().String() { // enable find the xtest pakcage's uses, but this will product some duplicate results return true } // builtin package symbol if x.Pkg() == nil && y.Pkg() == nil && x.Name() == y.Name() { return true } if x, ok := x.(*types.PkgName); ok { if y, ok := y.(*types.PkgName); ok { return x.Imported() == y.Imported() } } return false }
"context" "fmt"