repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
RlanderRISCSW/cpacs_tigl_gen
src/driver/main.cpp
5115
#include <boost/filesystem.hpp> #include <iostream> #include <iomanip> #include "../lib/SchemaParser.h" #include "../lib/TypeSystem.h" #include "../lib/CodeGen.h" #include "../lib/Tables.h" #include "../lib/Filesystem.h" #include "../lib/NotImplementedException.h" namespace fs = boost::filesystem; namespace tigl { const auto runtimeFiles = { "TixiHelper.h", "UniquePtr.h", }; void processDirectory(const std::string& inputDirectory, const std::string& runtimeDirectory, const std::string& outputDirectory, const std::string& typeSystemGraphVisFile, Filesystem& fs, const std::string& ns = "") { // load tables from this directory const Tables tables(inputDirectory); // iterate all *.xsd files in the input directory for (const auto& e : fs::directory_iterator(inputDirectory)) { if (fs::is_regular_file(e) && e.path().has_extension() && e.path().extension() == ".xsd") { // read types and elements std::cout << "Parsing " << e.path() << std::endl; auto types = xsd::parseSchema(e.path().string()); // generate type system from schema std::cout << "Creating type system" << std::endl; const auto& typeSystem = buildTypeSystem(types, tables); // write graph vis file for the generated type system if (!typeSystemGraphVisFile.empty()) { auto p = fs::path{ typeSystemGraphVisFile }; if (p.has_parent_path()) fs::create_directories(p.parent_path()); writeGraphVisFile(typeSystem, typeSystemGraphVisFile); } // create output directory const auto nsOutputDirectory = ns.empty() ? outputDirectory : outputDirectory + "/" + ns; fs::create_directories(nsOutputDirectory); // generate code std::cout << "Generating classes" << std::endl; genCode(nsOutputDirectory, typeSystem, ns, tables, fs); } } // recurse on sub directories for (const auto& e : fs::directory_iterator(inputDirectory)) { if (fs::is_directory(e)) { if (!ns.empty()) throw NotImplementedException("Nested input directories are not implemented. Only 1 level of subdirectories (namespaces) is allowed."); const auto leafDir = e.path().leaf().string(); processDirectory(e.path().string(), runtimeDirectory, outputDirectory, typeSystemGraphVisFile, fs, leafDir); } } } void run(const std::string& inputDirectory, const std::string& runtimeDirectory, const std::string& outputDirectory, const std::string& typeSystemGraphVisFile) { // create runtime output directory fs::create_directories(outputDirectory); std::cout << "Copying runtime" << std::endl; Filesystem fs; for (const auto& file : runtimeFiles) fs.newFile(outputDirectory + "/" + file).stream() << readFile(runtimeDirectory + "/" + file); // process schema files processDirectory(inputDirectory, runtimeDirectory, outputDirectory, typeSystemGraphVisFile, fs); fs.flushToDisk(); std::cout << "\tWrote " << std::setw(5) << fs.newlywritten << " new files" << std::endl; std::cout << "\tUpdated " << std::setw(5) << fs.overwritten << " existing files" << std::endl; std::cout << "\tSkipped " << std::setw(5) << fs.skipped << " files, no changes" << std::endl; std::cout << "\tDeleted " << std::setw(5) << fs.deleted << " files, pruned" << std::endl; } } int main(int argc, char* argv[]) { // parse command line arguments if (argc != 4 && argc != 5) { std::cerr << "Usage: CPACSGen configDir cpascGenSourceDir outputDir [typeSystemGraphVisFile] \n\n" << "Options:\n\n" << " configDir The directory containing the CPACS schema and\n" << " the table files.\n" << " runtimeDir The directory of where the runtime source files are.\n" << " outputDir The directory to which the CPACSGen output\n" << " file are written\n" << " typeSystemGraphVisFile GraphVis file visualizing the built type system." << std::endl; return -1; } const std::string inputDirectory = argv[1]; const std::string runtimeDirectory = argv[2]; const std::string outputDirectory = argv[3]; const std::string typeSystemGraphVisFile = argc > 4 ? argv[4] : ""; try { tigl::run(inputDirectory, runtimeDirectory, outputDirectory, typeSystemGraphVisFile); return 0; } catch (const std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; return -1; } catch (...) { std::cerr << "Unknown exception" << std::endl; return -1; } }
apache-2.0
EZWebvietnam/vieclam24h
application/helpers/file_cache_helper.php
13647
<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); /** * file_cache_helper * * This is a cache system that has been built for use in the * Codeigniter Framework. * * @author Matthew Craig <matt@taggedzi.com> * @copyright Matthew Craig 2011-03-28 * @version 1.0 * @link http://taggedzi.com/ * @package file_cache_helper */ /** Licence Copyright (c) 2011, Matthew Craig <matt@taggedzi.com> All rights reserved. Permitted Use You are permitted to use, copy, modify, and distribute the Software and its documentation, with or without modification, for any purpose, provided that the following conditions are met: 1. A copy of this license agreement must be included with the distribution. 2. Redistributions of source code must retain the above copyright notice in all source code files. 3. Redistributions in binary form must reproduce the above copyright notice in the documentation and/or other materials provided with the distribution. 4. Any files that have been modified must carry notices stating the nature of the change and the names of those who changed them. 5. Products derived from the Software must include an acknowledgment that they are derived from this code in their documentation and/or other materials provided with the distribution. Indemnity You agree to indemnify and hold harmless the authors of the Software and any contributors for any direct, indirect, incidental, or consequential third-party claims, actions or suits, as well as any related expenses, liabilities, damages, settlements or fees arising from your use or misuse of the Software, or a violation of any terms of this license. Disclaimer of Warranty THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF QUALITY, PERFORMANCE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. Limitations of Liability YOU ASSUME ALL RISK ASSOCIATED WITH THE INSTALLATION AND USE OF THE SOFTWARE. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS OF THE SOFTWARE BE LIABLE FOR CLAIMS, DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE. LICENSE HOLDERS ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USE AND ASSUME ALL RISKS ASSOCIATED WITH ITS USE, INCLUDING BUT NOT LIMITED TO THE RISKS OF PROGRAM ERRORS, DAMAGE TO EQUIPMENT, LOSS OF DATA OR SOFTWARE PROGRAMS, OR UNAVAILABILITY OR INTERRUPTION OF OPERATIONS. */ /** * save_cache * * This function use used to store data in a "file cache" in a location * specified in the application/config/file_cache.php * @param string $key The Key used to access the data. (the "name" of the data) * @param mixed $data The data to be stored, can be any type that can be serialized. * @param int $ttl The time to live in seconds from the time of storage. * @access public * @return boolean Returns TRUE if successful / FALSE if not. */ if( ! function_exists('save_cache')) { function save_cache ($key = null, $data = null, $ttl = 3600) { // if there is no key... stop if(is_null($key)) { return FALSE; } // if there is no data... stop if(is_null($data)) { return FALSE; } // Sanity Check on ttl settype($ttl, 'integer'); if(($ttl <= 0) || ($ttl > PHP_INT_MAX)) { return FALSE; } // setup the TTL $actual_ttl = time() + $ttl; // if the TTL is larger than PHP can handle truncate it // to the INT max for the platform. if ($actual_ttl > PHP_INT_MAX) { $actual_ttl = PHP_INT_MAX; } // Load the CI instance so that we can get the config var. $CI =& get_instance(); $CI->config->load('file_cache', TRUE); $file_path = $CI->config->item('file_cache_path', 'file_cache') . $CI->config->item('prefix', 'file_cache') . '_' . md5($key) . '.' . $CI->config->item('file_extension', 'file_cache'); // opening the file $h = fopen($file_path,'w'); // If the file failed to open... if ($h === FALSE) { return FALSE; } // serializing along with the ttl $data = serialize(array($actual_ttl,$data)); // Check to see if encryption is turned on. if ( $CI->config->item('encrypt_cache', 'file_cache')) { $CI->load->library('encrypt'); // Encrypt the serialized data $data = $CI->encrypt->encode($data); } // Write the serialized data to the file. if (fwrite($h,$data)===false) { return FALSE; } // Close the file fclose($h); // If we made it this far all must be well. return TRUE; } } /** * get_cache * * This function retreives a cached file by its "key" * @param string $key * @access public * @return mixed This returns FALSE if no data found, or returns the stored data. */ if( ! function_exists('get_cache')) { function get_cache($key = null) { $CI =& get_instance(); $CI->config->load('file_cache', TRUE); $file_path = $CI->config->item('file_cache_path', 'file_cache') . $CI->config->item('prefix', 'file_cache') . $CI->config->item('delimiter', 'file_cache') . md5($key) . '.' . $CI->config->item('file_extension', 'file_cache'); // Get the file and un-serialize the data. if (file_exists($file_path)) { $data = file_get_contents($file_path); // Check to see if encryption is turned on. if ( $CI->config->item('encrypt_cache', 'file_cache')) { $CI->load->library('encrypt'); // Encrypt the serialized data $data = $CI->encrypt->decode($data); } $data = @unserialize($data); // Check if the data was able to be retrieved. if ($data === FALSE) { unlink($file_path); return FALSE; } // Check the TTL if (time() > $data[0]) { unlink($file_path); return FALSE; } // Return the un-serialized data. return $data[1]; } else { // There was no file. return FALSE; } } } /** * remove_cache_key * * This function clears a single cache key. * @param string $key * @access public * @return boolean True if cleared, FALSE if not. */ if( ! function_exists('remove_cache_key')) { function remove_cache_key($key = null) { // if no key is called... we can't clear that key can we? if (is_null($key)) { return FALSE; } // Load the CI instance so that we can get the config var. $CI =& get_instance(); $CI->config->load('file_cache', TRUE); $file_path = $CI->config->item('file_cache_path', 'file_cache') . $CI->config->item('prefix', 'file_cache') . '_' . md5($key) . '.' . $CI->config->item('file_extension', 'file_cache'); if(file_exists($file_path)) { @unlink($file_path); return TRUE; } else { return FALSE; } } } /** * flush_cache * * This function removes all files associated with the cache * from the cache directory. * @access public * @return void */ if ( ! function_exists('flush_cache')) { function flush_cache() { $CI =& get_instance(); $CI->config->load('file_cache', TRUE); $CI->load->helper('file_helper'); $file_list = get_filenames($CI->config->item('file_cache_path', 'file_cache')); $removed_file_list = array(); // These are all boolean checks used to make sure we don't // delete files that are not part of the cache. $prefix_check = $extension_check = $ttl_check = FALSE; foreach($file_list as $file_name) { // Get the cache path from the config. $file_path = $CI->config->item('file_cache_path', 'file_cache') . $file_name; // setup the checks for safety. $prefix_check = $extension_check = $ttl_check = FALSE; // Make sure the file has the right prefix. $temp = explode($CI->config->item('delimiter', 'file_cache'), $file_name); $prefix = $temp[0]; if ($prefix == $CI->config->item('prefix', 'file_cache')) { // The prefix did match... trigger the check $prefix_check = TRUE; } // Make sure the file has the righ extension. $temp = explode('.', $file_name); $extension = end($temp); if ($extension == $CI->config->item('file_extension', 'file_cache')) { // The extension matched... trigger the check $extension_check = TRUE; } // Open the file and make sure the file has TTL data if(file_exists($file_path)) { $data = file_get_contents($file_path); // Check to see if encryption is turned on. if ( $CI->config->item('encrypt_cache', 'file_cache')) { $CI->load->library('encrypt'); // Encrypt the serialized data $data = $CI->encrypt->decode($data); } $data = @unserialize($data); // check to see if we could unserialize the file data.. if($data !== FALSE) { // check to make sure the first array entry is an integer if(is_int($data[0])) { $ttl_check = TRUE; } } } // IF all of the checks passed... delete the file. if ($prefix_check && $extension_check && $ttl_check) { @unlink($file_path); $removed_file_list[] = $file_path; } } return $removed_file_list; } } /** * cache_check_ttl * * This function checks the status of a cache file and * deletes it if it is corrupt OR the TTL has expired. * * WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * * This function is not meant to be used by the user, but by the internal * function "clean_cache". If you call this with a regular file there is * all most a 100% chance IT WILL DELETE IT. Since mostly likely your * file does not contain valid serialized data. * * END WARNING !!!!!!!!!!!!!!!!!!!!!!!!! * * @param string $file_name This is NOT the key, this is the generated filename. * @access public * @return void */ if( ! function_exists('check_cache_ttl')) { function check_cache_ttl ($file_name) { // if there is no key... stop if(is_null($file_name)) { return FALSE; } // Load the CI instance so that we can get the config var. $CI =& get_instance(); $CI->config->load('file_cache', TRUE); $file_path = $CI->config->item('file_cache_path', 'file_cache') . $file_name; // Check the prefix and file extension. as safety. $temp = explode($CI->config->item('delimiter', 'file_cache'), $file_name); $prefix = $temp[0]; if ($prefix != $CI->config->item('prefix', 'file_cache')) { // The prefix did not match... it must not be the cache we are looking for. return FALSE; } $temp = explode('.', $file_name); $extension = end($temp); if ($extension != $CI->config->item('file_extension', 'file_cache')) { // The extension not match... it must not be the cache we are looking for. return FALSE; } // Get the file and un-serialize the data. $data = file_get_contents($file_path); // Check to see if encryption is turned on. if ( $CI->config->item('encrypt_cache', 'file_cache')) { $CI->load->library('encrypt'); // Encrypt the serialized data $data = $CI->encrypt->decode($data); } $data = @unserialize($data); // Check if the data was able to be retrieved. if ($data === FALSE) { unlink($file_path); return TRUE; } // Check the TTL if (time() > $data[0]) { unlink($file_path); return TRUE; } // If we made it this far all must be well. return FALSE; } } /** * clean_cache * * This is a helper function that goes through the "cache" * directory and has expired, or corrupted data deleted. * @access public * @return void */ if( ! function_exists('clean_cache')) { function clean_cache() { $CI =& get_instance(); $CI->config->load('file_cache', TRUE); $CI->load->helper('file_helper'); $file_list = get_filenames($CI->config->item('file_cache_path', 'file_cache')); $removed_file_list = array(); foreach($file_list as $cache_file) { if(check_cache_ttl($cache_file)) { $removed_file_list[] = $cache_file; } } return $removed_file_list; } } /* End of file file_cache_helper.php */ /* Location: ./application/helpers/file_cache_helper.php */
apache-2.0
dylanswartz/nakamura
testscripts/SlingRuby/kerns/kern-296.rb
1157
#!/usr/bin/env ruby require 'rubygems' require 'bundler' Bundler.setup(:default) require 'nakamura/test' require 'nakamura/search' require 'test/unit.rb' include SlingSearch class TC_Kern296Test < Test::Unit::TestCase include SlingTest def test_move m = uniqueness() u1 = create_user("testuser#{m}") assert_not_nil(u1,"Expected User to be created ") g1 = create_group("g-testgroup#{m}") assert_not_nil(u1,"Expected Group to be created ") g1.add_member(@s, u1.name, "user") hasmember = g1.has_member(@s, u1.name) assert_equal(true,hasmember,"Expected user #{u1.name} to be a member of group #{g1.name} ") g1.remove_member(@s,u1.name,"user") hasmember = g1.has_member(@s, u1.name) assert_equal(false,hasmember,"Expected user #{u1.name} not to be a member of group #{g1.name} ") url = SlingUsers::Group.url_for(g1.name) res = @s.execute_post(@s.url_for("#{url}.delete.html")) assert_equal("200",res.code,"Expected delete group to be sucessful #{res.body}") res = @s.execute_get(@s.url_for("#{url}.json")) assert_not_equal("200", res.code, "Expected group to be gone: #{res.body}") end end
apache-2.0
Darpholgshon/metadata-extractor
src/main/java/com/drew/lang/StringUtil.java
3873
/* * Copyright 2002-2013 Drew Noakes * * 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. * * More information about this project is available at: * * http://drewnoakes.com/code/exif/ * http://code.google.com/p/metadata-extractor/ */ package com.drew.lang; import com.drew.lang.annotations.NotNull; import com.drew.lang.annotations.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Iterator; /** * @author Drew Noakes http://drewnoakes.com */ public class StringUtil { @NotNull public static String join(@NotNull Iterable<? extends CharSequence> strings, @NotNull String delimiter) { int capacity = 0; int delimLength = delimiter.length(); Iterator<? extends CharSequence> iter = strings.iterator(); if (iter.hasNext()) capacity += iter.next().length() + delimLength; StringBuilder buffer = new StringBuilder(capacity); iter = strings.iterator(); if (iter.hasNext()) { buffer.append(iter.next()); while (iter.hasNext()) { buffer.append(delimiter); buffer.append(iter.next()); } } return buffer.toString(); } @NotNull public static <T extends CharSequence> String join(@NotNull T[] strings, @NotNull String delimiter) { int capacity = 0; int delimLength = delimiter.length(); for (T value : strings) capacity += value.length() + delimLength; StringBuilder buffer = new StringBuilder(capacity); boolean first = true; for (T value : strings) { if (!first) { buffer.append(delimiter); } else { first = false; } buffer.append(value); } return buffer.toString(); } @NotNull public static String fromStream(@NotNull InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } public static int compare(@Nullable String s1, @Nullable String s2) { boolean null1 = s1 == null; boolean null2 = s2 == null; if (null1 && null2) { return 0; } else if (null1 && !null2) { return -1; } else if (null2) { return 1; } else { return s1.compareTo(s2); } } @Nullable public static String escapeForWiki(@Nullable String text) { if (text == null) return null; text = text.replaceAll("(\\W|^)(([A-Z][a-z0-9]+){2,})", "$1!$2"); if (text != null && text.length() > 120) text = text.substring(0, 120) + "..."; if (text != null) text = text.replace("[", "`[`").replace("]", "`]`").replace("<", "`<`").replace(">", "`>`").replace("*", "`*`"); return text; } @NotNull public static String urlEncode(@NotNull String name) { // Sufficient for now, it seems return name.replace(" ", "%20"); } }
apache-2.0
psiroky/guvnor
droolsjbpm-ide-common/src/test/java/org/drools/ide/common/server/util/BRDRLPersistenceTest.java
117474
/* * Copyright 2010 JBoss 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. */ package org.drools.ide.common.server.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.drools.ide.common.client.modeldriven.SuggestionCompletionEngine; import org.drools.ide.common.client.modeldriven.brl.ActionCallMethod; import org.drools.ide.common.client.modeldriven.brl.ActionExecuteWorkItem; import org.drools.ide.common.client.modeldriven.brl.ActionFieldFunction; import org.drools.ide.common.client.modeldriven.brl.ActionFieldValue; import org.drools.ide.common.client.modeldriven.brl.ActionGlobalCollectionAdd; import org.drools.ide.common.client.modeldriven.brl.ActionInsertFact; import org.drools.ide.common.client.modeldriven.brl.ActionInsertLogicalFact; import org.drools.ide.common.client.modeldriven.brl.ActionRetractFact; import org.drools.ide.common.client.modeldriven.brl.ActionSetField; import org.drools.ide.common.client.modeldriven.brl.ActionUpdateField; import org.drools.ide.common.client.modeldriven.brl.ActionWorkItemFieldValue; import org.drools.ide.common.client.modeldriven.brl.BaseSingleFieldConstraint; import org.drools.ide.common.client.modeldriven.brl.CompositeFactPattern; import org.drools.ide.common.client.modeldriven.brl.CompositeFieldConstraint; import org.drools.ide.common.client.modeldriven.brl.ConnectiveConstraint; import org.drools.ide.common.client.modeldriven.brl.DSLSentence; import org.drools.ide.common.client.modeldriven.brl.ExpressionField; import org.drools.ide.common.client.modeldriven.brl.ExpressionText; import org.drools.ide.common.client.modeldriven.brl.ExpressionUnboundFact; import org.drools.ide.common.client.modeldriven.brl.FactPattern; import org.drools.ide.common.client.modeldriven.brl.FreeFormLine; import org.drools.ide.common.client.modeldriven.brl.FromAccumulateCompositeFactPattern; import org.drools.ide.common.client.modeldriven.brl.FromCollectCompositeFactPattern; import org.drools.ide.common.client.modeldriven.brl.FromEntryPointFactPattern; import org.drools.ide.common.client.modeldriven.brl.IAction; import org.drools.ide.common.client.modeldriven.brl.IPattern; import org.drools.ide.common.client.modeldriven.brl.RuleAttribute; import org.drools.ide.common.client.modeldriven.brl.RuleModel; import org.drools.ide.common.client.modeldriven.brl.SingleFieldConstraint; import org.drools.ide.common.client.modeldriven.brl.SingleFieldConstraintEBLeftSide; import org.drools.ide.common.shared.workitems.PortableBooleanParameterDefinition; import org.drools.ide.common.shared.workitems.PortableFloatParameterDefinition; import org.drools.ide.common.shared.workitems.PortableIntegerParameterDefinition; import org.drools.ide.common.shared.workitems.PortableStringParameterDefinition; import org.drools.ide.common.shared.workitems.PortableWorkDefinition; import org.junit.Before; import org.junit.Test; public class BRDRLPersistenceTest { private BRLPersistence brlPersistence; @Before public void setUp() throws Exception { brlPersistence = BRDRLPersistence.getInstance(); } @Test public void testGenerateEmptyDRL() { String expected = "rule \"null\"\n\tdialect \"mvel\"\n\twhen\n\tthen\nend\n"; final String drl = brlPersistence.marshal( new RuleModel() ); assertNotNull( drl ); assertEquals( expected, drl ); } @Test public void testFreeForm() { RuleModel m = new RuleModel(); m.name = "with composite"; m.lhs = new IPattern[1]; m.rhs = new IAction[1]; FreeFormLine fl = new FreeFormLine(); fl.text = "Person()"; m.lhs[0] = fl; FreeFormLine fr = new FreeFormLine(); fr.text = "fun()"; m.rhs[0] = fr; String drl = brlPersistence.marshal( m ); assertNotNull( drl ); assertTrue( drl.indexOf( "Person()" ) > 0 ); assertTrue( drl.indexOf( "fun()" ) > drl.indexOf( "Person()" ) ); } @Test public void testBasics() { String expected = "rule \"my rule\"\n\tno-loop true\n\tdialect \"mvel\"\n\twhen\n\t\tPerson( )\n" + "\t\tAccident( )\n\tthen\n\t\tinsert( new Report() );\nend\n"; final RuleModel m = new RuleModel(); m.addLhsItem( new FactPattern( "Person" ) ); m.addLhsItem( new FactPattern( "Accident" ) ); m.addAttribute( new RuleAttribute( "no-loop", "true" ) ); m.addRhsItem( new ActionInsertFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testInsertLogical() { String expected = "rule \"my rule\"\n\tno-loop true\n\tdialect \"mvel\"\n\twhen\n\t\tPerson( )\n" + "\t\tAccident( )\n\tthen\n\t\tinsertLogical( new Report() );\nend\n"; final RuleModel m = new RuleModel(); m.addLhsItem( new FactPattern( "Person" ) ); m.addLhsItem( new FactPattern( "Accident" ) ); m.addAttribute( new RuleAttribute( "no-loop", "true" ) ); m.addRhsItem( new ActionInsertLogicalFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testAttr() { RuleModel m = new RuleModel(); m.attributes = new RuleAttribute[1]; m.attributes[0] = new RuleAttribute( "enabled", "true" ); final String drl = brlPersistence.marshal( m ); assertTrue( drl.indexOf( "enabled true" ) > 0 ); } @Test public void testEnumNoType() { //A legacy "Guvnor" enums (i.e pick-list of underlying field data-type) String expected = "rule \"my rule\"\n\tdialect \"mvel\"\n\twhen\n\t\tCheese( type == \"CheeseType.CHEDDAR\" )\n" + "\tthen\n\t\tinsert( new Report() );\nend\n"; final RuleModel m = new RuleModel(); final FactPattern pat = new FactPattern( "Cheese" ); m.addLhsItem( pat ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "type" ); con.setOperator( "==" ); con.setValue( "CheeseType.CHEDDAR" ); con.setConstraintValueType( BaseSingleFieldConstraint.TYPE_ENUM ); pat.addConstraint( con ); m.addRhsItem( new ActionInsertFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testEnumTypeString() { //A legacy "Guvnor" enums (i.e pick-list of underlying field data-type) String expected = "rule \"my rule\"\n\tdialect \"mvel\"\n\twhen\n\t\tCheese( type == \"CHEDDAR\" )\n" + "\tthen\n\t\tinsert( new Report() );\nend\n"; final RuleModel m = new RuleModel(); final FactPattern pat = new FactPattern( "Cheese" ); m.addLhsItem( pat ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "type" ); con.setOperator( "==" ); con.setValue( "CHEDDAR" ); con.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con.setConstraintValueType( BaseSingleFieldConstraint.TYPE_ENUM ); pat.addConstraint( con ); m.addRhsItem( new ActionInsertFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testEnumTypeStringInOperator() { //A legacy "Guvnor" enums (i.e pick-list of underlying field data-type) String expected = "rule \"my rule\"\n" + "\tdialect \"mvel\"\n" + "\twhen\n" + "\t\tCheese( type in ( \"CHEDDAR\", \"STILTON\" ) )\n" + "\tthen\n" + "\t\tinsert( new Report() );\n" + "end\n"; final RuleModel m = new RuleModel(); final FactPattern pat = new FactPattern( "Cheese" ); m.addLhsItem( pat ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "type" ); con.setOperator( "in" ); con.setValue( "( \"CHEDDAR\",\"STILTON\" )" ); con.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con.setConstraintValueType( BaseSingleFieldConstraint.TYPE_ENUM ); pat.addConstraint( con ); m.addRhsItem( new ActionInsertFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testEnumTypeNumeric() { //A legacy "Guvnor" enums (i.e pick-list of underlying field data-type) String expected = "rule \"my rule\"\n\tdialect \"mvel\"\n\twhen\n\t\tCheese( age == 100 )\n" + "\tthen\n\t\tinsert( new Report() );\nend\n"; final RuleModel m = new RuleModel(); final FactPattern pat = new FactPattern( "Cheese" ); m.addLhsItem( pat ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "age" ); con.setOperator( "==" ); con.setValue( "100" ); con.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ); con.setConstraintValueType( BaseSingleFieldConstraint.TYPE_ENUM ); pat.addConstraint( con ); m.addRhsItem( new ActionInsertFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testEnumTypeBoolean() { //A legacy "Guvnor" enums (i.e pick-list of underlying field data-type) String expected = "rule \"my rule\"\n\tdialect \"mvel\"\n\twhen\n\t\tCheese( smelly == true )\n" + "\tthen\n\t\tinsert( new Report() );\nend\n"; final RuleModel m = new RuleModel(); final FactPattern pat = new FactPattern( "Cheese" ); m.addLhsItem( pat ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "smelly" ); con.setOperator( "==" ); con.setValue( "true" ); con.setFieldType( SuggestionCompletionEngine.TYPE_BOOLEAN ); con.setConstraintValueType( BaseSingleFieldConstraint.TYPE_ENUM ); pat.addConstraint( con ); m.addRhsItem( new ActionInsertFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testEnumTypeDate() { //A legacy "Guvnor" enums (i.e pick-list of underlying field data-type) String expected = "rule \"my rule\"\n\tdialect \"mvel\"\n\twhen\n\t\tCheese( dateMade == \"31-Jan-2010\" )\n" + "\tthen\n\t\tinsert( new Report() );\nend\n"; final RuleModel m = new RuleModel(); final FactPattern pat = new FactPattern( "Cheese" ); m.addLhsItem( pat ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "dateMade" ); con.setOperator( "==" ); con.setValue( "31-Jan-2010" ); con.setFieldType( SuggestionCompletionEngine.TYPE_DATE ); con.setConstraintValueType( BaseSingleFieldConstraint.TYPE_ENUM ); pat.addConstraint( con ); m.addRhsItem( new ActionInsertFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testEnumTypeComparable() { //Java 1.5+ "true" enums are of type Comparable String expected = "rule \"my rule\"\n\tdialect \"mvel\"\n\twhen\n\t\tCheese( type == Cheese.CHEDDAR )\n" + "\tthen\n\t\tinsert( new Report() );\nend\n"; final RuleModel m = new RuleModel(); final FactPattern pat = new FactPattern( "Cheese" ); m.addLhsItem( pat ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "type" ); con.setOperator( "==" ); con.setValue( "Cheese.CHEDDAR" ); con.setFieldType( SuggestionCompletionEngine.TYPE_COMPARABLE ); con.setConstraintValueType( BaseSingleFieldConstraint.TYPE_ENUM ); pat.addConstraint( con ); m.addRhsItem( new ActionInsertFact( "Report" ) ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testMoreComplexRendering() { final RuleModel m = getComplexModel(); String expected = "rule \"Complex Rule\"\n" + "\tno-loop true\n" + "\tsalience -10\n" + "\tagenda-group \"aGroup\"\n" + "\tdialect \"mvel\"\n" + "\twhen\n" + "\t\t>p1 : Person( f1 : age < 42 )\n" + "\t\t>not (Cancel( )) \n" + "\tthen\n" + "\t\t>p1.setStatus( \"rejected\" );\n" + "\t\t>update( p1 );\n" + "\t\t>retract( p1 );\n" + "\t\tSend an email to administrator\n" + "end\n"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testFieldBindingWithNoConstraints() { // to satisfy JBRULES-850 RuleModel m = getModelWithNoConstraints(); String s = BRDRLPersistence.getInstance().marshal( m ); // System.out.println(s); assertTrue( s.indexOf( "Person( f1 : age)" ) != -1 ); } @Test public void textIsNullOperator() { final RuleModel m = new RuleModel(); m.name = "IsNullOperator"; final FactPattern pat = new FactPattern( "Person" ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "age" ); con.setOperator( "== null" ); pat.addConstraint( con ); m.addLhsItem( pat ); String s = BRDRLPersistence.getInstance().marshal( m ); assertTrue( s.indexOf( "Person( age == null )" ) != -1 ); } @Test public void textIsNotNullOperator() { final RuleModel m = new RuleModel(); m.name = "IsNotNullOperator"; final FactPattern pat = new FactPattern( "Person" ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "age" ); con.setOperator( "!= null" ); pat.addConstraint( con ); m.addLhsItem( pat ); String s = BRDRLPersistence.getInstance().marshal( m ); assertTrue( s.indexOf( "Person( age != null )" ) != -1 ); } // // public void testRoundTrip() { // final RuleModel m = getComplexModel(); // // final String xml = BRXMLPersistence.getInstance().marshal( m ); // // final RuleModel m2 = BRXMLPersistence.getInstance().unmarshal( xml ); // assertNotNull( m2 ); // assertEquals( m.name, // m2.name ); // assertEquals( m.lhs.length, // m2.lhs.length ); // assertEquals( m.rhs.length, // m2.rhs.length ); // assertEquals( 1, // m.attributes.length ); // // final RuleAttribute at = m.attributes[0]; // assertEquals( "no-loop", // at.attributeName ); // assertEquals( "true", // at.value ); // // final String newXML = BRXMLPersistence.getInstance().marshal( m2 ); // assertEquals( xml, // newXML ); // // } // private RuleModel getModelWithNoConstraints() { final RuleModel m = new RuleModel(); m.name = "Complex Rule"; final FactPattern pat = new FactPattern( "Person" ); pat.setBoundName( "p1" ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldBinding( "f1" ); con.setFieldName( "age" ); // con.operator = "<"; // con.value = "42"; pat.addConstraint( con ); m.addLhsItem( pat ); return m; } private RuleModel getComplexModel() { final RuleModel m = new RuleModel(); m.name = "Complex Rule"; m.addAttribute( new RuleAttribute( "no-loop", "true" ) ); m.addAttribute( new RuleAttribute( "salience", "-10" ) ); m.addAttribute( new RuleAttribute( "agenda-group", "aGroup" ) ); final FactPattern pat = new FactPattern( "Person" ); pat.setBoundName( "p1" ); final SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldBinding( "f1" ); con.setFieldName( "age" ); con.setOperator( "<" ); con.setValue( "42" ); pat.addConstraint( con ); m.addLhsItem( pat ); final CompositeFactPattern comp = new CompositeFactPattern( "not" ); comp.addFactPattern( new FactPattern( "Cancel" ) ); m.addLhsItem( comp ); final ActionUpdateField set = new ActionUpdateField(); set.variable = "p1"; set.addFieldValue( new ActionFieldValue( "status", "rejected", SuggestionCompletionEngine.TYPE_STRING ) ); m.addRhsItem( set ); final ActionRetractFact ret = new ActionRetractFact( "p1" ); m.addRhsItem( ret ); final DSLSentence sen = new DSLSentence(); sen.setDefinition( "Send an email to {administrator}" ); m.addRhsItem( sen ); return m; } @Test public void testOrComposite() throws Exception { RuleModel m = new RuleModel(); m.name = "or"; CompositeFactPattern cp = new CompositeFactPattern( CompositeFactPattern.COMPOSITE_TYPE_OR ); FactPattern p1 = new FactPattern( "Person" ); SingleFieldConstraint sf1 = new SingleFieldConstraint( "age" ); sf1.setOperator( "==" ); sf1.setValue( "42" ); p1.addConstraint( sf1 ); cp.addFactPattern( p1 ); FactPattern p2 = new FactPattern( "Person" ); SingleFieldConstraint sf2 = new SingleFieldConstraint( "age" ); sf2.setOperator( "==" ); sf2.setValue( "43" ); p2.addConstraint( sf2 ); cp.addFactPattern( p2 ); m.addLhsItem( cp ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result .indexOf( "( Person( age == 42 ) or Person( age == 43 ) )" ) > 0 ); } @Test public void testExistsMultiPatterns() throws Exception { String result = getCompositeFOL( CompositeFactPattern.COMPOSITE_TYPE_EXISTS ); assertTrue( result .indexOf( "exists (Person( age == 42 ) and Person( age == 43 ))" ) > 0 ); } @Test public void testNotMultiPatterns() throws Exception { String result = getCompositeFOL( CompositeFactPattern.COMPOSITE_TYPE_NOT ); assertTrue( result .indexOf( "not (Person( age == 42 ) and Person( age == 43 ))" ) > 0 ); } @Test public void testSingleExists() throws Exception { RuleModel m = new RuleModel(); m.name = "or"; CompositeFactPattern cp = new CompositeFactPattern( CompositeFactPattern.COMPOSITE_TYPE_EXISTS ); FactPattern p1 = new FactPattern( "Person" ); SingleFieldConstraint sf1 = new SingleFieldConstraint( "age" ); sf1.setOperator( "==" ); sf1.setValue( "42" ); p1.addConstraint( sf1 ); cp.addFactPattern( p1 ); m.addLhsItem( cp ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "exists (Person( age == 42 )) " ) > 0 ); } private String getCompositeFOL(String type) { RuleModel m = new RuleModel(); m.name = "or"; CompositeFactPattern cp = new CompositeFactPattern( type ); FactPattern p1 = new FactPattern( "Person" ); SingleFieldConstraint sf1 = new SingleFieldConstraint( "age" ); sf1.setOperator( "==" ); sf1.setValue( "42" ); p1.addConstraint( sf1 ); cp.addFactPattern( p1 ); FactPattern p2 = new FactPattern( "Person" ); SingleFieldConstraint sf2 = new SingleFieldConstraint( "age" ); sf2.setOperator( "==" ); sf2.setValue( "43" ); p2.addConstraint( sf2 ); cp.addFactPattern( p2 ); m.addLhsItem( cp ); String result = BRDRLPersistence.getInstance().marshal( m ); return result; } // public void testLoadEmpty() { // RuleModel m = BRXMLPersistence.getInstance().unmarshal( null ); // assertNotNull( m ); // // m = BRXMLPersistence.getInstance().unmarshal( "" ); // assertNotNull( m ); // } @Test public void testCompositeConstraints() { RuleModel m = new RuleModel(); m.name = "with composite"; FactPattern p1 = new FactPattern( "Person" ); p1.setBoundName( "p1" ); m.addLhsItem( p1 ); FactPattern p = new FactPattern( "Goober" ); m.addLhsItem( p ); CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = CompositeFieldConstraint.COMPOSITE_TYPE_OR; p.addConstraint( comp ); final SingleFieldConstraint X = new SingleFieldConstraint(); X.setFieldName( "goo" ); X.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); X.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); X.setValue( "foo" ); X.setOperator( "==" ); X.connectives = new ConnectiveConstraint[1]; X.connectives[0] = new ConnectiveConstraint(); X.connectives[0].setConstraintValueType( ConnectiveConstraint.TYPE_LITERAL ); X.connectives[0].setFieldType( SuggestionCompletionEngine.TYPE_STRING ); X.connectives[0].setOperator( "|| ==" ); X.connectives[0].setValue( "bar" ); comp.addConstraint( X ); final SingleFieldConstraint Y = new SingleFieldConstraint(); Y.setFieldName( "goo2" ); Y.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); Y.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); Y.setValue( "foo" ); Y.setOperator( "==" ); comp.addConstraint( Y ); CompositeFieldConstraint comp2 = new CompositeFieldConstraint(); comp2.compositeJunctionType = CompositeFieldConstraint.COMPOSITE_TYPE_AND; final SingleFieldConstraint Q1 = new SingleFieldConstraint(); Q1.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); Q1.setFieldName( "goo" ); Q1.setOperator( "==" ); Q1.setValue( "whee" ); Q1.setConstraintValueType( BaseSingleFieldConstraint.TYPE_LITERAL ); comp2.addConstraint( Q1 ); final SingleFieldConstraint Q2 = new SingleFieldConstraint(); Q2.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); Q2.setFieldName( "gabba" ); Q2.setOperator( "==" ); Q2.setValue( "whee" ); Q2.setConstraintValueType( BaseSingleFieldConstraint.TYPE_LITERAL ); comp2.addConstraint( Q2 ); // now nest it comp.addConstraint( comp2 ); final SingleFieldConstraint Z = new SingleFieldConstraint(); Z.setFieldName( "goo3" ); Z.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); Z.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); Z.setValue( "foo" ); Z.setOperator( "==" ); p.addConstraint( Z ); ActionInsertFact ass = new ActionInsertFact( "Whee" ); m.addRhsItem( ass ); String actual = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"with composite\" " + " \tdialect \"mvel\"\n when " + "p1 : Person( ) " + "Goober( goo == \"foo\" || == \"bar\" || goo2 == \"foo\" || ( goo == \"whee\" && gabba == \"whee\" ), goo3 == \"foo\" )" + " then " + "insert( new Whee() );" + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testFieldsDeclaredButNoConstraints() { RuleModel m = new RuleModel(); m.name = "boo"; FactPattern p = new FactPattern( "Person" ); // this isn't an effective constraint, so it should be ignored. p.addConstraint( new SingleFieldConstraint( "field1" ) ); m.addLhsItem( p ); String actual = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"boo\" \tdialect \"mvel\"\n when Person() then end"; assertEqualsIgnoreWhitespace( expected, actual ); SingleFieldConstraint con = (SingleFieldConstraint) p.constraintList.constraints[0]; con.setFieldBinding( "q" ); // now it should appear, as we are binding a var to it actual = BRDRLPersistence.getInstance().marshal( m ); expected = "rule \"boo\" dialect \"mvel\" when Person(q : field1) then end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testLiteralStrings() { RuleModel m = new RuleModel(); m.name = "test literal strings"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "goo" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); SingleFieldConstraint con2 = new SingleFieldConstraint(); con2.setFieldName( "field2" ); con2.setOperator( "==" ); con2.setValue( "variableHere" ); con2.setConstraintValueType( SingleFieldConstraint.TYPE_VARIABLE ); p.addConstraint( con2 ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal strings\"" + "\tdialect \"mvel\"\n when " + " Person(field1 == \"goo\", field2 == variableHere)" + " then " + "end", result ); } @Test public void testLHSExpressionString1() { RuleModel m = new RuleModel(); m.name = "test expressionsString1"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionText( "field1" ) ); con.setOperator( "==" ); con.setValue( "goo" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsString1\"" + "\tdialect \"mvel\"\n when " + " Person( field1 == \"goo\" )" + " then " + "end", result ); } @Test public void testLHSExpressionString2() { RuleModel m = new RuleModel(); m.name = "test expressionsString2"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "field1", "java.lang.String", SuggestionCompletionEngine.TYPE_STRING ) ); con.setOperator( "==" ); con.setValue( "Cheddar" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsString2\"" + "\tdialect \"mvel\"\n when " + " Person( field1 == \"Cheddar\" )" + " then " + "end", result ); } @Test public void testLHSExpressionJavaEnum() { RuleModel m = new RuleModel(); m.name = "test expressionsJavaEnum"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "field1", "CHEESE", SuggestionCompletionEngine.TYPE_COMPARABLE ) ); con.setOperator( "==" ); con.setValue( "CHEESE.Cheddar" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsJavaEnum\"" + "\tdialect \"mvel\"\n when " + " Person( field1 == CHEESE.Cheddar )" + " then " + "end", result ); } @Test public void testLHSExpressionNumber() { RuleModel m = new RuleModel(); m.name = "test expressionsNumber"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "field1", "java.lang.Integer", SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ) ); con.setOperator( "==" ); con.setValue( "55" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsNumber\"" + "\tdialect \"mvel\"\n when " + " Person( field1 == 55 )" + " then " + "end", result ); } @Test public void testLHSExpressionDate() { RuleModel m = new RuleModel(); m.name = "test expressionsDate"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "field1", "java.util.Date", SuggestionCompletionEngine.TYPE_DATE ) ); con.setOperator( "==" ); con.setValue( "27-Jun-2011" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsDate\"" + "\tdialect \"mvel\"\n when " + " Person( field1 == \"27-Jun-2011\" )" + " then " + "end", result ); } @Test public void testLHSExpressionBoolean() { RuleModel m = new RuleModel(); m.name = "test expressionsBoolean"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "field1", "java.lang.Boolean", SuggestionCompletionEngine.TYPE_BOOLEAN ) ); con.setOperator( "==" ); con.setValue( "true" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsBoolean\"" + "\tdialect \"mvel\"\n when " + " Person( field1 == true )" + " then " + "end", result ); } @Test public void testLHSExpressionNestedString() { RuleModel m = new RuleModel(); m.name = "test expressionsNestedString"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "favouriteCheese", "Cheese", SuggestionCompletionEngine.TYPE_OBJECT ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "name", "java.lang.String", SuggestionCompletionEngine.TYPE_STRING ) ); con.setOperator( "==" ); con.setValue( "Cheedar" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsNestedString\"" + "\tdialect \"mvel\"\n when " + " Person( favouriteCheese.name == \"Cheedar\" )" + " then " + "end", result ); } @Test public void testLHSExpressionNestedNumber() { RuleModel m = new RuleModel(); m.name = "test expressionsNestedNumber"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "favouriteCheese", "Cheese", SuggestionCompletionEngine.TYPE_OBJECT ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "age", "java.lang.Integer", SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ) ); con.setOperator( "==" ); con.setValue( "55" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsNestedNumber\"" + "\tdialect \"mvel\"\n when " + " Person( favouriteCheese.age == 55 )" + " then " + "end", result ); } @Test public void testLHSExpressionNestedDate() { RuleModel m = new RuleModel(); m.name = "test expressionsNestedDate"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "favouriteCheese", "Cheese", SuggestionCompletionEngine.TYPE_OBJECT ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "dateBrought", "java.util.Date", SuggestionCompletionEngine.TYPE_DATE ) ); con.setOperator( "==" ); con.setValue( "27-Jun-2011" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsNestedDate\"" + "\tdialect \"mvel\"\n when " + " Person( favouriteCheese.dateBrought == \"27-Jun-2011\" )" + " then " + "end", result ); } @Test public void testLHSExpressionNestedJavaEnum() { RuleModel m = new RuleModel(); m.name = "test expressionsNestedJavaEnum"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "favouriteCheese", "Cheese", SuggestionCompletionEngine.TYPE_OBJECT ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "genericName", "CHEESE", SuggestionCompletionEngine.TYPE_COMPARABLE ) ); con.setOperator( "==" ); con.setValue( "CHEESE.Cheddar" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsNestedJavaEnum\"" + "\tdialect \"mvel\"\n when " + " Person( favouriteCheese.genericName == CHEESE.Cheddar )" + " then " + "end", result ); } @Test public void testLHSExpressionNestedBoolean() { RuleModel m = new RuleModel(); m.name = "test expressionsNestedBoolean"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraintEBLeftSide con = new SingleFieldConstraintEBLeftSide(); con.getExpressionLeftSide().appendPart( new ExpressionUnboundFact( p ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "favouriteCheese", "Cheese", SuggestionCompletionEngine.TYPE_OBJECT ) ); con.getExpressionLeftSide().appendPart( new ExpressionField( "smelly", "java.lang.Boolean", SuggestionCompletionEngine.TYPE_BOOLEAN ) ); con.setOperator( "==" ); con.setValue( "true" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test expressionsNestedBoolean\"" + "\tdialect \"mvel\"\n when " + " Person( favouriteCheese.smelly == true )" + " then " + "end", result ); } @Test public void testLiteralNumerics() { RuleModel m = new RuleModel(); m.name = "test literal numerics"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "44" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); SingleFieldConstraint con2 = new SingleFieldConstraint(); con2.setFieldName( "field2" ); con2.setOperator( "==" ); con2.setValue( "variableHere" ); con2.setConstraintValueType( SingleFieldConstraint.TYPE_VARIABLE ); p.addConstraint( con2 ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal numerics\"" + "\tdialect \"mvel\"\n when " + " Person(field1 == 44, field2 == variableHere)" + " then " + "end", result ); } @Test public void testLiteralBigDecimalMvel() { RuleModel m = new RuleModel(); m.name = "test literal bigdecimal"; m.addAttribute( new RuleAttribute( "dialect", "mvel" ) ); FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_BIGDECIMAL ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "44" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionInsertFact ai = new ActionInsertFact( "Person" ); ai.addFieldValue( new ActionFieldValue( "field1", "55", SuggestionCompletionEngine.TYPE_NUMERIC_BIGDECIMAL ) ); m.addRhsItem( ai ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal bigdecimal\" \n" + "\tdialect \"mvel\"\n when \n" + " Person(field1 == 44B) \n" + " then \n" + "Person fact0 = new Person(); \n" + "fact0.setField1( 55B ); \n" + "insert( fact0 ); \n" + "end", result ); } @Test public void testLiteralBigIntegerMvel() { RuleModel m = new RuleModel(); m.name = "test literal biginteger"; m.addAttribute( new RuleAttribute( "dialect", "mvel" ) ); FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_BIGINTEGER ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "44" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionInsertFact ai = new ActionInsertFact( "Person" ); ai.addFieldValue( new ActionFieldValue( "field1", "55", SuggestionCompletionEngine.TYPE_NUMERIC_BIGINTEGER ) ); m.addRhsItem( ai ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal biginteger\" \n" + "\tdialect \"mvel\"\n when \n" + " Person(field1 == 44I ) \n" + " then \n" + "Person fact0 = new Person(); \n" + "fact0.setField1( 55I ); \n" + "insert( fact0 ); \n" + "end", result ); } @Test public void testLiteralBigDecimalJava() { RuleModel m = new RuleModel(); m.name = "test literal bigdecimal"; m.addAttribute( new RuleAttribute( "dialect", "java" ) ); FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_BIGDECIMAL ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "44" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionInsertFact ai = new ActionInsertFact( "Person" ); ai.addFieldValue( new ActionFieldValue( "field1", "55", SuggestionCompletionEngine.TYPE_NUMERIC_BIGDECIMAL ) ); m.addRhsItem( ai ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal bigdecimal\" \n" + "\tdialect \"java\"\n when \n" + " Person(field1 == 44B) \n" + " then \n" + "Person fact0 = new Person(); \n" + "fact0.setField1( new java.math.BigDecimal( \"55\" ) ); \n" + "insert( fact0 ); \n" + "end", result ); } @Test public void testLiteralBigIntegerJava() { RuleModel m = new RuleModel(); m.name = "test literal biginteger"; m.addAttribute( new RuleAttribute( "dialect", "java" ) ); FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_BIGINTEGER ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "44" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionInsertFact ai = new ActionInsertFact( "Person" ); ai.addFieldValue( new ActionFieldValue( "field1", "55", SuggestionCompletionEngine.TYPE_NUMERIC_BIGINTEGER ) ); m.addRhsItem( ai ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal biginteger\" \n" + "\tdialect \"java\"\n when \n" + " Person(field1 == 44I ) \n" + " then \n" + "Person fact0 = new Person(); \n" + "fact0.setField1( new java.math.BigInteger( \"55\" ) ); \n" + "insert( fact0 ); \n" + "end", result ); } @Test public void testLiteralBooleans() { RuleModel m = new RuleModel(); m.name = "test literal booleans"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_BOOLEAN ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "true" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); SingleFieldConstraint con2 = new SingleFieldConstraint(); con2.setFieldName( "field2" ); con2.setOperator( "==" ); con2.setValue( "variableHere" ); con2.setConstraintValueType( SingleFieldConstraint.TYPE_VARIABLE ); p.addConstraint( con2 ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal booleans\"" + "\tdialect \"mvel\"\n when " + " Person(field1 == true, field2 == variableHere)" + " then " + "end", result ); } @Test public void testLiteralDates() { RuleModel m = new RuleModel(); m.name = "test literal dates"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_DATE ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "31-Jan-2010" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); SingleFieldConstraint con2 = new SingleFieldConstraint(); con2.setFieldName( "field2" ); con2.setOperator( "==" ); con2.setValue( "variableHere" ); con2.setConstraintValueType( SingleFieldConstraint.TYPE_VARIABLE ); p.addConstraint( con2 ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal dates\"" + "\tdialect \"mvel\"\n when " + " Person(field1 == \"31-Jan-2010\", field2 == variableHere)" + " then " + "end", result ); } @Test public void testLiteralNoType() { RuleModel m = new RuleModel(); m.name = "test literal no type"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "bananna" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); SingleFieldConstraint con2 = new SingleFieldConstraint(); con2.setFieldName( "field2" ); con2.setOperator( "==" ); con2.setValue( "variableHere" ); con2.setConstraintValueType( SingleFieldConstraint.TYPE_VARIABLE ); p.addConstraint( con2 ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test literal no type\"" + "\tdialect \"mvel\"\n when " + " Person(field1 == \"bananna\", field2 == variableHere)" + " then " + "end", result ); } @Test public void testInOperatorString() { RuleModel m = new RuleModel(); m.name = "in"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con.setFieldName( "field1" ); con.setOperator( "in" ); con.setValue( "value1, value2" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"in\" \n" + "dialect \"mvel\" \n" + "when \n" + " Person(field1 in ( \"value1\", \"value2\" ) ) \n" + " then \n" + "end", result ); } @Test public void testInOperatorNumber() { RuleModel m = new RuleModel(); m.name = "in"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ); con.setFieldName( "field1" ); con.setOperator( "in" ); con.setValue( "55, 66" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"in\" \n" + "dialect \"mvel\" \n" + "when \n" + " Person(field1 in ( 55, 66 ) ) \n" + " then \n" + "end", result ); } @Test public void testNotInOperatorString() { RuleModel m = new RuleModel(); m.name = "not in"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con.setFieldName( "field1" ); con.setOperator( "not in" ); con.setValue( "value1, value2" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"not in\" \n" + "dialect \"mvel\" \n" + "when \n" + " Person(field1 not in ( \"value1\", \"value2\" ) ) \n" + " then \n" + "end", result ); } @Test public void testNotInOperatorNumber() { RuleModel m = new RuleModel(); m.name = "not in"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ); con.setFieldName( "field1" ); con.setOperator( "not in" ); con.setValue( "55, 66" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"not in\" \n" + "dialect \"mvel\" \n" + "when \n" + " Person(field1 not in ( 55, 66 ) ) \n" + " then \n" + "end", result ); } @Test public void testRHSDateInsertAction() { String oldValue = System.getProperty( "drools.dateformat" ); try { System.setProperty( "drools.dateformat", "dd-MMM-yyyy" ); RuleModel m = new RuleModel(); m.name = "RHS Date"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_DATE ); con.setFieldName( "dateOfBirth" ); con.setOperator( "==" ); con.setValue( "31-Jan-2000" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionInsertFact ai = new ActionInsertFact( "Birthday" ); ai.addFieldValue( new ActionFieldValue( "dob", "31-Jan-2000", SuggestionCompletionEngine.TYPE_DATE ) ); m.addRhsItem( ai ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(\"dd-MMM-yyyy\");" ) != -1 ); assertTrue( result.indexOf( "fact0.setDob( sdf.parse(\"31-Jan-2000\"" ) != -1 ); } finally { if ( oldValue == null ) { System.clearProperty( "drools.dateformat" ); } else { System.setProperty( "drools.dateformat", oldValue ); } } } @Test public void testRHSDateModifyAction() { String oldValue = System.getProperty( "drools.dateformat" ); try { System.setProperty( "drools.dateformat", "dd-MMM-yyyy" ); RuleModel m = new RuleModel(); m.name = "RHS Date"; FactPattern p = new FactPattern( "Person" ); p.setBoundName( "$p" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_DATE ); con.setFieldName( "dateOfBirth" ); con.setOperator( "==" ); con.setValue( "31-Jan-2000" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionUpdateField am = new ActionUpdateField( "$p" ); am.addFieldValue( new ActionFieldValue( "dob", "31-Jan-2000", SuggestionCompletionEngine.TYPE_DATE ) ); m.addRhsItem( am ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(\"dd-MMM-yyyy\");" ) != -1 ); assertTrue( result.indexOf( "$p.setDob( sdf.parse(\"31-Jan-2000\"" ) != -1 ); assertTrue( result.indexOf( "update( $p );" ) != -1 ); } finally { if ( oldValue == null ) { System.clearProperty( "drools.dateformat" ); } else { System.setProperty( "drools.dateformat", oldValue ); } } } @Test public void testRHSDateUpdateAction() { String oldValue = System.getProperty( "drools.dateformat" ); try { System.setProperty( "drools.dateformat", "dd-MMM-yyyy" ); RuleModel m = new RuleModel(); m.name = "RHS Date"; FactPattern p = new FactPattern( "Person" ); p.setBoundName( "$p" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_DATE ); con.setFieldName( "dateOfBirth" ); con.setOperator( "==" ); con.setValue( "31-Jan-2000" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionSetField au = new ActionSetField( "$p" ); au.addFieldValue( new ActionFieldValue( "dob", "31-Jan-2000", SuggestionCompletionEngine.TYPE_DATE ) ); m.addRhsItem( au ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(\"dd-MMM-yyyy\");" ) != -1 ); assertTrue( result.indexOf( "$p.setDob( sdf.parse(\"31-Jan-2000\"" ) != -1 ); assertTrue( result.indexOf( "update( $p );" ) == -1 ); } finally { if ( oldValue == null ) { System.clearProperty( "drools.dateformat" ); } else { System.setProperty( "drools.dateformat", oldValue ); } } } @Test public void testRHSExecuteWorkItem1() { RuleModel m = new RuleModel(); m.name = "WorkItem"; FactPattern p = new FactPattern( "Person" ); p.setBoundName( "$p" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con.setFieldName( "name" ); con.setOperator( "==" ); con.setValue( "Michael" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionExecuteWorkItem awi = new ActionExecuteWorkItem(); PortableWorkDefinition pwd = new PortableWorkDefinition(); pwd.setName( "WorkItem" ); awi.setWorkDefinition( pwd ); PortableBooleanParameterDefinition p1 = new PortableBooleanParameterDefinition(); p1.setName( "BooleanParameter" ); p1.setValue( Boolean.TRUE ); pwd.addParameter( p1 ); PortableFloatParameterDefinition p2 = new PortableFloatParameterDefinition(); p2.setName( "FloatParameter" ); p2.setValue( 123.456f ); pwd.addParameter( p2 ); PortableIntegerParameterDefinition p3 = new PortableIntegerParameterDefinition(); p3.setName( "IntegerParameter" ); p3.setValue( 123 ); pwd.addParameter( p3 ); PortableStringParameterDefinition p4 = new PortableStringParameterDefinition(); p4.setName( "StringParameter" ); p4.setValue( "hello" ); pwd.addParameter( p4 ); m.addRhsItem( awi ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "org.kie.process.instance.WorkItemManager wim = (org.kie.process.instance.WorkItemManager) drools.getWorkingMemory().getWorkItemManager();" ) != -1 ); assertTrue( result.indexOf( "org.kie.process.instance.impl.WorkItemImpl wiWorkItem = new org.kie.process.instance.impl.WorkItemImpl();" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"BooleanParameter\", Boolean.TRUE );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"FloatParameter\", 123.456f );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"IntegerParameter\", 123 );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"StringParameter\", \"hello\" );" ) != -1 ); assertTrue( result.indexOf( "wim.internalExecuteWorkItem( wiWorkItem );" ) != -1 ); } @Test public void testRHSExecuteWorkItem2() { RuleModel m = new RuleModel(); m.name = "WorkItem"; FactPattern p = new FactPattern( "Person" ); p.setBoundName( "$p" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con.setFieldName( "name" ); con.setOperator( "==" ); con.setValue( "Michael" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); p.addConstraint( con ); m.addLhsItem( p ); ActionExecuteWorkItem awi = new ActionExecuteWorkItem(); PortableWorkDefinition pwd = new PortableWorkDefinition(); pwd.setName( "WorkItem" ); awi.setWorkDefinition( pwd ); PortableBooleanParameterDefinition p1 = new PortableBooleanParameterDefinition(); p1.setName( "BooleanParameter" ); p1.setValue( Boolean.TRUE ); p1.setBinding( "" ); pwd.addParameter( p1 ); PortableFloatParameterDefinition p2 = new PortableFloatParameterDefinition(); p2.setName( "FloatParameter" ); p2.setValue( 123.456f ); p2.setBinding( "" ); pwd.addParameter( p2 ); PortableIntegerParameterDefinition p3 = new PortableIntegerParameterDefinition(); p3.setName( "IntegerParameter" ); p3.setValue( 123 ); p3.setBinding( "" ); pwd.addParameter( p3 ); PortableStringParameterDefinition p4 = new PortableStringParameterDefinition(); p4.setName( "StringParameter" ); p4.setValue( "hello" ); p4.setBinding( "" ); pwd.addParameter( p4 ); m.addRhsItem( awi ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "org.kie.process.instance.WorkItemManager wim = (org.kie.process.instance.WorkItemManager) drools.getWorkingMemory().getWorkItemManager();" ) != -1 ); assertTrue( result.indexOf( "org.kie.process.instance.impl.WorkItemImpl wiWorkItem = new org.kie.process.instance.impl.WorkItemImpl();" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"BooleanParameter\", Boolean.TRUE );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"FloatParameter\", 123.456f );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"IntegerParameter\", 123 );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"StringParameter\", \"hello\" );" ) != -1 ); assertTrue( result.indexOf( "wim.internalExecuteWorkItem( wiWorkItem );" ) != -1 ); } @Test //Test that WorkItem Parameters whose values are bound are created and //populated in the RHS if the Pattern is bound to the same variable public void testRHSExecuteWorkItemWithBindings() { RuleModel m = new RuleModel(); m.name = "WorkItem"; FactPattern fp1 = new FactPattern( "Person" ); fp1.setBoundName( "$p" ); SingleFieldConstraint con1 = new SingleFieldConstraint(); con1.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con1.setFieldName( "name" ); con1.setOperator( "==" ); con1.setValue( "Michael" ); con1.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp1.addConstraint( con1 ); m.addLhsItem( fp1 ); FactPattern fp2 = new FactPattern( "Boolean" ); fp2.setBoundName( "$b" ); SingleFieldConstraint con2 = new SingleFieldConstraint(); con2.setFieldType( SuggestionCompletionEngine.TYPE_BOOLEAN ); con2.setFieldName( "this" ); con2.setOperator( "==" ); con2.setValue( "true" ); con2.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp2.addConstraint( con2 ); m.addLhsItem( fp2 ); FactPattern fp3 = new FactPattern( "Float" ); fp3.setBoundName( "$f" ); SingleFieldConstraint con3 = new SingleFieldConstraint(); con3.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_FLOAT ); con3.setFieldName( "this" ); con3.setOperator( "==" ); con3.setValue( "123.456f" ); con3.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp3.addConstraint( con3 ); m.addLhsItem( fp3 ); FactPattern fp4 = new FactPattern( "Integer" ); fp4.setBoundName( "$i" ); SingleFieldConstraint con4 = new SingleFieldConstraint(); con4.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ); con4.setFieldName( "this" ); con4.setOperator( "==" ); con4.setValue( "123" ); con4.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp4.addConstraint( con4 ); m.addLhsItem( fp4 ); FactPattern fp5 = new FactPattern( "String" ); fp5.setBoundName( "$s" ); SingleFieldConstraint con5 = new SingleFieldConstraint(); con5.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con5.setFieldName( "this" ); con5.setOperator( "==" ); con5.setValue( "hello" ); con5.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp5.addConstraint( con5 ); m.addLhsItem( fp5 ); ActionExecuteWorkItem awi = new ActionExecuteWorkItem(); PortableWorkDefinition pwd = new PortableWorkDefinition(); pwd.setName( "WorkItem" ); awi.setWorkDefinition( pwd ); PortableBooleanParameterDefinition p1 = new PortableBooleanParameterDefinition(); p1.setName( "BooleanParameter" ); p1.setBinding( "$b" ); p1.setValue( Boolean.TRUE ); pwd.addParameter( p1 ); PortableFloatParameterDefinition p2 = new PortableFloatParameterDefinition(); p2.setName( "FloatParameter" ); p2.setBinding( "$f" ); p2.setValue( 123.456f ); pwd.addParameter( p2 ); PortableIntegerParameterDefinition p3 = new PortableIntegerParameterDefinition(); p3.setName( "IntegerParameter" ); p3.setBinding( "$i" ); p3.setValue( 123 ); pwd.addParameter( p3 ); PortableStringParameterDefinition p4 = new PortableStringParameterDefinition(); p4.setName( "StringParameter" ); p4.setBinding( "$s" ); p4.setValue( "hello" ); pwd.addParameter( p4 ); m.addRhsItem( awi ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "org.kie.process.instance.WorkItemManager wim = (org.kie.process.instance.WorkItemManager) drools.getWorkingMemory().getWorkItemManager();" ) != -1 ); assertTrue( result.indexOf( "org.kie.process.instance.impl.WorkItemImpl wiWorkItem = new org.kie.process.instance.impl.WorkItemImpl();" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"BooleanParameter\", $b );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"FloatParameter\", $f );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"IntegerParameter\", $i );" ) != -1 ); assertTrue( result.indexOf( "wiWorkItem.getParameters().put( \"StringParameter\", $s );" ) != -1 ); assertTrue( result.indexOf( "wim.internalExecuteWorkItem( wiWorkItem );" ) != -1 ); } @Test //Test that WorkItem Parameters whose values are bound are *NOT* created or //populated in the RHS if the Pattern is *NOT* bound to the same variable public void testRHSExecuteWorkItemWithMissingBindings1() { RuleModel m = new RuleModel(); m.name = "WorkItem"; FactPattern fp1 = new FactPattern( "Person" ); fp1.setBoundName( "$p" ); SingleFieldConstraint con1 = new SingleFieldConstraint(); con1.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con1.setFieldName( "name" ); con1.setOperator( "==" ); con1.setValue( "Michael" ); con1.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp1.addConstraint( con1 ); m.addLhsItem( fp1 ); FactPattern fp2 = new FactPattern( "Boolean" ); fp2.setBoundName( "$b1" ); SingleFieldConstraint con2 = new SingleFieldConstraint(); con2.setFieldType( SuggestionCompletionEngine.TYPE_BOOLEAN ); con2.setFieldName( "this" ); con2.setOperator( "==" ); con2.setValue( "true" ); con2.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp2.addConstraint( con2 ); m.addLhsItem( fp2 ); FactPattern fp3 = new FactPattern( "Float" ); fp3.setBoundName( "$f1" ); SingleFieldConstraint con3 = new SingleFieldConstraint(); con3.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_FLOAT ); con3.setFieldName( "this" ); con3.setOperator( "==" ); con3.setValue( "123.456f" ); con3.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp3.addConstraint( con3 ); m.addLhsItem( fp3 ); FactPattern fp4 = new FactPattern( "Integer" ); fp4.setBoundName( "$i1" ); SingleFieldConstraint con4 = new SingleFieldConstraint(); con4.setFieldType( SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ); con4.setFieldName( "this" ); con4.setOperator( "==" ); con4.setValue( "123" ); con4.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp4.addConstraint( con4 ); m.addLhsItem( fp4 ); FactPattern fp5 = new FactPattern( "String" ); fp5.setBoundName( "$s1" ); SingleFieldConstraint con5 = new SingleFieldConstraint(); con5.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con5.setFieldName( "this" ); con5.setOperator( "==" ); con5.setValue( "hello" ); con5.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp5.addConstraint( con5 ); m.addLhsItem( fp5 ); ActionExecuteWorkItem awi = new ActionExecuteWorkItem(); PortableWorkDefinition pwd = new PortableWorkDefinition(); pwd.setName( "WorkItem" ); awi.setWorkDefinition( pwd ); PortableBooleanParameterDefinition p1 = new PortableBooleanParameterDefinition(); p1.setName( "BooleanParameter" ); p1.setBinding( "$b" ); p1.setValue( Boolean.TRUE ); pwd.addParameter( p1 ); PortableFloatParameterDefinition p2 = new PortableFloatParameterDefinition(); p2.setName( "FloatParameter" ); p2.setBinding( "$f" ); p2.setValue( 123.456f ); pwd.addParameter( p2 ); PortableIntegerParameterDefinition p3 = new PortableIntegerParameterDefinition(); p3.setName( "IntegerParameter" ); p3.setBinding( "$i" ); p3.setValue( 123 ); pwd.addParameter( p3 ); PortableStringParameterDefinition p4 = new PortableStringParameterDefinition(); p4.setName( "StringParameter" ); p4.setBinding( "$s" ); p4.setValue( "hello" ); pwd.addParameter( p4 ); m.addRhsItem( awi ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "org.kie.process.instance.WorkItemManager wim = (org.kie.process.instance.WorkItemManager) drools.getWorkingMemory().getWorkItemManager();" ) != -1 ); assertTrue( result.indexOf( "org.kie.process.instance.impl.WorkItemImpl wiWorkItem = new org.kie.process.instance.impl.WorkItemImpl();" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"BooleanParameter\", $b1 );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"FloatParameter\", $f1 );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"IntegerParameter\", $i1 );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"StringParameter\", $s1 );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"BooleanParameter\", $b2 );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"FloatParameter\", $f2 );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"IntegerParameter\", $i2 );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"StringParameter\", $s2 );" ) != -1 ); assertTrue( result.indexOf( "wim.internalExecuteWorkItem( wiWorkItem );" ) != -1 ); } @Test //Test that WorkItem Parameters whose values are bound are *NOT* created or //populated in the RHS if the Pattern is *NOT* bound to the same variable public void testRHSExecuteWorkItemWithMissingBindings2() { RuleModel m = new RuleModel(); m.name = "WorkItem"; FactPattern fp1 = new FactPattern( "Person" ); fp1.setBoundName( "$p" ); SingleFieldConstraint con1 = new SingleFieldConstraint(); con1.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con1.setFieldName( "name" ); con1.setOperator( "==" ); con1.setValue( "Michael" ); con1.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); fp1.addConstraint( con1 ); m.addLhsItem( fp1 ); ActionExecuteWorkItem awi = new ActionExecuteWorkItem(); PortableWorkDefinition pwd = new PortableWorkDefinition(); pwd.setName( "WorkItem" ); awi.setWorkDefinition( pwd ); PortableBooleanParameterDefinition p1 = new PortableBooleanParameterDefinition(); p1.setName( "BooleanParameter" ); p1.setBinding( "$b2" ); p1.setValue( Boolean.TRUE ); pwd.addParameter( p1 ); PortableFloatParameterDefinition p2 = new PortableFloatParameterDefinition(); p2.setName( "FloatParameter" ); p2.setBinding( "$f2" ); p2.setValue( 123.456f ); pwd.addParameter( p2 ); PortableIntegerParameterDefinition p3 = new PortableIntegerParameterDefinition(); p3.setName( "IntegerParameter" ); p3.setBinding( "$i2" ); p3.setValue( 123 ); pwd.addParameter( p3 ); PortableStringParameterDefinition p4 = new PortableStringParameterDefinition(); p4.setName( "StringParameter" ); p4.setBinding( "$s2" ); p4.setValue( "hello" ); pwd.addParameter( p4 ); m.addRhsItem( awi ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "org.kie.process.instance.WorkItemManager wim = (org.kie.process.instance.WorkItemManager) drools.getWorkingMemory().getWorkItemManager();" ) != -1 ); assertTrue( result.indexOf( "org.kie.process.instance.impl.WorkItemImpl wiWorkItem = new org.kie.process.instance.impl.WorkItemImpl();" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"BooleanParameter\", $b );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"FloatParameter\", $f );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"IntegerParameter\", $i );" ) != -1 ); assertFalse( result.indexOf( "wiWorkItem.getParameters().put( \"StringParameter\", $s );" ) != -1 ); assertTrue( result.indexOf( "wim.internalExecuteWorkItem( wiWorkItem );" ) != -1 ); } @Test //Test that WorkItem Parameters can be used to set fields on existing Facts public void testRHSActionWorkItemSetFields() { RuleModel m = new RuleModel(); m.name = "WorkItem"; FactPattern fp1 = new FactPattern( "Results" ); fp1.setBoundName( "$r" ); m.addLhsItem( fp1 ); ActionExecuteWorkItem awi = new ActionExecuteWorkItem(); PortableWorkDefinition pwd = new PortableWorkDefinition(); pwd.setName( "WorkItem" ); awi.setWorkDefinition( pwd ); PortableBooleanParameterDefinition p1 = new PortableBooleanParameterDefinition(); p1.setName( "BooleanResult" ); pwd.addResult( p1 ); PortableFloatParameterDefinition p2 = new PortableFloatParameterDefinition(); p2.setName( "FloatResult" ); pwd.addResult( p2 ); PortableIntegerParameterDefinition p3 = new PortableIntegerParameterDefinition(); p3.setName( "IntegerResult" ); pwd.addResult( p3 ); PortableStringParameterDefinition p4 = new PortableStringParameterDefinition(); p4.setName( "StringResult" ); pwd.addResult( p4 ); m.addRhsItem( awi ); ActionSetField asf = new ActionSetField(); asf.variable = "$r"; ActionWorkItemFieldValue fv1 = new ActionWorkItemFieldValue( "ResultsBooleanResult", SuggestionCompletionEngine.TYPE_BOOLEAN, "WorkItem", "BooleanResult", Boolean.class.getName() ); asf.addFieldValue( fv1 ); ActionWorkItemFieldValue fv2 = new ActionWorkItemFieldValue( "ResultsFloatResult", SuggestionCompletionEngine.TYPE_NUMERIC_FLOAT, "WorkItem", "FloatResult", Float.class.getName() ); asf.addFieldValue( fv2 ); ActionWorkItemFieldValue fv3 = new ActionWorkItemFieldValue( "ResultsIntegerResult", SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER, "WorkItem", "IntegerResult", Integer.class.getName() ); asf.addFieldValue( fv3 ); ActionWorkItemFieldValue fv4 = new ActionWorkItemFieldValue( "ResultsStringResult", SuggestionCompletionEngine.TYPE_STRING, "WorkItem", "StringResult", String.class.getName() ); asf.addFieldValue( fv4 ); m.addRhsItem( asf ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "org.kie.process.instance.WorkItemManager wim = (org.kie.process.instance.WorkItemManager) drools.getWorkingMemory().getWorkItemManager();" ) != -1 ); assertTrue( result.indexOf( "org.kie.process.instance.impl.WorkItemImpl wiWorkItem = new org.kie.process.instance.impl.WorkItemImpl();" ) != -1 ); assertTrue( result.indexOf( "$r.setResultsBooleanResult( (java.lang.Boolean) wiWorkItem.getResult( \"BooleanResult\" ) );" ) != -1 ); assertTrue( result.indexOf( "$r.setResultsFloatResult( (java.lang.Float) wiWorkItem.getResult( \"FloatResult\" ) );" ) != -1 ); assertTrue( result.indexOf( "$r.setResultsIntegerResult( (java.lang.Integer) wiWorkItem.getResult( \"IntegerResult\" ) );" ) != -1 ); assertTrue( result.indexOf( "$r.setResultsStringResult( (java.lang.String) wiWorkItem.getResult( \"StringResult\" ) );" ) != -1 ); assertTrue( result.indexOf( "wim.internalExecuteWorkItem( wiWorkItem );" ) != -1 ); } @Test //Test that WorkItem Parameters can be used to set fields on new Fact public void testRHSActionWorkItemInsertFacts() { RuleModel m = new RuleModel(); m.name = "WorkItem"; ActionExecuteWorkItem awi = new ActionExecuteWorkItem(); PortableWorkDefinition pwd = new PortableWorkDefinition(); pwd.setName( "WorkItem" ); awi.setWorkDefinition( pwd ); PortableBooleanParameterDefinition p1 = new PortableBooleanParameterDefinition(); p1.setName( "BooleanResult" ); pwd.addResult( p1 ); PortableFloatParameterDefinition p2 = new PortableFloatParameterDefinition(); p2.setName( "FloatResult" ); pwd.addResult( p2 ); PortableIntegerParameterDefinition p3 = new PortableIntegerParameterDefinition(); p3.setName( "IntegerResult" ); pwd.addResult( p3 ); PortableStringParameterDefinition p4 = new PortableStringParameterDefinition(); p4.setName( "StringResult" ); pwd.addResult( p4 ); m.addRhsItem( awi ); ActionInsertFact aif = new ActionInsertFact(); aif.setBoundName( "$r" ); aif.factType = "Results"; ActionWorkItemFieldValue fv1 = new ActionWorkItemFieldValue( "ResultsBooleanResult", SuggestionCompletionEngine.TYPE_BOOLEAN, "WorkItem", "BooleanResult", Boolean.class.getName() ); aif.addFieldValue( fv1 ); ActionWorkItemFieldValue fv2 = new ActionWorkItemFieldValue( "ResultsFloatResult", SuggestionCompletionEngine.TYPE_NUMERIC_FLOAT, "WorkItem", "FloatResult", Float.class.getName() ); aif.addFieldValue( fv2 ); ActionWorkItemFieldValue fv3 = new ActionWorkItemFieldValue( "ResultsIntegerResult", SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER, "WorkItem", "IntegerResult", Integer.class.getName() ); aif.addFieldValue( fv3 ); ActionWorkItemFieldValue fv4 = new ActionWorkItemFieldValue( "ResultsStringResult", SuggestionCompletionEngine.TYPE_STRING, "WorkItem", "StringResult", String.class.getName() ); aif.addFieldValue( fv4 ); m.addRhsItem( aif ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "org.kie.process.instance.WorkItemManager wim = (org.kie.process.instance.WorkItemManager) drools.getWorkingMemory().getWorkItemManager();" ) != -1 ); assertTrue( result.indexOf( "org.kie.process.instance.impl.WorkItemImpl wiWorkItem = new org.kie.process.instance.impl.WorkItemImpl();" ) != -1 ); assertTrue( result.indexOf( "Results $r = new Results();" ) != -1 ); assertTrue( result.indexOf( "$r.setResultsBooleanResult( (java.lang.Boolean) wiWorkItem.getResult( \"BooleanResult\" ) );" ) != -1 ); assertTrue( result.indexOf( "$r.setResultsFloatResult( (java.lang.Float) wiWorkItem.getResult( \"FloatResult\" ) );" ) != -1 ); assertTrue( result.indexOf( "$r.setResultsIntegerResult( (java.lang.Integer) wiWorkItem.getResult( \"IntegerResult\" ) );" ) != -1 ); assertTrue( result.indexOf( "$r.setResultsStringResult( (java.lang.String) wiWorkItem.getResult( \"StringResult\" ) );" ) != -1 ); assertTrue( result.indexOf( "insert( $r );" ) != -1 ); } @Test public void testSubConstraints() { RuleModel m = new RuleModel(); m.name = "test sub constraints"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldName( "field1" ); p.addConstraint( con ); SingleFieldConstraint con2 = new SingleFieldConstraint(); con2.setFieldName( "field2" ); con2.setOperator( "==" ); con2.setValue( "variableHere" ); con2.setConstraintValueType( SingleFieldConstraint.TYPE_VARIABLE ); con2.setParent( con ); p.addConstraint( con2 ); m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); assertEqualsIgnoreWhitespace( "rule \"test sub constraints\"" + "\tdialect \"mvel\"\n when " + " Person(field1.field2 == variableHere)" + " then " + "end", result ); } private void assertEqualsIgnoreWhitespace(final String expected, final String actual) { final String cleanExpected = expected.replaceAll( "\\s+", "" ); final String cleanActual = actual.replaceAll( "\\s+", "" ); assertEquals( cleanExpected, cleanActual ); } @Test public void testReturnValueConstraint() { RuleModel m = new RuleModel(); m.name = "yeah"; FactPattern p = new FactPattern( "Goober" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setConstraintValueType( SingleFieldConstraint.TYPE_RET_VALUE ); con.setValue( "someFunc(x)" ); con.setOperator( "==" ); con.setFieldName( "goo" ); p.addConstraint( con ); m.addLhsItem( p ); String actual = BRDRLPersistence.getInstance().marshal( m ); // System.err.println(actual); String expected = "rule \"yeah\" " + "\tdialect \"mvel\"\n when " + "Goober( goo == ( someFunc(x) ) )" + " then " + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testPredicateConstraint() { RuleModel m = new RuleModel(); m.name = "yeah"; FactPattern p = new FactPattern( "Goober" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setConstraintValueType( SingleFieldConstraint.TYPE_PREDICATE ); con.setValue( "field soundslike 'poo'" ); p.addConstraint( con ); m.addLhsItem( p ); String actual = BRDRLPersistence.getInstance().marshal( m ); // System.err.println(actual); String expected = "rule \"yeah\" " + "\tdialect \"mvel\"\n when " + "Goober( eval( field soundslike 'poo' ) )" + " then " + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testConnective() { RuleModel m = new RuleModel(); m.name = "test literal strings"; FactPattern p = new FactPattern( "Person" ); SingleFieldConstraint con = new SingleFieldConstraint(); con.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); con.setFieldName( "field1" ); con.setOperator( "==" ); con.setValue( "goo" ); con.setConstraintValueType( SingleFieldConstraint.TYPE_VARIABLE ); p.addConstraint( con ); ConnectiveConstraint connective = new ConnectiveConstraint(); connective.setConstraintValueType( BaseSingleFieldConstraint.TYPE_LITERAL ); connective.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); connective.setOperator( "|| ==" ); connective.setValue( "blah" ); con.connectives = new ConnectiveConstraint[1]; con.connectives[0] = connective; m.addLhsItem( p ); String result = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"test literal strings\" " + "\tdialect \"mvel\"\n when " + "Person( field1 == goo || == \"blah\" )" + " then " + "end"; assertEqualsIgnoreWhitespace( expected, result ); } @Test public void testInvalidComposite() throws Exception { RuleModel m = new RuleModel(); CompositeFactPattern com = new CompositeFactPattern( "not" ); m.addLhsItem( com ); String s = BRDRLPersistence.getInstance().marshal( m ); assertNotNull( s ); m.addLhsItem( new CompositeFactPattern( "or" ) ); m.addLhsItem( new CompositeFactPattern( "exists" ) ); s = BRDRLPersistence.getInstance().marshal( m ); assertNotNull( s ); } @Test public void testAssertWithDSL() throws Exception { RuleModel m = new RuleModel(); DSLSentence sen = new DSLSentence(); sen.setDefinition( "I CAN HAS DSL" ); m.addRhsItem( sen ); ActionInsertFact ins = new ActionInsertFact( "Shizzle" ); ActionFieldValue val = new ActionFieldValue( "goo", "42", "Numeric" ); ins.fieldValues = new ActionFieldValue[1]; ins.fieldValues[0] = val; m.addRhsItem( ins ); ActionInsertLogicalFact insL = new ActionInsertLogicalFact( "Shizzle" ); ActionFieldValue valL = new ActionFieldValue( "goo", "42", "Numeric" ); insL.fieldValues = new ActionFieldValue[1]; insL.fieldValues[0] = valL; m.addRhsItem( insL ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( ">insert" ) > -1 ); assertTrue( result.indexOf( ">insertLogical" ) > -1 ); } @Test public void testDefaultMVEL() { RuleModel m = new RuleModel(); String s = BRDRLPersistence.getInstance().marshal( m ); assertTrue( s.indexOf( "mvel" ) > -1 ); m.addAttribute( new RuleAttribute( "dialect", "goober" ) ); s = BRDRLPersistence.getInstance().marshal( m ); assertFalse( s.indexOf( "mvel" ) > -1 ); assertTrue( s.indexOf( "goober" ) > -1 ); } @Test public void testLockOnActive() { RuleModel m = new RuleModel(); m.addAttribute( new RuleAttribute( "lock-on-active", "true" ) ); m.addAttribute( new RuleAttribute( "auto-focus", "true" ) ); m.addAttribute( new RuleAttribute( "duration", "42" ) ); String s = BRDRLPersistence.getInstance().marshal( m ); assertTrue( s.indexOf( "lock-on-active true" ) > -1 ); assertTrue( s.indexOf( "auto-focus true" ) > -1 ); assertTrue( s.indexOf( "duration 42" ) > -1 ); } @Test public void testAddGlobal() { String expected = "rule \"my rule\"\n\tno-loop true\n\tdialect \"mvel\"\n\twhen\n\t\tPerson( )\n" + "\t\tAccident( )\n\tthen\n\t\tinsert( new Report() );\n\t\tresults.add(f);\nend\n"; final RuleModel m = new RuleModel(); m.addLhsItem( new FactPattern( "Person" ) ); m.addLhsItem( new FactPattern( "Accident" ) ); m.addAttribute( new RuleAttribute( "no-loop", "true" ) ); m.addRhsItem( new ActionInsertFact( "Report" ) ); ActionGlobalCollectionAdd add = new ActionGlobalCollectionAdd(); add.globalName = "results"; add.factName = "f"; m.addRhsItem( add ); m.name = "my rule"; final String drl = brlPersistence.marshal( m ); assertEquals( expected, drl ); } @Test public void testCompositeOrConstraints() { RuleModel m = new RuleModel(); m.name = "or composite"; FactPattern p = new FactPattern( "Goober" ); m.addLhsItem( p ); CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = CompositeFieldConstraint.COMPOSITE_TYPE_OR; p.addConstraint( comp ); final SingleFieldConstraint sfc1 = new SingleFieldConstraint(); sfc1.setFactType( "Goober" ); sfc1.setFieldName( "gooField" ); sfc1.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc1.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc1.setValue( "gooValue" ); sfc1.setOperator( "==" ); comp.addConstraint( sfc1 ); final SingleFieldConstraint sfc2 = new SingleFieldConstraint(); sfc2.setFactType( "Goober" ); sfc2.setFieldName( "fooField" ); sfc2.setFieldType( SuggestionCompletionEngine.TYPE_OBJECT ); sfc2.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc2.setOperator( "!= null" ); comp.addConstraint( sfc2 ); final SingleFieldConstraint sfc3 = new SingleFieldConstraint(); sfc3.setFactType( "Bar" ); sfc3.setFieldName( "barField" ); sfc3.setParent( sfc2 ); sfc3.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc3.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc3.setValue( "barValue" ); sfc3.setOperator( "==" ); comp.addConstraint( sfc3 ); ActionInsertFact ass = new ActionInsertFact( "Whee" ); m.addRhsItem( ass ); String actual = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"or composite\"" + "dialect \"mvel\"\n" + "when\n" + "Goober( gooField == \"gooValue\" || fooField != null || fooField.barField == \"barValue\" )\n" + "then\n" + "insert( new Whee() );\n" + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testCompositeOrConstraintsComplex() { RuleModel m = new RuleModel(); m.name = "or composite complex"; FactPattern p = new FactPattern( "Goober" ); m.addLhsItem( p ); CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = CompositeFieldConstraint.COMPOSITE_TYPE_OR; p.addConstraint( comp ); final SingleFieldConstraint sfc1 = new SingleFieldConstraint(); sfc1.setFactType( "Goober" ); sfc1.setFieldName( "gooField" ); sfc1.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc1.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc1.setValue( "gooValue" ); sfc1.setOperator( "==" ); comp.addConstraint( sfc1 ); final SingleFieldConstraint sfc2 = new SingleFieldConstraint(); sfc2.setFactType( "Goober" ); sfc2.setFieldName( "fooField" ); sfc2.setFieldType( SuggestionCompletionEngine.TYPE_OBJECT ); sfc2.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc2.setOperator( "!= null" ); comp.addConstraint( sfc2 ); final SingleFieldConstraint sfc3 = new SingleFieldConstraint(); sfc3.setFactType( "Bar" ); sfc3.setFieldName( "barField" ); sfc3.setParent( sfc2 ); sfc3.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc3.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc3.setValue( "barValue" ); sfc3.setOperator( "==" ); comp.addConstraint( sfc3 ); final SingleFieldConstraint sfc4 = new SingleFieldConstraint(); sfc4.setFactType( "Goober" ); sfc4.setFieldName( "zooField" ); sfc4.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc4.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc4.setValue( "zooValue" ); sfc4.setOperator( "==" ); p.addConstraint( sfc4 ); ActionInsertFact ass = new ActionInsertFact( "Whee" ); m.addRhsItem( ass ); String actual = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"or composite complex\"" + "dialect \"mvel\"\n" + "when\n" + "Goober( gooField == \"gooValue\" || fooField != null || fooField.barField == \"barValue\", zooField == \"zooValue\" )\n" + "then\n" + "insert( new Whee() );\n" + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testCompositeAndConstraints() { RuleModel m = new RuleModel(); m.name = "and composite"; FactPattern p = new FactPattern( "Goober" ); m.addLhsItem( p ); CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = CompositeFieldConstraint.COMPOSITE_TYPE_AND; p.addConstraint( comp ); final SingleFieldConstraint sfc1 = new SingleFieldConstraint(); sfc1.setFactType( "Goober" ); sfc1.setFieldName( "gooField" ); sfc1.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc1.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc1.setValue( "gooValue" ); sfc1.setOperator( "==" ); comp.addConstraint( sfc1 ); final SingleFieldConstraint sfc2 = new SingleFieldConstraint(); sfc2.setFactType( "Goober" ); sfc2.setFieldName( "fooField" ); sfc2.setFieldType( SuggestionCompletionEngine.TYPE_OBJECT ); sfc2.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc2.setOperator( "!= null" ); comp.addConstraint( sfc2 ); final SingleFieldConstraint sfc3 = new SingleFieldConstraint(); sfc3.setFactType( "Bar" ); sfc3.setFieldName( "barField" ); sfc3.setParent( sfc2 ); sfc3.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc3.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc3.setValue( "barValue" ); sfc3.setOperator( "==" ); comp.addConstraint( sfc3 ); ActionInsertFact ass = new ActionInsertFact( "Whee" ); m.addRhsItem( ass ); String actual = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"and composite\"" + "dialect \"mvel\"\n" + "when\n" + "Goober( gooField == \"gooValue\" && fooField != null && fooField.barField == \"barValue\" )\n" + "then\n" + "insert( new Whee() );\n" + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testCompositeAndConstraintsComplex() { RuleModel m = new RuleModel(); m.name = "and composite complex"; FactPattern p = new FactPattern( "Goober" ); m.addLhsItem( p ); CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = CompositeFieldConstraint.COMPOSITE_TYPE_AND; p.addConstraint( comp ); final SingleFieldConstraint sfc1 = new SingleFieldConstraint(); sfc1.setFactType( "Goober" ); sfc1.setFieldName( "gooField" ); sfc1.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc1.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc1.setValue( "gooValue" ); sfc1.setOperator( "==" ); comp.addConstraint( sfc1 ); final SingleFieldConstraint sfc2 = new SingleFieldConstraint(); sfc2.setFactType( "Goober" ); sfc2.setFieldName( "fooField" ); sfc2.setFieldType( SuggestionCompletionEngine.TYPE_OBJECT ); sfc2.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc2.setOperator( "!= null" ); comp.addConstraint( sfc2 ); final SingleFieldConstraint sfc3 = new SingleFieldConstraint(); sfc1.setFactType( "Bar" ); sfc3.setFieldName( "barField" ); sfc3.setParent( sfc2 ); sfc3.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc3.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc3.setValue( "barValue" ); sfc3.setOperator( "==" ); comp.addConstraint( sfc3 ); final SingleFieldConstraint sfc4 = new SingleFieldConstraint(); sfc4.setFactType( "Goober" ); sfc4.setFieldName( "zooField" ); sfc4.setFieldType( SuggestionCompletionEngine.TYPE_STRING ); sfc4.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL ); sfc4.setValue( "zooValue" ); sfc4.setOperator( "==" ); p.addConstraint( sfc4 ); ActionInsertFact ass = new ActionInsertFact( "Whee" ); m.addRhsItem( ass ); String actual = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"and composite complex\"" + "dialect \"mvel\"\n" + "when\n" + "Goober( gooField == \"gooValue\" && fooField != null && fooField.barField == \"barValue\", zooField == \"zooValue\" )\n" + "then\n" + "insert( new Whee() );\n" + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testRHSSetMethodCallsMethodMVEL() { String oldValue = System.getProperty( "drools.dateformat" ); try { System.setProperty( "drools.dateformat", "dd-MMM-yyyy" ); RuleModel m = new RuleModel(); m.name = "RHS SetMethodCallsMethod"; m.addAttribute( new RuleAttribute( "dialect", "mvel" ) ); FactPattern p = new FactPattern( "Person" ); p.setBoundName( "$p" ); m.addLhsItem( p ); ActionCallMethod acm = new ActionCallMethod(); acm.methodName = "method"; acm.variable = "$p"; acm.addFieldValue( new ActionFieldFunction( "f1", "String", SuggestionCompletionEngine.TYPE_STRING ) ); acm.addFieldValue( new ActionFieldFunction( "f2", "true", SuggestionCompletionEngine.TYPE_BOOLEAN ) ); acm.addFieldValue( new ActionFieldFunction( "f3", "31-Jan-2012", SuggestionCompletionEngine.TYPE_DATE ) ); acm.addFieldValue( new ActionFieldFunction( "f4", "100", SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ) ); acm.addFieldValue( new ActionFieldFunction( "f5", "100", SuggestionCompletionEngine.TYPE_NUMERIC_BIGDECIMAL ) ); m.addRhsItem( acm ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(\"dd-MMM-yyyy\");" ) != -1 ); assertTrue( result.indexOf( "$p.method( \"String\", true, sdf.parse(\"31-Jan-2012\"), 100, 100B );" ) != -1 ); } finally { if ( oldValue == null ) { System.clearProperty( "drools.dateformat" ); } else { System.setProperty( "drools.dateformat", oldValue ); } } } @Test public void testRHSSetMethodCallsMethodJava() { String oldValue = System.getProperty( "drools.dateformat" ); try { System.setProperty( "drools.dateformat", "dd-MMM-yyyy" ); RuleModel m = new RuleModel(); m.name = "RHS SetMethodCallsMethod"; m.addAttribute( new RuleAttribute( "dialect", "java" ) ); FactPattern p = new FactPattern( "Person" ); p.setBoundName( "$p" ); m.addLhsItem( p ); ActionCallMethod acm = new ActionCallMethod(); acm.methodName = "method"; acm.variable = "$p"; acm.addFieldValue( new ActionFieldFunction( "f1", "String", SuggestionCompletionEngine.TYPE_STRING ) ); acm.addFieldValue( new ActionFieldFunction( "f2", "true", SuggestionCompletionEngine.TYPE_BOOLEAN ) ); acm.addFieldValue( new ActionFieldFunction( "f3", "31-Jan-2012", SuggestionCompletionEngine.TYPE_DATE ) ); acm.addFieldValue( new ActionFieldFunction( "f4", "100", SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ) ); acm.addFieldValue( new ActionFieldFunction( "f5", "100", SuggestionCompletionEngine.TYPE_NUMERIC_BIGDECIMAL ) ); m.addRhsItem( acm ); String result = BRDRLPersistence.getInstance().marshal( m ); assertTrue( result.indexOf( "java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(\"dd-MMM-yyyy\");" ) != -1 ); assertTrue( result.indexOf( "$p.method( \"String\", true, sdf.parse(\"31-Jan-2012\"), 100, new java.math.BigDecimal(\"100\") );" ) != -1 ); } finally { if ( oldValue == null ) { System.clearProperty( "drools.dateformat" ); } else { System.setProperty( "drools.dateformat", oldValue ); } } } @Test public void testFromAccumulateWithEmbeddedFromEntryPoint() { RuleModel m = new RuleModel(); m.name = "r1"; SingleFieldConstraint sfc = new SingleFieldConstraint( "bar" ); sfc.setFactType( SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ); sfc.setFieldBinding( "$a" ); sfc.setOperator( "==" ); sfc.setValue( "777" ); FactPattern fp = new FactPattern( "Foo" ); fp.addConstraint( sfc ); FromEntryPointFactPattern fep = new FromEntryPointFactPattern(); fep.setEntryPointName( "ep" ); fep.setFactPattern( fp ); FromAccumulateCompositeFactPattern fac = new FromAccumulateCompositeFactPattern(); fac.setSourcePattern( fep ); fac.setFactPattern( new FactPattern( "java.util.List" ) ); fac.setFunction( "max($a)" ); m.addLhsItem( fac ); String actual = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"r1\"\n" + "dialect \"mvel\"\n" + "when\n" + "java.util.List( ) from accumulate ( Foo( $a : bar == 777 ) from entry-point \"ep\", \n" + "max($a))\n" + "then\n" + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } @Test public void testFromCollectWithEmbeddedFromEntryPoint() { RuleModel m = new RuleModel(); m.name = "r1"; SingleFieldConstraint sfc = new SingleFieldConstraint( "bar" ); sfc.setFactType( SuggestionCompletionEngine.TYPE_NUMERIC_INTEGER ); sfc.setFieldBinding( "$a" ); sfc.setOperator( "==" ); sfc.setValue( "777" ); FactPattern fp = new FactPattern( "Foo" ); fp.addConstraint( sfc ); FromEntryPointFactPattern fep = new FromEntryPointFactPattern(); fep.setEntryPointName( "ep" ); fep.setFactPattern( fp ); FromCollectCompositeFactPattern fac = new FromCollectCompositeFactPattern(); fac.setRightPattern( fep ); fac.setFactPattern( new FactPattern( "java.util.List" ) ); m.addLhsItem( fac ); String actual = BRDRLPersistence.getInstance().marshal( m ); String expected = "rule \"r1\"\n" + "dialect \"mvel\"\n" + "when\n" + "java.util.List( ) from collect ( Foo( $a : bar == 777 ) from entry-point \"ep\" ) \n" + "then\n" + "end"; assertEqualsIgnoreWhitespace( expected, actual ); } }
apache-2.0
lilshim/stock-data-visualize-demo
Assets/OVR/Scripts/OVRCommon.cs
4601
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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. ************************************************************************************/ using UnityEngine; using System.Collections.Generic; using Ovr; /// <summary> /// Miscellaneous extension methods that any script can use. /// </summary> public static class OVRExtensions { /// <summary> /// Converts a plain C# matrix to a Unity matrix. /// </summary> /// <returns>The matrix as a Unity Matrix4x4.</returns> /// <param name="ovrMat">The matrix as a Matrix4f.</param> public static Matrix4x4 ToMatrix4x4(this Matrix4f ovrMat) { Matrix4x4 mat = new Matrix4x4(); mat[0, 0] = ovrMat.m[0, 0]; mat[0, 1] = ovrMat.m[0, 1]; mat[0, 2] = ovrMat.m[0, 2]; mat[0, 3] = ovrMat.m[0, 3]; mat[1, 0] = ovrMat.m[1, 0]; mat[1, 1] = ovrMat.m[1, 1]; mat[1, 2] = ovrMat.m[1, 2]; mat[1, 3] = ovrMat.m[1, 3]; mat[2, 0] = ovrMat.m[2, 0]; mat[2, 1] = ovrMat.m[2, 1]; mat[2, 2] = ovrMat.m[2, 2]; mat[2, 3] = ovrMat.m[2, 3]; mat[3, 0] = ovrMat.m[3, 0]; mat[3, 1] = ovrMat.m[3, 1]; mat[3, 2] = ovrMat.m[3, 2]; mat[3, 3] = ovrMat.m[3, 3]; return mat; } /// <summary> /// Converts a plain C# Sizei to a Unity Vector2. /// </summary> /// <returns>The size as a Unity Vector2.</returns> /// <param name="size">The size as a C# Sizei.</param> public static Vector2 ToVector2(this Sizei size) { return new Vector2(size.w, size.h); } /// <summary> /// Converts a plain C# Vector2i to a Unity Vector2. /// </summary> /// <returns>The vector as a Unity Vector2.</returns> /// <param name="size">The vector as a C# Vector2i.</param> public static Vector2 ToVector2(this Vector2i vec) { return new Vector2(vec.x, vec.y); } /// <summary> /// Converts a plain C# Vector2 to a Unity Vector2. /// </summary> /// <returns>The vector as a Unity Vector2.</returns> /// <param name="size">The vector as a C# Vector2.</param> public static Vector2 ToVector2(this Vector2f vec) { return new Vector2(vec.x, vec.y); } /// <summary> /// Converts a plain C# Vector3 to a Unity Vector3. /// </summary> /// <returns>The vector as a Unity Vector3.</returns> /// <param name="size">The vector as a C# Vector3.</param> public static Vector3 ToVector3(this Vector3f vec, bool rhToLh) { Vector3 v = new Vector3(vec.x, vec.y, vec.z); if (rhToLh) v.z = -v.z; return v; } /// <summary> /// Converts a plain C# Quatf to a Unity Quaternion. /// </summary> /// <returns>The quaternion as a Unity Quaternion.</returns> /// <param name="size">The quaternion as a C# Quatf.</param> public static Quaternion ToQuaternion(this Quatf quat, bool rhToLh) { Quaternion q = new Quaternion(quat.x, quat.y, quat.z, quat.w); if (rhToLh) { q.x = -q.x; q.y = -q.y; } return q; } /// <summary> /// Converts a plain C# Posef to a Unity OVRPose. /// </summary> /// <returns>The pose as a Unity OVRPose.</returns> /// <param name="size">The pose as a C# Posef.</param> public static OVRPose ToPose(this Posef pose, bool rhToLh) { return new OVRPose { position = pose.Position.ToVector3(rhToLh), orientation = pose.Orientation.ToQuaternion(rhToLh) }; } } /// <summary> /// An affine transformation built from a Unity position and orientation. /// </summary> public struct OVRPose { /// <summary> /// The position. /// </summary> public Vector3 position; /// <summary> /// The orientation. /// </summary> public Quaternion orientation; } /// <summary> /// Selects a human eye. /// </summary> public enum OVREye { Center = -1, Left = Ovr.Eye.Left, Right = Ovr.Eye.Right, Count = Ovr.Eye.Count, }
apache-2.0
speedovation/kiwi-node-plugins
node_modules/jayson/examples/method_routing/client.js
252
var jayson = require(__dirname + '/../..'); // create a client var client = jayson.client.http({ port: 3000 }); // invoke "add_2" client.request('add_2', [3], function(err, response) { if(err) throw err; console.log(response.result); // 5! });
apache-2.0
bit-zyl/Alluxio-Nvdimm
underfs/swift/src/test/java/alluxio/underfs/swift/SwiftUnderFileSystemFactoryTest.java
1408
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.underfs.swift; import alluxio.underfs.UnderFileSystemFactory; import alluxio.underfs.UnderFileSystemRegistry; import org.junit.Assert; import org.junit.Test; /** * Unit tests for the {@link SwiftUnderFileSystem}. */ public class SwiftUnderFileSystemFactoryTest { /** * This test ensures the Swift UFS module correctly accepts paths that begin with swift://. */ @Test public void factory() { UnderFileSystemFactory factory = UnderFileSystemRegistry.find("swift://localhost/test/path"); UnderFileSystemFactory factory2 = UnderFileSystemRegistry.find("file://localhost/test/path"); Assert.assertNotNull("A UnderFileSystemFactory should exist for swift paths when using this " + "module", factory); Assert.assertNull("A UnderFileSystemFactory should not exist for non supported paths when " + "using this module", factory2); } }
apache-2.0
vergilchiu/hive
ql/src/test/org/apache/hadoop/hive/ql/udf/generic/TestGenericUDFFactorial.java
3087
/** * 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. */ package org.apache.hadoop.hive.ql.udf.generic; import junit.framework.TestCase; import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredJavaObject; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredObject; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; public class TestGenericUDFFactorial extends TestCase { public void testFactorial() throws HiveException { GenericUDFFactorial udf = new GenericUDFFactorial(); ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableIntObjectInspector; ObjectInspector[] arguments = { valueOI0 }; udf.initialize(arguments); // date str runAndVerify(5, 120L, udf); runAndVerify(0, 1L, udf); runAndVerify(20, 2432902008176640000L, udf); // outside of [0..20] range runAndVerify(-1, null, udf); runAndVerify(21, null, udf); // null input runAndVerify(null, null, udf); } public void testWrongInputType() throws HiveException { @SuppressWarnings("resource") GenericUDFFactorial udf = new GenericUDFFactorial(); ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableDoubleObjectInspector; ObjectInspector[] arguments = { valueOI0 }; try { udf.initialize(arguments); assertTrue("GenericUDFFactorial.initialize() shold throw UDFArgumentTypeException", false); } catch (UDFArgumentTypeException e) { // UDFArgumentTypeException is expected } } private void runAndVerify(Integer in, Long expResult, GenericUDF udf) throws HiveException { DeferredObject valueObj0 = new DeferredJavaObject(in != null ? new IntWritable(in) : null); DeferredObject[] args = { valueObj0 }; LongWritable output = (LongWritable) udf.evaluate(args); if (expResult == null) { assertNull("factorial() test ", output); } else { assertNotNull("factorial() test ", output); assertEquals("factorial() test ", expResult.longValue(), output.get()); } } }
apache-2.0
hxiaodon/seaweedfs
weed/storage/volume_info_test.go
303
package storage import "testing" func TestSortVolumeInfos(t *testing.T) { vis := []*VolumeInfo{ &VolumeInfo{ Id: 2, }, &VolumeInfo{ Id: 1, }, &VolumeInfo{ Id: 3, }, } sortVolumeInfos(vis) for i := 0; i < len(vis); i++ { if vis[i].Id != VolumeId(i+1) { t.Fatal() } } }
apache-2.0
AkihiroSuda/docker
libnetwork/diagnostic/server.go
6489
package diagnostic import ( "context" "encoding/json" "fmt" "net/http" "sync" "sync/atomic" "github.com/docker/docker/libnetwork/internal/caller" stackdump "github.com/docker/docker/pkg/signal" "github.com/sirupsen/logrus" ) // HTTPHandlerFunc TODO type HTTPHandlerFunc func(interface{}, http.ResponseWriter, *http.Request) type httpHandlerCustom struct { ctx interface{} F func(interface{}, http.ResponseWriter, *http.Request) } // ServeHTTP TODO func (h httpHandlerCustom) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.F(h.ctx, w, r) } var diagPaths2Func = map[string]HTTPHandlerFunc{ "/": notImplemented, "/help": help, "/ready": ready, "/stackdump": stackTrace, } // Server when the debug is enabled exposes a // This data structure is protected by the Agent mutex so does not require and additional mutex here type Server struct { enable int32 srv *http.Server port int mux *http.ServeMux registeredHanders map[string]bool sync.Mutex } // New creates a new diagnostic server func New() *Server { return &Server{ registeredHanders: make(map[string]bool), } } // Init initialize the mux for the http handling and register the base hooks func (s *Server) Init() { s.mux = http.NewServeMux() // Register local handlers s.RegisterHandler(s, diagPaths2Func) } // RegisterHandler allows to register new handlers to the mux and to a specific path func (s *Server) RegisterHandler(ctx interface{}, hdlrs map[string]HTTPHandlerFunc) { s.Lock() defer s.Unlock() for path, fun := range hdlrs { if _, ok := s.registeredHanders[path]; ok { continue } s.mux.Handle(path, httpHandlerCustom{ctx, fun}) s.registeredHanders[path] = true } } // ServeHTTP this is the method called bu the ListenAndServe, and is needed to allow us to // use our custom mux func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mux.ServeHTTP(w, r) } // EnableDiagnostic opens a TCP socket to debug the passed network DB func (s *Server) EnableDiagnostic(ip string, port int) { s.Lock() defer s.Unlock() s.port = port if s.enable == 1 { logrus.Info("The server is already up and running") return } logrus.Infof("Starting the diagnostic server listening on %d for commands", port) srv := &http.Server{Addr: fmt.Sprintf("%s:%d", ip, port), Handler: s} s.srv = srv s.enable = 1 go func(n *Server) { // Ignore ErrServerClosed that is returned on the Shutdown call if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { logrus.Errorf("ListenAndServe error: %s", err) atomic.SwapInt32(&n.enable, 0) } }(s) } // DisableDiagnostic stop the dubug and closes the tcp socket func (s *Server) DisableDiagnostic() { s.Lock() defer s.Unlock() s.srv.Shutdown(context.Background()) // nolint:errcheck s.srv = nil s.enable = 0 logrus.Info("Disabling the diagnostic server") } // IsDiagnosticEnabled returns true when the debug is enabled func (s *Server) IsDiagnosticEnabled() bool { s.Lock() defer s.Unlock() return s.enable == 1 } func notImplemented(ctx interface{}, w http.ResponseWriter, r *http.Request) { r.ParseForm() // nolint:errcheck _, json := ParseHTTPFormOptions(r) rsp := WrongCommand("not implemented", fmt.Sprintf("URL path: %s no method implemented check /help\n", r.URL.Path)) // audit logs log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) log.Info("command not implemented done") HTTPReply(w, rsp, json) // nolint:errcheck } func help(ctx interface{}, w http.ResponseWriter, r *http.Request) { r.ParseForm() // nolint:errcheck _, json := ParseHTTPFormOptions(r) // audit logs log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) log.Info("help done") n, ok := ctx.(*Server) var result string if ok { for path := range n.registeredHanders { result += fmt.Sprintf("%s\n", path) } HTTPReply(w, CommandSucceed(&StringCmd{Info: result}), json) // nolint:errcheck } } func ready(ctx interface{}, w http.ResponseWriter, r *http.Request) { r.ParseForm() // nolint:errcheck _, json := ParseHTTPFormOptions(r) // audit logs log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) log.Info("ready done") HTTPReply(w, CommandSucceed(&StringCmd{Info: "OK"}), json) // nolint:errcheck } func stackTrace(ctx interface{}, w http.ResponseWriter, r *http.Request) { r.ParseForm() // nolint:errcheck _, json := ParseHTTPFormOptions(r) // audit logs log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) log.Info("stack trace") path, err := stackdump.DumpStacks("/tmp/") if err != nil { log.WithError(err).Error("failed to write goroutines dump") HTTPReply(w, FailCommand(err), json) // nolint:errcheck } else { log.Info("stack trace done") HTTPReply(w, CommandSucceed(&StringCmd{Info: fmt.Sprintf("goroutine stacks written to %s", path)}), json) // nolint:errcheck } } // DebugHTTPForm helper to print the form url parameters func DebugHTTPForm(r *http.Request) { for k, v := range r.Form { logrus.Debugf("Form[%q] = %q\n", k, v) } } // JSONOutput contains details on JSON output printing type JSONOutput struct { enable bool prettyPrint bool } // ParseHTTPFormOptions easily parse the JSON printing options func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput) { _, unsafe := r.Form["unsafe"] v, json := r.Form["json"] var pretty bool if len(v) > 0 { pretty = v[0] == "pretty" } return unsafe, &JSONOutput{enable: json, prettyPrint: pretty} } // HTTPReply helper function that takes care of sending the message out func HTTPReply(w http.ResponseWriter, r *HTTPResult, j *JSONOutput) (int, error) { var response []byte if j.enable { w.Header().Set("Content-Type", "application/json") var err error if j.prettyPrint { response, err = json.MarshalIndent(r, "", " ") if err != nil { response, _ = json.MarshalIndent(FailCommand(err), "", " ") } } else { response, err = json.Marshal(r) if err != nil { response, _ = json.Marshal(FailCommand(err)) } } } else { response = []byte(r.String()) } return fmt.Fprint(w, string(response)) }
apache-2.0
pvillard31/nifi
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConfigVerificationResultDTO.java
1855
/* * 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. */ package org.apache.nifi.web.api.dto; import io.swagger.annotations.ApiModelProperty; public class ConfigVerificationResultDTO { private String outcome; private String verificationStepName; private String explanation; @ApiModelProperty(value = "The outcome of the verification", allowableValues = "SUCCESSFUL, FAILED, SKIPPED") public String getOutcome() { return outcome; } public void setOutcome(final String outcome) { this.outcome = outcome; } @ApiModelProperty("The name of the verification step") public String getVerificationStepName() { return verificationStepName; } public void setVerificationStepName(final String verificationStepName) { this.verificationStepName = verificationStepName; } @ApiModelProperty("An explanation of why the step was or was not successful") public String getExplanation() { return explanation; } public void setExplanation(final String explanation) { this.explanation = explanation; } }
apache-2.0
jokeog/Projuct1.0
app/src/main/java/com/mikepenz/materialdrawer/app/decorators/EventDecorator.java
918
package com.mikepenz.materialdrawer.app.decorators; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.spans.DotSpan; import java.util.Collection; import java.util.HashSet; /** * Decorate several days with a dot */ public class EventDecorator implements DayViewDecorator { private int color; private HashSet<CalendarDay> dates; public EventDecorator(int color, Collection<CalendarDay> dates) { this.color = color; this.dates = new HashSet<>(dates); } @Override public boolean shouldDecorate(CalendarDay day) { return dates.contains(day); } @Override public void decorate(DayViewFacade view) { view.addSpan(new DotSpan(5, color)); } }
apache-2.0
JiYou/jitsi-meet
service/xmpp/XMPPEvents.js
1571
var XMPPEvents = { CONNECTION_FAILED: "xmpp.connection.failed", CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle", CALL_INCOMING: "xmpp.callincoming.jingle", DISPOSE_CONFERENCE: "xmpp.dispose_conference", GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown", KICKED: "xmpp.kicked", BRIDGE_DOWN: "xmpp.bridge_down", USER_ID_CHANGED: "xmpp.user_id_changed", // We joined the MUC MUC_JOINED: "xmpp.muc_joined", // A member joined the MUC MUC_MEMBER_JOINED: "xmpp.muc_member_joined", // A member left the MUC MUC_MEMBER_LEFT: "xmpp.muc_member_left", MUC_ROLE_CHANGED: "xmpp.muc_role_changed", MUC_DESTROYED: "xmpp.muc_destroyed", DISPLAY_NAME_CHANGED: "xmpp.display_name_changed", REMOTE_STATS: "xmpp.remote_stats", LOCAL_ROLE_CHANGED: "xmpp.localrole_changed", PRESENCE_STATUS: "xmpp.presence_status", RESERVATION_ERROR: "xmpp.room_reservation_error", SUBJECT_CHANGED: "xmpp.subject_changed", MESSAGE_RECEIVED: "xmpp.message_received", SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message", PASSWORD_REQUIRED: "xmpp.password_required", AUTHENTICATION_REQUIRED: "xmpp.authentication_required", CHAT_ERROR_RECEIVED: "xmpp.chat_error_received", ETHERPAD: "xmpp.etherpad", DEVICE_AVAILABLE: "xmpp.device_available", START_MUTED: "xmpp.start_muted", PEERCONNECTION_READY: "xmpp.peerconnection_ready", CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed", AUDIO_MUTED: "xmpp.audio_muted", VIDEO_MUTED: "xmpp.video_muted" }; module.exports = XMPPEvents;
apache-2.0
thunderace/newtifry
appengine/mako.0.9.0/lexer.py
16788
# mako/lexer.py # Copyright (C) 2006-2013 the Mako authors and contributors <see AUTHORS file> # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """provides the Lexer class for parsing template strings into parse trees.""" import re import codecs from mako import parsetree, exceptions, compat from mako.pygen import adjust_whitespace _regexp_cache = {} class Lexer(object): def __init__(self, text, filename=None, disable_unicode=False, input_encoding=None, preprocessor=None): self.text = text self.filename = filename self.template = parsetree.TemplateNode(self.filename) self.matched_lineno = 1 self.matched_charpos = 0 self.lineno = 1 self.match_position = 0 self.tag = [] self.control_line = [] self.ternary_stack = [] self.disable_unicode = disable_unicode self.encoding = input_encoding if compat.py3k and disable_unicode: raise exceptions.UnsupportedError( "Mako for Python 3 does not " "support disabling Unicode") if preprocessor is None: self.preprocessor = [] elif not hasattr(preprocessor, '__iter__'): self.preprocessor = [preprocessor] else: self.preprocessor = preprocessor @property def exception_kwargs(self): return {'source':self.text, 'lineno':self.matched_lineno, 'pos':self.matched_charpos, 'filename':self.filename} def match(self, regexp, flags=None): """compile the given regexp, cache the reg, and call match_reg().""" try: reg = _regexp_cache[(regexp, flags)] except KeyError: if flags: reg = re.compile(regexp, flags) else: reg = re.compile(regexp) _regexp_cache[(regexp, flags)] = reg return self.match_reg(reg) def match_reg(self, reg): """match the given regular expression object to the current text position. if a match occurs, update the current text and line position. """ mp = self.match_position match = reg.match(self.text, self.match_position) if match: (start, end) = match.span() if end == start: self.match_position = end + 1 else: self.match_position = end self.matched_lineno = self.lineno lines = re.findall(r"\n", self.text[mp:self.match_position]) cp = mp - 1 while (cp >= 0 and cp<self.textlength and self.text[cp] != '\n'): cp -=1 self.matched_charpos = mp - cp self.lineno += len(lines) #print "MATCHED:", match.group(0), "LINE START:", # self.matched_lineno, "LINE END:", self.lineno #print "MATCH:", regexp, "\n", self.text[mp : mp + 15], \ # (match and "TRUE" or "FALSE") return match def parse_until_text(self, *text): startpos = self.match_position text_re = r'|'.join(text) brace_level = 0 while True: match = self.match(r'#.*\n') if match: continue match = self.match(r'(\"\"\"|\'\'\'|\"|\')((?<!\\)\\\1|.)*?\1', re.S) if match: continue match = self.match(r'(%s)' % text_re) if match: if match.group(1) == '}' and brace_level > 0: brace_level -= 1 continue return \ self.text[startpos:\ self.match_position-len(match.group(1))],\ match.group(1) match = self.match(r"(.*?)(?=\"|\'|#|%s)" % text_re, re.S) if match: brace_level += match.group(1).count('{') brace_level -= match.group(1).count('}') continue raise exceptions.SyntaxException( "Expected: %s" % ','.join(text), **self.exception_kwargs) def append_node(self, nodecls, *args, **kwargs): kwargs.setdefault('source', self.text) kwargs.setdefault('lineno', self.matched_lineno) kwargs.setdefault('pos', self.matched_charpos) kwargs['filename'] = self.filename node = nodecls(*args, **kwargs) if len(self.tag): self.tag[-1].nodes.append(node) else: self.template.nodes.append(node) # build a set of child nodes for the control line # (used for loop variable detection) # also build a set of child nodes on ternary control lines # (used for determining if a pass needs to be auto-inserted if self.control_line: control_frame = self.control_line[-1] control_frame.nodes.append(node) if not (isinstance(node, parsetree.ControlLine) and control_frame.is_ternary(node.keyword)): if self.ternary_stack and self.ternary_stack[-1]: self.ternary_stack[-1][-1].nodes.append(node) if isinstance(node, parsetree.Tag): if len(self.tag): node.parent = self.tag[-1] self.tag.append(node) elif isinstance(node, parsetree.ControlLine): if node.isend: self.control_line.pop() self.ternary_stack.pop() elif node.is_primary: self.control_line.append(node) self.ternary_stack.append([]) elif self.control_line and \ self.control_line[-1].is_ternary(node.keyword): self.ternary_stack[-1].append(node) elif self.control_line and \ not self.control_line[-1].is_ternary(node.keyword): raise exceptions.SyntaxException( "Keyword '%s' not a legal ternary for keyword '%s'" % (node.keyword, self.control_line[-1].keyword), **self.exception_kwargs) _coding_re = re.compile(r'#.*coding[:=]\s*([-\w.]+).*\r?\n') def decode_raw_stream(self, text, decode_raw, known_encoding, filename): """given string/unicode or bytes/string, determine encoding from magic encoding comment, return body as unicode or raw if decode_raw=False """ if isinstance(text, compat.text_type): m = self._coding_re.match(text) encoding = m and m.group(1) or known_encoding or 'ascii' return encoding, text if text.startswith(codecs.BOM_UTF8): text = text[len(codecs.BOM_UTF8):] parsed_encoding = 'utf-8' m = self._coding_re.match(text.decode('utf-8', 'ignore')) if m is not None and m.group(1) != 'utf-8': raise exceptions.CompileException( "Found utf-8 BOM in file, with conflicting " "magic encoding comment of '%s'" % m.group(1), text.decode('utf-8', 'ignore'), 0, 0, filename) else: m = self._coding_re.match(text.decode('utf-8', 'ignore')) if m: parsed_encoding = m.group(1) else: parsed_encoding = known_encoding or 'ascii' if decode_raw: try: text = text.decode(parsed_encoding) except UnicodeDecodeError: raise exceptions.CompileException( "Unicode decode operation of encoding '%s' failed" % parsed_encoding, text.decode('utf-8', 'ignore'), 0, 0, filename) return parsed_encoding, text def parse(self): self.encoding, self.text = self.decode_raw_stream(self.text, not self.disable_unicode, self.encoding, self.filename,) for preproc in self.preprocessor: self.text = preproc(self.text) # push the match marker past the # encoding comment. self.match_reg(self._coding_re) self.textlength = len(self.text) while (True): if self.match_position > self.textlength: break if self.match_end(): break if self.match_expression(): continue if self.match_control_line(): continue if self.match_comment(): continue if self.match_tag_start(): continue if self.match_tag_end(): continue if self.match_python_block(): continue if self.match_text(): continue if self.match_position > self.textlength: break raise exceptions.CompileException("assertion failed") if len(self.tag): raise exceptions.SyntaxException("Unclosed tag: <%%%s>" % self.tag[-1].keyword, **self.exception_kwargs) if len(self.control_line): raise exceptions.SyntaxException( "Unterminated control keyword: '%s'" % self.control_line[-1].keyword, self.text, self.control_line[-1].lineno, self.control_line[-1].pos, self.filename) return self.template def match_tag_start(self): match = self.match(r''' \<% # opening tag ([\w\.\:]+) # keyword ((?:\s+\w+|\s*=\s*|".*?"|'.*?')*) # attrname, = \ # sign, string expression \s* # more whitespace (/)?> # closing ''', re.I | re.S | re.X) if match: keyword, attr, isend = match.groups() self.keyword = keyword attributes = {} if attr: for att in re.findall( r"\s*(\w+)\s*=\s*(?:'([^']*)'|\"([^\"]*)\")", attr): key, val1, val2 = att text = val1 or val2 text = text.replace('\r\n', '\n') attributes[key] = text self.append_node(parsetree.Tag, keyword, attributes) if isend: self.tag.pop() else: if keyword == 'text': match = self.match(r'(.*?)(?=\</%text>)', re.S) if not match: raise exceptions.SyntaxException( "Unclosed tag: <%%%s>" % self.tag[-1].keyword, **self.exception_kwargs) self.append_node(parsetree.Text, match.group(1)) return self.match_tag_end() return True else: return False def match_tag_end(self): match = self.match(r'\</%[\t ]*(.+?)[\t ]*>') if match: if not len(self.tag): raise exceptions.SyntaxException( "Closing tag without opening tag: </%%%s>" % match.group(1), **self.exception_kwargs) elif self.tag[-1].keyword != match.group(1): raise exceptions.SyntaxException( "Closing tag </%%%s> does not match tag: <%%%s>" % (match.group(1), self.tag[-1].keyword), **self.exception_kwargs) self.tag.pop() return True else: return False def match_end(self): match = self.match(r'\Z', re.S) if match: string = match.group() if string: return string else: return True else: return False def match_text(self): match = self.match(r""" (.*?) # anything, followed by: ( (?<=\n)(?=[ \t]*(?=%|\#\#)) # an eval or line-based # comment preceded by a # consumed newline and whitespace | (?=\${) # an expression | (?=\#\*) # multiline comment | (?=</?[%&]) # a substitution or block or call start or end # - don't consume | (\\\r?\n) # an escaped newline - throw away | \Z # end of string )""", re.X | re.S) if match: text = match.group(1) if text: self.append_node(parsetree.Text, text) return True else: return False def match_python_block(self): match = self.match(r"<%(!)?") if match: line, pos = self.matched_lineno, self.matched_charpos text, end = self.parse_until_text(r'%>') # the trailing newline helps # compiler.parse() not complain about indentation text = adjust_whitespace(text) + "\n" self.append_node( parsetree.Code, text, match.group(1)=='!', lineno=line, pos=pos) return True else: return False def match_expression(self): match = self.match(r"\${") if match: line, pos = self.matched_lineno, self.matched_charpos text, end = self.parse_until_text(r'\|', r'}') if end == '|': escapes, end = self.parse_until_text(r'}') else: escapes = "" text = text.replace('\r\n', '\n') self.append_node( parsetree.Expression, text, escapes.strip(), lineno=line, pos=pos) return True else: return False def match_control_line(self): match = self.match( r"(?<=^)[\t ]*(%(?!%)|##)[\t ]*((?:(?:\\r?\n)|[^\r\n])*)" r"(?:\r?\n|\Z)", re.M) if match: operator = match.group(1) text = match.group(2) if operator == '%': m2 = re.match(r'(end)?(\w+)\s*(.*)', text) if not m2: raise exceptions.SyntaxException( "Invalid control line: '%s'" % text, **self.exception_kwargs) isend, keyword = m2.group(1, 2) isend = (isend is not None) if isend: if not len(self.control_line): raise exceptions.SyntaxException( "No starting keyword '%s' for '%s'" % (keyword, text), **self.exception_kwargs) elif self.control_line[-1].keyword != keyword: raise exceptions.SyntaxException( "Keyword '%s' doesn't match keyword '%s'" % (text, self.control_line[-1].keyword), **self.exception_kwargs) self.append_node(parsetree.ControlLine, keyword, isend, text) else: self.append_node(parsetree.Comment, text) return True else: return False def match_comment(self): """matches the multiline version of a comment""" match = self.match(r"<%doc>(.*?)</%doc>", re.S) if match: self.append_node(parsetree.Comment, match.group(1)) return True else: return False
apache-2.0
bitclaw/netsuite-php
src/Classes/BillingScheduleRecurrenceMode.php
167
<?php namespace Fungku\NetSuite\Classes; class BillingScheduleRecurrenceMode { static $paramtypesmap = array( ); const _dom = "_dom"; const _dowim = "_dowim"; }
apache-2.0
KevinLoiseau/manageiq
spec/javascripts/directives/selectpickerForSelectTag_spec.js
928
describe('selectpicker-for-select-tag initialization', function() { var $scope, form; beforeEach(module('ManageIQ')); beforeEach(inject(function($compile, $rootScope, miqService) { $scope = $rootScope; var element = angular.element( '<form name="angularForm">' + '<select id="action_typ" name="action_typ" selectpicker-for-select-tag ng-model="scheduleModel.action_typ"><option>Mustard</option><option>Ketchup</option><option>Relish</option></select>' + '</form>' ); spyOn(miqService, 'miqFlashClear'); elem = $compile(element)($rootScope); form = $scope.angularForm; })); describe('selectpicker-for-select-tag', function() { it('attaches selectpicker classes', function() { form.action_typ.$setViewValue('Mustard'); expect(elem[0][0].className).toMatch(/bs-select-hidden/); expect(elem[0][1].className).toMatch(/dropdown-toggle/); }); }); });
apache-2.0
sungsoo/optiq-project
core/src/main/java/net/hydromatic/optiq/QueryableTable.java
1784
/* * 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. */ package net.hydromatic.optiq; import net.hydromatic.linq4j.QueryProvider; import net.hydromatic.linq4j.Queryable; import net.hydromatic.linq4j.expressions.Expression; import java.lang.reflect.Type; /** * Extension to {@link Table} that can translate itself to a {@link Queryable}. */ public interface QueryableTable extends Table { /** Converts this table into a {@link Queryable}. */ <T> Queryable<T> asQueryable(QueryProvider queryProvider, SchemaPlus schema, String tableName); /** Returns the element type of the collection that will implement this * table. */ Type getElementType(); /** Generates an expression with which this table can be referenced in * generated code. * * @param schema Schema * @param tableName Table name (unique within schema) * @param clazz The desired collection class; for example {@code Queryable}. */ Expression getExpression(SchemaPlus schema, String tableName, Class clazz); } // End QueryableTable.java
apache-2.0
jakubmalek/guava
guava/src/com/google/common/collect/FilteredMultimapValues.java
2970
/* * Copyright (C) 2013 The Guava 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 com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.j2objc.annotations.Weak; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; /** * Implementation for {@link FilteredMultimap#values()}. * * @author Louis Wasserman */ @GwtCompatible final class FilteredMultimapValues<K, V> extends AbstractCollection<V> { @Weak private final FilteredMultimap<K, V> multimap; FilteredMultimapValues(FilteredMultimap<K, V> multimap) { this.multimap = checkNotNull(multimap); } @Override public Iterator<V> iterator() { return Maps.valueIterator(multimap.entries().iterator()); } @Override public boolean contains(@Nullable Object o) { return multimap.containsValue(o); } @Override public int size() { return multimap.size(); } @Override public boolean remove(@Nullable Object o) { Predicate<? super Entry<K, V>> entryPredicate = multimap.entryPredicate(); for (Iterator<Entry<K, V>> unfilteredItr = multimap.unfiltered().entries().iterator(); unfilteredItr.hasNext(); ) { Map.Entry<K, V> entry = unfilteredItr.next(); if (entryPredicate.apply(entry) && Objects.equal(entry.getValue(), o)) { unfilteredItr.remove(); return true; } } return false; } @Override public boolean removeAll(Collection<?> c) { return Iterables.removeIf( multimap.unfiltered().entries(), // explicit <Entry<K, V>> is required to build with JDK6 Predicates.<Entry<K, V>>and( multimap.entryPredicate(), Maps.<V>valuePredicateOnEntries(Predicates.in(c)))); } @Override public boolean retainAll(Collection<?> c) { return Iterables.removeIf( multimap.unfiltered().entries(), // explicit <Entry<K, V>> is required to build with JDK6 Predicates.<Entry<K, V>>and( multimap.entryPredicate(), Maps.<V>valuePredicateOnEntries(Predicates.not(Predicates.in(c))))); } @Override public void clear() { multimap.clear(); } }
apache-2.0
manishgupta88/carbondata
integration/spark-common/src/main/scala/org/apache/carbondata/spark/rdd/CarbonScanRDD.scala
34134
/* * 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. */ package org.apache.carbondata.spark.rdd import java.text.SimpleDateFormat import java.util.{ArrayList, Date, List} import scala.collection.JavaConverters._ import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.reflect.ClassTag import scala.util.Random import scala.util.control.Breaks.{break, breakable} import org.apache.hadoop.conf.Configuration import org.apache.hadoop.mapred.JobConf import org.apache.hadoop.mapreduce._ import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl import org.apache.spark._ import org.apache.spark.deploy.SparkHadoopUtil import org.apache.spark.sql.hive.DistributionUtil import org.apache.spark.sql.SparkSession import org.apache.spark.sql.carbondata.execution.datasources.tasklisteners.CarbonLoadTaskCompletionListener import org.apache.spark.sql.execution.SQLExecution import org.apache.spark.sql.profiler.{GetPartition, Profiler} import org.apache.spark.sql.util.SparkSQLUtil.sessionState import org.apache.spark.util.TaskCompletionListener import org.apache.carbondata.common.logging.LogServiceFactory import org.apache.carbondata.converter.SparkDataTypeConverterImpl import org.apache.carbondata.core.constants.{CarbonCommonConstants, CarbonCommonConstantsInternal} import org.apache.carbondata.core.datastore.block.Distributable import org.apache.carbondata.core.datastore.impl.FileFactory import org.apache.carbondata.core.indexstore.PartitionSpec import org.apache.carbondata.core.metadata.AbsoluteTableIdentifier import org.apache.carbondata.core.metadata.schema.table.TableInfo import org.apache.carbondata.core.scan.expression.Expression import org.apache.carbondata.core.scan.expression.conditional.ImplicitExpression import org.apache.carbondata.core.scan.filter.FilterUtil import org.apache.carbondata.core.scan.model.QueryModel import org.apache.carbondata.core.stats.{QueryStatistic, QueryStatisticsConstants} import org.apache.carbondata.core.statusmanager.FileFormat import org.apache.carbondata.core.util._ import org.apache.carbondata.core.util.path.CarbonTablePath import org.apache.carbondata.hadoop._ import org.apache.carbondata.hadoop.api.{CarbonFileInputFormat, CarbonInputFormat} import org.apache.carbondata.hadoop.api.CarbonTableInputFormat import org.apache.carbondata.hadoop.readsupport.CarbonReadSupport import org.apache.carbondata.hadoop.stream.CarbonStreamInputFormat import org.apache.carbondata.hadoop.util.CarbonInputFormatUtil import org.apache.carbondata.processing.util.CarbonLoaderUtil import org.apache.carbondata.spark.InitInputMetrics import org.apache.carbondata.spark.util.Util /** * This RDD is used to perform query on CarbonData file. Before sending tasks to scan * CarbonData file, this RDD will leverage CarbonData's index information to do CarbonData file * level filtering in driver side. */ class CarbonScanRDD[T: ClassTag]( @transient private val spark: SparkSession, val columnProjection: CarbonProjection, var filterExpression: Expression, identifier: AbsoluteTableIdentifier, @transient private val serializedTableInfo: Array[Byte], @transient private val tableInfo: TableInfo, inputMetricsStats: InitInputMetrics, @transient val partitionNames: Seq[PartitionSpec], val dataTypeConverterClz: Class[_ <: DataTypeConverter] = classOf[SparkDataTypeConverterImpl], val readSupportClz: Class[_ <: CarbonReadSupport[_]] = SparkReadSupport.readSupportClass) extends CarbonRDDWithTableInfo[T](spark, Nil, serializedTableInfo) { private val queryId = sparkContext.getConf.get("queryId", System.nanoTime() + "") private val jobTrackerId: String = { val formatter = new SimpleDateFormat("yyyyMMddHHmm") formatter.format(new Date()) } private var vectorReader = false private var directFill = false private val bucketedTable = tableInfo.getFactTable.getBucketingInfo @transient val LOGGER = LogServiceFactory.getLogService(this.getClass.getName) override def internalGetPartitions: Array[Partition] = { val startTime = System.currentTimeMillis() var partitions: Array[Partition] = Array.empty[Partition] var getSplitsStartTime: Long = -1 var getSplitsEndTime: Long = -1 var distributeStartTime: Long = -1 var distributeEndTime: Long = -1 val tablePath = tableInfo.getOrCreateAbsoluteTableIdentifier().getTablePath var numSegments = 0 var numStreamSegments = 0 var numBlocks = 0 try { val conf = FileFactory.getConfiguration val jobConf = new JobConf(conf) SparkHadoopUtil.get.addCredentials(jobConf) val job = Job.getInstance(jobConf) val fileLevelExternal = tableInfo.getFactTable().getTableProperties().get("_filelevelformat") val format = if (fileLevelExternal != null && fileLevelExternal.equalsIgnoreCase("true")) { prepareFileInputFormatForDriver(job.getConfiguration) } else { prepareInputFormatForDriver(job.getConfiguration) } // initialise query_id for job job.getConfiguration.set("query.id", queryId) // get splits getSplitsStartTime = System.currentTimeMillis() val splits = format.getSplits(job) getSplitsEndTime = System.currentTimeMillis() if ((splits == null) && format.isInstanceOf[CarbonFileInputFormat[Object]]) { throw new SparkException( "CarbonData file not exist in the segment_null (SDK writer Output) path") } numSegments = format.getNumSegments numStreamSegments = format.getNumStreamSegments numBlocks = format.getNumBlocks // separate split // 1. for batch splits, invoke distributeSplits method to create partitions // 2. for stream splits, create partition for each split by default val columnarSplits = new ArrayList[InputSplit]() val streamSplits = new ArrayBuffer[InputSplit]() splits.asScala.foreach { split => val carbonInputSplit = split.asInstanceOf[CarbonInputSplit] if (FileFormat.ROW_V1 == carbonInputSplit.getFileFormat) { streamSplits += split } else { columnarSplits.add(split) } } distributeStartTime = System.currentTimeMillis() val batchPartitions = distributeColumnarSplits(columnarSplits) distributeEndTime = System.currentTimeMillis() // check and remove InExpression from filterExpression checkAndRemoveInExpressinFromFilterExpression(batchPartitions) if (streamSplits.isEmpty) { partitions = batchPartitions.toArray } else { val index = batchPartitions.length val streamPartitions: mutable.Buffer[Partition] = streamSplits.zipWithIndex.map { splitWithIndex => val multiBlockSplit = new CarbonMultiBlockSplit( Seq(splitWithIndex._1.asInstanceOf[CarbonInputSplit]).asJava, splitWithIndex._1.getLocations, FileFormat.ROW_V1) new CarbonSparkPartition(id, splitWithIndex._2 + index, multiBlockSplit) } if (batchPartitions.isEmpty) { partitions = streamPartitions.toArray } else { // should keep the order by index of partition batchPartitions.appendAll(streamPartitions) partitions = batchPartitions.toArray } logInfo( s""" | Identified no.of.streaming splits/tasks: ${ streamPartitions.size }, | no.of.streaming files: ${format.getHitedStreamFiles}, | no.of.total streaming files: ${format.getNumStreamFiles}, | no.of.total streaming segement: ${format.getNumStreamSegments} """.stripMargin) } partitions } finally { Profiler.invokeIfEnable { val endTime = System.currentTimeMillis() val executionId = spark.sparkContext.getLocalProperty(SQLExecution.EXECUTION_ID_KEY) if (executionId != null) { Profiler.send( GetPartition( executionId.toLong, tableInfo.getDatabaseName + "." + tableInfo.getFactTable.getTableName, tablePath, queryId, partitions.length, startTime, endTime, getSplitsStartTime, getSplitsEndTime, numSegments, numStreamSegments, numBlocks, distributeStartTime, distributeEndTime, if (filterExpression == null) "" else filterExpression.getStatement, if (columnProjection == null) "" else columnProjection.getAllColumns.mkString(",") ) ) } } } } private def distributeColumnarSplits(splits: List[InputSplit]): mutable.Buffer[Partition] = { // this function distributes the split based on following logic: // 1. based on data locality, to make split balanced on all available nodes // 2. if the number of split for one var statistic = new QueryStatistic() val statisticRecorder = CarbonTimeStatisticsFactory.createDriverRecorder() var parallelism = sparkContext.defaultParallelism val result = new ArrayList[Partition](parallelism) var noOfBlocks = 0 var noOfNodes = 0 var noOfTasks = 0 if (!splits.isEmpty) { statistic.addStatistics(QueryStatisticsConstants.BLOCK_ALLOCATION, System.currentTimeMillis) statisticRecorder.recordStatisticsForDriver(statistic, queryId) statistic = new QueryStatistic() val carbonDistribution = if (directFill) { CarbonCommonConstants.CARBON_TASK_DISTRIBUTION_MERGE_FILES } else { CarbonProperties.getInstance().getProperty( CarbonCommonConstants.CARBON_TASK_DISTRIBUTION, CarbonCommonConstants.CARBON_TASK_DISTRIBUTION_DEFAULT) } // If bucketing is enabled on table then partitions should be grouped based on buckets. if (bucketedTable != null) { var i = 0 val bucketed = splits.asScala.map(_.asInstanceOf[CarbonInputSplit]).groupBy(f => f.getBucketId) (0 until bucketedTable.getNumOfRanges).map { bucketId => val bucketPartitions = bucketed.getOrElse(bucketId.toString, Nil) val multiBlockSplit = new CarbonMultiBlockSplit( bucketPartitions.asJava, bucketPartitions.flatMap(_.getLocations).toArray) val partition = new CarbonSparkPartition(id, i, multiBlockSplit) i += 1 result.add(partition) } } else { val useCustomDistribution = CarbonProperties.getInstance().getProperty( CarbonCommonConstants.CARBON_CUSTOM_BLOCK_DISTRIBUTION, "false").toBoolean || carbonDistribution.equalsIgnoreCase(CarbonCommonConstants.CARBON_TASK_DISTRIBUTION_CUSTOM) if (useCustomDistribution) { // create a list of block based on split val blockList = splits.asScala.map(_.asInstanceOf[Distributable]) // get the list of executors and map blocks to executors based on locality val activeNodes = DistributionUtil.ensureExecutorsAndGetNodeList(blockList, sparkContext) // divide the blocks among the tasks of the nodes as per the data locality val nodeBlockMapping = CarbonLoaderUtil.nodeBlockTaskMapping(blockList.asJava, -1, parallelism, activeNodes.toList.asJava) var i = 0 // Create Spark Partition for each task and assign blocks nodeBlockMapping.asScala.foreach { case (node, blockList) => blockList.asScala.foreach { blocksPerTask => val splits = blocksPerTask.asScala.map(_.asInstanceOf[CarbonInputSplit]) if (blocksPerTask.size() != 0) { val multiBlockSplit = new CarbonMultiBlockSplit(splits.asJava, Array(node)) val partition = new CarbonSparkPartition(id, i, multiBlockSplit) result.add(partition) i += 1 } } } noOfNodes = nodeBlockMapping.size } else if (carbonDistribution.equalsIgnoreCase( CarbonCommonConstants.CARBON_TASK_DISTRIBUTION_BLOCKLET)) { // Use blocklet distribution // Randomize the blocklets for better shuffling Random.shuffle(splits.asScala).zipWithIndex.foreach { splitWithIndex => val multiBlockSplit = new CarbonMultiBlockSplit( Seq(splitWithIndex._1.asInstanceOf[CarbonInputSplit]).asJava, splitWithIndex._1.getLocations) val partition = new CarbonSparkPartition(id, splitWithIndex._2, multiBlockSplit) result.add(partition) } } else if (carbonDistribution.equalsIgnoreCase( CarbonCommonConstants.CARBON_TASK_DISTRIBUTION_MERGE_FILES)) { // sort blocks in reverse order of length val blockSplits = splits .asScala .map(_.asInstanceOf[CarbonInputSplit]) .groupBy(f => f.getBlockPath) .map { blockSplitEntry => new CarbonMultiBlockSplit( blockSplitEntry._2.asJava, blockSplitEntry._2.flatMap(f => f.getLocations).distinct.toArray) }.toArray.sortBy(_.getLength)(implicitly[Ordering[Long]].reverse) val defaultMaxSplitBytes = sessionState(spark).conf.filesMaxPartitionBytes val openCostInBytes = sessionState(spark).conf.filesOpenCostInBytes val defaultParallelism = spark.sparkContext.defaultParallelism val totalBytes = blockSplits.map(_.getLength + openCostInBytes).sum val bytesPerCore = totalBytes / defaultParallelism val maxSplitBytes = Math .min(defaultMaxSplitBytes, Math.max(openCostInBytes, bytesPerCore)) LOGGER.info(s"Planning scan with bin packing, max size: $maxSplitBytes bytes, " + s"open cost is considered as scanning $openCostInBytes bytes.") val currentFiles = new ArrayBuffer[CarbonMultiBlockSplit] var currentSize = 0L def closePartition(): Unit = { if (currentFiles.nonEmpty) { result.add(combineSplits(currentFiles, currentSize, result.size())) } currentFiles.clear() currentSize = 0 } blockSplits.foreach { file => if (currentSize + file.getLength > maxSplitBytes) { closePartition() } // Add the given file to the current partition. currentSize += file.getLength + openCostInBytes currentFiles += file } closePartition() } else { // Use block distribution splits.asScala.map(_.asInstanceOf[CarbonInputSplit]).groupBy { f => f.getSegmentId.concat(f.getBlockPath) }.values.zipWithIndex.foreach { splitWithIndex => val multiBlockSplit = new CarbonMultiBlockSplit( splitWithIndex._1.asJava, splitWithIndex._1.flatMap(f => f.getLocations).distinct.toArray) val partition = new CarbonSparkPartition(id, splitWithIndex._2, multiBlockSplit) result.add(partition) } } } noOfBlocks = splits.size noOfTasks = result.size() statistic.addStatistics(QueryStatisticsConstants.BLOCK_IDENTIFICATION, System.currentTimeMillis) statisticRecorder.recordStatisticsForDriver(statistic, queryId) statisticRecorder.logStatisticsAsTableDriver() } logInfo( s""" | Identified no.of.blocks: $noOfBlocks, | no.of.tasks: $noOfTasks, | no.of.nodes: $noOfNodes, | parallelism: $parallelism """.stripMargin) result.asScala } def combineSplits( splits: ArrayBuffer[CarbonMultiBlockSplit], size: Long, partitionId: Int ): CarbonSparkPartition = { val carbonInputSplits = splits.flatMap(_.getAllSplits.asScala) // Computes total number of bytes can be retrieved from each host. val hostToNumBytes = mutable.HashMap.empty[String, Long] splits.foreach { split => split.getLocations.filter(_ != "localhost").foreach { host => hostToNumBytes(host) = hostToNumBytes.getOrElse(host, 0L) + split.getLength } } // Takes the first 3 hosts with the most data to be retrieved val locations = hostToNumBytes .toSeq .sortBy(_._2)(implicitly[Ordering[Long]].reverse) .take(3) .map(_._1) .toArray val multiBlockSplit = new CarbonMultiBlockSplit(carbonInputSplits.asJava, locations) new CarbonSparkPartition(id, partitionId, multiBlockSplit) } override def internalCompute(split: Partition, context: TaskContext): Iterator[T] = { val queryStartTime = System.currentTimeMillis val carbonPropertiesFilePath = System.getProperty("carbon.properties.filepath", null) if (null == carbonPropertiesFilePath) { System.setProperty("carbon.properties.filepath", System.getProperty("user.dir") + '/' + "conf" + '/' + "carbon.properties" ) } val executionId = context.getLocalProperty(SQLExecution.EXECUTION_ID_KEY) val taskId = split.index val attemptId = new TaskAttemptID(jobTrackerId, id, TaskType.MAP, split.index, 0) val attemptContext = new TaskAttemptContextImpl(FileFactory.getConfiguration, attemptId) val format = prepareInputFormatForExecutor(attemptContext.getConfiguration) val inputSplit = split.asInstanceOf[CarbonSparkPartition].split.value TaskMetricsMap.getInstance().registerThreadCallback() inputMetricsStats.initBytesReadCallback(context, inputSplit) val iterator = if (inputSplit.getAllSplits.size() > 0) { val model = format.createQueryModel(inputSplit, attemptContext, filterExpression) // one query id per table model.setQueryId(queryId) // get RecordReader by FileFormat var reader: RecordReader[Void, Object] = inputSplit.getFileFormat match { case FileFormat.ROW_V1 => // create record reader for row format DataTypeUtil.setDataTypeConverter(dataTypeConverterClz.newInstance()) val inputFormat = new CarbonStreamInputFormat inputFormat.setIsVectorReader(vectorReader) inputFormat.setInputMetricsStats(inputMetricsStats) model.setStatisticsRecorder( CarbonTimeStatisticsFactory.createExecutorRecorder(model.getQueryId)) inputFormat.setModel(model) val streamReader = inputFormat.createRecordReader(inputSplit, attemptContext) .asInstanceOf[RecordReader[Void, Object]] streamReader case _ => // create record reader for CarbonData file format if (vectorReader) { model.setDirectVectorFill(directFill) val carbonRecordReader = createVectorizedCarbonRecordReader(model, inputMetricsStats, "true") if (carbonRecordReader == null) { new CarbonRecordReader(model, format.getReadSupportClass(attemptContext.getConfiguration), inputMetricsStats, attemptContext.getConfiguration) } else { carbonRecordReader } } else { new CarbonRecordReader(model, format.getReadSupportClass(attemptContext.getConfiguration), inputMetricsStats, attemptContext.getConfiguration) } } val closeReader = () => { if (reader != null) { try { reader.close() } catch { case e: Exception => LogServiceFactory.getLogService(this.getClass.getCanonicalName).error(e) } reader = null } } // create a statistics recorder val recorder = CarbonTimeStatisticsFactory.createExecutorRecorder(model.getQueryId()) model.setStatisticsRecorder(recorder) new Iterator[Any] { private var havePair = false private var finished = false private var first = true override def hasNext: Boolean = { if (context.isInterrupted) { throw new TaskKilledException } if (first) { first = false addTaskCompletionListener( split, context, queryStartTime, executionId, taskId, model, reader) // initialize the reader reader.initialize(inputSplit, attemptContext) } if (!finished && !havePair) { finished = !reader.nextKeyValue havePair = !finished } if (finished) { closeReader.apply() } !finished } override def next(): Any = { if (!hasNext) { throw new java.util.NoSuchElementException("End of stream") } havePair = false val value = reader.getCurrentValue value } } } else { new Iterator[Any] { override def hasNext: Boolean = false override def next(): Any = throw new java.util.NoSuchElementException("End of stream") } } iterator.asInstanceOf[Iterator[T]] } private def addTaskCompletionListener(split: Partition, context: TaskContext, queryStartTime: Long, executionId: String, taskId: Int, model: QueryModel, reader: RecordReader[Void, Object]) = { // TODO: rewrite this logic to call free memory in FailureListener on failures and // On success, // TODO: no memory leak should be there, resources should be freed on // success completion. val onCompleteCallbacksField = context.getClass.getDeclaredField("onCompleteCallbacks") onCompleteCallbacksField.setAccessible(true) val listeners = onCompleteCallbacksField.get(context) .asInstanceOf[ArrayBuffer[TaskCompletionListener]] val isAdded = listeners.exists(p => p.isInstanceOf[CarbonLoadTaskCompletionListener]) model.setFreeUnsafeMemory(!isAdded) // add task completion before calling initialize as initialize method will internally // call for usage of unsafe method for processing of one blocklet and if there is any // exceptionwhile doing that the unsafe memory occupied for that task will not // get cleared context.addTaskCompletionListener { new QueryTaskCompletionListener(!isAdded, reader, inputMetricsStats, executionId, taskId, queryStartTime, model.getStatisticsRecorder, split, queryId) } } private def close() { TaskMetricsMap.getInstance().updateReadBytes(Thread.currentThread().getId) inputMetricsStats.updateAndClose() } def prepareInputFormatForDriver(conf: Configuration): CarbonTableInputFormat[Object] = { CarbonInputFormat.setTableInfo(conf, tableInfo) CarbonInputFormat.setDatabaseName(conf, tableInfo.getDatabaseName) CarbonInputFormat.setTableName(conf, tableInfo.getFactTable.getTableName) if (partitionNames != null) { CarbonInputFormat.setPartitionsToPrune(conf, partitionNames.asJava) } CarbonInputFormat.setTransactionalTable(conf, tableInfo.isTransactionalTable) createInputFormat(conf) } def prepareFileInputFormatForDriver(conf: Configuration): CarbonFileInputFormat[Object] = { CarbonInputFormat.setTableInfo(conf, tableInfo) CarbonInputFormat.setDatabaseName(conf, tableInfo.getDatabaseName) CarbonInputFormat.setTableName(conf, tableInfo.getFactTable.getTableName) if (partitionNames != null) { CarbonInputFormat.setPartitionsToPrune(conf, partitionNames.asJava) } createFileInputFormat(conf) } private def prepareInputFormatForExecutor(conf: Configuration): CarbonInputFormat[Object] = { CarbonInputFormat.setCarbonReadSupport(conf, readSupportClz) val tableInfo1 = getTableInfo CarbonInputFormat.setTableInfo(conf, tableInfo1) CarbonInputFormat.setDatabaseName(conf, tableInfo1.getDatabaseName) CarbonInputFormat.setTableName(conf, tableInfo1.getFactTable.getTableName) CarbonInputFormat.setDataTypeConverter(conf, dataTypeConverterClz) createInputFormat(conf) } private def createFileInputFormat(conf: Configuration): CarbonFileInputFormat[Object] = { val format = new CarbonFileInputFormat[Object] CarbonInputFormat.setTablePath(conf, identifier.appendWithLocalPrefix(identifier.getTablePath)) CarbonInputFormat.setQuerySegment(conf, identifier) CarbonInputFormat.setFilterPredicates(conf, filterExpression) CarbonInputFormat.setColumnProjection(conf, columnProjection) CarbonInputFormatUtil.setDataMapJobIfConfigured(conf) // when validate segments is disabled in thread local update it to CarbonTableInputFormat val carbonSessionInfo = ThreadLocalSessionInfo.getCarbonSessionInfo if (carbonSessionInfo != null) { val tableUniqueKey = identifier.getDatabaseName + "." + identifier.getTableName val validateInputSegmentsKey = CarbonCommonConstants.VALIDATE_CARBON_INPUT_SEGMENTS + tableUniqueKey CarbonInputFormat.setValidateSegmentsToAccess(conf, carbonSessionInfo.getThreadParams .getProperty(validateInputSegmentsKey, "true").toBoolean) val queryOnPreAggStreamingKey = CarbonCommonConstantsInternal.QUERY_ON_PRE_AGG_STREAMING + tableUniqueKey val queryOnPreAggStreaming = carbonSessionInfo.getThreadParams .getProperty(queryOnPreAggStreamingKey, "false").toBoolean val inputSegmentsKey = CarbonCommonConstants.CARBON_INPUT_SEGMENTS + tableUniqueKey CarbonInputFormat.setValidateSegmentsToAccess(conf, carbonSessionInfo.getThreadParams .getProperty(validateInputSegmentsKey, "true").toBoolean) CarbonInputFormat .setQuerySegment(conf, carbonSessionInfo.getThreadParams .getProperty(inputSegmentsKey, CarbonProperties.getInstance().getProperty(inputSegmentsKey, "*"))) if (queryOnPreAggStreaming) { CarbonInputFormat.setAccessStreamingSegments(conf, queryOnPreAggStreaming) carbonSessionInfo.getThreadParams.removeProperty(queryOnPreAggStreamingKey) carbonSessionInfo.getThreadParams.removeProperty(inputSegmentsKey) carbonSessionInfo.getThreadParams.removeProperty(validateInputSegmentsKey) } } format } private def createInputFormat(conf: Configuration): CarbonTableInputFormat[Object] = { val format = new CarbonTableInputFormat[Object] CarbonInputFormat.setTablePath(conf, identifier.appendWithLocalPrefix(identifier.getTablePath)) CarbonInputFormat.setQuerySegment(conf, identifier) CarbonInputFormat.setFilterPredicates(conf, filterExpression) CarbonInputFormat.setColumnProjection(conf, columnProjection) CarbonInputFormatUtil.setDataMapJobIfConfigured(conf) // when validate segments is disabled in thread local update it to CarbonTableInputFormat val carbonSessionInfo = ThreadLocalSessionInfo.getCarbonSessionInfo if (carbonSessionInfo != null) { val tableUniqueKey = identifier.getDatabaseName + "." + identifier.getTableName val validateInputSegmentsKey = CarbonCommonConstants.VALIDATE_CARBON_INPUT_SEGMENTS + tableUniqueKey CarbonInputFormat.setValidateSegmentsToAccess(conf, carbonSessionInfo.getThreadParams .getProperty(validateInputSegmentsKey, "true").toBoolean) val queryOnPreAggStreamingKey = CarbonCommonConstantsInternal.QUERY_ON_PRE_AGG_STREAMING + tableUniqueKey val queryOnPreAggStreaming = carbonSessionInfo.getThreadParams .getProperty(queryOnPreAggStreamingKey, "false").toBoolean val inputSegmentsKey = CarbonCommonConstants.CARBON_INPUT_SEGMENTS + tableUniqueKey CarbonInputFormat.setValidateSegmentsToAccess(conf, carbonSessionInfo.getThreadParams .getProperty(validateInputSegmentsKey, "true").toBoolean) CarbonInputFormat .setQuerySegment(conf, carbonSessionInfo.getThreadParams .getProperty(inputSegmentsKey, CarbonProperties.getInstance().getProperty(inputSegmentsKey, "*"))) if (queryOnPreAggStreaming) { CarbonInputFormat.setAccessStreamingSegments(conf, queryOnPreAggStreaming) carbonSessionInfo.getThreadParams.removeProperty(queryOnPreAggStreamingKey) carbonSessionInfo.getThreadParams.removeProperty(inputSegmentsKey) carbonSessionInfo.getThreadParams.removeProperty(validateInputSegmentsKey) } } format } /** * This method will check and remove InExpression from filterExpression to prevent the List * Expression values from serializing and deserializing on executor * * @param identifiedPartitions */ private def checkAndRemoveInExpressinFromFilterExpression( identifiedPartitions: mutable.Buffer[Partition]) = { if (null != filterExpression) { if (identifiedPartitions.nonEmpty && !checkForBlockWithoutBlockletInfo(identifiedPartitions)) { FilterUtil.removeInExpressionNodeWithPositionIdColumn(filterExpression) } else if (identifiedPartitions.nonEmpty) { // the below piece of code will serialize only the required blocklet ids val filterValues = FilterUtil.getImplicitFilterExpression(filterExpression) if (null != filterValues) { val implicitExpression = filterValues.asInstanceOf[ImplicitExpression] identifiedPartitions.foreach { partition => // for each partition get the list if input split val inputSplit = partition.asInstanceOf[CarbonSparkPartition].split.value val splitList = if (inputSplit.isInstanceOf[CarbonMultiBlockSplit]) { inputSplit.asInstanceOf[CarbonMultiBlockSplit].getAllSplits } else { new java.util.ArrayList().add(inputSplit.asInstanceOf[CarbonInputSplit]) }.asInstanceOf[java.util.List[CarbonInputSplit]] // for each split and given block path set all the valid blocklet ids splitList.asScala.map { split => val uniqueBlockPath = split.getPath.toString val shortBlockPath = CarbonTablePath .getShortBlockId(uniqueBlockPath .substring(uniqueBlockPath.lastIndexOf("/Part") + 1)) val blockletIds = implicitExpression.getBlockIdToBlockletIdMapping.get(shortBlockPath) split.setValidBlockletIds(blockletIds) } } // remove the right child of the expression here to prevent serialization of // implicit filter values to executor FilterUtil.setTrueExpressionAsRightChild(filterExpression) } } } } /** * This method will check for presence of any block from old store (version 1.1). If any of the * blocks identified does not contain the blocklet info that means that block is from old store * * @param identifiedPartitions * @return */ private def checkForBlockWithoutBlockletInfo( identifiedPartitions: mutable.Buffer[Partition]): Boolean = { var isBlockWithoutBlockletInfoPresent = false breakable { identifiedPartitions.foreach { value => val inputSplit = value.asInstanceOf[CarbonSparkPartition].split.value val splitList = if (inputSplit.isInstanceOf[CarbonMultiBlockSplit]) { inputSplit.asInstanceOf[CarbonMultiBlockSplit].getAllSplits } else { new java.util.ArrayList().add(inputSplit.asInstanceOf[CarbonInputSplit]) }.asInstanceOf[java.util.List[CarbonInputSplit]] // check for block from old store (version 1.1 and below) if (Util.isBlockWithoutBlockletInfoExists(splitList)) { isBlockWithoutBlockletInfoPresent = true break } } } isBlockWithoutBlockletInfoPresent } /** * Get the preferred locations where to launch this task. */ override def getPreferredLocations(split: Partition): Seq[String] = { val theSplit = split.asInstanceOf[CarbonSparkPartition] val firstOptionLocation = theSplit.split.value.getLocations.filter(_ != "localhost") firstOptionLocation } def createVectorizedCarbonRecordReader(queryModel: QueryModel, inputMetricsStats: InputMetricsStats, enableBatch: String): RecordReader[Void, Object] = { val name = "org.apache.carbondata.spark.vectorreader.VectorizedCarbonRecordReader" try { val cons = Class.forName(name).getDeclaredConstructors cons.head.setAccessible(true) cons.head.newInstance(queryModel, inputMetricsStats, enableBatch) .asInstanceOf[RecordReader[Void, Object]] } catch { case e: Exception => LOGGER.error(e) null } } // TODO find the better way set it. def setVectorReaderSupport(boolean: Boolean): Unit = { vectorReader = boolean } // TODO find the better way set it. def setDirectScanSupport(isDirectScan: Boolean): Unit = { directFill = isDirectScan } }
apache-2.0
dunkhong/grr
grr/server/grr_response_server/ip_resolver_test.py
1259
#!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import socket from absl import app import ipaddress from grr_response_core.lib import utils from grr_response_server import ip_resolver from grr.test_lib import test_lib class IPResolverTest(test_lib.GRRBaseTest): def testIPInfo(self): args = [] def MockGetNameInfo(ip, unused_flags): args.append(ip) return "test.com", ip[1] resolver = ip_resolver.IPResolver() with utils.Stubber(socket, "getnameinfo", MockGetNameInfo): for ip, result in [ ("192.168.0.1", ip_resolver.IPInfo.INTERNAL), ("10.0.0.7", ip_resolver.IPInfo.INTERNAL), ("::1", ip_resolver.IPInfo.INTERNAL), ("69.50.225.155", ip_resolver.IPInfo.EXTERNAL), ("69.50.225.155", ip_resolver.IPInfo.EXTERNAL), ]: info, _ = resolver.RetrieveIPInfo(ipaddress.ip_address(ip)) self.assertEqual(info, result) # There is one external address but it was resolved twice. There is a cache # so getnameinfo should have been called only once. self.assertLen(args, 1) def main(argv): test_lib.main(argv) if __name__ == "__main__": app.run(main)
apache-2.0
luotao1/Paddle
python/paddle/fluid/tests/unittests/test_sync_batch_norm_op.py
13293
# Copyright (c) 2019 PaddlePaddle Authors. 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. """ test for sync bachnorm op. for both FP64 and FP16 input. """ from __future__ import print_function import unittest import numpy as np import os import six import paddle import paddle.fluid.core as core import paddle.fluid as fluid import paddle.nn as nn from paddle.fluid import compiler from paddle.fluid import Program, program_guard from op_test import OpTest, _set_use_system_allocator _set_use_system_allocator(True) def create_or_get_tensor(scope, var_name, var, place): """Get tensor, if not found, create a new one.""" tensor = scope.var(var_name).get_tensor() if var is not None: assert isinstance(var, np.ndarray) tensor.set_recursive_sequence_lengths([]) tensor.set(var, place) return tensor class TestSyncBatchNormOpTraining(unittest.TestCase): """sync_batch_norm op test.""" def setUp(self): """Setup.""" #self.dtype = np.float32 self.dtype = np.float32 if core.is_compiled_with_rocm() else np.float64 self.N = 8 self.C = 16 self.H = 32 self.W = 32 self.dshape = [self.N, self.C, self.H, self.W] self.atol = 1e-3 def _build_program(self, place, layout, seed, sync_bn=False, only_forward=False): """Build program.""" main = fluid.Program() startup = fluid.Program() main.random_seed = seed startup.random_seed = seed use_cudnn = self.dtype == np.float16 with fluid.unique_name.guard(): with fluid.program_guard(main, startup): data = fluid.layers.data( name='input', shape=self.dshape, dtype=self.dtype, append_batch_size=False) conv = fluid.layers.conv2d( input=data, num_filters=32, filter_size=1, param_attr=fluid.ParamAttr(name='conv2d_weight'), bias_attr=False, use_cudnn=use_cudnn) bn = fluid.layers.batch_norm( conv, param_attr=fluid.ParamAttr(name='bn_scale'), bias_attr=fluid.ParamAttr(name='bn_bias'), moving_mean_name='bn_moving_mean', moving_variance_name='bn_moving_variance', data_layout=layout, is_test=only_forward) if core.is_compiled_with_rocm(): bn = fluid.layers.cast(bn, 'float32') else: bn = fluid.layers.cast(bn, 'float64') sigmoid = fluid.layers.sigmoid(bn) out = fluid.layers.reduce_sum(sigmoid) if not sync_bn: out = out / core.get_cuda_device_count() if not only_forward: sgd_opt = fluid.optimizer.SGD(learning_rate=0.0) sgd_opt.backward(out) return main, startup, [out, conv, bn] def _compare(self, place, layout, only_forward): """Compare results.""" seed = 10 os.environ['FLAGS_cudnn_deterministic'] = "1" scope = core.Scope() data = np.random.random(size=self.dshape).astype(self.dtype) * 4. - 2 data = create_or_get_tensor(scope, "input", OpTest.np_dtype_to_fluid_dtype(data), place) # Single-GPU, N = 32 per GPU main, startup, outs = self._build_program(place, layout, seed, False, only_forward) exe = fluid.Executor(place) exe.run(startup) fetch_names = [v.name for v in outs] + [ 'bn_moving_mean', 'bn_moving_variance', 'bn_scale', 'bn_bias' ] if not only_forward: others = [ 'batch_norm_0.tmp_0', 'batch_norm_0.tmp_1', 'bn_scale@GRAD', 'bn_bias@GRAD', 'batch_norm_0.tmp_3@GRAD', 'conv2d_0.tmp_0@GRAD' ] fetch_names += others bn_fetches = exe.run(program=main, feed={'input': data}, fetch_list=fetch_names) ##################################################################### # Multi-GPUs, self.N / core.get_cuda_device_count() per GPU assert core.get_cuda_device_count() > 1 main, startup, outs = self._build_program(place, layout, seed, True, only_forward) exe = fluid.Executor(place) exe.run(startup) fetch_names = [v.name for v in outs] + [ 'bn_moving_mean', 'bn_moving_variance', 'bn_scale', 'bn_bias' ] if not only_forward: others = [ 'batch_norm_0.tmp_0', 'batch_norm_0.tmp_1', 'bn_scale@GRAD', 'bn_bias@GRAD', 'batch_norm_0.tmp_3@GRAD', 'conv2d_0.tmp_0@GRAD' ] fetch_names += others for nm in fetch_names: fv = fluid.framework._get_var(str(nm), program=main) fv.persistable = True build_strategy = fluid.BuildStrategy() build_strategy.sync_batch_norm = True build_strategy.enable_inplace = False build_strategy.memory_optimize = False comp_prog = compiler.CompiledProgram(main).with_data_parallel( outs[0].name if not only_forward else None, build_strategy=build_strategy) sync_bn_fetches = exe.run(program=comp_prog, feed={'input': data}, fetch_list=fetch_names) for i in six.moves.xrange(1, len(sync_bn_fetches)): bn_val = bn_fetches[i] sync_bn_val = sync_bn_fetches[i] if sync_bn_val.shape != bn_val.shape: sync_bn_val = sync_bn_val[:bn_val.shape[0]] self.assertTrue( np.allclose( bn_val, sync_bn_val, atol=self.atol), "Output (" + fetch_names[i] + ") has diff. \n" + "\nBN " + str(bn_val) + "\n" + "Sync BN " + str(sync_bn_val)) def test_train(self): """Test training.""" if not core.is_compiled_with_cuda(): return places = [core.CUDAPlace(0)] for place in places: for layout in ["NCHW", "NHWC"]: self._compare(place, layout, False) def test_infer(self): """Test inference.""" if not core.is_compiled_with_cuda(): return places = [core.CUDAPlace(0)] for place in places: for layout in ["NCHW", "NHWC"]: self._compare(place, layout, True) class TestFP16SyncBatchNormOpTraining(TestSyncBatchNormOpTraining): """sync_batch_norm op test for FP16 input.""" def setUp(self): """Setup.""" self.dtype = np.float16 self.N = 8 self.C = 16 self.H = 32 self.W = 32 self.dshape = [self.N, self.C, self.H, self.W] self.atol = 1e-2 class TestDygraphSyncBatchNormAPIError(unittest.TestCase): def test_errors(self): if not core.is_compiled_with_cuda(): return with program_guard(Program(), Program()): my_sync_batch_norm = paddle.nn.SyncBatchNorm(10) x1 = fluid.create_lod_tensor( np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CUDAPlace(0)) self.assertRaises(TypeError, my_sync_batch_norm, x1) # the input dtype of SyncBatchNorm must be float16 or float32 or float64 # float16 only can be set on GPU place x2 = fluid.layers.data(name='x2', shape=[3, 4, 5, 6], dtype="int32") self.assertRaises(TypeError, my_sync_batch_norm, x2) class TestConvertSyncBatchNorm(unittest.TestCase): def test_convert(self): if not core.is_compiled_with_cuda(): return with program_guard(Program(), Program()): compare_model = paddle.nn.Sequential( paddle.nn.Conv2D(3, 5, 3), paddle.nn.BatchNorm2D(5), paddle.nn.BatchNorm2D(5)) model = paddle.nn.Sequential( paddle.nn.Conv2D(3, 5, 3), paddle.nn.BatchNorm2D(5), paddle.nn.BatchNorm2D( 5, weight_attr=fluid.ParamAttr(name='bn.scale'), bias_attr=fluid.ParamAttr(name='bn.bias'))) model = paddle.nn.SyncBatchNorm.convert_sync_batchnorm(model) for idx, sublayer in enumerate(compare_model.sublayers()): if isinstance(sublayer, paddle.nn.BatchNorm2D): self.assertEqual( isinstance(model[idx], paddle.nn.SyncBatchNorm), True) class TestConvertSyncBatchNormCast1(unittest.TestCase): def test_convert(self): if not core.is_compiled_with_cuda(): return class Net(nn.Layer): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2D(3, 5, 3) self.bn = [] bn = self.add_sublayer('bn', nn.BatchNorm2D(5)) self.bn.append(bn) def forward(self, x): x = self.conv1(x) for bn in self.bn: x = bn(x) return x model = nn.Sequential() model.add_sublayer('net1', Net()) model.add_sublayer('net2', Net()) compare_model = nn.Sequential() compare_model.add_sublayer('net1', Net()) compare_model.add_sublayer('net2', Net()) model = nn.SyncBatchNorm.convert_sync_batchnorm(model) self.assertEqual(len(compare_model.sublayers()), len(model.sublayers())) class TestConvertSyncBatchNormCase2(unittest.TestCase): def test_convert(self): if not core.is_compiled_with_cuda(): return with fluid.dygraph.guard(fluid.CUDAPlace(0)): class SyBNNet(paddle.nn.Layer): def __init__(self, in_ch=3, out_ch=3, dirate=1): super(SyBNNet, self).__init__() self.bn_s1 = paddle.nn.SyncBatchNorm.convert_sync_batchnorm( paddle.nn.BatchNorm3D( out_ch, weight_attr=paddle.ParamAttr( regularizer=paddle.regularizer.L2Decay(0.)))) self.bn_s2 = paddle.nn.SyncBatchNorm.convert_sync_batchnorm( paddle.nn.BatchNorm3D( out_ch, data_format='NDHWC')) def forward(self, x): x = self.bn_s1(x) out = paddle.sum(paddle.abs(self.bn_s2(x))) return out class BNNet(paddle.nn.Layer): def __init__(self, in_ch=3, out_ch=3, dirate=1): super(BNNet, self).__init__() self.bn_s1 = paddle.nn.BatchNorm3D( out_ch, weight_attr=paddle.ParamAttr( regularizer=paddle.regularizer.L2Decay(0.))) self.bn_s2 = paddle.nn.SyncBatchNorm.convert_sync_batchnorm( paddle.nn.BatchNorm3D( out_ch, data_format='NDHWC')) def forward(self, x): x = self.bn_s1(x) out = paddle.sum(paddle.abs(self.bn_s2(x))) return out bn_model = BNNet() sybn_model = SyBNNet() np.random.seed(10) data = np.random.random([3, 3, 3, 3, 3]).astype('float32') x = paddle.to_tensor(data) bn_out = bn_model(x) sybn_out = sybn_model(x) self.assertTrue( np.allclose(bn_out.numpy(), sybn_out.numpy()), "Output has diff. \n" + "\nBN " + str(bn_out.numpy()) + "\n" + "Sync BN " + str(sybn_out.numpy())) class TestDygraphSyncBatchNormDataFormatError(unittest.TestCase): def test_errors(self): if not core.is_compiled_with_cuda(): return with fluid.dygraph.guard(fluid.CUDAPlace(0)): my_sync_batch_norm = paddle.nn.SyncBatchNorm(10, data_format='CN') data = np.random.random([3, 3, 3]).astype('float32') x = paddle.to_tensor(data) self.assertRaises(ValueError, my_sync_batch_norm, x) if __name__ == '__main__': unittest.main()
apache-2.0
hmmlopez/citrus
modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractServerParser.java
3268
/* * Copyright 2006-2014 the original author or 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 com.consol.citrus.config.xml; import com.consol.citrus.channel.MessageSelectingQueueChannel; import com.consol.citrus.config.util.BeanDefinitionParserUtils; import com.consol.citrus.server.AbstractServer; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; /** * Abstract server parser adds endpoint adapter construction and basic server property parsing. * @author Christoph Deppisch * @since 1.4 */ public abstract class AbstractServerParser extends AbstractBeanDefinitionParser { @Override protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { BeanDefinitionBuilder serverBuilder = BeanDefinitionBuilder.genericBeanDefinition(getServerClass()); BeanDefinitionParserUtils.setPropertyValue(serverBuilder, element.getAttribute("auto-start"), "autoStart"); BeanDefinitionParserUtils.setPropertyValue(serverBuilder, element.getAttribute("timeout"), "defaultTimeout"); if (element.hasAttribute("endpoint-adapter")) { BeanDefinitionParserUtils.setPropertyReference(serverBuilder, element.getAttribute("endpoint-adapter"), "endpointAdapter"); } else { String channelId = element.getAttribute(ID_ATTRIBUTE) + AbstractServer.DEFAULT_CHANNEL_ID_SUFFIX; BeanDefinitionParserUtils.registerBean(channelId, MessageSelectingQueueChannel.class, parserContext, shouldFireEvents()); } BeanDefinitionParserUtils.setPropertyReference(serverBuilder, element.getAttribute("interceptors"), "interceptors"); BeanDefinitionParserUtils.setPropertyReference(serverBuilder, element.getAttribute("actor"), "actor"); parseServer(serverBuilder, element, parserContext); return serverBuilder.getBeanDefinition(); } /** * Parses element and adds server properties to bean definition via provided builder. * Subclasses must implement this parsing method in order to add detailed server bean definition properties. * @param serverBuilder * @param element * @param parserContext * @return */ protected abstract void parseServer(BeanDefinitionBuilder serverBuilder, Element element, ParserContext parserContext); /** * Subclasses must provide proper server class implementation. * @return */ protected abstract Class<? extends AbstractServer> getServerClass(); }
apache-2.0
SSEHUB/EASyProducer
Plugins/Instantiation/de.uni_hildesheim.sse.vil.buildlang.ui/src/de/uni_hildesheim/sse/ui/outline/VirtualOutlineNode.java
850
package de.uni_hildesheim.sse.ui.outline; import org.eclipse.swt.graphics.Image; import org.eclipse.xtext.ui.editor.outline.IOutlineNode; import org.eclipse.xtext.ui.editor.outline.impl.AbstractOutlineNode; /** * That class is for creating a virtual node. * @author Dernek * */ public class VirtualOutlineNode extends AbstractOutlineNode { /** * The constructor of a virtual outline node. * * @param parent The parent-node of this node. * @param image The image of this node displayed in the outline view. * @param text The text of this node diyplayed in the outline view. * @param isLeaf <b>True</b> if this node is a leaf. <b>False</b> otherwise. */ protected VirtualOutlineNode(IOutlineNode parent, Image image, Object text, boolean isLeaf) { super(parent, image, text, isLeaf); } }
apache-2.0
cxysteven/Paddle
paddle/utils/CpuId.cpp
2071
/* Copyright (c) 2016 PaddlePaddle Authors. 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. */ #include "paddle/utils/CpuId.h" #include "paddle/utils/Util.h" #ifdef _WIN32 #include <intrin.h> /// for MSVC #define CPUID(info, x) __cpuidex(info, x, 0) #elif !defined(__ANDROID__) #include <cpuid.h> /// for GCC/Clang #define CPUID(info, x) __cpuid_count(x, 0, info[0], info[1], info[2], info[3]) #endif namespace paddle { SIMDFlags::SIMDFlags() { #if !defined(__ANDROID__) unsigned int cpuInfo[4]; // CPUID: https://en.wikipedia.org/wiki/CPUID // clang-format off CPUID(cpuInfo, 0x00000001); simd_flags_ |= cpuInfo[3] & (1 << 25) ? SIMD_SSE : SIMD_NONE; simd_flags_ |= cpuInfo[3] & (1 << 26) ? SIMD_SSE2 : SIMD_NONE; simd_flags_ |= cpuInfo[2] & (1 << 0) ? SIMD_SSE3 : SIMD_NONE; simd_flags_ |= cpuInfo[2] & (1 << 9) ? SIMD_SSSE3 : SIMD_NONE; simd_flags_ |= cpuInfo[2] & (1 << 19) ? SIMD_SSE41 : SIMD_NONE; simd_flags_ |= cpuInfo[2] & (1 << 20) ? SIMD_SSE42 : SIMD_NONE; simd_flags_ |= cpuInfo[2] & (1 << 12) ? SIMD_FMA3 : SIMD_NONE; simd_flags_ |= cpuInfo[2] & (1 << 28) ? SIMD_AVX : SIMD_NONE; CPUID(cpuInfo, 0x00000007); simd_flags_ |= cpuInfo[1] & (1 << 5) ? SIMD_AVX2 : SIMD_NONE; simd_flags_ |= cpuInfo[1] & (1 << 16) ? SIMD_AVX512: SIMD_NONE; CPUID(cpuInfo, 0x80000001); simd_flags_ |= cpuInfo[2] & (1 << 16) ? SIMD_FMA4 : SIMD_NONE; // clang-fotmat on #else simd_flags_ = SIMD_NEON; #endif } SIMDFlags const* SIMDFlags::instance() { static SIMDFlags instance; return &instance; } } // namespace paddle
apache-2.0
iisquare/analysis-ik-online
solr4.x/src/main/java/com/iisquare/solr/wltea/util/MongoUtil.java
1135
package com.iisquare.solr.wltea.util; import java.net.UnknownHostException; import java.util.Arrays; import com.mongodb.BasicDBList; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; /** * MongoClient本身支持连接池 */ public class MongoUtil { private static MongoClient mongoClient = null; public static synchronized MongoClient connect(String host, int port, String userName, String database, String password) { if (null != mongoClient) return mongoClient; MongoCredential credential = MongoCredential.createCredential(userName, database, password.toCharArray()); try { mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential)); } catch (UnknownHostException e) { return null; } return mongoClient; } public static synchronized void close() { if (null != mongoClient) { mongoClient.close(); mongoClient = null; } } public static BasicDBList arrayToList(Object[] objs) { BasicDBList list = new BasicDBList(); if (!list.addAll(Arrays.asList(objs))) return null; return list; } }
apache-2.0
gastaldi/hibernate-validator
hibernate-validator/src/main/java/org/hibernate/validator/util/IdentitySet.java
2574
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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 org.hibernate.validator.util; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Set that compares object by identity rather than equality. Wraps around a <code>IdentityHashMap</code> * * @author Emmanuel Bernard */ public class IdentitySet implements Set { private Map<Object, Object> map; private Object CONTAINS = new Object(); public IdentitySet() { this( 10 ); } public IdentitySet(int size) { this.map = new IdentityHashMap<Object, Object>( size ); } public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public boolean contains(Object o) { return map.containsKey( o ); } public Iterator iterator() { return map.keySet().iterator(); } public Object[] toArray() { return map.keySet().toArray(); } public boolean add(Object o) { return map.put( o, CONTAINS ) == null; } public boolean remove(Object o) { return map.remove( o ) == CONTAINS; } public boolean addAll(Collection c) { boolean doThing = false; for ( Object o : c ) { doThing = doThing || add( o ); } return doThing; } public void clear() { map.clear(); } public boolean removeAll(Collection c) { boolean remove = false; for ( Object o : c ) { remove = remove || remove( o ); } return remove; } public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } public boolean containsAll(Collection c) { for ( Object o : c ) { if ( !contains( o ) ) { return false; } } return true; } public Object[] toArray(Object[] a) { return map.keySet().toArray( a ); } @Override public String toString() { return "IdentitySet{" + "map=" + map + '}'; } }
apache-2.0
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/theinternet/pages/JavaScriptAlertsPage.java
991
package com.frameworkium.integration.theinternet.pages; import com.frameworkium.core.htmlelements.element.Button; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import io.qameta.allure.Step; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; public class JavaScriptAlertsPage extends BasePage<JavaScriptAlertsPage> { @Visible @FindBy(css = "button[onclick='jsAlert()']") private Button jsAlertButton; @FindBy(css = "p#result") private WebElement resultArea; @Step("Click alert") public JavaScriptAlertsPage clickAlertButtonAndAccept() { jsAlertButton.click(); driver.switchTo().alert().accept(); wait.until(visibilityOf(resultArea)); return this; } @Step("Click prompt") public String getResultText() { return resultArea.getText(); } }
apache-2.0
google/pprof
internal/driver/driver_test.go
47778
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package driver import ( "bytes" "flag" "fmt" "io/ioutil" "net" _ "net/http/pprof" "os" "reflect" "regexp" "runtime" "strconv" "strings" "testing" "time" "github.com/google/pprof/internal/plugin" "github.com/google/pprof/internal/proftest" "github.com/google/pprof/internal/symbolz" "github.com/google/pprof/profile" ) var updateFlag = flag.Bool("update", false, "Update the golden files") func TestParse(t *testing.T) { // Override weblist command to collect output in buffer pprofCommands["weblist"].postProcess = nil // Our mockObjTool.Open will always return success, causing // driver.locateBinaries to "find" the binaries below in a non-existent // directory. As a workaround, point the search path to the fake // directory containing out fake binaries. savePath := os.Getenv("PPROF_BINARY_PATH") os.Setenv("PPROF_BINARY_PATH", "/path/to") defer os.Setenv("PPROF_BINARY_PATH", savePath) testcase := []struct { flags, source string }{ {"text,functions,flat", "cpu"}, {"text,functions,noinlines,flat", "cpu"}, {"text,filefunctions,noinlines,flat", "cpu"}, {"text,addresses,noinlines,flat", "cpu"}, {"tree,addresses,flat,nodecount=4", "cpusmall"}, {"text,functions,flat,nodecount=5,call_tree", "unknown"}, {"text,alloc_objects,flat", "heap_alloc"}, {"text,files,flat", "heap"}, {"text,files,flat,focus=[12]00,taghide=[X3]00", "heap"}, {"text,inuse_objects,flat", "heap"}, {"text,lines,cum,hide=line[X3]0", "cpu"}, {"text,lines,cum,show=[12]00", "cpu"}, {"text,lines,cum,hide=line[X3]0,focus=[12]00", "cpu"}, {"topproto,lines,cum,hide=mangled[X3]0", "cpu"}, {"topproto,lines", "cpu"}, {"tree,lines,cum,focus=[24]00", "heap"}, {"tree,relative_percentages,cum,focus=[24]00", "heap"}, {"tree,lines,cum,show_from=line2", "cpu"}, {"callgrind", "cpu"}, {"callgrind,call_tree", "cpu"}, {"callgrind", "heap"}, {"dot,functions,flat", "cpu"}, {"dot,functions,flat,call_tree", "cpu"}, {"dot,lines,flat,focus=[12]00", "heap"}, {"dot,unit=minimum", "heap_sizetags"}, {"dot,addresses,flat,ignore=[X3]002,focus=[X1]000", "contention"}, {"dot,files,cum", "contention"}, {"comments,add_comment=some-comment", "cpu"}, {"comments", "heap"}, {"tags", "cpu"}, {"tags,tagignore=tag[13],tagfocus=key[12]", "cpu"}, {"tags", "heap"}, {"tags,unit=bytes", "heap"}, {"traces", "cpu"}, {"traces,addresses", "cpu"}, {"traces", "heap_tags"}, {"dot,alloc_space,flat,focus=[234]00", "heap_alloc"}, {"dot,alloc_space,flat,tagshow=[2]00", "heap_alloc"}, {"dot,alloc_space,flat,hide=line.*1?23?", "heap_alloc"}, {"dot,inuse_space,flat,tagfocus=1mb:2gb", "heap"}, {"dot,inuse_space,flat,tagfocus=30kb:,tagignore=1mb:2mb", "heap"}, {"disasm=line[13],addresses,flat", "cpu"}, {"peek=line.*01", "cpu"}, {"weblist=line(1000|3000)$,addresses,flat", "cpu"}, {"tags,tagfocus=400kb:", "heap_request"}, {"tags,tagfocus=+400kb:", "heap_request"}, {"dot", "long_name_funcs"}, {"text", "long_name_funcs"}, } baseConfig := currentConfig() defer setCurrentConfig(baseConfig) for _, tc := range testcase { t.Run(tc.flags+":"+tc.source, func(t *testing.T) { // Reset config before processing setCurrentConfig(baseConfig) testUI := &proftest.TestUI{T: t, AllowRx: "Generating report in|Ignoring local file|expression matched no samples|Interpreted .* as range, not regexp"} f := baseFlags() f.args = []string{tc.source} flags := strings.Split(tc.flags, ",") // Encode profile into a protobuf and decode it again. protoTempFile, err := ioutil.TempFile("", "profile_proto") if err != nil { t.Errorf("cannot create tempfile: %v", err) } defer os.Remove(protoTempFile.Name()) defer protoTempFile.Close() f.strings["output"] = protoTempFile.Name() if flags[0] == "topproto" { f.bools["proto"] = false f.bools["topproto"] = true f.bools["addresses"] = true } // First pprof invocation to save the profile into a profile.proto. // Pass in flag set hen setting defaults, because otherwise default // transport will try to add flags to the default flag set. o1 := setDefaults(&plugin.Options{Flagset: f}) o1.Fetch = testFetcher{} o1.Sym = testSymbolizer{} o1.UI = testUI if err := PProf(o1); err != nil { t.Fatalf("%s %q: %v", tc.source, tc.flags, err) } // Reset config after the proto invocation setCurrentConfig(baseConfig) // Read the profile from the encoded protobuf outputTempFile, err := ioutil.TempFile("", "profile_output") if err != nil { t.Errorf("cannot create tempfile: %v", err) } defer os.Remove(outputTempFile.Name()) defer outputTempFile.Close() f = baseFlags() f.strings["output"] = outputTempFile.Name() f.args = []string{protoTempFile.Name()} delete(f.bools, "proto") addFlags(&f, flags) solution := solutionFilename(tc.source, &f) // Apply the flags for the second pprof run, and identify name of // the file containing expected results if flags[0] == "topproto" { addFlags(&f, flags) solution = solutionFilename(tc.source, &f) delete(f.bools, "topproto") f.bools["text"] = true } // Second pprof invocation to read the profile from profile.proto // and generate a report. // Pass in flag set hen setting defaults, because otherwise default // transport will try to add flags to the default flag set. o2 := setDefaults(&plugin.Options{Flagset: f}) o2.Sym = testSymbolizeDemangler{} o2.Obj = new(mockObjTool) o2.UI = testUI if err := PProf(o2); err != nil { t.Errorf("%s: %v", tc.source, err) } b, err := ioutil.ReadFile(outputTempFile.Name()) if err != nil { t.Errorf("Failed to read profile %s: %v", outputTempFile.Name(), err) } // Read data file with expected solution solution = "testdata/" + solution sbuf, err := ioutil.ReadFile(solution) if err != nil { t.Fatalf("reading solution file %s: %v", solution, err) } if runtime.GOOS == "windows" { if flags[0] == "dot" { // The .dot test has the paths inside strings, so \ must be escaped. sbuf = bytes.Replace(sbuf, []byte("testdata/"), []byte(`testdata\\`), -1) sbuf = bytes.Replace(sbuf, []byte("/path/to/"), []byte(`\\path\\to\\`), -1) } else { sbuf = bytes.Replace(sbuf, []byte("testdata/"), []byte(`testdata\`), -1) sbuf = bytes.Replace(sbuf, []byte("/path/to/"), []byte(`\path\to\`), -1) } } if flags[0] == "svg" { b = removeScripts(b) sbuf = removeScripts(sbuf) } if string(b) != string(sbuf) { t.Errorf("diff %s %s", solution, tc.source) d, err := proftest.Diff(sbuf, b) if err != nil { t.Fatalf("diff %s %v", solution, err) } t.Errorf("%s\n%s\n", solution, d) if *updateFlag { err := ioutil.WriteFile(solution, b, 0644) if err != nil { t.Errorf("failed to update the solution file %q: %v", solution, err) } } } }) } } // removeScripts removes <script > .. </script> pairs from its input func removeScripts(in []byte) []byte { beginMarker := []byte("<script") endMarker := []byte("</script>") if begin := bytes.Index(in, beginMarker); begin > 0 { if end := bytes.Index(in[begin:], endMarker); end > 0 { in = append(in[:begin], removeScripts(in[begin+end+len(endMarker):])...) } } return in } // addFlags parses flag descriptions and adds them to the testFlags func addFlags(f *testFlags, flags []string) { for _, flag := range flags { fields := strings.SplitN(flag, "=", 2) switch len(fields) { case 1: f.bools[fields[0]] = true case 2: if i, err := strconv.Atoi(fields[1]); err == nil { f.ints[fields[0]] = i } else { f.strings[fields[0]] = fields[1] } } } } func testSourceURL(port int) string { return fmt.Sprintf("http://%s/", net.JoinHostPort(testSourceAddress, strconv.Itoa(port))) } // solutionFilename returns the name of the solution file for the test func solutionFilename(source string, f *testFlags) string { name := []string{"pprof", strings.TrimPrefix(source, testSourceURL(8000))} name = addString(name, f, []string{"flat", "cum"}) name = addString(name, f, []string{"functions", "filefunctions", "files", "lines", "addresses"}) name = addString(name, f, []string{"noinlines"}) name = addString(name, f, []string{"inuse_space", "inuse_objects", "alloc_space", "alloc_objects"}) name = addString(name, f, []string{"relative_percentages"}) name = addString(name, f, []string{"seconds"}) name = addString(name, f, []string{"call_tree"}) name = addString(name, f, []string{"text", "tree", "callgrind", "dot", "svg", "tags", "dot", "traces", "disasm", "peek", "weblist", "topproto", "comments"}) if f.strings["focus"] != "" || f.strings["tagfocus"] != "" { name = append(name, "focus") } if f.strings["ignore"] != "" || f.strings["tagignore"] != "" { name = append(name, "ignore") } if f.strings["show_from"] != "" { name = append(name, "show_from") } name = addString(name, f, []string{"hide", "show"}) if f.strings["unit"] != "minimum" { name = addString(name, f, []string{"unit"}) } return strings.Join(name, ".") } func addString(name []string, f *testFlags, components []string) []string { for _, c := range components { if f.bools[c] || f.strings[c] != "" || f.ints[c] != 0 { return append(name, c) } } return name } // testFlags implements the plugin.FlagSet interface. type testFlags struct { bools map[string]bool ints map[string]int floats map[string]float64 strings map[string]string args []string stringLists map[string][]string } func (testFlags) ExtraUsage() string { return "" } func (testFlags) AddExtraUsage(eu string) {} func (f testFlags) Bool(s string, d bool, c string) *bool { if b, ok := f.bools[s]; ok { return &b } return &d } func (f testFlags) Int(s string, d int, c string) *int { if i, ok := f.ints[s]; ok { return &i } return &d } func (f testFlags) Float64(s string, d float64, c string) *float64 { if g, ok := f.floats[s]; ok { return &g } return &d } func (f testFlags) String(s, d, c string) *string { if t, ok := f.strings[s]; ok { return &t } return &d } func (f testFlags) StringList(s, d, c string) *[]*string { if t, ok := f.stringLists[s]; ok { // convert slice of strings to slice of string pointers before returning. tp := make([]*string, len(t)) for i, v := range t { tp[i] = &v } return &tp } return &[]*string{} } func (f testFlags) Parse(func()) []string { return f.args } func baseFlags() testFlags { return testFlags{ bools: map[string]bool{ "proto": true, "trim": true, "compact_labels": true, }, ints: map[string]int{ "nodecount": 20, }, floats: map[string]float64{ "nodefraction": 0.05, "edgefraction": 0.01, "divide_by": 1.0, }, strings: map[string]string{ "unit": "minimum", }, } } const testStart = 0x1000 const testOffset = 0x5000 type testFetcher struct{} func (testFetcher) Fetch(s string, d, t time.Duration) (*profile.Profile, string, error) { var p *profile.Profile switch s { case "cpu", "unknown": p = cpuProfile() case "cpusmall": p = cpuProfileSmall() case "heap": p = heapProfile() case "heap_alloc": p = heapProfile() p.SampleType = []*profile.ValueType{ {Type: "alloc_objects", Unit: "count"}, {Type: "alloc_space", Unit: "bytes"}, } case "heap_request": p = heapProfile() for _, s := range p.Sample { s.NumLabel["request"] = s.NumLabel["bytes"] } case "heap_sizetags": p = heapProfile() tags := []int64{2, 4, 8, 16, 32, 64, 128, 256} for _, s := range p.Sample { numValues := append(s.NumLabel["bytes"], tags...) s.NumLabel["bytes"] = numValues } case "heap_tags": p = heapProfile() for i := 0; i < len(p.Sample); i += 2 { s := p.Sample[i] if s.Label == nil { s.Label = make(map[string][]string) } s.NumLabel["request"] = s.NumLabel["bytes"] s.Label["key1"] = []string{"tag"} } case "contention": p = contentionProfile() case "symbolz": p = symzProfile() case "long_name_funcs": p = longNameFuncsProfile() default: return nil, "", fmt.Errorf("unexpected source: %s", s) } return p, testSourceURL(8000) + s, nil } type testSymbolizer struct{} func (testSymbolizer) Symbolize(_ string, _ plugin.MappingSources, _ *profile.Profile) error { return nil } type testSymbolizeDemangler struct{} func (testSymbolizeDemangler) Symbolize(_ string, _ plugin.MappingSources, p *profile.Profile) error { for _, fn := range p.Function { if fn.Name == "" || fn.SystemName == fn.Name { fn.Name = fakeDemangler(fn.SystemName) } } return nil } func testFetchSymbols(source, post string) ([]byte, error) { var buf bytes.Buffer switch source { case testSourceURL(8000) + "symbolz": for _, address := range strings.Split(post, "+") { a, _ := strconv.ParseInt(address, 0, 64) fmt.Fprintf(&buf, "%v\t", address) if a-testStart > testOffset { fmt.Fprintf(&buf, "wrong_source_%v_", address) continue } fmt.Fprintf(&buf, "%#x\n", a-testStart) } return buf.Bytes(), nil case testSourceURL(8001) + "symbolz": for _, address := range strings.Split(post, "+") { a, _ := strconv.ParseInt(address, 0, 64) fmt.Fprintf(&buf, "%v\t", address) if a-testStart < testOffset { fmt.Fprintf(&buf, "wrong_source_%v_", address) continue } fmt.Fprintf(&buf, "%#x\n", a-testStart-testOffset) } return buf.Bytes(), nil default: return nil, fmt.Errorf("unexpected source: %s", source) } } type testSymbolzSymbolizer struct{} func (testSymbolzSymbolizer) Symbolize(variables string, sources plugin.MappingSources, p *profile.Profile) error { return symbolz.Symbolize(p, false, sources, testFetchSymbols, nil) } func fakeDemangler(name string) string { switch name { case "mangled1000": return "line1000" case "mangled2000": return "line2000" case "mangled2001": return "line2001" case "mangled3000": return "line3000" case "mangled3001": return "line3001" case "mangled3002": return "line3002" case "mangledNEW": return "operator new" case "mangledMALLOC": return "malloc" default: return name } } // longNameFuncsProfile returns a profile with function names which should be // shortened in graph and flame views. func longNameFuncsProfile() *profile.Profile { var longNameFuncsM = []*profile.Mapping{ { ID: 1, Start: 0x1000, Limit: 0x4000, File: "/path/to/testbinary", HasFunctions: true, HasFilenames: true, HasLineNumbers: true, HasInlineFrames: true, }, } var longNameFuncsF = []*profile.Function{ {ID: 1, Name: "path/to/package1.object.function1", SystemName: "path/to/package1.object.function1", Filename: "path/to/package1.go"}, {ID: 2, Name: "(anonymous namespace)::Bar::Foo", SystemName: "(anonymous namespace)::Bar::Foo", Filename: "a/long/path/to/package2.cc"}, {ID: 3, Name: "java.bar.foo.FooBar.run(java.lang.Runnable)", SystemName: "java.bar.foo.FooBar.run(java.lang.Runnable)", Filename: "FooBar.java"}, } var longNameFuncsL = []*profile.Location{ { ID: 1000, Mapping: longNameFuncsM[0], Address: 0x1000, Line: []profile.Line{ {Function: longNameFuncsF[0], Line: 1}, }, }, { ID: 2000, Mapping: longNameFuncsM[0], Address: 0x2000, Line: []profile.Line{ {Function: longNameFuncsF[1], Line: 4}, }, }, { ID: 3000, Mapping: longNameFuncsM[0], Address: 0x3000, Line: []profile.Line{ {Function: longNameFuncsF[2], Line: 9}, }, }, } return &profile.Profile{ PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"}, Period: 1, DurationNanos: 10e9, SampleType: []*profile.ValueType{ {Type: "samples", Unit: "count"}, {Type: "cpu", Unit: "milliseconds"}, }, Sample: []*profile.Sample{ { Location: []*profile.Location{longNameFuncsL[0], longNameFuncsL[1], longNameFuncsL[2]}, Value: []int64{1000, 1000}, }, { Location: []*profile.Location{longNameFuncsL[0], longNameFuncsL[1]}, Value: []int64{100, 100}, }, { Location: []*profile.Location{longNameFuncsL[2]}, Value: []int64{10, 10}, }, }, Location: longNameFuncsL, Function: longNameFuncsF, Mapping: longNameFuncsM, } } func cpuProfile() *profile.Profile { var cpuM = []*profile.Mapping{ { ID: 1, Start: 0x1000, Limit: 0x4000, File: "/path/to/testbinary", HasFunctions: true, HasFilenames: true, HasLineNumbers: true, HasInlineFrames: true, }, } var cpuF = []*profile.Function{ {ID: 1, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"}, {ID: 2, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"}, {ID: 3, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"}, {ID: 4, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"}, {ID: 5, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"}, {ID: 6, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"}, } var cpuL = []*profile.Location{ { ID: 1000, Mapping: cpuM[0], Address: 0x1000, Line: []profile.Line{ {Function: cpuF[0], Line: 1}, }, }, { ID: 2000, Mapping: cpuM[0], Address: 0x2000, Line: []profile.Line{ {Function: cpuF[2], Line: 9}, {Function: cpuF[1], Line: 4}, }, }, { ID: 3000, Mapping: cpuM[0], Address: 0x3000, Line: []profile.Line{ {Function: cpuF[5], Line: 2}, {Function: cpuF[4], Line: 5}, {Function: cpuF[3], Line: 6}, }, }, { ID: 3001, Mapping: cpuM[0], Address: 0x3001, Line: []profile.Line{ {Function: cpuF[4], Line: 8}, {Function: cpuF[3], Line: 9}, }, }, { ID: 3002, Mapping: cpuM[0], Address: 0x3002, Line: []profile.Line{ {Function: cpuF[5], Line: 5}, {Function: cpuF[3], Line: 9}, }, }, } return &profile.Profile{ PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"}, Period: 1, DurationNanos: 10e9, SampleType: []*profile.ValueType{ {Type: "samples", Unit: "count"}, {Type: "cpu", Unit: "milliseconds"}, }, Sample: []*profile.Sample{ { Location: []*profile.Location{cpuL[0], cpuL[1], cpuL[2]}, Value: []int64{1000, 1000}, Label: map[string][]string{ "key1": {"tag1"}, "key2": {"tag1"}, }, }, { Location: []*profile.Location{cpuL[0], cpuL[3]}, Value: []int64{100, 100}, Label: map[string][]string{ "key1": {"tag2"}, "key3": {"tag2"}, }, }, { Location: []*profile.Location{cpuL[1], cpuL[4]}, Value: []int64{10, 10}, Label: map[string][]string{ "key1": {"tag3"}, "key2": {"tag2"}, }, }, { Location: []*profile.Location{cpuL[2]}, Value: []int64{10, 10}, Label: map[string][]string{ "key1": {"tag4"}, "key2": {"tag1"}, }, }, }, Location: cpuL, Function: cpuF, Mapping: cpuM, } } func cpuProfileSmall() *profile.Profile { var cpuM = []*profile.Mapping{ { ID: 1, Start: 0x1000, Limit: 0x4000, File: "/path/to/testbinary", HasFunctions: true, HasFilenames: true, HasLineNumbers: true, HasInlineFrames: true, }, } var cpuL = []*profile.Location{ { ID: 1000, Mapping: cpuM[0], Address: 0x1000, }, { ID: 2000, Mapping: cpuM[0], Address: 0x2000, }, { ID: 3000, Mapping: cpuM[0], Address: 0x3000, }, { ID: 4000, Mapping: cpuM[0], Address: 0x4000, }, { ID: 5000, Mapping: cpuM[0], Address: 0x5000, }, } return &profile.Profile{ PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"}, Period: 1, DurationNanos: 10e9, SampleType: []*profile.ValueType{ {Type: "samples", Unit: "count"}, {Type: "cpu", Unit: "milliseconds"}, }, Sample: []*profile.Sample{ { Location: []*profile.Location{cpuL[0], cpuL[1], cpuL[2]}, Value: []int64{1000, 1000}, }, { Location: []*profile.Location{cpuL[3], cpuL[1], cpuL[4]}, Value: []int64{1000, 1000}, }, { Location: []*profile.Location{cpuL[2]}, Value: []int64{1000, 1000}, }, { Location: []*profile.Location{cpuL[4]}, Value: []int64{1000, 1000}, }, }, Location: cpuL, Function: nil, Mapping: cpuM, } } func heapProfile() *profile.Profile { var heapM = []*profile.Mapping{ { ID: 1, BuildID: "buildid", Start: 0x1000, Limit: 0x4000, HasFunctions: true, HasFilenames: true, HasLineNumbers: true, HasInlineFrames: true, }, } var heapF = []*profile.Function{ {ID: 1, Name: "pruneme", SystemName: "pruneme", Filename: "prune.h"}, {ID: 2, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"}, {ID: 3, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"}, {ID: 4, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"}, {ID: 5, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"}, {ID: 6, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"}, {ID: 7, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"}, {ID: 8, Name: "mangledMALLOC", SystemName: "mangledMALLOC", Filename: "malloc.h"}, {ID: 9, Name: "mangledNEW", SystemName: "mangledNEW", Filename: "new.h"}, } var heapL = []*profile.Location{ { ID: 1000, Mapping: heapM[0], Address: 0x1000, Line: []profile.Line{ {Function: heapF[0], Line: 100}, {Function: heapF[7], Line: 100}, {Function: heapF[1], Line: 1}, }, }, { ID: 2000, Mapping: heapM[0], Address: 0x2000, Line: []profile.Line{ {Function: heapF[8], Line: 100}, {Function: heapF[3], Line: 2}, {Function: heapF[2], Line: 3}, }, }, { ID: 3000, Mapping: heapM[0], Address: 0x3000, Line: []profile.Line{ {Function: heapF[8], Line: 100}, {Function: heapF[6], Line: 3}, {Function: heapF[5], Line: 2}, {Function: heapF[4], Line: 4}, }, }, { ID: 3001, Mapping: heapM[0], Address: 0x3001, Line: []profile.Line{ {Function: heapF[0], Line: 100}, {Function: heapF[8], Line: 100}, {Function: heapF[5], Line: 2}, {Function: heapF[4], Line: 4}, }, }, { ID: 3002, Mapping: heapM[0], Address: 0x3002, Line: []profile.Line{ {Function: heapF[6], Line: 3}, {Function: heapF[4], Line: 4}, }, }, } return &profile.Profile{ Comments: []string{"comment", "#hidden comment"}, PeriodType: &profile.ValueType{Type: "allocations", Unit: "bytes"}, Period: 524288, SampleType: []*profile.ValueType{ {Type: "inuse_objects", Unit: "count"}, {Type: "inuse_space", Unit: "bytes"}, }, Sample: []*profile.Sample{ { Location: []*profile.Location{heapL[0], heapL[1], heapL[2]}, Value: []int64{10, 1024000}, NumLabel: map[string][]int64{"bytes": {102400}}, }, { Location: []*profile.Location{heapL[0], heapL[3]}, Value: []int64{20, 4096000}, NumLabel: map[string][]int64{"bytes": {204800}}, }, { Location: []*profile.Location{heapL[1], heapL[4]}, Value: []int64{40, 65536000}, NumLabel: map[string][]int64{"bytes": {1638400}}, }, { Location: []*profile.Location{heapL[2]}, Value: []int64{80, 32768000}, NumLabel: map[string][]int64{"bytes": {409600}}, }, }, DropFrames: ".*operator new.*|malloc", Location: heapL, Function: heapF, Mapping: heapM, } } func contentionProfile() *profile.Profile { var contentionM = []*profile.Mapping{ { ID: 1, BuildID: "buildid-contention", Start: 0x1000, Limit: 0x4000, HasFunctions: true, HasFilenames: true, HasLineNumbers: true, HasInlineFrames: true, }, } var contentionF = []*profile.Function{ {ID: 1, Name: "mangled1000", SystemName: "mangled1000", Filename: "testdata/file1000.src"}, {ID: 2, Name: "mangled2000", SystemName: "mangled2000", Filename: "testdata/file2000.src"}, {ID: 3, Name: "mangled2001", SystemName: "mangled2001", Filename: "testdata/file2000.src"}, {ID: 4, Name: "mangled3000", SystemName: "mangled3000", Filename: "testdata/file3000.src"}, {ID: 5, Name: "mangled3001", SystemName: "mangled3001", Filename: "testdata/file3000.src"}, {ID: 6, Name: "mangled3002", SystemName: "mangled3002", Filename: "testdata/file3000.src"}, } var contentionL = []*profile.Location{ { ID: 1000, Mapping: contentionM[0], Address: 0x1000, Line: []profile.Line{ {Function: contentionF[0], Line: 1}, }, }, { ID: 2000, Mapping: contentionM[0], Address: 0x2000, Line: []profile.Line{ {Function: contentionF[2], Line: 2}, {Function: contentionF[1], Line: 3}, }, }, { ID: 3000, Mapping: contentionM[0], Address: 0x3000, Line: []profile.Line{ {Function: contentionF[5], Line: 2}, {Function: contentionF[4], Line: 3}, {Function: contentionF[3], Line: 5}, }, }, { ID: 3001, Mapping: contentionM[0], Address: 0x3001, Line: []profile.Line{ {Function: contentionF[4], Line: 3}, {Function: contentionF[3], Line: 5}, }, }, { ID: 3002, Mapping: contentionM[0], Address: 0x3002, Line: []profile.Line{ {Function: contentionF[5], Line: 4}, {Function: contentionF[3], Line: 3}, }, }, } return &profile.Profile{ PeriodType: &profile.ValueType{Type: "contentions", Unit: "count"}, Period: 524288, SampleType: []*profile.ValueType{ {Type: "contentions", Unit: "count"}, {Type: "delay", Unit: "nanoseconds"}, }, Sample: []*profile.Sample{ { Location: []*profile.Location{contentionL[0], contentionL[1], contentionL[2]}, Value: []int64{10, 10240000}, }, { Location: []*profile.Location{contentionL[0], contentionL[3]}, Value: []int64{20, 40960000}, }, { Location: []*profile.Location{contentionL[1], contentionL[4]}, Value: []int64{40, 65536000}, }, { Location: []*profile.Location{contentionL[2]}, Value: []int64{80, 32768000}, }, }, Location: contentionL, Function: contentionF, Mapping: contentionM, Comments: []string{"Comment #1", "Comment #2"}, } } func symzProfile() *profile.Profile { var symzM = []*profile.Mapping{ { ID: 1, Start: testStart, Limit: 0x4000, File: "/path/to/testbinary", }, } var symzL = []*profile.Location{ {ID: 1, Mapping: symzM[0], Address: testStart}, {ID: 2, Mapping: symzM[0], Address: testStart + 0x1000}, {ID: 3, Mapping: symzM[0], Address: testStart + 0x2000}, } return &profile.Profile{ PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"}, Period: 1, DurationNanos: 10e9, SampleType: []*profile.ValueType{ {Type: "samples", Unit: "count"}, {Type: "cpu", Unit: "milliseconds"}, }, Sample: []*profile.Sample{ { Location: []*profile.Location{symzL[0], symzL[1], symzL[2]}, Value: []int64{1, 1}, }, }, Location: symzL, Mapping: symzM, } } var autoCompleteTests = []struct { in string out string }{ {"", ""}, {"xyz", "xyz"}, // no match {"dis", "disasm"}, // single match {"t", "t"}, // many matches {"top abc", "top abc"}, // no function name match {"top mangledM", "top mangledMALLOC"}, // single function name match {"top cmd cmd mangledM", "top cmd cmd mangledMALLOC"}, {"top mangled", "top mangled"}, // many function name matches {"cmd mangledM", "cmd mangledM"}, // invalid command {"top mangledM cmd", "top mangledM cmd"}, // cursor misplaced {"top edMA", "top mangledMALLOC"}, // single infix function name match {"top -mangledM", "top -mangledMALLOC"}, // ignore sign handled {"lin", "lines"}, // single variable match {"EdGeF", "edgefraction"}, // single capitalized match {"help dis", "help disasm"}, // help command match {"help relative_perc", "help relative_percentages"}, // help variable match {"help coMpa", "help compact_labels"}, // help variable capitalized match } func TestAutoComplete(t *testing.T) { complete := newCompleter(functionNames(heapProfile())) for _, test := range autoCompleteTests { if out := complete(test.in); out != test.out { t.Errorf("autoComplete(%s) = %s; want %s", test.in, out, test.out) } } } func TestTagFilter(t *testing.T) { var tagFilterTests = []struct { desc, value string tags map[string][]string want bool }{ { "1 key with 1 matching value", "tag2", map[string][]string{"value1": {"tag1", "tag2"}}, true, }, { "1 key with no matching values", "tag3", map[string][]string{"value1": {"tag1", "tag2"}}, false, }, { "two keys, each with value matching different one value in list", "tag1,tag3", map[string][]string{"value1": {"tag1", "tag2"}, "value2": {"tag3"}}, true, }, {"two keys, all value matching different regex value in list", "t..[12],t..3", map[string][]string{"value1": {"tag1", "tag2"}, "value2": {"tag3"}}, true, }, { "one key, not all values in list matched", "tag2,tag3", map[string][]string{"value1": {"tag1", "tag2"}}, false, }, { "key specified, list of tags where all tags in list matched", "key1=tag1,tag2", map[string][]string{"key1": {"tag1", "tag2"}}, true, }, {"key specified, list of tag values where not all are matched", "key1=tag1,tag2", map[string][]string{"key1": {"tag1"}}, true, }, { "key included for regex matching, list of values where all values in list matched", "key1:tag1,tag2", map[string][]string{"key1": {"tag1", "tag2"}}, true, }, { "key included for regex matching, list of values where not only second value matched", "key1:tag1,tag2", map[string][]string{"key1": {"tag2"}}, false, }, { "key included for regex matching, list of values where not only first value matched", "key1:tag1,tag2", map[string][]string{"key1": {"tag1"}}, false, }, } for _, test := range tagFilterTests { t.Run(test.desc, func(t *testing.T) { filter, err := compileTagFilter(test.desc, test.value, nil, &proftest.TestUI{T: t}, nil) if err != nil { t.Fatalf("tagFilter %s:%v", test.desc, err) } s := profile.Sample{ Label: test.tags, } if got := filter(&s); got != test.want { t.Errorf("tagFilter %s: got %v, want %v", test.desc, got, test.want) } }) } } func TestIdentifyNumLabelUnits(t *testing.T) { var tagFilterTests = []struct { desc string tagVals []map[string][]int64 tagUnits []map[string][]string wantUnits map[string]string allowedRx string wantIgnoreErrCount int }{ { "Multiple keys, no units for all keys", []map[string][]int64{{"keyA": {131072}, "keyB": {128}}}, []map[string][]string{{"keyA": {}, "keyB": {""}}}, map[string]string{"keyA": "keyA", "keyB": "keyB"}, "", 0, }, { "Multiple keys, different units for each key", []map[string][]int64{{"keyA": {131072}, "keyB": {128}}}, []map[string][]string{{"keyA": {"bytes"}, "keyB": {"kilobytes"}}}, map[string]string{"keyA": "bytes", "keyB": "kilobytes"}, "", 0, }, { "Multiple keys with multiple values, different units for each key", []map[string][]int64{{"keyC": {131072, 1}, "keyD": {128, 252}}}, []map[string][]string{{"keyC": {"bytes", "bytes"}, "keyD": {"kilobytes", "kilobytes"}}}, map[string]string{"keyC": "bytes", "keyD": "kilobytes"}, "", 0, }, { "Multiple keys with multiple values, some units missing", []map[string][]int64{{"key1": {131072, 1}, "A": {128, 252}, "key3": {128}, "key4": {1}}, {"key3": {128}, "key4": {1}}}, []map[string][]string{{"key1": {"", "bytes"}, "A": {"kilobytes", ""}, "key3": {""}, "key4": {"hour"}}, {"key3": {"seconds"}, "key4": {""}}}, map[string]string{"key1": "bytes", "A": "kilobytes", "key3": "seconds", "key4": "hour"}, "", 0, }, { "One key with three units in same sample", []map[string][]int64{{"key": {8, 8, 16}}}, []map[string][]string{{"key": {"bytes", "megabytes", "kilobytes"}}}, map[string]string{"key": "bytes"}, `(For tag key used unit bytes, also encountered unit\(s\) kilobytes, megabytes)`, 1, }, { "One key with four units in same sample", []map[string][]int64{{"key": {8, 8, 16, 32}}}, []map[string][]string{{"key": {"bytes", "kilobytes", "a", "megabytes"}}}, map[string]string{"key": "bytes"}, `(For tag key used unit bytes, also encountered unit\(s\) a, kilobytes, megabytes)`, 1, }, { "One key with two units in same sample", []map[string][]int64{{"key": {8, 8}}}, []map[string][]string{{"key": {"bytes", "seconds"}}}, map[string]string{"key": "bytes"}, `(For tag key used unit bytes, also encountered unit\(s\) seconds)`, 1, }, { "One key with different units in different samples", []map[string][]int64{{"key1": {8}}, {"key1": {8}}, {"key1": {8}}}, []map[string][]string{{"key1": {"bytes"}}, {"key1": {"kilobytes"}}, {"key1": {"megabytes"}}}, map[string]string{"key1": "bytes"}, `(For tag key1 used unit bytes, also encountered unit\(s\) kilobytes, megabytes)`, 1, }, { "Key alignment, unit not specified", []map[string][]int64{{"alignment": {8}}}, []map[string][]string{nil}, map[string]string{"alignment": "bytes"}, "", 0, }, { "Key request, unit not specified", []map[string][]int64{{"request": {8}}, {"request": {8, 8}}}, []map[string][]string{nil, nil}, map[string]string{"request": "bytes"}, "", 0, }, { "Check units not over-written for keys with default units", []map[string][]int64{{ "alignment": {8}, "request": {8}, "bytes": {8}, }}, []map[string][]string{{ "alignment": {"seconds"}, "request": {"minutes"}, "bytes": {"hours"}, }}, map[string]string{ "alignment": "seconds", "request": "minutes", "bytes": "hours", }, "", 0, }, } for _, test := range tagFilterTests { t.Run(test.desc, func(t *testing.T) { p := profile.Profile{Sample: make([]*profile.Sample, len(test.tagVals))} for i, numLabel := range test.tagVals { s := profile.Sample{ NumLabel: numLabel, NumUnit: test.tagUnits[i], } p.Sample[i] = &s } testUI := &proftest.TestUI{T: t, AllowRx: test.allowedRx} units := identifyNumLabelUnits(&p, testUI) if !reflect.DeepEqual(test.wantUnits, units) { t.Errorf("got %v units, want %v", units, test.wantUnits) } if got, want := testUI.NumAllowRxMatches, test.wantIgnoreErrCount; want != got { t.Errorf("got %d errors logged, want %d errors logged", got, want) } }) } } func TestNumericTagFilter(t *testing.T) { var tagFilterTests = []struct { desc, value string tags map[string][]int64 identifiedUnits map[string]string want bool }{ { "Match when unit conversion required", "128kb", map[string][]int64{"key1": {131072}, "key2": {128}}, map[string]string{"key1": "bytes", "key2": "kilobytes"}, true, }, { "Match only when values equal after unit conversion", "512kb", map[string][]int64{"key1": {512}, "key2": {128}}, map[string]string{"key1": "bytes", "key2": "kilobytes"}, false, }, { "Match when values and units initially equal", "10bytes", map[string][]int64{"key1": {10}, "key2": {128}}, map[string]string{"key1": "bytes", "key2": "kilobytes"}, true, }, { "Match range without lower bound, no unit conversion required", ":10bytes", map[string][]int64{"key1": {8}}, map[string]string{"key1": "bytes"}, true, }, { "Match range without lower bound, unit conversion required", ":10kb", map[string][]int64{"key1": {8}}, map[string]string{"key1": "bytes"}, true, }, { "Match range without upper bound, unit conversion required", "10b:", map[string][]int64{"key1": {8}}, map[string]string{"key1": "kilobytes"}, true, }, { "Match range without upper bound, no unit conversion required", "10b:", map[string][]int64{"key1": {12}}, map[string]string{"key1": "bytes"}, true, }, { "Don't match range without upper bound, no unit conversion required", "10b:", map[string][]int64{"key1": {8}}, map[string]string{"key1": "bytes"}, false, }, { "Multiple keys with different units, don't match range without upper bound", "10kb:", map[string][]int64{"key1": {8}}, map[string]string{"key1": "bytes", "key2": "kilobytes"}, false, }, { "Match range without upper bound, unit conversion required", "10b:", map[string][]int64{"key1": {8}}, map[string]string{"key1": "kilobytes"}, true, }, { "Don't match range without lower bound, no unit conversion required", ":10b", map[string][]int64{"key1": {12}}, map[string]string{"key1": "bytes"}, false, }, { "Match specific key, key present, one of two values match", "bytes=5b", map[string][]int64{"bytes": {10, 5}}, map[string]string{"bytes": "bytes"}, true, }, { "Match specific key, key present and value matches", "bytes=1024b", map[string][]int64{"bytes": {1024}}, map[string]string{"bytes": "kilobytes"}, false, }, { "Match specific key, matching key present and value matches, also non-matching key", "bytes=1024b", map[string][]int64{"bytes": {1024}, "key2": {5}}, map[string]string{"bytes": "bytes", "key2": "bytes"}, true, }, { "Match specific key and range of values, value matches", "bytes=512b:1024b", map[string][]int64{"bytes": {780}}, map[string]string{"bytes": "bytes"}, true, }, { "Match specific key and range of values, value too large", "key1=1kb:2kb", map[string][]int64{"key1": {4096}}, map[string]string{"key1": "bytes"}, false, }, { "Match specific key and range of values, value too small", "key1=1kb:2kb", map[string][]int64{"key1": {256}}, map[string]string{"key1": "bytes"}, false, }, { "Match specific key and value, unit conversion required", "bytes=1024b", map[string][]int64{"bytes": {1}}, map[string]string{"bytes": "kilobytes"}, true, }, { "Match specific key and value, key does not appear", "key2=256bytes", map[string][]int64{"key1": {256}}, map[string]string{"key1": "bytes"}, false, }, { "Match negative key and range of values, value matches", "bytes=-512b:-128b", map[string][]int64{"bytes": {-256}}, map[string]string{"bytes": "bytes"}, true, }, { "Match negative key and range of values, value outside range", "bytes=-512b:-128b", map[string][]int64{"bytes": {-2048}}, map[string]string{"bytes": "bytes"}, false, }, { "Match exact value, unitless tag", "pid=123", map[string][]int64{"pid": {123}}, nil, true, }, { "Match range, unitless tag", "pid=123:123", map[string][]int64{"pid": {123}}, nil, true, }, { "Don't match range, unitless tag", "pid=124:124", map[string][]int64{"pid": {123}}, nil, false, }, { "Match range without upper bound, unitless tag", "pid=100:", map[string][]int64{"pid": {123}}, nil, true, }, { "Don't match range without upper bound, unitless tag", "pid=200:", map[string][]int64{"pid": {123}}, nil, false, }, { "Match range without lower bound, unitless tag", "pid=:200", map[string][]int64{"pid": {123}}, nil, true, }, { "Don't match range without lower bound, unitless tag", "pid=:100", map[string][]int64{"pid": {123}}, nil, false, }, } for _, test := range tagFilterTests { t.Run(test.desc, func(t *testing.T) { wantErrMsg := strings.Join([]string{"(", test.desc, ":Interpreted '", test.value[strings.Index(test.value, "=")+1:], "' as range, not regexp", ")"}, "") filter, err := compileTagFilter(test.desc, test.value, test.identifiedUnits, &proftest.TestUI{T: t, AllowRx: wantErrMsg}, nil) if err != nil { t.Fatalf("%v", err) } s := profile.Sample{ NumLabel: test.tags, } if got := filter(&s); got != test.want { t.Fatalf("got %v, want %v", got, test.want) } }) } } // TestOptionsHaveHelp tests that a help message is supplied for every // selectable option. func TestOptionsHaveHelp(t *testing.T) { for _, f := range configFields { // Check all choices if this is a group, else check f.name. names := f.choices if len(names) == 0 { names = []string{f.name} } for _, name := range names { if _, ok := configHelp[name]; !ok { t.Errorf("missing help message for %q", name) } } } } type testSymbolzMergeFetcher struct{} func (testSymbolzMergeFetcher) Fetch(s string, d, t time.Duration) (*profile.Profile, string, error) { var p *profile.Profile switch s { case testSourceURL(8000) + "symbolz": p = symzProfile() case testSourceURL(8001) + "symbolz": p = symzProfile() p.Mapping[0].Start += testOffset p.Mapping[0].Limit += testOffset for i := range p.Location { p.Location[i].Address += testOffset } default: return nil, "", fmt.Errorf("unexpected source: %s", s) } return p, s, nil } func TestSymbolzAfterMerge(t *testing.T) { baseConfig := currentConfig() defer setCurrentConfig(baseConfig) f := baseFlags() f.args = []string{ testSourceURL(8000) + "symbolz", testSourceURL(8001) + "symbolz", } o := setDefaults(nil) o.Flagset = f o.Obj = new(mockObjTool) src, cmd, err := parseFlags(o) if err != nil { t.Fatalf("parseFlags: %v", err) } if len(cmd) != 1 || cmd[0] != "proto" { t.Fatalf("parseFlags returned command %v, want [proto]", cmd) } o.Fetch = testSymbolzMergeFetcher{} o.Sym = testSymbolzSymbolizer{} p, err := fetchProfiles(src, o) if err != nil { t.Fatalf("fetchProfiles: %v", err) } if len(p.Location) != 3 { t.Errorf("Got %d locations after merge, want %d", len(p.Location), 3) } for i, l := range p.Location { if len(l.Line) != 1 { t.Errorf("Number of lines for symbolz %#x in iteration %d, got %d, want %d", l.Address, i, len(l.Line), 1) continue } address := l.Address - l.Mapping.Start if got, want := l.Line[0].Function.Name, fmt.Sprintf("%#x", address); got != want { t.Errorf("symbolz %#x, got %s, want %s", address, got, want) } } } type mockObjTool struct{} func (*mockObjTool) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) { return &mockFile{file, "abcdef", 0}, nil } func (m *mockObjTool) Disasm(file string, start, end uint64, intelSyntax bool) ([]plugin.Inst, error) { const fn1 = "line1000" const fn3 = "line3000" const file1 = "testdata/file1000.src" const file3 = "testdata/file3000.src" data := []plugin.Inst{ {Addr: 0x1000, Text: "instruction one", Function: fn1, File: file1, Line: 1}, {Addr: 0x1001, Text: "instruction two", Function: fn1, File: file1, Line: 1}, {Addr: 0x1002, Text: "instruction three", Function: fn1, File: file1, Line: 2}, {Addr: 0x1003, Text: "instruction four", Function: fn1, File: file1, Line: 1}, {Addr: 0x3000, Text: "instruction one", Function: fn3, File: file3}, {Addr: 0x3001, Text: "instruction two", Function: fn3, File: file3}, {Addr: 0x3002, Text: "instruction three", Function: fn3, File: file3}, {Addr: 0x3003, Text: "instruction four", Function: fn3, File: file3}, {Addr: 0x3004, Text: "instruction five", Function: fn3, File: file3}, } var result []plugin.Inst for _, inst := range data { if inst.Addr >= start && inst.Addr <= end { result = append(result, inst) } } return result, nil } type mockFile struct { name, buildID string base uint64 } // Name returns the underlyinf file name, if available func (m *mockFile) Name() string { return m.name } // ObjAddr returns the objdump address corresponding to a runtime address. func (m *mockFile) ObjAddr(addr uint64) (uint64, error) { return addr - m.base, nil } // BuildID returns the GNU build ID of the file, or an empty string. func (m *mockFile) BuildID() string { return m.buildID } // SourceLine reports the source line information for a given // address in the file. Due to inlining, the source line information // is in general a list of positions representing a call stack, // with the leaf function first. func (*mockFile) SourceLine(addr uint64) ([]plugin.Frame, error) { // Return enough data to support the SourceLine() calls needed for // weblist on cpuProfile() contents. frame := func(fn, file string, line int) plugin.Frame { return plugin.Frame{Func: fn, File: file, Line: line} } switch addr { case 0x1000: return []plugin.Frame{ frame("mangled1000", "testdata/file1000.src", 1), }, nil case 0x1001: return []plugin.Frame{ frame("mangled1000", "testdata/file1000.src", 1), }, nil case 0x1002: return []plugin.Frame{ frame("mangled1000", "testdata/file1000.src", 2), }, nil case 0x1003: return []plugin.Frame{ frame("mangled1000", "testdata/file1000.src", 1), }, nil case 0x2000: return []plugin.Frame{ frame("mangled2001", "testdata/file2000.src", 9), frame("mangled2000", "testdata/file2000.src", 4), }, nil case 0x3000: return []plugin.Frame{ frame("mangled3002", "testdata/file3000.src", 2), frame("mangled3001", "testdata/file3000.src", 5), frame("mangled3000", "testdata/file3000.src", 6), }, nil case 0x3001: return []plugin.Frame{ frame("mangled3001", "testdata/file3000.src", 8), frame("mangled3000", "testdata/file3000.src", 9), }, nil case 0x3002: return []plugin.Frame{ frame("mangled3002", "testdata/file3000.src", 5), frame("mangled3000", "testdata/file3000.src", 9), }, nil } return nil, nil } // Symbols returns a list of symbols in the object file. // If r is not nil, Symbols restricts the list to symbols // with names matching the regular expression. // If addr is not zero, Symbols restricts the list to symbols // containing that address. func (m *mockFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) { switch r.String() { case "line[13]": return []*plugin.Sym{ { Name: []string{"line1000"}, File: m.name, Start: 0x1000, End: 0x1003, }, { Name: []string{"line3000"}, File: m.name, Start: 0x3000, End: 0x3004, }, }, nil } return nil, fmt.Errorf("unimplemented") } // Close closes the file, releasing associated resources. func (*mockFile) Close() error { return nil }
apache-2.0
ilivoo/ilivoo
voom/src/main/java/com/ilivoo/voom/model/testrecache/entity/PlayerEntity.java
2937
package com.ilivoo.voom.model.testrecache.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import com.ilivoo.common.recache.annotation.CacheEntity; import com.ilivoo.common.recache.annotation.Index; import com.ilivoo.common.recache.annotation.Persister; import com.ilivoo.common.recache.core.SerializerEntity; /** * 1. 实体类必须存在一个无参数的构造方法 * @author fengxiang * */ @Entity @CacheEntity(size=1000, persister=@Persister("0,30 * * * * ?")) @NamedQueries({ @NamedQuery(name="PlayerEntity.name", query="select name from PlayerEntity where id = ?"), @NamedQuery(name="PlayerEntity.account", query="select account from PlayerEntity where id = ?"), @NamedQuery(name="PlayerEntity.country", query="select country from PlayerEntity where id = ?")}) public class PlayerEntity extends SerializerEntity<Long> { @Id private Long id; @Index(query="PlayerEntity.name", unique=true) @Column(unique=true, columnDefinition="varchar(200)") private String name; @Index(query="PlayerEntity.account", unique=true) @Column(unique=true, columnDefinition="varchar(200)") private String account; @Index(query="PlayerEntity.country") @Column(columnDefinition="varchar(50)", nullable=false) private String country; @Column(columnDefinition="int default 0", nullable=false) private int adult; @Column(columnDefinition="bit default 0", nullable=false) private boolean gm; @Lob private String json; private int[] map; @Override public boolean evict() { return false; } @Override public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public int getAdult() { return adult; } public void setAdult(int adult) { this.adult = adult; } public boolean isGm() { return gm; } public void setGm(boolean gm) { this.gm = gm; } public String getJson() { return json; } public void setJson(String json) { this.json = json; } public int[] getMap() { return map; } public void setMap(int[] map) { this.map = map; } public void setId(Long id) { this.id = id; } }
apache-2.0
ChrisA89/assertj-core
src/main/java/org/assertj/core/error/ShouldContainCharSequence.java
4666
/** * 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 2012-2017 the original author or authors. */ package org.assertj.core.error; import java.util.Set; import org.assertj.core.internal.ComparisonStrategy; import org.assertj.core.internal.StandardComparisonStrategy; /** * Creates an error message indicating that an assertion that verifies that a {@code CharSequence} contains another * {@code CharSequence} failed. * * @author Alex Ruiz * @author Joel Costigliola * @author Mikhail Mazursky */ public class ShouldContainCharSequence extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainCharSequence}</code>. * * @param actual the actual value in the failed assertion. * @param sequence the sequence of values expected to be in {@code actual}. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequence sequence) { return new ShouldContainCharSequence("%nExpecting:%n <%s>%nto contain:%n <%s> %s", actual, sequence, StandardComparisonStrategy.instance()); } /** * Creates a new <code>{@link ShouldContainCharSequence}</code>. * * @param actual the actual value in the failed assertion. * @param sequence the sequence of values expected to be in {@code actual}. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequence sequence, ComparisonStrategy comparisonStrategy) { return new ShouldContainCharSequence("%nExpecting:%n <%s>%nto contain:%n <%s> %s", actual, sequence, comparisonStrategy); } /** * Creates a new <code>{@link ShouldContainCharSequence}</code>. * * @param actual the actual value in the failed assertion. * @param strings the sequence of values expected to be in {@code actual}. * @param notFound the values not found. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequence[] strings, Set<? extends CharSequence> notFound, ComparisonStrategy comparisonStrategy) { return new ShouldContainCharSequence("%nExpecting:%n <%s>%nto contain:%n <%s>%nbut could not find:%n <%s>%n %s", actual, strings, notFound, comparisonStrategy); } /** * Creates a new <code>{@link ShouldContainCharSequence}</code>. * * @param actual the actual value in the failed assertion. * @param strings the sequence of values expected to be in {@code actual}. * @param notFound the values not found. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContain(CharSequence actual, CharSequence[] strings, Set<? extends CharSequence> notFound) { return shouldContain(actual, strings, notFound, StandardComparisonStrategy.instance()); } /** * Creates a new <code>{@link ShouldContainCharSequence}</code>. * * @param actual the actual value in the failed assertion. * @param sequence the sequence of values expected to be in {@code actual}. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainIgnoringCase(CharSequence actual, CharSequence sequence) { return new ShouldContainCharSequence("%nExpecting:%n <%s>%nto contain:%n <%s>%n (ignoring case)", actual, sequence, StandardComparisonStrategy.instance()); } private ShouldContainCharSequence(String format, CharSequence actual, CharSequence sequence, ComparisonStrategy comparisonStrategy) { super(format, actual, sequence, comparisonStrategy); } private ShouldContainCharSequence(String format, CharSequence actual, CharSequence[] values, Set<? extends CharSequence> notFound, ComparisonStrategy comparisonStrategy) { super(format, actual, values, notFound, comparisonStrategy); } }
apache-2.0
AlexanderMatveenko/omim
map/country_tree.cpp
6527
#include "map/country_tree.hpp" #include "map/framework.hpp" #include "storage/storage.hpp" namespace storage { namespace { int const RootItemIndex = 0; int const ChildItemsOffset = 1; } inline TIndex GetIndexChild(TIndex const & index, int i) { TIndex child(index); if (child.m_group == TIndex::INVALID) child.m_group = i; else if (child.m_country == TIndex::INVALID) child.m_country = i; else if (child.m_region == TIndex::INVALID) child.m_region = i; return child; } inline TIndex GetIndexParent(TIndex const & index) { ASSERT(index != TIndex(), ()); TIndex parent(index); if (parent.m_region != TIndex::INVALID) parent.m_region = TIndex::INVALID; else if (parent.m_country != TIndex::INVALID) parent.m_country = TIndex::INVALID; else parent.m_group = TIndex::INVALID; return parent; } CountryTree::CountryTree(shared_ptr<ActiveMapsLayout> activeMaps) { m_layout = activeMaps; ConnectToCoreStorage(); } CountryTree::~CountryTree() { DisconnectFromCoreStorage(); } CountryTree & CountryTree::operator=(CountryTree const & other) { if (this == &other) return *this; DisconnectFromCoreStorage(); m_levelItems = other.m_levelItems; m_listener = other.m_listener; m_layout = other.m_layout; ConnectToCoreStorage(); return *this; } ActiveMapsLayout & CountryTree::GetActiveMapLayout() { ASSERT(IsValid(), ()); return *m_layout; } ActiveMapsLayout const & CountryTree::GetActiveMapLayout() const { ASSERT(IsValid(), ()); return *m_layout; } bool CountryTree::IsValid() const { return m_layout != nullptr; } void CountryTree::SetDefaultRoot() { SetRoot(TIndex()); } void CountryTree::SetParentAsRoot() { ASSERT(HasParent(), ()); SetRoot(GetIndexParent(GetCurrentRoot())); } void CountryTree::SetChildAsRoot(int childPosition) { ASSERT(!IsLeaf(childPosition), ()); SetRoot(GetChild(childPosition)); } void CountryTree::ResetRoot() { m_levelItems.clear(); } bool CountryTree::HasRoot() const { return !m_levelItems.empty(); } bool CountryTree::HasParent() const { return GetCurrentRoot() != TIndex(); } int CountryTree::GetChildCount() const { ASSERT(HasRoot(), ()); return m_levelItems.size() - ChildItemsOffset; } bool CountryTree::IsLeaf(int childPosition) const { return GetStorage().CountriesCount(GetChild(childPosition)) == 0; } string const & CountryTree::GetChildName(int position) const { return GetStorage().CountryName(GetChild(position)); } TStatus CountryTree::GetLeafStatus(int position) const { return GetStorage().CountryStatusEx(GetChild(position)); } MapOptions CountryTree::GetLeafOptions(int position) const { TStatus status; MapOptions options; GetStorage().CountryStatusEx(GetChild(position), status, options); return options; } LocalAndRemoteSizeT const CountryTree::GetDownloadableLeafSize(int position) const { return GetActiveMapLayout().GetDownloadableCountrySize(GetChild(position)); } LocalAndRemoteSizeT const CountryTree::GetLeafSize(int position, MapOptions const & options) const { return GetActiveMapLayout().GetCountrySize(GetChild(position), options); } LocalAndRemoteSizeT const CountryTree::GetRemoteLeafSizes(int position) const { return GetActiveMapLayout().GetRemoteCountrySizes(GetChild(position)); } bool CountryTree::IsCountryRoot() const { TIndex index = GetCurrentRoot(); ASSERT(index.m_region == TIndex::INVALID, ()); if (index.m_country != TIndex::INVALID) return true; return false; } string const & CountryTree::GetRootName() const { return GetStorage().CountryName(GetCurrentRoot()); } void CountryTree::DownloadCountry(int childPosition, MapOptions const & options) { ASSERT(IsLeaf(childPosition), ()); GetActiveMapLayout().DownloadMap(GetChild(childPosition), options); } void CountryTree::DeleteCountry(int childPosition, MapOptions const & options) { ASSERT(IsLeaf(childPosition), ()); GetActiveMapLayout().DeleteMap(GetChild(childPosition), options); } void CountryTree::RetryDownloading(int childPosition) { ASSERT(IsLeaf(childPosition), ()); GetActiveMapLayout().RetryDownloading(GetChild(childPosition)); } void CountryTree::CancelDownloading(int childPosition) { GetStorage().DeleteFromDownloader(GetChild(childPosition)); } void CountryTree::SetListener(CountryTreeListener * listener) { m_listener = listener; } void CountryTree::ResetListener() { m_listener = nullptr; } void CountryTree::ShowLeafOnMap(int position) { ASSERT(IsLeaf(position), ()); GetActiveMapLayout().ShowMap(GetChild(position)); } Storage const & CountryTree::GetStorage() const { ASSERT(IsValid(), ()); return m_layout->GetStorage(); } Storage & CountryTree::GetStorage() { ASSERT(IsValid(), ()); return m_layout->GetStorage(); } void CountryTree::ConnectToCoreStorage() { if (IsValid()) { m_subscribeSlotID = GetStorage().Subscribe(bind(&CountryTree::NotifyStatusChanged, this, _1), bind(&CountryTree::NotifyProgressChanged, this, _1, _2)); } } void CountryTree::DisconnectFromCoreStorage() { if (IsValid()) GetStorage().Unsubscribe(m_subscribeSlotID); } TIndex const & CountryTree::GetCurrentRoot() const { ASSERT(HasRoot(), ()); return m_levelItems[RootItemIndex]; } void CountryTree::SetRoot(TIndex index) { ResetRoot(); size_t const count = GetStorage().CountriesCount(index); m_levelItems.reserve(ChildItemsOffset + count); m_levelItems.push_back(index); for (size_t i = 0; i < count; ++i) m_levelItems.push_back(GetIndexChild(index, i)); } TIndex const & CountryTree::GetChild(int childPosition) const { ASSERT(childPosition < GetChildCount(), ()); return m_levelItems[ChildItemsOffset + childPosition]; } int CountryTree::GetChildPosition(TIndex const & index) { int result = -1; if (HasRoot()) { auto iter = find(m_levelItems.begin(), m_levelItems.end(), index); if (iter != m_levelItems.end()) result = distance(m_levelItems.begin(), iter) - ChildItemsOffset; } return result; } void CountryTree::NotifyStatusChanged(TIndex const & index) { if (m_listener != nullptr) { int position = GetChildPosition(index); if (position != -1) m_listener->ItemStatusChanged(position); } } void CountryTree::NotifyProgressChanged(TIndex const & index, LocalAndRemoteSizeT const & sizes) { if (m_listener != nullptr) { int position = GetChildPosition(index); if (position != -1) m_listener->ItemProgressChanged(position, sizes); } } }
apache-2.0
CaioProiete/serilog
test/Serilog.PerformanceTests/LevelControlBenchmark.cs
1760
using BenchmarkDotNet.Attributes; using Serilog.Core; using Serilog.Events; using Serilog.PerformanceTests.Support; namespace Serilog.PerformanceTests { /// <summary> /// Tests the overhead of determining the active logging level. /// </summary> public class LevelControlBenchmark { ILogger _off, _levelSwitchOff, _minLevel, _levelSwitch; readonly LogEvent _event = Some.InformationEvent(); [GlobalSetup] public void Setup() { _off = new LoggerConfiguration() .MinimumLevel.Fatal() .WriteTo.Sink(new NullSink()) .CreateLogger(); _levelSwitchOff = new LoggerConfiguration() .MinimumLevel.ControlledBy(new LoggingLevelSwitch(LogEventLevel.Fatal)) .WriteTo.Sink(new NullSink()) .CreateLogger(); _minLevel = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Sink(new NullSink()) .CreateLogger(); _levelSwitch = new LoggerConfiguration() .MinimumLevel.ControlledBy(new LoggingLevelSwitch(LogEventLevel.Information)) .WriteTo.Sink(new NullSink()) .CreateLogger(); } [Benchmark(Baseline = true)] public void Off() { _off.Write(_event); } [Benchmark] public void LevelSwitchOff() { _levelSwitchOff.Write(_event); } [Benchmark] public void MinimumLevelOn() { _minLevel.Write(_event); } [Benchmark] public void LevelSwitchOn() { _levelSwitch.Write(_event); } } }
apache-2.0
mdogan/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/datastructures/spi/blocking/operation/package-info.java
857
/* * Copyright (c) 2008-2020, Hazelcast, 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. */ /** * Contains the operations that are used by the * {@link com.hazelcast.cp.internal.datastructures.spi.blocking.AbstractBlockingService} abstraction */ package com.hazelcast.cp.internal.datastructures.spi.blocking.operation;
apache-2.0
vclfiddle/vclfiddle
web/test/unit/services/RequestMetadataService.test.js
7218
var expect = require('chai').expect; describe('RequestMetadataService', function () { describe('#parseInputRequests()', function () { it('should parse a basic curl command', function (done) { RequestMetadataService.parseInputRequests('curl http://www.vclfiddle.net', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.includedRequests.length).to.equal(1); expect(allRequests.includedRequests[0].entryIndex).to.equal(0); expect(allRequests.includedRequests[0].summary.method).to.equal('GET'); expect(allRequests.includedRequests[0].summary.url).to.equal('http://www.vclfiddle.net'); expect(allRequests.includedRequests[0].summary.httpVersion).to.equal('HTTP/1.1'); expect(allRequests.includedRequests[0].payload).to.equal('GET / HTTP/1.1\r\nHost: www.vclfiddle.net\r\nConnection: close\r\n\r\n'); done(); }); }); it('should parse a curl command with custom headers', function (done) { RequestMetadataService.parseInputRequests('curl --header "Accept: */*" http://www.vclfiddle.net -H \'DNT: 1\'', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.includedRequests.length).to.equal(1); expect(allRequests.includedRequests[0].summary.url).to.equal('http://www.vclfiddle.net'); expect(allRequests.includedRequests[0].payload).to.contain('Accept: */*\r\n'); expect(allRequests.includedRequests[0].payload).to.contain('DNT: 1\r\n'); done(); }); }); it('should parse a curl command with Host header override', function (done) { RequestMetadataService.parseInputRequests('curl --header "Host: not.vclfiddle.net" http://www.vclfiddle.net', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.includedRequests.length).to.equal(1); expect(allRequests.includedRequests[0].payload).to.contain('Host: not.vclfiddle.net\r\n'); expect(allRequests.includedRequests[0].payload).to.not.contain('Host: www.vclfiddle.net\r\n'); done(); }); }); it('should ignore custom Connection: headers with a warning', function (done) { RequestMetadataService.parseInputRequests('curl --header "Connection: Upgrade" http://www.vclfiddle.net', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.includedRequests.length).to.equal(1); expect(allRequests.includedRequests[0].payload).to.not.contain('pgrade'); expect(allRequests.includedRequests[0].warnings).to.contain('Connection request header not supported.'); done(); }); }); it('should categorise requests for hosts other than the first as excluded', function (done) { RequestMetadataService.parseInputRequests('curl --header "Host: first" http://www.vclfiddle.net\ncurl --header "Host: second" http://www.vclfiddle.net', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.includedRequests.length).to.equal(1); expect(allRequests.excludedRequests.length).to.equal(1); expect(allRequests.excludedRequests[0].excludeReason).to.equal('Ignored'); expect(allRequests.excludedRequests[0].message).to.contain('Host does not match first request'); done(); }); }); it('should exclude command with missing url', function (done) { RequestMetadataService.parseInputRequests('curl --header "Host: www.vclfiddle.net"', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.excludedRequests.length).to.equal(1); expect(allRequests.excludedRequests[0].excludeReason).to.equal('Ignored'); expect(allRequests.excludedRequests[0].message).to.contain('URL argument missing'); done(); }); }); it('should exclude command with invalid url', function (done) { RequestMetadataService.parseInputRequests('curl :www.vclfiddle.net', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.excludedRequests.length).to.equal(1); expect(allRequests.excludedRequests[0].excludeReason).to.equal('Ignored'); expect(allRequests.excludedRequests[0].message).to.contain('URL argument invalid'); expect(allRequests.excludedRequests[0].message).to.contain(':www.vclfiddle.net'); done(); }); }); it('should understand the -0 argument for HTTP/1.0', function (done) { RequestMetadataService.parseInputRequests('curl http://www.vclfiddle.net -0', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.includedRequests.length).to.equal(1); expect(allRequests.includedRequests[0].summary.httpVersion).to.equal('HTTP/1.0'); expect(allRequests.includedRequests[0].payload).to.contain('GET / HTTP/1.0\r\n'); done(); }); }); it('should understand HTTPS and exclude', function (done) { RequestMetadataService.parseInputRequests('curl https://www.vclfiddle.net', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.excludedRequests.length).to.equal(1); expect(allRequests.excludedRequests[0].excludeReason).to.equal('Unsupported'); expect(allRequests.excludedRequests[0].message).to.contain('Protocol not supported: https'); done(); }); }); it('should ignore understand the POST method and request body', function (done) { RequestMetadataService.parseInputRequests('curl http://www.vclfiddle.net --data "login=please"', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.excludedRequests.length).to.equal(1); expect(allRequests.excludedRequests[0].excludeReason).to.equal('Unsupported'); expect(allRequests.excludedRequests[0].message).to.contain('Method not supported: POST'); done(); }); }); it('should ignore the --compressed arg', function (done) { RequestMetadataService.parseInputRequests('curl http://www.vclfiddle.net --compressed', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.includedRequests.length).to.equal(1); expect(allRequests.includedRequests[0].payload).to.not.contain('Accept-Encoding:'); expect(allRequests.includedRequests[0].warnings).to.be.empty; done(); }); }); it('should show warnings for unsupported or excess curl arguments', function (done) { RequestMetadataService.parseInputRequests('curl http://www.vclfiddle.net --progress-bar --next', function (err, input, allRequests) { if (err) return done(err); expect(allRequests.includedRequests.length).to.equal(1); expect(allRequests.includedRequests[0].payload).to.contain('GET / HTTP/1.1\r\nHost: www.vclfiddle.net\r\n'); expect(allRequests.includedRequests[0].warnings).to.contain('Unsupported options: next, progress-bar'); done(); }); }); it('should understand --user-agent and --referrer arguments and their shorthand'); }); });
apache-2.0
tejas-kale/d3
legacy/misc.js
1284
function length_json(json_obj) { // Initialize variables var length = 0; // Iterate over JSON to determine the number of keys for(var key in json_obj) { if(json_obj.hasOwnProperty(key)) length++; } // Return length return length; } function keys_json(json_obj) { // Initialize variables var keys = []; // Iterate over JSON to get all keys for(var key in json_obj) keys.push(key); // Return key return keys; } function get_json_values(data, key) { // Get all values to be plotted var data_length = length_json(data); var all_values = []; for (var i=0; i < data_length; i++) { all_values.push(data[i][key]); } return all_values; } function get_dasharray_properties(line_name) { // Set dasharray on- and off-length values based on line type switch(line_name) { case "solid": { var dasharray_props = "1,0"; break; } case "dotted": { var dasharray_props = "2,2"; break; } case "dashed": { var dasharray_props = "5,5"; break; } case "dotdash": { var dasharray_props = "2,2,5,2"; break; } case "twodash": { var dasharray_props = "2,2,10,2"; break; } case "longdash": { var dasharray_props = "10,10"; break; } } // Return dasharray lengths return dasharray_props; }
apache-2.0
cloudendpoints/endpoints-java
endpoints-framework/src/main/java/com/google/api/server/spi/config/validation/InvalidParameterAnnotationsException.java
1245
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.server.spi.config.validation; import com.google.api.server.spi.config.model.ApiParameterConfig; /** * Exception for parameters with annotations they are not allowed to have. * * @author Eric Orth */ public class InvalidParameterAnnotationsException extends ApiParameterConfigInvalidException { private static final String ERROR_MESSAGE = "Invalid parameter configuration. A parameter in the method path should not have a " + "default value or be marked @nullable."; public InvalidParameterAnnotationsException(ApiParameterConfig config) { super(config, ERROR_MESSAGE); } }
apache-2.0
francisdb/flicklib
flicklib-ehcache/src/main/java/com/flicklib/service/cache/HttpEHCache.java
2385
/* * This file is part of Flicklib. * * Copyright (C) Francis De Brabandere * * 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 com.flicklib.service.cache; import java.net.URL; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.flicklib.service.Source; import com.flicklib.service.SourceLoader; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class HttpEHCache extends HttpCacheSourceLoader { private static final Logger LOGGER = LoggerFactory .getLogger(HttpEHCache.class); private final CacheManager manager; private final Cache cache; @Inject public HttpEHCache( final SourceLoader resolver) { super(resolver); URL url = getClass().getResource("/ehcache-flicklib.xml"); manager = new CacheManager(url); manager.addCache("httpCache"); cache = manager.getCache("httpCache"); LOGGER.debug("Started cache, " + cache.getSize() + " pages cached."); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOGGER.debug(cache.getStatistics().toString()); try { manager.shutdown(); } catch (Exception e) { LOGGER.info("error during shutdown:" + e.getMessage(), e); } LOGGER.debug("shut down cache."); } }); } @Override protected Source getFromCache(String url) { Element element = cache.get(url); return (Source) (element != null ? element.getObjectValue() : null); } @Override protected void put(String url, Source page) { LOGGER.debug("Caching result for " + url + " (" + (page != null ? page.getContentType() : "null") + ")"); cache.put(new Element(url, page)); } @Override public RestBuilder url(String url) { throw new UnsupportedOperationException("not implemented"); } }
apache-2.0
adgistics/Adgistics.Build
NArrange/src/NArrange.Core/IElementArranger.cs
3294
#region Header /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (c) 2007-2008 James Nies and NArrange contributors. * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *<author>James Nies</author> *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #endregion Header namespace NArrange.Core { using NArrange.Core.CodeElements; /// <summary> /// Element arranger interface. /// </summary> public interface IElementArranger { #region Methods /// <summary> /// Arranges the specified element within the parent element. /// </summary> /// <param name="parentElement">The parent element.</param> /// <param name="codeElement">The code element.</param> void ArrangeElement(ICodeElement parentElement, ICodeElement codeElement); /// <summary> /// Determines whether or not this arranger can handle arrangement of /// the specified element. /// </summary> /// <param name="codeElement">The code element.</param> /// <returns> /// <c>true</c> if this instance can arrange the specified code element; otherwise, <c>false</c>. /// </returns> bool CanArrange(ICodeElement codeElement); /// <summary> /// Determines whether or not this arranger can handle arrangement of /// the specified element. /// </summary> /// <param name="parentElement">The parent element.</param> /// <param name="codeElement">The code element.</param> /// <returns> /// <c>true</c> if this instance can arrange the specified parent element; otherwise, <c>false</c>. /// </returns> bool CanArrange(ICodeElement parentElement, ICodeElement codeElement); #endregion Methods } }
apache-2.0
geeag/kafka
tests/kafkatest/sanity_checks/test_console_consumer.py
4228
# 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. import time from ducktape.mark import matrix from ducktape.mark import parametrize from ducktape.tests.test import Test from ducktape.utils.util import wait_until from kafkatest.services.console_consumer import ConsoleConsumer from kafkatest.services.kafka import KafkaService from kafkatest.services.verifiable_producer import VerifiableProducer from kafkatest.services.zookeeper import ZookeeperService from kafkatest.utils.remote_account import line_count, file_exists from kafkatest.version import LATEST_0_8_2 class ConsoleConsumerTest(Test): """Sanity checks on console consumer service class.""" def __init__(self, test_context): super(ConsoleConsumerTest, self).__init__(test_context) self.topic = "topic" self.zk = ZookeeperService(test_context, num_nodes=1) self.kafka = KafkaService(self.test_context, num_nodes=1, zk=self.zk, topics={self.topic: {"partitions": 1, "replication-factor": 1}}) self.consumer = ConsoleConsumer(self.test_context, num_nodes=1, kafka=self.kafka, topic=self.topic, new_consumer=False) def setUp(self): self.zk.start() @parametrize(security_protocol='PLAINTEXT', new_consumer=False) @parametrize(security_protocol='SASL_SSL', sasl_mechanism='PLAIN') @matrix(security_protocol=['PLAINTEXT', 'SSL', 'SASL_PLAINTEXT', 'SASL_SSL']) def test_lifecycle(self, security_protocol, new_consumer=True, sasl_mechanism='GSSAPI'): """Check that console consumer starts/stops properly, and that we are capturing log output.""" self.kafka.security_protocol = security_protocol self.kafka.client_sasl_mechanism = sasl_mechanism self.kafka.interbroker_sasl_mechanism = sasl_mechanism self.kafka.start() self.consumer.security_protocol = security_protocol self.consumer.new_consumer = new_consumer t0 = time.time() self.consumer.start() node = self.consumer.nodes[0] wait_until(lambda: self.consumer.alive(node), timeout_sec=10, backoff_sec=.2, err_msg="Consumer was too slow to start") self.logger.info("consumer started in %s seconds " % str(time.time() - t0)) # Verify that log output is happening wait_until(lambda: file_exists(node, ConsoleConsumer.LOG_FILE), timeout_sec=10, err_msg="Timed out waiting for logging to start.") assert line_count(node, ConsoleConsumer.LOG_FILE) > 0 # Verify no consumed messages assert line_count(node, ConsoleConsumer.STDOUT_CAPTURE) == 0 self.consumer.stop_node(node) def test_version(self): """Check that console consumer v0.8.2.X successfully starts and consumes messages.""" self.kafka.start() num_messages = 1000 self.producer = VerifiableProducer(self.test_context, num_nodes=1, kafka=self.kafka, topic=self.topic, max_messages=num_messages, throughput=1000) self.producer.start() self.producer.wait() self.consumer.nodes[0].version = LATEST_0_8_2 self.consumer.consumer_timeout_ms = 1000 self.consumer.start() self.consumer.wait() num_consumed = len(self.consumer.messages_consumed[1]) num_produced = self.producer.num_acked assert num_produced == num_consumed, "num_produced: %d, num_consumed: %d" % (num_produced, num_consumed)
apache-2.0
Forexware/quickfixj
src/main/java/quickfix/field/Nested3PartyID.java
1155
/******************************************************************************* * Copyright (c) quickfixengine.org All rights reserved. * * This file is part of the QuickFIX FIX Engine * * This file may be distributed under the terms of the quickfixengine.org * license as defined by quickfixengine.org and appearing in the file * LICENSE included in the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.quickfixengine.org/LICENSE for licensing information. * * Contact ask@quickfixengine.org if any conditions of this licensing * are not clear to you. ******************************************************************************/ package quickfix.field; import quickfix.StringField; public class Nested3PartyID extends StringField { static final long serialVersionUID = 20050617; public static final int FIELD = 949; public Nested3PartyID() { super(949); } public Nested3PartyID(String data) { super(949, data); } }
apache-2.0
groboclown/p4ic4idea
p4java/r17-2/src/test/java/com/perforce/p4java/tests/dev/unit/features121/TrackingTest.java
3977
/** * Copyright (c) 2011 Perforce Software. All rights reserved. */ package com.perforce.p4java.tests.dev.unit.features121; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.net.URISyntaxException; import java.util.Map; import java.util.Properties; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.perforce.p4java.client.IClient; import com.perforce.p4java.exception.P4JavaException; import com.perforce.p4java.option.server.LoginOptions; import com.perforce.p4java.server.CmdSpec; import com.perforce.p4java.server.IOptionsServer; import com.perforce.p4java.server.ServerFactory; import com.perforce.p4java.server.callback.ICommandCallback; import com.perforce.p4java.tests.dev.annotations.Jobs; import com.perforce.p4java.tests.dev.annotations.TestId; import com.perforce.p4java.tests.dev.unit.P4JavaTestCase; /** * Test tracking ("-Ztrack") */ @Jobs({ "job041786" }) @TestId("Dev121_TrackingTest") public class TrackingTest extends P4JavaTestCase { IOptionsServer server = null; IClient client = null; String serverMessage = null; long completedTime = 0; /** * @BeforeClass annotation to a method to be run before all the tests in a * class. */ @BeforeClass public static void oneTimeSetUp() { // one-time initialization code (before all the tests). } /** * @AfterClass annotation to a method to be run after all the tests in a * class. */ @AfterClass public static void oneTimeTearDown() { // one-time cleanup code (after all the tests). } /** * @Before annotation to a method to be run before each test in a class. */ @Before public void setUp() { // initialization code (before each test). } /** * @After annotation to a method to be run after each test in a class. */ @After public void tearDown() { // cleanup code (after each test). } /** * Test tracking ("-Ztrack") */ @Test public void testTracking() { try { Properties props = new Properties(); props.put("enableTracking", "true"); server = ServerFactory .getOptionsServer(this.serverUrlString, props); assertNotNull(server); // Register callback server.registerCallback(new ICommandCallback() { public void receivedServerMessage(int key, int genericCode, int severityCode, String message) { serverMessage = message; } public void receivedServerInfoLine(int key, String infoLine) { serverMessage = infoLine; } public void receivedServerErrorLine(int key, String errorLine) { serverMessage = errorLine; } public void issuingServerCommand(int key, String command) { serverMessage = command; } public void completedServerCommand(int key, long millisecsTaken) { completedTime = millisecsTaken; } }); // Connect to the server. server.connect(); if (server.isConnected()) { if (server.supportsUnicode()) { server.setCharsetName("utf8"); } } // Set the server user server.setUserName(this.userName); // Login using the normal method server.login(this.password, new LoginOptions()); client = getDefaultClient(server); assertNotNull(client); server.setCurrentClient(client); Map<String, Object>[] result = server.execMapCmd( CmdSpec.PRINT.toString(), new String[] {"//depot/basic/readonly/grep/P4CmdGetter.java"}, null); assertNotNull(result); // Verifying the result Map<String, Object> lastResult = result[result.length - 1]; assertNotNull(lastResult); assertNotNull(lastResult.get("data")); assertTrue(((String)lastResult.get("data")).contains("db.user")); } catch (P4JavaException e) { fail("Unexpected exception: " + e.getLocalizedMessage()); } catch (URISyntaxException e) { fail("Unexpected exception: " + e.getLocalizedMessage()); } } }
apache-2.0
fceller/arangodb
3rdParty/fuerte/src/jwt.cpp
5422
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2018 ArangoDB GmbH, Cologne, Germany /// /// 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 holder is ArangoDB GmbH, Cologne, Germany /// /// @author Simon Grätzer //////////////////////////////////////////////////////////////////////////////// #include <chrono> #include <fuerte/helper.h> #include <fuerte/jwt.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/md5.h> #include <openssl/rand.h> #include <openssl/sha.h> #include <velocypack/Builder.h> #include <velocypack/velocypack-aliases.h> #ifdef OPENSSL_NO_SSL2 // OpenSSL > 1.1.0 deprecates RAND_pseudo_bytes #define RAND_BYTES RAND_bytes #else #define RAND_BYTES RAND_pseudo_bytes #endif namespace arangodb { namespace fuerte { inline namespace v1 { /// generate a JWT token for internal cluster communication std::string jwt::generateInternalToken(std::string const& secret, std::string const& id) { std::chrono::seconds iss = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()); /*std::chrono::seconds exp = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()) + _validFor;*/ VPackBuilder bodyBuilder; bodyBuilder.openObject(); bodyBuilder.add("server_id", VPackValue(id)); bodyBuilder.add("iss", VPackValue("arangodb")); bodyBuilder.add("iat", VPackValue(iss.count())); // bodyBuilder.add("exp", VPackValue(exp.count())); bodyBuilder.close(); return generateRawJwt(secret, bodyBuilder.slice()); } std::string jwt::generateUserToken(std::string const& secret, std::string const& username) { assert(!secret.empty()); std::chrono::seconds iss = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()); /*std::chrono::seconds exp = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()) + _validFor;*/ VPackBuilder bodyBuilder; bodyBuilder.openObject(); bodyBuilder.add("preferred_username", VPackValue(username)); bodyBuilder.add("iss", VPackValue("arangodb")); bodyBuilder.add("iat", VPackValue(iss.count())); // bodyBuilder.add("exp", VPackValue(exp.count())); bodyBuilder.close(); return generateRawJwt(secret, bodyBuilder.slice()); } std::string jwt::generateRawJwt(std::string const& secret, VPackSlice const& body) { VPackBuilder headerBuilder; { VPackObjectBuilder h(&headerBuilder); headerBuilder.add("alg", VPackValue("HS256")); headerBuilder.add("typ", VPackValue("JWT")); } std::string fullMessage(encodeBase64(headerBuilder.toJson()) + "." + encodeBase64(body.toJson())); std::string signature = sslHMAC(secret.c_str(), secret.length(), fullMessage.c_str(), fullMessage.length(), Algorithm::ALGORITHM_SHA256); return fullMessage + "." + encodeBase64U(signature); } // code from ArangoDBs SslInterface.cpp std::string jwt::sslHMAC(char const* key, size_t keyLength, char const* message, size_t messageLen, Algorithm algorithm) { EVP_MD* evp_md = nullptr; if (algorithm == Algorithm::ALGORITHM_SHA1) { evp_md = const_cast<EVP_MD*>(EVP_sha1()); } else if (algorithm == jwt::Algorithm::ALGORITHM_SHA224) { evp_md = const_cast<EVP_MD*>(EVP_sha224()); } else if (algorithm == jwt::Algorithm::ALGORITHM_MD5) { evp_md = const_cast<EVP_MD*>(EVP_md5()); } else if (algorithm == jwt::Algorithm::ALGORITHM_SHA384) { evp_md = const_cast<EVP_MD*>(EVP_sha384()); } else if (algorithm == jwt::Algorithm::ALGORITHM_SHA512) { evp_md = const_cast<EVP_MD*>(EVP_sha512()); } else { // default evp_md = const_cast<EVP_MD*>(EVP_sha256()); } unsigned char* md = nullptr; try { md = static_cast<unsigned char*>(malloc(EVP_MAX_MD_SIZE + 1)); if (!md) { return ""; } unsigned int md_len; HMAC(evp_md, key, (int)keyLength, (const unsigned char*)message, messageLen, md, &md_len); std::string copy((char*)md, md_len); free(md); return copy; } catch (...) { free(md); } return ""; } bool jwt::verifyHMAC(char const* challenge, size_t challengeLength, char const* secret, size_t secretLen, char const* response, size_t responseLen, jwt::Algorithm algorithm) { // challenge = key // secret, secretLen = message // result must == BASE64(response, responseLen) std::string s = sslHMAC(challenge, challengeLength, secret, secretLen, algorithm); if (s.length() == responseLen && s.compare(std::string(response, responseLen)) == 0) { return true; } return false; } }}} // namespace arangodb::fuerte::v1
apache-2.0
nknize/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/CloseFollowerIndexStep.java
2167
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.ilm; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.indices.close.CloseIndexRequest; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetadata; import java.util.Map; import static org.elasticsearch.xpack.core.ilm.UnfollowAction.CCR_METADATA_KEY; final class CloseFollowerIndexStep extends AsyncRetryDuringSnapshotActionStep { static final String NAME = "close-follower-index"; CloseFollowerIndexStep(StepKey key, StepKey nextStepKey, Client client) { super(key, nextStepKey, client); } @Override public boolean isRetryable() { return true; } @Override void performDuringNoSnapshot(IndexMetadata indexMetadata, ClusterState currentClusterState, Listener listener) { String followerIndex = indexMetadata.getIndex().getName(); Map<String, String> customIndexMetadata = indexMetadata.getCustomData(CCR_METADATA_KEY); if (customIndexMetadata == null) { listener.onResponse(true); return; } if (indexMetadata.getState() == IndexMetadata.State.OPEN) { CloseIndexRequest closeIndexRequest = new CloseIndexRequest(followerIndex) .masterNodeTimeout(getMasterTimeout(currentClusterState)); getClient().admin().indices().close(closeIndexRequest, ActionListener.wrap( r -> { if (r.isAcknowledged() == false) { throw new ElasticsearchException("close index request failed to be acknowledged"); } listener.onResponse(true); }, listener::onFailure) ); } else { listener.onResponse(true); } } }
apache-2.0
ern/elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/InternalVariableWidthHistogram.java
22531
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.aggregations.bucket.histogram; import org.apache.lucene.util.PriorityQueue; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.search.DocValueFormat; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.InternalAggregation; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation; import org.elasticsearch.search.aggregations.KeyComparable; import org.elasticsearch.search.aggregations.bucket.IteratorAndCurrent; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; public class InternalVariableWidthHistogram extends InternalMultiBucketAggregation< InternalVariableWidthHistogram, InternalVariableWidthHistogram.Bucket> implements Histogram, HistogramFactory { public static class Bucket extends InternalMultiBucketAggregation.InternalBucket implements Histogram.Bucket, KeyComparable<Bucket> { public static class BucketBounds { public double min; public double max; public BucketBounds(double min, double max) { assert min <= max; this.min = min; this.max = max; } public BucketBounds(StreamInput in) throws IOException { this(in.readDouble(), in.readDouble()); } public void writeTo(StreamOutput out) throws IOException { out.writeDouble(min); out.writeDouble(max); } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; BucketBounds that = (BucketBounds) obj; return min == that.min && max == that.max; } @Override public int hashCode() { return Objects.hash(getClass(), min, max); } } private final BucketBounds bounds; private long docCount; private InternalAggregations aggregations; protected final transient DocValueFormat format; private double centroid; public Bucket(double centroid, BucketBounds bounds, long docCount, DocValueFormat format, InternalAggregations aggregations) { this.format = format; this.centroid = centroid; this.bounds = bounds; this.docCount = docCount; this.aggregations = aggregations; } /** * Read from a stream. */ public Bucket(StreamInput in, DocValueFormat format) throws IOException { this.format = format; centroid = in.readDouble(); docCount = in.readVLong(); bounds = new BucketBounds(in); aggregations = InternalAggregations.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeDouble(centroid); out.writeVLong(docCount); bounds.writeTo(out); aggregations.writeTo(out); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != InternalVariableWidthHistogram.Bucket.class) { return false; } InternalVariableWidthHistogram.Bucket that = (InternalVariableWidthHistogram.Bucket) obj; return centroid == that.centroid && bounds.equals(that.bounds) && docCount == that.docCount && Objects.equals(aggregations, that.aggregations); } @Override public int hashCode() { return Objects.hash(getClass(), centroid, bounds, docCount, aggregations); } @Override public String getKeyAsString() { return format.format((double) getKey()).toString(); } /** * Buckets are compared using their centroids. But, in the final XContent returned by the aggregation, * we want the bucket's key to be its min. Otherwise, it would look like the distances between centroids * are buckets, which is incorrect. */ @Override public Object getKey() { return centroid; } public double min() { return bounds.min; } public double max() { return bounds.max; } public double centroid() { return centroid; } @Override public long getDocCount() { return docCount; } @Override public Aggregations getAggregations() { return aggregations; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { String keyAsString = format.format((double) getKey()).toString(); builder.startObject(); builder.field(CommonFields.MIN.getPreferredName(), min()); if (format != DocValueFormat.RAW) { builder.field(CommonFields.MIN_AS_STRING.getPreferredName(), format.format(min())); } builder.field(CommonFields.KEY.getPreferredName(), getKey()); if (format != DocValueFormat.RAW) { builder.field(CommonFields.KEY_AS_STRING.getPreferredName(), keyAsString); } builder.field(CommonFields.MAX.getPreferredName(), max()); if (format != DocValueFormat.RAW) { builder.field(CommonFields.MAX_AS_STRING.getPreferredName(), format.format(max())); } builder.field(CommonFields.DOC_COUNT.getPreferredName(), docCount); aggregations.toXContentInternal(builder, params); builder.endObject(); return builder; } @Override public int compareKey(InternalVariableWidthHistogram.Bucket other) { return Double.compare(centroid, other.centroid); // Use centroid for bucket ordering } public DocValueFormat getFormatter() { return format; } } static class EmptyBucketInfo { final InternalAggregations subAggregations; EmptyBucketInfo(InternalAggregations subAggregations) { this.subAggregations = subAggregations; } EmptyBucketInfo(StreamInput in) throws IOException { this(InternalAggregations.readFrom(in)); } public void writeTo(StreamOutput out) throws IOException { subAggregations.writeTo(out); } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } EmptyBucketInfo that = (EmptyBucketInfo) obj; return Objects.equals(subAggregations, that.subAggregations); } @Override public int hashCode() { return Objects.hash(getClass(), subAggregations); } } private List<Bucket> buckets; private final DocValueFormat format; private final int targetNumBuckets; final EmptyBucketInfo emptyBucketInfo; InternalVariableWidthHistogram( String name, List<Bucket> buckets, EmptyBucketInfo emptyBucketInfo, int targetNumBuckets, DocValueFormat formatter, Map<String, Object> metaData ) { super(name, metaData); this.buckets = buckets; this.emptyBucketInfo = emptyBucketInfo; this.format = formatter; this.targetNumBuckets = targetNumBuckets; } /** * Stream from a stream. */ public InternalVariableWidthHistogram(StreamInput in) throws IOException { super(in); emptyBucketInfo = new EmptyBucketInfo(in); format = in.readNamedWriteable(DocValueFormat.class); buckets = in.readList(stream -> new Bucket(stream, format)); targetNumBuckets = in.readVInt(); } @Override protected void doWriteTo(StreamOutput out) throws IOException { emptyBucketInfo.writeTo(out); out.writeNamedWriteable(format); out.writeList(buckets); out.writeVInt(targetNumBuckets); } @Override public String getWriteableName() { return VariableWidthHistogramAggregationBuilder.NAME; } @Override public List<Bucket> getBuckets() { return Collections.unmodifiableList(buckets); } DocValueFormat getFormatter() { return format; } public int getTargetBuckets() { return targetNumBuckets; } public EmptyBucketInfo getEmptyBucketInfo() { return emptyBucketInfo; } @Override public InternalVariableWidthHistogram create(List<Bucket> buckets) { return new InternalVariableWidthHistogram(name, buckets, emptyBucketInfo, targetNumBuckets, format, metadata); } @Override public Bucket createBucket(InternalAggregations aggregations, Bucket prototype) { return new Bucket(prototype.centroid, prototype.bounds, prototype.docCount, prototype.format, aggregations); } @Override public Bucket createBucket(Number key, long docCount, InternalAggregations aggregations) { return new Bucket(key.doubleValue(), new Bucket.BucketBounds(key.doubleValue(), key.doubleValue()), docCount, format, aggregations); } @Override public Number getKey(MultiBucketsAggregation.Bucket bucket) { return ((Bucket) bucket).centroid; } @Override public Number nextKey(Number key) { return nextKey(key.doubleValue()); } /** * This method should not be called for this specific subclass of InternalHistogram, since there should not be * empty buckets when clustering. = */ private double nextKey(double key) { return key + 1; } @Override protected Bucket reduceBucket(List<Bucket> buckets, ReduceContext context) { List<InternalAggregations> aggregations = new ArrayList<>(buckets.size()); long docCount = 0; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; double sum = 0; for (InternalVariableWidthHistogram.Bucket bucket : buckets) { docCount += bucket.docCount; min = Math.min(min, bucket.bounds.min); max = Math.max(max, bucket.bounds.max); sum += bucket.docCount * bucket.centroid; aggregations.add((InternalAggregations) bucket.getAggregations()); } InternalAggregations aggs = InternalAggregations.reduce(aggregations, context); double centroid = sum / docCount; Bucket.BucketBounds bounds = new Bucket.BucketBounds(min, max); return new Bucket(centroid, bounds, docCount, format, aggs); } public List<Bucket> reduceBuckets(List<InternalAggregation> aggregations, ReduceContext reduceContext) { PriorityQueue<IteratorAndCurrent<Bucket>> pq = new PriorityQueue<>(aggregations.size()) { @Override protected boolean lessThan(IteratorAndCurrent<Bucket> a, IteratorAndCurrent<Bucket> b) { return Double.compare(a.current().centroid, b.current().centroid) < 0; } }; for (InternalAggregation aggregation : aggregations) { InternalVariableWidthHistogram histogram = (InternalVariableWidthHistogram) aggregation; if (histogram.buckets.isEmpty() == false) { pq.add(new IteratorAndCurrent<>(histogram.buckets.iterator())); } } List<Bucket> reducedBuckets = new ArrayList<>(); if (pq.size() > 0) { double key = pq.top().current().centroid(); // list of buckets coming from different shards that have the same key List<Bucket> currentBuckets = new ArrayList<>(); do { IteratorAndCurrent<Bucket> top = pq.top(); if (Double.compare(top.current().centroid(), key) != 0) { // The key changes, reduce what we already buffered and reset the buffer for current buckets. final Bucket reduced = reduceBucket(currentBuckets, reduceContext); reduceContext.consumeBucketsAndMaybeBreak(1); reducedBuckets.add(reduced); currentBuckets.clear(); key = top.current().centroid(); } currentBuckets.add(top.current()); if (top.hasNext()) { Bucket prev = top.current(); top.next(); assert top.current().compareKey(prev) >= 0 : "shards must return data sorted by centroid"; pq.updateTop(); } else { pq.pop(); } } while (pq.size() > 0); if (currentBuckets.isEmpty() == false) { final Bucket reduced = reduceBucket(currentBuckets, reduceContext); reduceContext.consumeBucketsAndMaybeBreak(1); reducedBuckets.add(reduced); } } mergeBucketsIfNeeded(reducedBuckets, targetNumBuckets, reduceContext); return reducedBuckets; } class BucketRange { int startIdx; int endIdx; /** * These are optional utility fields * They're useful for determining whether buckets should be merged */ double min; double max; double centroid; long docCount; public void mergeWith(BucketRange other) { startIdx = Math.min(startIdx, other.startIdx); endIdx = Math.max(endIdx, other.endIdx); if (docCount + other.docCount > 0) { // Avoids div by 0 error. This condition could be false if the optional docCount field was not set centroid = ((centroid * docCount) + (other.centroid * other.docCount)) / (docCount + other.docCount); docCount += other.docCount; } min = Math.min(min, other.min); max = Math.max(max, other.max); } } /** * For each range {startIdx, endIdx} in <code>ranges</code>, all the buckets in that index range * from <code>buckets</code> are merged, and this merged bucket replaces the entire range. */ private void mergeBucketsWithPlan(List<Bucket> buckets, List<BucketRange> plan, ReduceContext reduceContext) { for (int i = plan.size() - 1; i >= 0; i--) { BucketRange range = plan.get(i); int endIdx = range.endIdx; int startIdx = range.startIdx; if (startIdx == endIdx) continue; List<Bucket> toMerge = new ArrayList<>(); for (int idx = endIdx; idx > startIdx; idx--) { toMerge.add(buckets.get(idx)); buckets.remove(idx); } toMerge.add(buckets.get(startIdx)); // Don't remove the startIdx bucket because it will be replaced by the merged bucket int toRemove = toMerge.stream().mapToInt(b -> countInnerBucket(b) + 1).sum(); reduceContext.consumeBucketsAndMaybeBreak(-toRemove + 1); Bucket merged_bucket = reduceBucket(toMerge, reduceContext); buckets.set(startIdx, merged_bucket); } } /** * Makes a merge plan by simulating the merging of the two closest buckets, until the target number of buckets is reached. * Distance is determined by centroid comparison. * Then, this plan is actually executed and the underlying buckets are merged. * * Requires: <code>buckets</code> is sorted by centroid. */ private void mergeBucketsIfNeeded(List<Bucket> buckets, int targetNumBuckets, ReduceContext reduceContext) { // Make a plan for getting the target number of buckets // Each range represents a set of adjacent bucket indices of buckets that will be merged together List<BucketRange> ranges = new ArrayList<>(); // Initialize each range to represent an individual bucket for (int i = 0; i < buckets.size(); i++) { // Since buckets is sorted by centroid, ranges will be as well BucketRange range = new BucketRange(); range.centroid = buckets.get(i).centroid; range.docCount = buckets.get(i).getDocCount(); range.startIdx = i; range.endIdx = i; ranges.add(range); } // Continually merge the two closest ranges until the target is reached while (ranges.size() > targetNumBuckets) { // Find two closest ranges (i.e. the two closest buckets after the previous merges are completed) // We only have to make one pass through the list because it is sorted by centroid int closestIdx = 0; // After this loop, (closestIdx, closestIdx + 1) will be the 2 closest buckets double smallest_distance = Double.POSITIVE_INFINITY; for (int i = 0; i < ranges.size() - 1; i++) { double new_distance = ranges.get(i + 1).centroid - ranges.get(i).centroid; // Positive because buckets is sorted if (new_distance < smallest_distance) { closestIdx = i; smallest_distance = new_distance; } } // Merge the two closest ranges ranges.get(closestIdx).mergeWith(ranges.get(closestIdx + 1)); ranges.remove(closestIdx + 1); } // Execute the plan (merge the underlying buckets) mergeBucketsWithPlan(buckets, ranges, reduceContext); } private void mergeBucketsWithSameMin(List<Bucket> buckets, ReduceContext reduceContext) { // Create a merge plan List<BucketRange> ranges = new ArrayList<>(); // Initialize each range to represent an individual bucket for (int i = 0; i < buckets.size(); i++) { BucketRange range = new BucketRange(); range.min = buckets.get(i).min(); range.startIdx = i; range.endIdx = i; ranges.add(range); } // Merge ranges with same min value int i = 0; while (i < ranges.size() - 1) { BucketRange range = ranges.get(i); BucketRange nextRange = ranges.get(i + 1); if (range.min == nextRange.min) { range.mergeWith(nextRange); ranges.remove(i + 1); } else { i++; } } // Execute the plan (merge the underlying buckets) mergeBucketsWithPlan(buckets, ranges, reduceContext); } /** * When two adjacent buckets A, B overlap (A.max &gt; B.min) then their boundary is set to * the midpoint: (A.max + B.min) / 2. * * After this adjustment, A will contain more values than indicated and B will have less. */ private void adjustBoundsForOverlappingBuckets(List<Bucket> buckets, ReduceContext reduceContext) { for (int i = 1; i < buckets.size(); i++) { Bucket curBucket = buckets.get(i); Bucket prevBucket = buckets.get(i - 1); if (curBucket.bounds.min < prevBucket.bounds.max) { // We don't want overlapping buckets --> Adjust their bounds // TODO: Think of a fairer way to do this. Should prev.max = cur.min? curBucket.bounds.min = (prevBucket.bounds.max + curBucket.bounds.min) / 2; prevBucket.bounds.max = curBucket.bounds.min; } } } @Override public InternalAggregation reduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) { List<Bucket> reducedBuckets = reduceBuckets(aggregations, reduceContext); if (reduceContext.isFinalReduce()) { buckets.sort(Comparator.comparing(Bucket::min)); mergeBucketsWithSameMin(reducedBuckets, reduceContext); adjustBoundsForOverlappingBuckets(reducedBuckets, reduceContext); } return new InternalVariableWidthHistogram(getName(), reducedBuckets, emptyBucketInfo, targetNumBuckets, format, metadata); } @Override public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { builder.startArray(CommonFields.BUCKETS.getPreferredName()); for (Bucket bucket : buckets) { bucket.toXContent(builder, params); } builder.endArray(); return builder; } @Override public InternalAggregation createAggregation(List<MultiBucketsAggregation.Bucket> buckets) { // convert buckets to the right type List<Bucket> buckets2 = new ArrayList<>(buckets.size()); for (Object b : buckets) { buckets2.add((Bucket) b); } buckets2 = Collections.unmodifiableList(buckets2); return new InternalVariableWidthHistogram(name, buckets2, emptyBucketInfo, targetNumBuckets, format, getMetadata()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; if (super.equals(obj) == false) return false; InternalVariableWidthHistogram that = (InternalVariableWidthHistogram) obj; return Objects.equals(buckets, that.buckets) && Objects.equals(format, that.format) && Objects.equals(emptyBucketInfo, that.emptyBucketInfo); } @Override public int hashCode() { return Objects.hash(super.hashCode(), buckets, format, emptyBucketInfo); } }
apache-2.0
ghchinoy/tensorflow
tensorflow/python/ops/ragged/ragged_reduce_op_test.py
14273
# Copyright 2018 The TensorFlow Authors. 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. # ============================================================================== """Tests for ragged_math_ops.reduce_<AGGREGATE> ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.ops.ragged import ragged_math_ops from tensorflow.python.ops.ragged import ragged_test_util from tensorflow.python.platform import googletest _MAX_INT32 = dtypes.int32.max _MIN_INT32 = dtypes.int32.min _NAN = np.nan def mean(*values): return 1.0 * sum(values) / len(values) @test_util.run_all_in_graph_and_eager_modes class RaggedReduceOpsTest(ragged_test_util.RaggedTensorTestCase, parameterized.TestCase): @parameterized.parameters( #========================================================================= # Docstring examples. RaggedTensor for testing is: # [[3, 1, 4], # [1, 5, ], # [9, ], # [2, 6 ]] #========================================================================= dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=0, expected=[15, 12, 4] # = [3+1+9+2, 1+5+6, 4] ), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=-2, expected=[15, 12, 4] # = [3+1+9+2, 1+5+6, 4] ), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=1, expected=[8, 6, 9, 8] # = [3+1+4, 1+5, 9, 2+6] ), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=-1, expected=[8, 6, 9, 8] # = [3+1+4, 1+5, 9, 2+6] ), dict( ragged_reduce_op=ragged_math_ops.reduce_prod, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=0, expected=[54, 30, 4] # = [3*1*9*2, 1*5*6, 4] ), dict( ragged_reduce_op=ragged_math_ops.reduce_prod, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=1, expected=[12, 5, 9, 12] # = [3*1*4, 1*5, 9, 2*6] ), dict( ragged_reduce_op=ragged_math_ops.reduce_min, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=0, expected=[1, 1, 4] # = [min(3, 1, 9, 2), min(1, 5, 6), 4] ), dict( ragged_reduce_op=ragged_math_ops.reduce_min, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=1, expected=[1, 1, 9, 2] # = [min(3, 1, 4), min(1, 5), 9, min(2, 6)] ), dict( ragged_reduce_op=ragged_math_ops.reduce_max, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=0, expected=[9, 6, 4] # = [max(3, 1, 9, 2), max(1, 5, 6), 4] ), dict( ragged_reduce_op=ragged_math_ops.reduce_max, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=1, expected=[4, 5, 9, 6] # = [max(3, 1, 4), max(1, 5), 9, max(2, 6)] ), dict( ragged_reduce_op=ragged_math_ops.reduce_mean, rt_input=[[3, 1, 4], [1, 5], [9], [2, 6]], axis=0, expected=[3.75, 4, 4] # = [mean(3, 1, 9, 2), mean(1, 5, 6), 4] ), dict( ragged_reduce_op=ragged_math_ops.reduce_any, rt_input=[[True, True], [True, True, False, True], [False, True]], axis=0, expected=[True, True, False, True]), dict( ragged_reduce_op=ragged_math_ops.reduce_any, rt_input=[[True, True], [True, True, False, True], [False, True]], axis=1, expected=[True, True, True]), dict( ragged_reduce_op=ragged_math_ops.reduce_all, rt_input=[[True, True], [True, True, False, True], [False, True]], axis=0, expected=[False, True, False, True]), dict( ragged_reduce_op=ragged_math_ops.reduce_all, rt_input=[[True, True], [True, True, False, True], [False, True]], axis=1, expected=[True, False, False]), #========================================================================= # Examples with the following RaggedTensor (ragged_rank=1): # [[0, 1, 2, 3], # [4 ], # [ ], # [5, 6 ], # [7 ], # [8, 9 ]] #========================================================================= # axis=None dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=None, expected=0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9), dict( ragged_reduce_op=ragged_math_ops.reduce_prod, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=None, expected=0 * 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9), dict( ragged_reduce_op=ragged_math_ops.reduce_min, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=None, expected=min(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)), dict( ragged_reduce_op=ragged_math_ops.reduce_max, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=None, expected=max(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)), dict( ragged_reduce_op=ragged_math_ops.reduce_mean, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=None, expected=mean(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)), # axis=0 dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=0, expected=[0 + 4 + 5 + 7 + 8, 1 + 6 + 9, 2, 3]), dict( ragged_reduce_op=ragged_math_ops.reduce_prod, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=0, expected=[0 * 4 * 5 * 7 * 8, 1 * 6 * 9, 2, 3]), dict( ragged_reduce_op=ragged_math_ops.reduce_min, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=0, expected=[min(0, 4, 5, 7, 8), min(1, 6, 9), 2, 3]), dict( ragged_reduce_op=ragged_math_ops.reduce_max, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=0, expected=[max(0, 4, 5, 7, 8), max(1, 6, 9), 2, 3]), dict( ragged_reduce_op=ragged_math_ops.reduce_mean, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=0, expected=[mean(0, 4, 5, 7, 8), mean(1, 6, 9), 2, 3]), # axis=1 # Note: we don't test mean here because it gives a NaN, and this will # cause assertEqual to fail (since NaN != NaN). See testMeanNan(). dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=1, expected=[0 + 1 + 2 + 3, 4, 0, 5 + 6, 7, 8 + 9]), dict( ragged_reduce_op=ragged_math_ops.reduce_prod, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=1, expected=[0 * 1 * 2 * 3, 4, 1, 5 * 6, 7, 8 * 9]), dict( ragged_reduce_op=ragged_math_ops.reduce_min, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=1, expected=[min(0, 1, 2, 3), 4, _MAX_INT32, min(5, 6), 7, min(8, 9)]), dict( ragged_reduce_op=ragged_math_ops.reduce_max, rt_input=[[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]], axis=1, expected=[max(0, 1, 2, 3), 4, _MIN_INT32, max(5, 6), 7, max(8, 9)]), #========================================================================= # Examples with ragged_rank=2: # [[[1, 2], [ ], [3, 4, 5]], # [[6, 7], [ ], [8 ]], # [ ], # [[9 ] ]] #========================================================================= dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=[], expected=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]]), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=None, expected=sum([1, 2, 3, 4, 5, 6, 7, 8, 9])), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=0, expected=[[1 + 6 + 9, 2 + 7], [], [3 + 8, 4, 5]]), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=1, expected=[[1 + 3, 2 + 4, 5], [6 + 8, 7], [], [9]]), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=2, expected=[[1 + 2, 0, 3 + 4 + 5], [6 + 7, 0, 8], [], [9]]), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=[0, 1], expected=[1 + 3 + 6 + 8 + 9, 2 + 4 + 7, 5]), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=[0, 2], expected=[1 + 6 + 9 + 2 + 7, 0, 3 + 8 + 4 + 5]), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=[1, 2], expected=[1 + 2 + 3 + 4 + 5, 6 + 7 + 8, 0, 9]), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=[0, 1, 2], expected=sum([1, 2, 3, 4, 5, 6, 7, 8, 9])), #========================================================================= # Examples for ragged_reduce_mean ragged_rank=2: # [[[1, 2], [3, 4, 5]], # [[6, 7], [8 ]], # [[9 ] ]] #========================================================================= dict( ragged_reduce_op=ragged_math_ops.reduce_mean, rt_input=[[[1, 2], [3, 4, 5]], [[6, 7], [8]], [[9]]], axis=0, expected=[[mean(1, 6, 9), mean(2, 7)], [mean(3, 8), 4, 5]]), dict( ragged_reduce_op=ragged_math_ops.reduce_mean, rt_input=[[[1, 2], [3, 4, 5]], [[6, 7], [8]], [[9]]], axis=1, expected=[[mean(1, 3), mean(2, 4), 5], [mean(6, 8), 7], [9]]), dict( ragged_reduce_op=ragged_math_ops.reduce_mean, rt_input=[[[1, 2], [3, 4, 5]], [[6, 7], [8]], [[9]]], axis=2, expected=[[mean(1, 2), mean(3, 4, 5)], [mean(6, 7), 8], [9]]), # Test case for GitHub issue 27497, multiple negative axes. dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=[-2, -1], expected=[1 + 2 + 3 + 4 + 5, 6 + 7 + 8, 0, 9]), dict( ragged_reduce_op=ragged_math_ops.reduce_sum, rt_input=[[[1, 2], [], [3, 4, 5]], [[6, 7], [], [8]], [], [[9]]], axis=[-3, -2, -1], expected=sum([1, 2, 3, 4, 5, 6, 7, 8, 9])), ) def testReduce(self, ragged_reduce_op, rt_input, axis, expected): rt_input = ragged_factory_ops.constant(rt_input) reduced = ragged_reduce_op(rt_input, axis) self.assertRaggedEqual(reduced, expected) def assertEqualWithNan(self, actual, expected): """Like assertEqual, but NaN==NaN.""" self.assertTrue( ((actual == expected) | (np.isnan(actual) & np.isnan(expected))).all()) def testMeanNan(self): rt_as_list = [[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]] expected = ( np.array([0 + 1 + 2 + 3, 4, 0, 5 + 6, 7, 8 + 9]) / np.array( [4, 1, 0, 2, 1, 2])) rt_input = ragged_factory_ops.constant(rt_as_list) reduced = ragged_math_ops.reduce_mean(rt_input, axis=1) self.assertEqualWithNan(self.evaluate(reduced), expected) def testMeanWithTensorInputs(self): tensor = [[1.0, 2.0, 3.0], [10.0, 20.0, 30.0]] expected = [2.0, 20.0] reduced = ragged_math_ops.reduce_mean(tensor, axis=1) self.assertRaggedEqual(reduced, expected) def testErrors(self): rt_input = ragged_factory_ops.constant([[1, 2, 3], [4, 5]]) axis = array_ops.placeholder_with_default(constant_op.constant([0]), None) if not context.executing_eagerly(): self.assertRaisesRegexp( ValueError, r'axis must be known at graph construction time.', ragged_math_ops.reduce_sum, rt_input, axis) self.assertRaisesRegexp(TypeError, r'axis must be an int; got str.*', ragged_math_ops.reduce_sum, rt_input, ['x']) if __name__ == '__main__': googletest.main()
apache-2.0
alaski/nova
nova/tests/unit/test_flavors.py
19106
# Copyright 2011 Ken Pepple # 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. """ Unit Tests for flavors code """ from nova.compute import flavors from nova import context from nova import db from nova import exception from nova import objects from nova.objects import base as obj_base from nova import test DEFAULT_FLAVORS = [ {'memory_mb': 512, 'root_gb': 1, 'deleted_at': None, 'name': 'm1.tiny', 'deleted': 0, 'created_at': None, 'ephemeral_gb': 0, 'updated_at': None, 'disabled': False, 'vcpus': 1, 'extra_specs': {}, 'swap': 0, 'rxtx_factor': 1.0, 'is_public': True, 'flavorid': '1', 'vcpu_weight': None, 'id': 2}, {'memory_mb': 2048, 'root_gb': 20, 'deleted_at': None, 'name': 'm1.small', 'deleted': 0, 'created_at': None, 'ephemeral_gb': 0, 'updated_at': None, 'disabled': False, 'vcpus': 1, 'extra_specs': {}, 'swap': 0, 'rxtx_factor': 1.0, 'is_public': True, 'flavorid': '2', 'vcpu_weight': None, 'id': 5}, {'memory_mb': 4096, 'root_gb': 40, 'deleted_at': None, 'name': 'm1.medium', 'deleted': 0, 'created_at': None, 'ephemeral_gb': 0, 'updated_at': None, 'disabled': False, 'vcpus': 2, 'extra_specs': {}, 'swap': 0, 'rxtx_factor': 1.0, 'is_public': True, 'flavorid': '3', 'vcpu_weight': None, 'id': 1}, {'memory_mb': 8192, 'root_gb': 80, 'deleted_at': None, 'name': 'm1.large', 'deleted': 0, 'created_at': None, 'ephemeral_gb': 0, 'updated_at': None, 'disabled': False, 'vcpus': 4, 'extra_specs': {}, 'swap': 0, 'rxtx_factor': 1.0, 'is_public': True, 'flavorid': '4', 'vcpu_weight': None, 'id': 3}, {'memory_mb': 16384, 'root_gb': 160, 'deleted_at': None, 'name': 'm1.xlarge', 'deleted': 0, 'created_at': None, 'ephemeral_gb': 0, 'updated_at': None, 'disabled': False, 'vcpus': 8, 'extra_specs': {}, 'swap': 0, 'rxtx_factor': 1.0, 'is_public': True, 'flavorid': '5', 'vcpu_weight': None, 'id': 4} ] CONTEXT = context.RequestContext('fake', 'fake', is_admin=False) DEFAULT_FLAVOR_OBJS = [ objects.Flavor._obj_from_primitive(CONTEXT, objects.Flavor.VERSION, {'nova_object.data': flavor}) for flavor in DEFAULT_FLAVORS ] class InstanceTypeTestCase(test.TestCase): """Test cases for flavor code.""" def test_will_not_get_bad_default_instance_type(self): # ensures error raised on bad default flavor. self.flags(default_flavor='unknown_flavor') self.assertRaises(exception.FlavorNotFound, flavors.get_default_flavor) def test_flavor_get_by_None_name_returns_default(self): # Ensure get by name returns default flavor with no name. default = flavors.get_default_flavor() actual = flavors.get_flavor_by_name(None) self.assertIsInstance(default, objects.Flavor) self.assertIsInstance(actual, objects.Flavor) self.assertEqual(default.flavorid, actual.flavorid) def test_will_not_get_flavor_with_bad_name(self): # Ensure get by name returns default flavor with bad name. self.assertRaises(exception.FlavorNotFound, flavors.get_flavor_by_name, 10000) def test_will_not_get_instance_by_unknown_flavor_id(self): # Ensure get by flavor raises error with wrong flavorid. self.assertRaises(exception.FlavorNotFound, flavors.get_flavor_by_flavor_id, 'unknown_flavor') def test_will_get_instance_by_flavor_id(self): default_instance_type = flavors.get_default_flavor() flavorid = default_instance_type.flavorid fetched = flavors.get_flavor_by_flavor_id(flavorid) self.assertIsInstance(fetched, objects.Flavor) self.assertEqual(default_instance_type.flavorid, fetched.flavorid) def test_get_all_flavors_sorted_list_sort(self): # Test default sort all_flavors = flavors.get_all_flavors_sorted_list() self.assertEqual(len(DEFAULT_FLAVORS), len(all_flavors)) for i in range(len(all_flavors)): f = all_flavors[i] self.assertIsInstance(f, objects.Flavor) self.assertEqual(DEFAULT_FLAVORS[i]['flavorid'], f.flavorid) # Test sorted by name all_flavors = flavors.get_all_flavors_sorted_list(sort_key='name') expected = sorted(DEFAULT_FLAVORS, key=lambda item: item['name']) self.assertEqual(len(expected), len(all_flavors)) for i in range(len(all_flavors)): f = all_flavors[i] self.assertIsInstance(f, objects.Flavor) self.assertEqual(expected[i]['flavorid'], f.flavorid) def test_get_all_flavors_sorted_list_limit(self): limited_flavors = flavors.get_all_flavors_sorted_list(limit=2) self.assertEqual(2, len(limited_flavors)) def test_get_all_flavors_sorted_list_marker(self): all_flavors = flavors.get_all_flavors_sorted_list() # Set the 3rd result as the marker marker_flavorid = all_flavors[2].flavorid marked_flavors = flavors.get_all_flavors_sorted_list( marker=marker_flavorid) # We expect everything /after/ the 3rd result expected_results = all_flavors[3:] self.assertEqual(len(expected_results), len(marked_flavors)) for i in range(len(marked_flavors)): f = marked_flavors[i] self.assertIsInstance(f, objects.Flavor) self.assertEqual(expected_results[i].flavorid, f.flavorid) class InstanceTypeToolsTest(test.TestCase): def _dict_to_metadata(self, data): return [{'key': key, 'value': value} for key, value in data.items()] def _test_extract_flavor(self, prefix): instance_type = flavors.get_default_flavor() instance_type_p = obj_base.obj_to_primitive(instance_type) metadata = {} flavors.save_flavor_info(metadata, instance_type, prefix) instance = {'system_metadata': self._dict_to_metadata(metadata)} _instance_type = flavors.extract_flavor(instance, prefix) _instance_type_p = obj_base.obj_to_primitive(_instance_type) props = flavors.system_metadata_flavor_props.keys() for key in list(instance_type_p.keys()): if key not in props: del instance_type_p[key] self.assertEqual(instance_type_p, _instance_type_p) def test_extract_flavor(self): self._test_extract_flavor('') def test_extract_flavor_no_sysmeta(self): instance = {} prefix = '' result = flavors.extract_flavor(instance, prefix) self.assertIsNone(result) def test_extract_flavor_prefix(self): self._test_extract_flavor('foo_') def test_save_flavor_info(self): instance_type = flavors.get_default_flavor() example = {} example_prefix = {} for key in flavors.system_metadata_flavor_props.keys(): example['instance_type_%s' % key] = instance_type[key] example_prefix['fooinstance_type_%s' % key] = instance_type[key] metadata = {} flavors.save_flavor_info(metadata, instance_type) self.assertEqual(example, metadata) metadata = {} flavors.save_flavor_info(metadata, instance_type, 'foo') self.assertEqual(example_prefix, metadata) def test_delete_flavor_info(self): instance_type = flavors.get_default_flavor() metadata = {} flavors.save_flavor_info(metadata, instance_type) flavors.save_flavor_info(metadata, instance_type, '_') flavors.delete_flavor_info(metadata, '', '_') self.assertEqual(metadata, {}) def test_flavor_numa_extras_are_saved(self): instance_type = flavors.get_default_flavor() instance_type['extra_specs'] = { 'hw:numa_mem.0': '123', 'hw:numa_cpus.0': '456', 'hw:numa_mem.1': '789', 'hw:numa_cpus.1': 'ABC', 'foo': 'bar', } sysmeta = flavors.save_flavor_info({}, instance_type) _instance_type = flavors.extract_flavor({'system_metadata': sysmeta}) expected_extra_specs = { 'hw:numa_mem.0': '123', 'hw:numa_cpus.0': '456', 'hw:numa_mem.1': '789', 'hw:numa_cpus.1': 'ABC', } self.assertEqual(expected_extra_specs, _instance_type['extra_specs']) flavors.delete_flavor_info(sysmeta, '') self.assertEqual({}, sysmeta) class InstanceTypeFilteringTest(test.TestCase): """Test cases for the filter option available for instance_type_get_all.""" def setUp(self): super(InstanceTypeFilteringTest, self).setUp() self.context = context.get_admin_context() def assertFilterResults(self, filters, expected): inst_types = objects.FlavorList.get_all( self.context, filters=filters) inst_names = [i.name for i in inst_types] self.assertEqual(inst_names, expected) def test_no_filters(self): filters = None expected = ['m1.tiny', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge'] self.assertFilterResults(filters, expected) def test_min_memory_mb_filter(self): # Exclude tiny instance which is 512 MB. filters = dict(min_memory_mb=513) expected = ['m1.small', 'm1.medium', 'm1.large', 'm1.xlarge'] self.assertFilterResults(filters, expected) def test_min_root_gb_filter(self): # Exclude everything but large and xlarge which have >= 80 GB. filters = dict(min_root_gb=80) expected = ['m1.large', 'm1.xlarge'] self.assertFilterResults(filters, expected) def test_min_memory_mb_AND_root_gb_filter(self): # Exclude everything but large and xlarge which have >= 80 GB. filters = dict(min_memory_mb=16384, min_root_gb=80) expected = ['m1.xlarge'] self.assertFilterResults(filters, expected) class CreateInstanceTypeTest(test.TestCase): def assertInvalidInput(self, *create_args, **create_kwargs): self.assertRaises(exception.InvalidInput, flavors.create, *create_args, **create_kwargs) def test_create_with_valid_name(self): # Names can contain alphanumeric and [_.- ] flavors.create('azAZ09. -_', 64, 1, 120) # And they are not limited to ascii characters # E.g.: m1.huge in simplified Chinese flavors.create(u'm1.\u5DE8\u5927', 6400, 100, 12000) def test_name_with_special_characters(self): # Names can contain all printable characters flavors.create('_foo.bar-123', 64, 1, 120) # Ensure instance types raises InvalidInput for invalid characters. self.assertInvalidInput('foobar\x00', 64, 1, 120) def test_name_with_non_printable_characters(self): # Names cannot contain printable characters self.assertInvalidInput(u'm1.\u0868 #', 64, 1, 120) def test_name_length_checks(self): MAX_LEN = 255 # Flavor name with 255 characters or less is valid. flavors.create('a' * MAX_LEN, 64, 1, 120) # Flavor name which is more than 255 characters will cause error. self.assertInvalidInput('a' * (MAX_LEN + 1), 64, 1, 120) # Flavor name which is empty should cause an error self.assertInvalidInput('', 64, 1, 120) def test_all_whitespace_flavor_names_rejected(self): self.assertInvalidInput(' ', 64, 1, 120) def test_flavorid_with_invalid_characters(self): # Ensure Flavor ID can only contain [a-zA-Z0-9_.- ] self.assertInvalidInput('a', 64, 1, 120, flavorid=u'\u2605') self.assertInvalidInput('a', 64, 1, 120, flavorid='%%$%$@#$#@$@#$^%') def test_flavorid_length_checks(self): MAX_LEN = 255 # Flavor ID which is more than 255 characters will cause error. self.assertInvalidInput('a', 64, 1, 120, flavorid='a' * (MAX_LEN + 1)) def test_memory_must_be_positive_db_integer(self): self.assertInvalidInput('flavor1', 'foo', 1, 120) self.assertInvalidInput('flavor1', -1, 1, 120) self.assertInvalidInput('flavor1', 0, 1, 120) self.assertInvalidInput('flavor1', db.MAX_INT + 1, 1, 120) flavors.create('flavor1', 1, 1, 120) def test_vcpus_must_be_positive_db_integer(self): self.assertInvalidInput('flavor`', 64, 'foo', 120) self.assertInvalidInput('flavor1', 64, -1, 120) self.assertInvalidInput('flavor1', 64, 0, 120) self.assertInvalidInput('flavor1', 64, db.MAX_INT + 1, 120) flavors.create('flavor1', 64, 1, 120) def test_root_gb_must_be_nonnegative_db_integer(self): self.assertInvalidInput('flavor1', 64, 1, 'foo') self.assertInvalidInput('flavor1', 64, 1, -1) self.assertInvalidInput('flavor1', 64, 1, db.MAX_INT + 1) flavors.create('flavor1', 64, 1, 0) flavors.create('flavor2', 64, 1, 120) def test_ephemeral_gb_must_be_nonnegative_db_integer(self): self.assertInvalidInput('flavor1', 64, 1, 120, ephemeral_gb='foo') self.assertInvalidInput('flavor1', 64, 1, 120, ephemeral_gb=-1) self.assertInvalidInput('flavor1', 64, 1, 120, ephemeral_gb=db.MAX_INT + 1) flavors.create('flavor1', 64, 1, 120, ephemeral_gb=0) flavors.create('flavor2', 64, 1, 120, ephemeral_gb=120) def test_swap_must_be_nonnegative_db_integer(self): self.assertInvalidInput('flavor1', 64, 1, 120, swap='foo') self.assertInvalidInput('flavor1', 64, 1, 120, swap=-1) self.assertInvalidInput('flavor1', 64, 1, 120, swap=db.MAX_INT + 1) flavors.create('flavor1', 64, 1, 120, swap=0) flavors.create('flavor2', 64, 1, 120, swap=1) def test_rxtx_factor_must_be_positive_float(self): self.assertInvalidInput('flavor1', 64, 1, 120, rxtx_factor='foo') self.assertInvalidInput('flavor1', 64, 1, 120, rxtx_factor=-1.0) self.assertInvalidInput('flavor1', 64, 1, 120, rxtx_factor=0.0) flavor = flavors.create('flavor1', 64, 1, 120, rxtx_factor=1.0) self.assertEqual(1.0, flavor.rxtx_factor) flavor = flavors.create('flavor2', 64, 1, 120, rxtx_factor=1.1) self.assertEqual(1.1, flavor.rxtx_factor) def test_rxtx_factor_must_be_within_sql_float_range(self): _context = context.get_admin_context() db.flavor_get_all(_context) # We do * 10 since this is an approximation and we need to make sure # the difference is noticeble. over_rxtx_factor = db.SQL_SP_FLOAT_MAX * 10 self.assertInvalidInput('flavor1', 64, 1, 120, rxtx_factor=over_rxtx_factor) flavor = flavors.create('flavor2', 64, 1, 120, rxtx_factor=db.SQL_SP_FLOAT_MAX) self.assertEqual(db.SQL_SP_FLOAT_MAX, flavor.rxtx_factor) def test_is_public_must_be_valid_bool_string(self): self.assertInvalidInput('flavor1', 64, 1, 120, is_public='foo') flavors.create('flavor1', 64, 1, 120, is_public='TRUE') flavors.create('flavor2', 64, 1, 120, is_public='False') flavors.create('flavor3', 64, 1, 120, is_public='Yes') flavors.create('flavor4', 64, 1, 120, is_public='No') flavors.create('flavor5', 64, 1, 120, is_public='Y') flavors.create('flavor6', 64, 1, 120, is_public='N') flavors.create('flavor7', 64, 1, 120, is_public='1') flavors.create('flavor8', 64, 1, 120, is_public='0') flavors.create('flavor9', 64, 1, 120, is_public='true') def test_flavorid_populated(self): flavor1 = flavors.create('flavor1', 64, 1, 120) self.assertIsNotNone(flavor1.flavorid) flavor2 = flavors.create('flavor2', 64, 1, 120, flavorid='') self.assertIsNotNone(flavor2.flavorid) flavor3 = flavors.create('flavor3', 64, 1, 120, flavorid='foo') self.assertEqual('foo', flavor3.flavorid) def test_default_values(self): flavor1 = flavors.create('flavor1', 64, 1, 120) self.assertIsNotNone(flavor1.flavorid) self.assertEqual(flavor1.ephemeral_gb, 0) self.assertEqual(flavor1.swap, 0) self.assertEqual(flavor1.rxtx_factor, 1.0) def test_basic_create(self): # Ensure instance types can be created. ctxt = context.get_admin_context() original_list = objects.FlavorList.get_all(ctxt) # Create new type and make sure values stick flavor = flavors.create('flavor', 64, 1, 120) self.assertEqual(flavor.name, 'flavor') self.assertEqual(flavor.memory_mb, 64) self.assertEqual(flavor.vcpus, 1) self.assertEqual(flavor.root_gb, 120) # Ensure new type shows up in list new_list = objects.FlavorList.get_all(ctxt) self.assertNotEqual(len(original_list), len(new_list), 'flavor was not created') def test_create_then_delete(self): ctxt = context.get_admin_context() original_list = objects.FlavorList.get_all(ctxt) flavor = flavors.create('flavor', 64, 1, 120) # Ensure new type shows up in list new_list = objects.FlavorList.get_all(ctxt) self.assertNotEqual(len(original_list), len(new_list), 'instance type was not created') flavor.destroy() self.assertRaises(exception.FlavorNotFound, objects.Flavor.get_by_name, ctxt, flavor.name) # Deleted instance should not be in list anymore new_list = objects.FlavorList.get_all(ctxt) self.assertEqual(len(original_list), len(new_list)) for i, f in enumerate(original_list): self.assertIsInstance(f, objects.Flavor) self.assertEqual(f.flavorid, new_list[i].flavorid) def test_duplicate_names_fail(self): # Ensures that name duplicates raise FlavorExists flavors.create('flavor', 256, 1, 120, 200, 'flavor1') self.assertRaises(exception.FlavorExists, flavors.create, 'flavor', 64, 1, 120) def test_duplicate_flavorids_fail(self): # Ensures that flavorid duplicates raise FlavorExists flavors.create('flavor1', 64, 1, 120, flavorid='flavorid') self.assertRaises(exception.FlavorIdExists, flavors.create, 'flavor2', 64, 1, 120, flavorid='flavorid')
apache-2.0
skoulouzis/lobcder
milton2/milton-server-ce/src/main/java/io/milton/dns/record/IPSECKEYRecord.java
5464
// Copyright (c) 2004 Brian Wellington (bwelling@xbill.org) package io.milton.dns.record; import io.milton.dns.Address; import io.milton.dns.Name; import io.milton.dns.TextParseException; import io.milton.dns.utils.base64; import java.io.*; import java.net.*; import io.milton.dns.utils.*; /** * IPsec Keying Material (RFC 4025) * * @author Brian Wellington */ public class IPSECKEYRecord extends Record { private static final long serialVersionUID = 3050449702765909687L; public static class Algorithm { private Algorithm() {} public static final int DSA = 1; public static final int RSA = 2; } public static class Gateway { private Gateway() {} public static final int None = 0; public static final int IPv4 = 1; public static final int IPv6 = 2; public static final int Name = 3; } private int precedence; private int gatewayType; private int algorithmType; private Object gateway; private byte [] key; IPSECKEYRecord() {} Record getObject() { return new IPSECKEYRecord(); } /** * Creates an IPSECKEY Record from the given data. * @param precedence The record's precedence. * @param gatewayType The record's gateway type. * @param algorithmType The record's algorithm type. * @param gateway The record's gateway. * @param key The record's public key. */ public IPSECKEYRecord(Name name, int dclass, long ttl, int precedence, int gatewayType, int algorithmType, Object gateway, byte [] key) { super(name, Type.IPSECKEY, dclass, ttl); this.precedence = checkU8("precedence", precedence); this.gatewayType = checkU8("gatewayType", gatewayType); this.algorithmType = checkU8("algorithmType", algorithmType); switch (gatewayType) { case Gateway.None: this.gateway = null; break; case Gateway.IPv4: if (!(gateway instanceof InetAddress)) throw new IllegalArgumentException("\"gateway\" " + "must be an IPv4 " + "address"); this.gateway = gateway; break; case Gateway.IPv6: if (!(gateway instanceof Inet6Address)) throw new IllegalArgumentException("\"gateway\" " + "must be an IPv6 " + "address"); this.gateway = gateway; break; case Gateway.Name: if (!(gateway instanceof Name)) throw new IllegalArgumentException("\"gateway\" " + "must be a DNS " + "name"); this.gateway = checkName("gateway", (Name) gateway); break; default: throw new IllegalArgumentException("\"gatewayType\" " + "must be between 0 and 3"); } this.key = key; } void rrFromWire(DNSInput in) throws IOException { precedence = in.readU8(); gatewayType = in.readU8(); algorithmType = in.readU8(); switch (gatewayType) { case Gateway.None: gateway = null; break; case Gateway.IPv4: gateway = InetAddress.getByAddress(in.readByteArray(4)); break; case Gateway.IPv6: gateway = InetAddress.getByAddress(in.readByteArray(16)); break; case Gateway.Name: gateway = new Name(in); break; default: throw new WireParseException("invalid gateway type"); } if (in.remaining() > 0) key = in.readByteArray(); } void rdataFromString(Tokenizer st, Name origin) throws IOException { precedence = st.getUInt8(); gatewayType = st.getUInt8(); algorithmType = st.getUInt8(); switch (gatewayType) { case Gateway.None: String s = st.getString(); if (!s.equals(".")) throw new TextParseException("invalid gateway format"); gateway = null; break; case Gateway.IPv4: gateway = st.getAddress(Address.IPv4); break; case Gateway.IPv6: gateway = st.getAddress(Address.IPv6); break; case Gateway.Name: gateway = st.getName(origin); break; default: throw new WireParseException("invalid gateway type"); } key = st.getBase64(false); } String rrToString() { StringBuffer sb = new StringBuffer(); sb.append(precedence); sb.append(" "); sb.append(gatewayType); sb.append(" "); sb.append(algorithmType); sb.append(" "); switch (gatewayType) { case Gateway.None: sb.append("."); break; case Gateway.IPv4: case Gateway.IPv6: InetAddress gatewayAddr = (InetAddress) gateway; sb.append(gatewayAddr.getHostAddress()); break; case Gateway.Name: sb.append(gateway); break; } if (key != null) { sb.append(" "); sb.append(base64.toString(key)); } return sb.toString(); } /** Returns the record's precedence. */ public int getPrecedence() { return precedence; } /** Returns the record's gateway type. */ public int getGatewayType() { return gatewayType; } /** Returns the record's algorithm type. */ public int getAlgorithmType() { return algorithmType; } /** Returns the record's gateway. */ public Object getGateway() { return gateway; } /** Returns the record's public key */ public byte [] getKey() { return key; } void rrToWire(DNSOutput out, Compression c, boolean canonical) { out.writeU8(precedence); out.writeU8(gatewayType); out.writeU8(algorithmType); switch (gatewayType) { case Gateway.None: break; case Gateway.IPv4: case Gateway.IPv6: InetAddress gatewayAddr = (InetAddress) gateway; out.writeByteArray(gatewayAddr.getAddress()); break; case Gateway.Name: Name gatewayName = (Name) gateway; gatewayName.toWire(out, null, canonical); break; } if (key != null) out.writeByteArray(key); } }
apache-2.0
b-slim/druid
server/src/test/java/io/druid/server/lookup/cache/LookupExtractorFactoryMapContainerTest.java
4475
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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. */ package io.druid.server.lookup.cache; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import io.druid.jackson.DefaultObjectMapper; import io.druid.query.lookup.LookupExtractorFactoryContainer; import io.druid.query.lookup.MapLookupExtractorFactory; import org.junit.Assert; import org.junit.Test; /** */ public class LookupExtractorFactoryMapContainerTest { private final ObjectMapper mapper; private final String jsonStr; private final LookupExtractorFactoryMapContainer testContainer; public LookupExtractorFactoryMapContainerTest() { mapper = new DefaultObjectMapper(); mapper.registerSubtypes(MapLookupExtractorFactory.class); jsonStr = "{\n" + " \"version\": \"v1\",\n" + " \"lookupExtractorFactory\": {\n" + " \"type\": \"map\",\n" + " \"map\": {\"k\": \"v\"},\n" + " \"isOneToOne\": true\n" + " }\n" + "}\n"; testContainer = new LookupExtractorFactoryMapContainer( "v1", ImmutableMap.<String, Object>of( "type", "map", "map", ImmutableMap.of("k", "v"), "isOneToOne", true ) ); } @Test public void testSerde() throws Exception { LookupExtractorFactoryMapContainer actual = mapper.readValue( mapper.writeValueAsString( mapper.readValue(jsonStr, LookupExtractorFactoryMapContainer.class) ), LookupExtractorFactoryMapContainer.class ); Assert.assertEquals("v1", actual.getVersion()); Assert.assertEquals(testContainer, actual); } @Test public void testReplaces() { LookupExtractorFactoryMapContainer l0 = new LookupExtractorFactoryMapContainer(null, ImmutableMap.of()); LookupExtractorFactoryMapContainer l1 = new LookupExtractorFactoryMapContainer(null, ImmutableMap.of()); LookupExtractorFactoryMapContainer l2 = new LookupExtractorFactoryMapContainer("V2", ImmutableMap.of()); LookupExtractorFactoryMapContainer l3 = new LookupExtractorFactoryMapContainer("V3", ImmutableMap.of()); Assert.assertFalse(l0.replaces(l1)); Assert.assertFalse(l1.replaces(l2)); Assert.assertTrue(l2.replaces(l1)); Assert.assertFalse(l2.replaces(l3)); Assert.assertTrue(l3.replaces(l2)); } //test interchangeability with LookupExtractorFactoryContainer //read and write as LookupExtractorFactoryContainer //then read as LookupExtractorFactoryMapContainer @Test public void testInterchangeability1() throws Exception { LookupExtractorFactoryMapContainer actual = mapper.readValue( mapper.writeValueAsString( mapper.readValue(jsonStr, LookupExtractorFactoryContainer.class) ), LookupExtractorFactoryMapContainer.class ); Assert.assertEquals("v1", actual.getVersion()); Assert.assertEquals(testContainer, actual); } //test interchangeability with LookupExtractorFactoryContainer //read and write as LookupExtractorFactoryMapContainer //then read as LookupExtractorFactoryContainer @Test public void testInterchangeability2() throws Exception { LookupExtractorFactoryContainer actual = mapper.readValue( mapper.writeValueAsString( mapper.readValue(jsonStr, LookupExtractorFactoryMapContainer.class) ), LookupExtractorFactoryContainer.class ); Assert.assertEquals("v1", actual.getVersion()); Assert.assertEquals( actual, new LookupExtractorFactoryContainer( "v1", new MapLookupExtractorFactory(ImmutableMap.of("k", "v"), true) ) ); } }
apache-2.0
Servoy/wicket
wicket/src/main/java/org/apache/wicket/markup/repeater/Item.java
4110
/* * 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. */ package org.apache.wicket.markup.repeater; import java.util.Comparator; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.model.IModel; import org.apache.wicket.version.undo.Change; /** * Container that holds components in a RefreshingView. One Item represents one entire row of the * view. Users should add all containing components to the Item instead of the view, this is * accomplished by implementing refreshingView.populateItem(Item item). * * @see RefreshingView * * @author Igor Vaynberg (ivaynberg) * * @param <T> * Model object type */ public class Item<T> extends WebMarkupContainer { private static final long serialVersionUID = 1L; /** relative index of this item */ private int index; /** * @param id * component id * @param index * relative index of this item in the pageable view * @param model * model for this item */ public Item(final String id, int index, final IModel<T> model) { super(id.intern(), model); this.index = index; } /** * @param id * component id * @param index * relative index of this item in the pageable view */ public Item(final String id, int index) { super(id.intern()); this.index = index; } /** * Sets the index of this item * * @param index * new index */ public void setIndex(int index) { if (this.index != index) { if (isVersioned()) { addStateChange(new Change() { final int oldIndex = Item.this.index; private static final long serialVersionUID = 1L; @Override public void undo() { Item.this.index = oldIndex; } @Override public String toString() { return "IndexChange[component: " + getPath() + ", index: " + oldIndex + "]"; } }); } this.index = index; } } /** * @return the index assigned to this item */ public int getIndex() { return index; } /** * @return the primary key assigned to this item */ public String getPrimaryKey() { return getId(); } /** * Comparator that compares Items by their index property * * @author Igor Vaynberg (ivaynberg) * */ public static class IndexComparator implements Comparator<Item<?>> { private static final Comparator<Item<?>> instance = new IndexComparator(); /** * @return static instance of the comparator */ public static final Comparator<Item<?>> getInstance() { return instance; } /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Item<?> lhs, Item<?> rhs) { return lhs.getIndex() - rhs.getIndex(); } }; /** * Gets model * * @return model */ @SuppressWarnings("unchecked") public final IModel<T> getModel() { return (IModel<T>)getDefaultModel(); } /** * Sets model * * @param model */ public final void setModel(IModel<T> model) { setDefaultModel(model); } /** * Gets model object * * @return model object */ @SuppressWarnings("unchecked") public final T getModelObject() { return (T)getDefaultModelObject(); } /** * Sets model object * * @param object */ public final void setModelObject(T object) { setDefaultModelObject(object); } }
apache-2.0
joshisa/sciscitatio
lib/h5p/libraries/H5P.TextInputField-1.0/text-input-field.js
2255
var H5P = H5P || {}; /** * Text Input Field module * @external {jQuery} $ H5P.jQuery */ H5P.TextInputField = (function ($) { // CSS Classes: var MAIN_CONTAINER = 'h5p-text-input-field'; var INPUT_LABEL = 'h5p-text-input-field-label'; var INPUT_FIELD = 'h5p-text-input-field-textfield'; /** * Initialize module. * @param {Object} params Behavior settings * @param {Number} id Content identification * @returns {Object} TextInputField TextInputField instance */ function TextInputField(params, id) { this.$ = $(this); this.id = id; // Set default behavior. this.params = $.extend({}, { taskDescription: 'Input field', placeholderText: '', inputFieldSize: '1', requiredField: false }, params); } /** * Attach function called by H5P framework to insert H5P content into page. * * @param {jQuery} $container The container which will be appended to. */ TextInputField.prototype.attach = function ($container) { var self = this; this.$inner = $container.addClass(MAIN_CONTAINER); this.$taskDescription = $('<div>', { 'class': INPUT_LABEL, 'html': self.params.taskDescription }).appendTo(self.$inner); this.$inputField = $('<textarea>', { 'class': INPUT_FIELD, 'rows': parseInt(self.params.inputFieldSize, 10), 'placeholder': self.params.placeholderText, 'tabindex': '0' }).appendTo(self.$inner); }; /** * Returns true if input field is not required or non-empty * @returns {boolean} True if input field is filled or not required */ TextInputField.prototype.isRequiredInputFilled = function () { if (!this.params.requiredField) { return true; } if (this.params.requiredField && this.$inputField.val().length) { return true; } return false; }; /** * Retrieves the text input field * @returns {description:string, value:string} Returns input field */ TextInputField.prototype.getInput = function () { // Remove trailing newlines return { description: this.params.taskDescription.replace(/^\s+|\s+$/g, '').replace(/(<p>|<\/p>)/img, ""), value: this.$inputField.val() }; }; return TextInputField; }(H5P.jQuery));
apache-2.0
Donnerbart/hazelcast-simulator
tests/tests-common/src/main/java/com/hazelcast/simulator/tests/icache/AddRemoveListenerICacheTest.java
4623
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.simulator.tests.icache; import com.hazelcast.core.IList; import com.hazelcast.simulator.test.AbstractTest; import com.hazelcast.simulator.test.BaseThreadState; import com.hazelcast.simulator.test.annotations.AfterRun; import com.hazelcast.simulator.test.annotations.Prepare; import com.hazelcast.simulator.test.annotations.Setup; import com.hazelcast.simulator.test.annotations.TimeStep; import com.hazelcast.simulator.test.annotations.Verify; import com.hazelcast.simulator.tests.icache.helpers.ICacheEntryEventFilter; import com.hazelcast.simulator.tests.icache.helpers.ICacheEntryListener; import com.hazelcast.simulator.tests.icache.helpers.ICacheListenerOperationCounter; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.configuration.FactoryBuilder; import javax.cache.configuration.MutableCacheEntryListenerConfiguration; import static com.hazelcast.simulator.tests.icache.helpers.CacheUtils.createCacheManager; /** * In this test we concurrently add remove cache listeners while putting and getting from the cache. * * This test is out side of normal usage, however has found problems where put operations hang. * This type of test could uncover memory leaks in the process of adding and removing listeners. * The max size of the cache used in this test is keyCount int key/value pairs. */ public class AddRemoveListenerICacheTest extends AbstractTest { public int keyCount = 1000; public boolean syncEvents = true; private final ICacheEntryListener<Integer, Long> listener = new ICacheEntryListener<Integer, Long>(); private final ICacheEntryEventFilter<Integer, Long> filter = new ICacheEntryEventFilter<Integer, Long>(); private IList<ICacheListenerOperationCounter> results; private CacheManager cacheManager; private Cache<Integer, Long> cache; private MutableCacheEntryListenerConfiguration<Integer, Long> listenerConfiguration; @Setup public void setup() { results = targetInstance.getList(name); cacheManager = createCacheManager(targetInstance); cacheManager.getCache(name); } @Prepare(global = false) public void prepare() { cache = cacheManager.getCache(name); listenerConfiguration = new MutableCacheEntryListenerConfiguration<Integer, Long>( FactoryBuilder.factoryOf(listener), FactoryBuilder.factoryOf(filter), false, syncEvents); } @TimeStep(prob = 0.25) public void register(ThreadState state) { try { cache.registerCacheEntryListener(listenerConfiguration); state.operationCounter.register++; } catch (IllegalArgumentException e) { state.operationCounter.registerIllegalArgException++; } } @TimeStep(prob = 0.25) public void deregister(ThreadState state) { cache.deregisterCacheEntryListener(listenerConfiguration); state.operationCounter.deRegister++; } @TimeStep(prob = 0.25) public void put(ThreadState state) { cache.put(state.randomInt(keyCount), 1L); state.operationCounter.put++; } @TimeStep(prob = 0.25) public void get(ThreadState state) { cache.get(state.randomInt(keyCount)); state.operationCounter.put++; } @AfterRun public void afterRun(ThreadState state) { logger.info(name + ": " + state.operationCounter); results.add(state.operationCounter); } public class ThreadState extends BaseThreadState { private final ICacheListenerOperationCounter operationCounter = new ICacheListenerOperationCounter(); } @Verify(global = true) public void globalVerify() { ICacheListenerOperationCounter total = new ICacheListenerOperationCounter(); for (ICacheListenerOperationCounter i : results) { total.add(i); } logger.info(name + ": " + total + " from " + results.size() + " worker threads"); } }
apache-2.0
synchromedia/OpenGSN
admin-client/src/generated-sources/com/greenstarnetwork/services/networkmanager/NetworkManagerRequest.java
8682
/** * Copyright 2009-2011 École de technologie supérieure, * Communication Research Centre Canada, * Inocybe Technologies Inc. and 6837247 CANADA 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. */ package com.greenstarnetwork.services.networkmanager; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for networkManagerRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="networkManagerRequest"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="arguments"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="commandId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "networkManagerRequest", propOrder = { "arguments", "commandId" }) public class NetworkManagerRequest { @XmlElement(required = true) protected NetworkManagerRequest.Arguments arguments; protected String commandId; /** * Gets the value of the arguments property. * * @return * possible object is * {@link NetworkManagerRequest.Arguments } * */ public NetworkManagerRequest.Arguments getArguments() { return arguments; } /** * Sets the value of the arguments property. * * @param value * allowed object is * {@link NetworkManagerRequest.Arguments } * */ public void setArguments(NetworkManagerRequest.Arguments value) { this.arguments = value; } /** * Gets the value of the commandId property. * * @return * possible object is * {@link String } * */ public String getCommandId() { return commandId; } /** * Sets the value of the commandId property. * * @param value * allowed object is * {@link String } * */ public void setCommandId(String value) { this.commandId = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entry" }) public static class Arguments { protected List<NetworkManagerRequest.Arguments.Entry> entry; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link NetworkManagerRequest.Arguments.Entry } * * */ public List<NetworkManagerRequest.Arguments.Entry> getEntry() { if (entry == null) { entry = new ArrayList<NetworkManagerRequest.Arguments.Entry>(); } return this.entry; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "key", "value" }) public static class Entry { protected String key; protected String value; /** * Gets the value of the key property. * * @return * possible object is * {@link String } * */ public String getKey() { return key; } /** * Sets the value of the key property. * * @param value * allowed object is * {@link String } * */ public void setKey(String value) { this.key = value; } /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } } } }
apache-2.0
xingwu1/azure-sdk-for-node
lib/services/networkManagement2/lib/models/serviceEndpointPolicyDefinitionListResult.js
1895
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Response for ListServiceEndpointPolicyDefinition API service call. Retrieves * all service endpoint policy definition that belongs to a service endpoint * policy. */ class ServiceEndpointPolicyDefinitionListResult extends Array { /** * Create a ServiceEndpointPolicyDefinitionListResult. * @property {string} [nextLink] The URL to get the next set of results. */ constructor() { super(); } /** * Defines the metadata of ServiceEndpointPolicyDefinitionListResult * * @returns {object} metadata of ServiceEndpointPolicyDefinitionListResult * */ mapper() { return { required: false, serializedName: 'ServiceEndpointPolicyDefinitionListResult', type: { name: 'Composite', className: 'ServiceEndpointPolicyDefinitionListResult', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'ServiceEndpointPolicyDefinitionElementType', type: { name: 'Composite', className: 'ServiceEndpointPolicyDefinition' } } } }, nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } } } } }; } } module.exports = ServiceEndpointPolicyDefinitionListResult;
apache-2.0
frreiss/tensorflow-fred
tensorflow/python/kernel_tests/reduction_ops_test.py
44401
# Copyright 2015 The TensorFlow Authors. 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. # ============================================================================== """Functional tests for reduction ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import numbers import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test # The maximum input rank to test. _MAX_RANK = 5 def _powerset(iterable): """Helper for generating all possible reduction_axes arguments. Example: powerset([0,1,2]): () (0,) (1,) (2,) (0,1) (0,2) (1,2) (0,1,2) Args: iterable: An iterable of items to generate the powerset of. Returns: The powerset of all items in iterable. """ s = list(iterable) return itertools.chain.from_iterable( itertools.combinations(s, r) for r in range(len(s) + 1)) class ReducedShapeTest(test.TestCase): def _check(self, shape, axes, result): output = math_ops.reduced_shape(shape, axes=axes) self.assertAllEqual(output, result) @test_util.run_deprecated_v1 def testSimple(self): with self.cached_session(): self._check([3], [], [3]) self._check([3], [0], [1]) self._check([5, 3], [], [5, 3]) self._check([5, 3], [0], [1, 3]) self._check([5, 3], [1], [5, 1]) self._check([5, 3], [0, 1], [1, 1]) @test_util.run_deprecated_v1 def testZeros(self): """Check that reduced_shape does the right thing with zero dimensions.""" with self.cached_session(): self._check([0], [], [0]) self._check([0], [0], [1]) self._check([0, 3], [], [0, 3]) self._check([0, 3], [0], [1, 3]) self._check([0, 3], [1], [0, 1]) self._check([0, 3], [0, 1], [1, 1]) self._check([3, 0], [], [3, 0]) self._check([3, 0], [0], [1, 0]) self._check([3, 0], [1], [3, 1]) self._check([3, 0], [0, 1], [1, 1]) @test_util.run_deprecated_v1 def testNegAxes(self): with self.cached_session(): self._check([10, 10, 10], [-1], [10, 10, 1]) self._check([10, 10, 10], [-1, 2], [10, 10, 1]) self._check([10, 10, 10], [-1, -1], [10, 10, 1]) self._check([10, 10, 10], [-1, 0], [1, 10, 1]) self._check([10, 10, 10], [-3], [1, 10, 10]) class ReductionUnknownShape(test.TestCase): @test_util.run_deprecated_v1 def testBasic(self): with self.cached_session(): for dtype, reductions in [(dtypes.float32, (math_ops.reduce_sum, math_ops.reduce_mean, math_ops.reduce_prod, math_ops.reduce_max, math_ops.reduce_min, math_ops.reduce_euclidean_norm)), (dtypes.bool, (math_ops.reduce_all, math_ops.reduce_any))]: for reduction in reductions: x = array_ops.placeholder( dtype=dtype, shape=None) # Some tensor w/ unknown shape. y = reduction(x) self.assertEqual(y.shape, ()) class ReductionInvalidKeepdims(test.TestCase): def testBasic(self): # Test case for GitHub issue 46700. for dtype, reductions in [ (dtypes.float32, (math_ops.reduce_sum, math_ops.reduce_mean, math_ops.reduce_prod, math_ops.reduce_max, math_ops.reduce_min, math_ops.reduce_euclidean_norm)), (dtypes.bool, (math_ops.reduce_all, math_ops.reduce_any)) ]: for reduction in reductions: with self.assertRaisesRegex(ValueError, "The truth value"): x = True if dtype == dtypes.bool else 1 y = reduction( input_tensor=x, keepdims=np.array([63600, 1], dtype=np.float16)) self.evaluate(y) class BaseReductionTest(test.TestCase): def _tf_reduce(self, x, reduction_axes, keepdims): raise NotImplementedError() def _np_reduce(self, x, reduction_axes, keepdims): raise NotImplementedError() def _makeIncremental(self, shape, dtype): data = np.arange(np.prod(shape)).reshape(shape).astype(dtype.as_numpy_dtype) if dtype.is_complex: data -= 2j * data return data def _makeRandom(self, shape, dtype): data = np.random.rand(*shape).astype(dtype.as_numpy_dtype) if dtype.is_complex: data -= 2j * data return data def _compare(self, x, reduction_axes, keepdims, feed_dict=None): np_ans = self._np_reduce(x, reduction_axes, keepdims) with self.cached_session() as sess: tf_ans = self._tf_reduce(x, reduction_axes, keepdims) out = sess.run(tf_ans, feed_dict) self.assertAllClose(np_ans, out) self.assertShapeEqual(np_ans, tf_ans) def _compareAll(self, x, reduction_axes, feed_dict=None): if reduction_axes is not None and np.shape(reduction_axes) == (1,): # Test scalar reduction_axes argument self._compareAll(x, reduction_axes[0]) self._compare(x, reduction_axes, keepdims=False, feed_dict=feed_dict) self._compare(x, reduction_axes, keepdims=True, feed_dict=feed_dict) def _compareAllAxes(self, x, feed_dict=None): self._compareAll(x, None) for axes in _powerset(range(x.ndim)): self._compareAll(x, axes, feed_dict) def _compareGradient(self, x, reduction_axes, rtol=1e-8, atol=1e-8): if reduction_axes is not None and np.shape(reduction_axes) == (1,): # Test scalar reduction_axes argument self._compareGradient(x, reduction_axes[0], rtol=rtol, atol=atol) with self.cached_session(): t = ops.convert_to_tensor(x) su = self._tf_reduce(t, reduction_axes, False) jacob_t, jacob_n = gradient_checker.compute_gradient( t, x.shape, su, su.get_shape().as_list(), x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=rtol, atol=atol) def _compareGradientAxes(self, x, rtol=1e-8, atol=1e-8): self._compareGradient(x, None, rtol=rtol, atol=atol) self._compareGradient(x, [], rtol=rtol, atol=atol) self._compareGradient(x, 0, rtol=rtol, atol=atol) self._compareGradient(x, [1], rtol=rtol, atol=atol) self._compareGradient(x, [2], rtol=rtol, atol=atol) self._compareGradient(x, [1, 2], rtol=rtol, atol=atol) self._compareGradient(x, [0, 1, 2, 3], rtol=rtol, atol=atol) class SumReductionTest(BaseReductionTest): def _tf_reduce(self, x, reduction_axes, keepdims): return math_ops.reduce_sum(x, reduction_axes, keepdims) def _np_reduce(self, x, reduction_axes, keepdims): if isinstance(reduction_axes, list) or isinstance(reduction_axes, np.ndarray): reduction_axes = tuple(reduction_axes) return np.sum(x, axis=reduction_axes, keepdims=keepdims) def testAxesType(self): for dtype in [dtypes.int64, dtypes.int32]: with self.cached_session(): v = math_ops.reduce_sum([0, 0], constant_op.constant(0, dtype=dtype)) tf_v = self.evaluate(v) self.assertAllEqual(tf_v, 0) @test_util.run_deprecated_v1 def testInfinity(self): for dtype in [np.float32, np.float64]: for special_value_x in [-np.inf, np.inf]: for special_value_y in [-np.inf, np.inf]: np_arr = np.array([special_value_x, special_value_y]).astype(dtype) self._compareAll(np_arr, None) @test_util.run_deprecated_v1 def testInt32(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.int32) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testFloat16(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float16) self._compareAllAxes(np_arr) # test that mean doesn't overflow # only on GPU, since it has the more accurate implementation if not test.is_gpu_available(): return arr = np.ones([68000], dtype=np.float16) with self.session(graph=ops.Graph(), use_gpu=True) as sess: tf_arr = variables.Variable(arr) self.evaluate(variables.global_variables_initializer()) tf_mean = math_ops.reduce_mean(tf_arr, 0, False) tf_out_mean = self.evaluate(tf_mean) self.assertAllClose(tf_out_mean, 1.) @test_util.run_deprecated_v1 def testFloat32(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float32) self._compareAllAxes(np_arr) for _ in range(10): size_x = int(2**np.random.uniform(0, 15)) size_y = int(2**np.random.uniform(0, 15)) if size_x * size_y > 1e7: size_y = int(1e7 / size_x) arr = np.ones([size_x, size_y], dtype=np.float32) col_sum = np.sum(arr, axis=0) row_sum = np.sum(arr, axis=1) with self.session(graph=ops.Graph(), use_gpu=True) as sess: tf_row_sum = self._tf_reduce(arr, 1, False) tf_col_sum = self._tf_reduce(arr, 0, False) tf_out_row, tf_out_col = self.evaluate([tf_row_sum, tf_col_sum]) self.assertAllClose(col_sum, tf_out_col) self.assertAllClose(row_sum, tf_out_row) for size_x in [1, 3, 16, 33]: for size_y in [1, 3, 16, 33]: for size_z in [1, 3, 16, 33]: arr = np.ones([size_x, size_y, size_z], dtype=np.float32) sum_y = np.sum(arr, axis=1) sum_xz = np.sum(arr, axis=(0, 2)) with self.session(graph=ops.Graph(), use_gpu=True) as sess: tf_sum_xz = self._tf_reduce(arr, [0, 2], False) tf_sum_y = self._tf_reduce(arr, 1, False) tf_out_sum_xz, tf_out_sum_y = self.evaluate([tf_sum_xz, tf_sum_y]) self.assertAllClose(sum_y, tf_out_sum_y) self.assertAllClose(sum_xz, tf_out_sum_xz) @test_util.run_deprecated_v1 def testFloat64(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float64) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testComplex64(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.complex64) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testComplex128(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.complex128) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testInvalidIndex(self): np_arr = np.arange(0, 10).reshape([2, 5]).astype(np.float32) input_tensor = ops.convert_to_tensor(np_arr) with self.assertRaisesWithPredicateMatch( ValueError, lambda e: "Invalid reduction dimension" in str(e)): math_ops.reduce_sum(input_tensor, [-3]) with self.assertRaisesWithPredicateMatch( ValueError, lambda e: "Invalid reduction dimension" in str(e)): math_ops.reduce_sum(input_tensor, [2]) with self.assertRaisesWithPredicateMatch( ValueError, lambda e: "Invalid reduction dimension" in str(e)): math_ops.reduce_sum(input_tensor, [0, 2]) @test_util.run_deprecated_v1 def testPartialShapes(self): np.random.seed(1618) # Input shape is unknown. reduction_axes = [1, 2] c_unknown = array_ops.placeholder(dtypes.float32) s_unknown = math_ops.reduce_sum(c_unknown, reduction_axes) self.assertEqual(tensor_shape.unknown_shape(), s_unknown.get_shape()) np_input = np.random.randn(3, 3, 3) self._compareAll(np_input, reduction_axes, {c_unknown: np_input}) # Input shape only has known rank. c_known_rank = array_ops.placeholder(dtypes.float32) c_known_rank.set_shape(tensor_shape.unknown_shape(rank=3)) s_known_rank = math_ops.reduce_sum( c_known_rank, reduction_axes, keepdims=True) self.assertEqual(3, s_known_rank.get_shape().rank) np_input = np.random.randn(3, 3, 3) self._compareAll(np_input, reduction_axes, {c_known_rank: np_input}) # Reduction indices are unknown. unknown_indices = array_ops.placeholder(dtypes.int32) c_unknown_indices = constant_op.constant([[10.0], [20.0]]) s_unknown_indices = math_ops.reduce_sum( c_unknown_indices, unknown_indices, keepdims=False) self.assertEqual(tensor_shape.unknown_shape(), s_unknown_indices.get_shape()) s_unknown_indices_keep = math_ops.reduce_sum( c_unknown_indices, unknown_indices, keepdims=True) self.assertEqual(2, s_unknown_indices_keep.get_shape().rank) @test_util.run_deprecated_v1 def testWrongShapeForReductionIndices(self): reduction_axes = [[1], [2]] c_unknown = array_ops.placeholder(dtypes.float32) with self.assertRaisesWithPredicateMatch(ValueError, ".*must be at most rank 1.*"): math_ops.reduce_sum(c_unknown, reduction_axes) def testInvalidRepeatedReductionIndices(self): reduction_axes = constant_op.constant([0, 0]) c = constant_op.constant([1.0, 2.0]) with self.assertRaisesWithPredicateMatch( errors.InvalidArgumentError, ".*Axes contains duplicate dimension: 0.*"): self.evaluate(math_ops.reduce_sum(c, reduction_axes)) # Int64?? @test_util.run_deprecated_v1 def testGradient(self): for dtype in [ dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128 ]: x = self._makeIncremental([2, 3, 4, 2], dtype) self._compareGradientAxes(x) @test_util.run_deprecated_v1 def testHighRank(self): # Do a bunch of random high dimensional reductions np.random.seed(42) for _ in range(20): rank = np.random.randint(4, 10 + 1) axes, = np.nonzero(np.random.randint(2, size=rank)) shape = tuple(np.random.randint(1, 3 + 1, size=rank)) data = np.random.randint(1024, size=shape) self._compareAll(data, axes) # Check some particular axis patterns for rank in 4, 7, 10: shape = tuple(np.random.randint(1, 3 + 1, size=rank)) data = np.random.randint(1024, size=shape) for axes in ([], np.arange(rank), np.arange(0, rank, 2), np.arange(1, rank, 2)): self._compareAll(data, axes) @test_util.run_deprecated_v1 def testExpand(self): # Reduce an empty tensor to a nonempty tensor x = np.zeros((5, 0)) self._compareAll(x, [1]) @test_util.run_deprecated_v1 def testEmptyGradients(self): with self.session(): x = array_ops.zeros([0, 3]) y = math_ops.reduce_sum(x, [1]) error = gradient_checker.compute_gradient_error(x, [0, 3], y, [0]) self.assertEqual(error, 0) @test_util.run_deprecated_v1 def testDegenerate(self): with self.session(): for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128): # A large number is needed to get Eigen to die x = array_ops.zeros((0, 9938), dtype=dtype) y = math_ops.reduce_sum(x, [0]) self.assertAllEqual(y, np.zeros(9938)) class MeanReductionTest(BaseReductionTest): def _tf_reduce(self, x, reduction_axes, keepdims): return math_ops.reduce_mean(x, reduction_axes, keepdims) def _np_reduce(self, x, reduction_axes, keepdims): if isinstance(reduction_axes, list) or isinstance(reduction_axes, np.ndarray): reduction_axes = tuple(reduction_axes) elif isinstance(reduction_axes, numbers.Integral): reduction_axes = (reduction_axes,) if reduction_axes is None: count = np.prod(x.shape) else: count = np.prod([x.shape[ax] for ax in reduction_axes]) # np.mean automatically converts integer inputs to float, while TensorFlow's # reduce_mean does not. For integer inputs, we emulate TensorFlow's behavior # using np.sum and truncating division. np_sum = np.sum(x, axis=reduction_axes, keepdims=keepdims) if np.issubdtype(x.dtype, np.integer): return np_sum // count return np_sum / count def testAxesType(self): for dtype in [dtypes.int64, dtypes.int32]: with self.cached_session(): v = math_ops.reduce_mean([0, 0], constant_op.constant(0, dtype=dtype)) tf_v = self.evaluate(v) self.assertAllEqual(tf_v, 0) @test_util.run_deprecated_v1 def testInfinity(self): for dtype in [np.float32, np.float64]: for special_value_x in [-np.inf, np.inf]: for special_value_y in [-np.inf, np.inf]: np_arr = np.array([special_value_x, special_value_y]).astype(dtype) self._compareAll(np_arr, None) @test_util.run_deprecated_v1 def testInt32(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.int32) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testUint8(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeRandom((2,) * rank, dtypes.uint8) self._compareAllAxes(np_arr) # This tests the issue reported in b/145030710. @test_util.run_deprecated_v1 def testSizeOverflowUint8(self): np_arr = self._makeRandom((2**8,), dtypes.uint8) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testSizeOverflowInt8(self): np_arr = self._makeRandom((2**7,), dtypes.int8) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testSizeOverflowUint16(self): np_arr = self._makeRandom((2**16,), dtypes.uint16) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testSizeOverflowInt16(self): np_arr = self._makeRandom((2**15,), dtypes.int16) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testFloat32(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float32) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testFloat64(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float64) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testComplex64(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.complex64) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testComplex128(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.complex128) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testGradient(self): s = [2, 3, 4, 2] for dtype in [dtypes.float32, dtypes.float64]: x = self._makeIncremental(s, dtype) self._compareGradientAxes(x, rtol=1e-3, atol=1e-3) @test_util.run_deprecated_v1 def testEmptyGradients(self): with self.session(): x = array_ops.zeros([0, 3]) y = math_ops.reduce_mean(x, [1]) error = gradient_checker.compute_gradient_error(x, [0, 3], y, [0]) self.assertEqual(error, 0) @test_util.run_deprecated_v1 def testDegenerate(self): with self.session(): for dtype in (dtypes.float16, dtypes.float32, dtypes.float64): # A large number is needed to get Eigen to die x = array_ops.zeros((0, 9938), dtype=dtype) y = math_ops.reduce_mean(x, [0]).eval() self.assertEqual(y.shape, (9938,)) self.assertTrue(np.all(np.isnan(y))) class EuclideanNormReductionTest(BaseReductionTest): def _tf_reduce(self, x, reduction_axes, keepdims): return math_ops.reduce_euclidean_norm(x, reduction_axes, keepdims) def _np_reduce(self, x, reduction_axes, keepdims): if isinstance(reduction_axes, list) or isinstance(reduction_axes, np.ndarray): reduction_axes = tuple(reduction_axes) np_fro = np.sqrt( np.sum(x * np.conj(x), axis=reduction_axes, keepdims=keepdims)) if np.issubdtype(x.dtype, np.integer): np_fro = np.floor(np_fro) return np_fro @test_util.run_deprecated_v1 def testAxesType(self): for dtype in [dtypes.int64, dtypes.int32]: with self.cached_session(): v = math_ops.reduce_mean([0, 0], constant_op.constant(0, dtype=dtype)) tf_v = self.evaluate(v) self.assertAllEqual(tf_v, 0) @test_util.run_deprecated_v1 def testInfinity(self): for dtype in [np.float32, np.float64]: for special_value_x in [-np.inf, np.inf]: for special_value_y in [-np.inf, np.inf]: np_arr = np.array([special_value_x, special_value_y]).astype(dtype) self._compareAll(np_arr, None) @test_util.run_deprecated_v1 def testSingleton(self): for dtype in [np.float32, np.float64]: np_arr = np.array([-1.]).astype(dtype) self._compareAll(np_arr, None) @test_util.run_deprecated_v1 def testInt32(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.int32) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testFloat32(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float32) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testFloat64(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float64) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testComplex64(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.complex64) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testComplex128(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.complex128) self._compareAllAxes(np_arr) with self.session(): for dtype in (dtypes.float16, dtypes.float32, dtypes.float64): # A large number is needed to get Eigen to die x = array_ops.zeros((0, 9938), dtype=dtype) y = math_ops.reduce_euclidean_norm(x, [0]).eval() self.assertEqual(y.shape, (9938,)) self.assertAllEqual(y, np.zeros(9938)) @test_util.run_deprecated_v1 def testGradient(self): shape = [2, 3, 4, 2] for dtype in [dtypes.float32, dtypes.float64]: # zero value entry will result NaN gradient if reduction doesn't happen. # e.g., `tf.math.reduce_sum([0, 1], axis=[])` so add one to avoid it. x = self._makeIncremental(shape, dtype) + 1.0 self._compareGradientAxes(x, rtol=1e-2, atol=1e-2) class ProdReductionTest(BaseReductionTest): def _tf_reduce(self, x, reduction_axes, keepdims): return math_ops.reduce_prod(x, reduction_axes, keepdims) def _np_reduce(self, x, reduction_axes, keepdims): if isinstance(reduction_axes, list) or isinstance(reduction_axes, np.ndarray): reduction_axes = tuple(reduction_axes) return np.prod(x, axis=reduction_axes, keepdims=keepdims) def testAxesType(self): for dtype in [dtypes.int64, dtypes.int32]: with self.cached_session(): v = math_ops.reduce_prod([0, 0], constant_op.constant(0, dtype=dtype)) tf_v = self.evaluate(v) self.assertAllEqual(tf_v, 0) @test_util.run_deprecated_v1 def testInfinity(self): for dtype in [np.float32, np.float64]: for special_value_x in [-np.inf, np.inf]: for special_value_y in [-np.inf, np.inf]: np_arr = np.array([special_value_x, special_value_y]).astype(dtype) self._compareAll(np_arr, None) @test_util.run_deprecated_v1 def testInt32(self): # Numpy automatically upgrades the type of np.prod from int32 to int64, so # Numpy does not overflow an int32 np.prod while TensorFlow does. To avoid # overflow, limit array values. for rank in range(1, _MAX_RANK): np_arr = self._makeIncremental((2,) * rank, dtypes.int32) % 5 + 1 self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testInt64(self): for rank in range(1, _MAX_RANK): # Avoid overflow by limiting array values. np_arr = self._makeIncremental((2,) * rank, dtypes.int64) % 11 + 1 self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testFloat32(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float32) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testFloat64(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.float64) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testComplex64(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.complex64) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testComplex128(self): for rank in range(1, _MAX_RANK + 1): np_arr = self._makeIncremental((2,) * rank, dtypes.complex128) self._compareAllAxes(np_arr) @test_util.run_deprecated_v1 def testGradientWithZeros(self): s = [2, 3, 4, 2] x = self._makeIncremental(s, dtypes.float32) / 20. # No zeros in input self._compareGradientAxes(x, rtol=1e-3, atol=1e-3) # Zero at beginning x1 = x.copy() x1[:, :, 0, :] = 0 self._compareGradientAxes(x1, rtol=1e-3, atol=1e-3) # Zero at end x2 = x.copy() x2[:, :, -1, :] = 0 self._compareGradientAxes(x2, rtol=1e-3, atol=1e-3) # Zero in middle x3 = x.copy() x3[:, :, 2, :] = 0 self._compareGradientAxes(x3, rtol=1e-3, atol=1e-3) # All zeros x4 = x.copy() x4[:, :, :, :] = 0 self._compareGradientAxes(x4, rtol=1e-3, atol=1e-3) @test_util.run_deprecated_v1 def testEmptyGradients(self): with self.session(): x = array_ops.zeros([0, 3]) y = math_ops.reduce_prod(x, [1]) error = gradient_checker.compute_gradient_error(x, [0, 3], y, [0]) self.assertEqual(error, 0) @test_util.run_deprecated_v1 def testDegenerate(self): with self.session(): for dtype in (dtypes.float16, dtypes.float32, dtypes.float64): # A large number is needed to get Eigen to die x = array_ops.zeros((0, 9938), dtype=dtype) y = math_ops.reduce_prod(x, [0]) self.assertAllEqual(y, np.ones(9938)) class MinReductionTest(test.TestCase): def _compare(self, x, reduction_axes, keepdims, use_gpu=False): np_ans = x if reduction_axes is None: np_ans = np.amin(np_ans, keepdims=keepdims) else: for ra in reduction_axes[::-1]: np_ans = np.amin(np_ans, axis=ra, keepdims=keepdims) with self.cached_session(use_gpu=use_gpu): if reduction_axes is not None: reduction_axes = np.array(reduction_axes).astype(np.int32) tf_ans = math_ops.reduce_min(x, reduction_axes, keepdims) out = self.evaluate(tf_ans) self.assertAllClose(np_ans, out) self.assertShapeEqual(np_ans, tf_ans) def _compareAll(self, x, reduction_axes): self._compare(x, reduction_axes, False, use_gpu=True) self._compare(x, reduction_axes, True, use_gpu=True) def testAxesType(self): for dtype in [dtypes.int64, dtypes.int32]: with self.cached_session(): v = math_ops.reduce_min([0, 0], constant_op.constant(0, dtype=dtype)) tf_v = self.evaluate(v) self.assertAllEqual(tf_v, 0) def testSpecialValues(self): for dtype in [np.float32, np.float64]: for size in range(1, 4): for arr in itertools.product([-np.inf, 1., np.nan, np.inf], repeat=size): self._compareAll(np.array(arr, dtype=dtype), None) def testFloatReduce3D(self): # Create a 3D array of floats and reduce across all possible # dimensions np_arr = np.arange(1, 31).reshape([2, 3, 5]).astype(np.float32) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) self._compareAll(np_arr, [1]) self._compareAll(np_arr, [2]) self._compareAll(np_arr, [0, 1]) self._compareAll(np_arr, [1, 2]) self._compareAll(np_arr, [0, 2]) self._compareAll(np_arr, [0, 1, 2]) def testDoubleReduce3D(self): # Create a 3D array of doubles and reduce across all possible # dimensions np_arr = np.arange(1, 31).reshape([2, 3, 5]).astype(np.float64) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) self._compareAll(np_arr, [1]) self._compareAll(np_arr, [2]) self._compareAll(np_arr, [0, 1]) self._compareAll(np_arr, [1, 2]) self._compareAll(np_arr, [0, 2]) self._compareAll(np_arr, [0, 1, 2]) @test_util.run_deprecated_v1 def testGradient(self): s = [2, 3, 4, 2] x = np.arange(1.0, 49.0).reshape(s).astype(np.float64) with self.cached_session(): t = ops.convert_to_tensor(x) su = math_ops.reduce_min(t, [1, 2]) jacob_t, jacob_n = gradient_checker.compute_gradient( t, s, su, [2, 2], x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8) @test_util.run_deprecated_v1 def testGradient2(self): s = [2, 3, 4, 2] x = np.arange(1.0, 49.0).reshape(s).astype(np.float64) with self.cached_session(): t = ops.convert_to_tensor(x) su = math_ops.reduce_min(t, [1]) jacob_t, jacob_n = gradient_checker.compute_gradient( t, s, su, [2, 4, 2], x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8) @test_util.run_deprecated_v1 def testGradient3(self): s = [2, 3, 4, 2] x = np.arange(1.0, 49.0).reshape(s).astype(np.float64) with self.cached_session(): t = ops.convert_to_tensor(x) su = math_ops.reduce_min(t, [2]) jacob_t, jacob_n = gradient_checker.compute_gradient( t, s, su, [2, 3, 2], x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8) @test_util.run_deprecated_v1 def testGradient4(self): s = [2, 3, 4, 2] x = np.arange(1.0, 49.0).reshape(s).astype(np.float64) with self.cached_session(): t = ops.convert_to_tensor(x) su = math_ops.reduce_min(t) jacob_t, jacob_n = gradient_checker.compute_gradient( t, s, su, [1], x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8) @test_util.run_deprecated_v1 def testEmptyGradients(self): with self.cached_session(): x = array_ops.zeros([0, 3]) y = math_ops.reduce_min(x, [1]) error = gradient_checker.compute_gradient_error(x, [0, 3], y, [0]) self.assertEqual(error, 0) class MaxReductionTest(test.TestCase): def _compare(self, x, reduction_axes, keepdims, use_gpu=False): np_ans = x if reduction_axes is None: np_ans = np.amax(np_ans, keepdims=keepdims) else: for ra in reduction_axes[::-1]: np_ans = np.amax(np_ans, axis=ra, keepdims=keepdims) with self.cached_session(use_gpu=use_gpu): if reduction_axes is not None: reduction_axes = np.array(reduction_axes).astype(np.int32) tf_ans = math_ops.reduce_max(x, reduction_axes, keepdims) out = self.evaluate(tf_ans) self.assertAllClose(np_ans, out) self.assertShapeEqual(np_ans, tf_ans) def _compareAll(self, x, reduction_axes): self._compare(x, reduction_axes, False, use_gpu=True) self._compare(x, reduction_axes, True, use_gpu=True) def testAxesType(self): for dtype in [dtypes.int64, dtypes.int32]: with self.cached_session(): v = math_ops.reduce_max([0, 0], constant_op.constant(0, dtype=dtype)) tf_v = self.evaluate(v) self.assertAllEqual(tf_v, 0) def testSpecialValues(self): for dtype in [np.float32, np.float64]: for size in range(1, 4): for arr in itertools.product([-np.inf, 1., np.nan, np.inf], repeat=size): self._compareAll(np.array(arr, dtype=dtype), None) def testInt64Reduce3D(self): # Create a 3D array of int64s and reduce across all possible # dimensions np_arr = np.arange(-31, -1).reshape([2, 3, 5]).astype(np.int64) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) self._compareAll(np_arr, [1]) self._compareAll(np_arr, [2]) self._compareAll(np_arr, [0, 1]) self._compareAll(np_arr, [1, 2]) self._compareAll(np_arr, [0, 2]) self._compareAll(np_arr, [0, 1, 2]) def testFloatReduce3D(self): # Create a 3D array of floats and reduce across all possible # dimensions np_arr = np.arange(-31, -1).reshape([2, 3, 5]).astype(np.float32) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) self._compareAll(np_arr, [1]) self._compareAll(np_arr, [2]) self._compareAll(np_arr, [0, 1]) self._compareAll(np_arr, [1, 2]) self._compareAll(np_arr, [0, 2]) self._compareAll(np_arr, [0, 1, 2]) def testDoubleReduce3D(self): # Create a 3D array of doubles and reduce across all possible # dimensions np_arr = np.arange(-31, -1).reshape([2, 3, 5]).astype(np.float64) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) self._compareAll(np_arr, [1]) self._compareAll(np_arr, [2]) self._compareAll(np_arr, [0, 1]) self._compareAll(np_arr, [1, 2]) self._compareAll(np_arr, [0, 2]) self._compareAll(np_arr, [0, 1, 2]) @test_util.run_deprecated_v1 def testGradient(self): s = [2, 3, 4, 2] x = np.arange(-49.0, -1.0).reshape(s).astype(np.float64) with self.cached_session(): t = ops.convert_to_tensor(x) su = math_ops.reduce_max(t, [1, 2]) jacob_t, jacob_n = gradient_checker.compute_gradient( t, s, su, [2, 2], x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8) @test_util.run_deprecated_v1 def testGradient2(self): s = [2, 3, 4, 2] x = np.arange(-49.0, -1.0).reshape(s).astype(np.float64) with self.cached_session(): t = ops.convert_to_tensor(x) su = math_ops.reduce_max(t, [1]) jacob_t, jacob_n = gradient_checker.compute_gradient( t, s, su, [2, 4, 2], x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8) @test_util.run_deprecated_v1 def testGradient3(self): s = [2, 3, 4, 2] x = np.arange(-49.0, -1.0).reshape(s).astype(np.float64) with self.cached_session(): t = ops.convert_to_tensor(x) su = math_ops.reduce_max(t, [2]) jacob_t, jacob_n = gradient_checker.compute_gradient( t, s, su, [2, 3, 2], x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8) @test_util.run_deprecated_v1 def testGradient4(self): s = [2, 3, 4, 2] x = np.arange(-49.0, -1.0).reshape(s).astype(np.float64) with self.cached_session(): t = ops.convert_to_tensor(x) su = math_ops.reduce_max(t) jacob_t, jacob_n = gradient_checker.compute_gradient( t, s, su, [1], x_init_value=x, delta=1) self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8) @test_util.run_deprecated_v1 def testEmptyGradients(self): with self.cached_session(): x = array_ops.zeros([0, 3]) y = math_ops.reduce_max(x, [1]) error = gradient_checker.compute_gradient_error(x, [0, 3], y, [0]) self.assertEqual(error, 0) class AllReductionTest(test.TestCase): def _compare(self, x, reduction_axes, keepdims, use_gpu=False): np_ans = x if reduction_axes is None: np_ans = np.all(np_ans, keepdims=keepdims) else: for ra in reduction_axes[::-1]: np_ans = np.all(np_ans, axis=ra, keepdims=keepdims) with self.cached_session(use_gpu=use_gpu): if reduction_axes is not None: reduction_axes = np.array(reduction_axes).astype(np.int32) tf_ans = math_ops.reduce_all(x, reduction_axes, keepdims) out = self.evaluate(tf_ans) self.assertAllEqual(np_ans, out) self.assertShapeEqual(np_ans, tf_ans) def _compareAll(self, x, reduction_axes): self._compare(x, reduction_axes, False, use_gpu=True) self._compare(x, reduction_axes, False, use_gpu=False) self._compare(x, reduction_axes, True, use_gpu=True) self._compare(x, reduction_axes, True, use_gpu=False) def testAxesType(self): for dtype in [dtypes.int64, dtypes.int32]: with self.session(): v = math_ops.reduce_all([True, True], constant_op.constant(0, dtype=dtype)) tf_v = self.evaluate(v) self.assertAllEqual(tf_v, True) def testAll3D(self): # Create a 3D array of bools and reduce across all possible # dimensions np_arr = (np.random.uniform(0, 1, 30) > 0.1).reshape([2, 3, 5]) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) self._compareAll(np_arr, [1]) self._compareAll(np_arr, [2]) self._compareAll(np_arr, [0, 1]) self._compareAll(np_arr, [1, 2]) self._compareAll(np_arr, [0, 2]) self._compareAll(np_arr, [0, 1, 2]) def testEmpty(self): self._compareAll([], [0]) class AnyReductionTest(test.TestCase): def _compare(self, x, reduction_axes, keepdims, use_gpu=False): np_ans = x if reduction_axes is None: np_ans = np.any(np_ans, keepdims=keepdims) else: for ra in reduction_axes[::-1]: np_ans = np.any(np_ans, axis=ra, keepdims=keepdims) with self.cached_session(use_gpu=use_gpu): if reduction_axes is not None: reduction_axes = np.array(reduction_axes).astype(np.int32) tf_ans = math_ops.reduce_any(x, reduction_axes, keepdims) out = self.evaluate(tf_ans) self.assertAllEqual(np_ans, out) self.assertShapeEqual(np_ans, tf_ans) def _compareAll(self, x, reduction_axes): self._compare(x, reduction_axes, False, use_gpu=True) self._compare(x, reduction_axes, False, use_gpu=False) self._compare(x, reduction_axes, True, use_gpu=True) self._compare(x, reduction_axes, True, use_gpu=False) def testAxesType(self): for dtype in [dtypes.int64, dtypes.int32]: with self.session(): v = math_ops.reduce_any([True, True], constant_op.constant(0, dtype=dtype)) tf_v = self.evaluate(v) self.assertAllEqual(tf_v, True) def testAll3D(self): # Create a 3D array of bools and reduce across all possible # dimensions np_arr = (np.random.uniform(0, 1, 30) > 0.9).reshape([2, 3, 5]) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) self._compareAll(np_arr, [1]) self._compareAll(np_arr, [2]) self._compareAll(np_arr, [0, 1]) self._compareAll(np_arr, [1, 2]) self._compareAll(np_arr, [0, 2]) self._compareAll(np_arr, [0, 1, 2]) def testEmpty(self): self._compareAll([], [0]) class CountNonzeroReductionTest(test.TestCase): def _compare(self, x, reduction_axes, keepdims, use_gpu=False, zero=0, feed_dict=None): np_ans = (x != zero).astype(np.int32) if reduction_axes is None: np_ans = np.sum(np_ans, keepdims=keepdims) else: reduction_axes = np.array(reduction_axes).astype(np.int32) for ra in reduction_axes.ravel()[::-1]: np_ans = np.sum(np_ans, axis=ra, keepdims=keepdims) with self.cached_session(use_gpu=use_gpu) as sess: tf_ans = math_ops.count_nonzero(x, reduction_axes, keepdims) out = sess.run(tf_ans, feed_dict) self.assertAllClose(np_ans, out) self.assertShapeEqual(np_ans, tf_ans) def _compareAll(self, x, reduction_axes, feed_dict=None): if reduction_axes is not None and np.shape(reduction_axes) == (1,): # Test scalar reduction_axes argument self._compareAll(x, reduction_axes[0]) self._compare(x, reduction_axes, False, use_gpu=True, feed_dict=feed_dict) self._compare(x, reduction_axes, False, use_gpu=False, feed_dict=feed_dict) self._compare(x, reduction_axes, True, use_gpu=True, feed_dict=feed_dict) self._compare(x, reduction_axes, True, use_gpu=False, feed_dict=feed_dict) @test_util.run_deprecated_v1 def testBoolReduce1D(self): # Create a 1D array of floats np_arr = np.asarray([False, False, True, False, False, True]) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) @test_util.run_deprecated_v1 def testFloatReduce1D(self): # Create a 1D array of floats np_arr = np.asarray([0.0, 1.0, -1.0, 0.0, 0.0, 3.0]).astype(np.float32) self._compareAll(np_arr, [0]) @test_util.run_deprecated_v1 def testFloatReduce4D(self): # Create a 4D array of floats and reduce across some # dimensions np_arr = np.floor(np.arange(0.0, 210.0) / 100.0).reshape([2, 3, 5, 7]).astype( np.float32) self._compareAll(np_arr, None) self._compareAll(np_arr, []) self._compareAll(np_arr, [0]) self._compareAll(np_arr, [1]) self._compareAll(np_arr, [2]) self._compareAll(np_arr, [0, 1]) self._compareAll(np_arr, [1, 2]) # Need specialization for reduce(4D, [0, 2]) # self._compareAll(np_arr, [0, 2]) self._compareAll(np_arr, [0, 1, 2]) self._compareAll(np_arr, [1, 2, 3]) self._compareAll(np_arr, [0, 1, 2, 3]) @test_util.run_deprecated_v1 def testExpand(self): # Reduce an empty tensor to a nonempty tensor x = np.zeros((5, 0)) self._compareAll(x, [1]) @test_util.run_deprecated_v1 def testDegenerate(self): for use_gpu in False, True: with self.cached_session(use_gpu=use_gpu): for dtype in (dtypes.bool,): # A large number is needed to get Eigen to die x = array_ops.zeros((0, 9938), dtype=dtype) y = math_ops.count_nonzero(x, [0]) self.assertAllEqual(y, np.zeros(9938)) def testStringReduce(self): # Test case for GitHub issue 18712 with self.cached_session() as sess: v = math_ops.count_nonzero(constant_op.constant(["test"])) self.assertAllClose(self.evaluate(v), 1) @test_util.run_deprecated_v1 def testStringReduce1D(self): # Create a 1D array of strings x = np.asarray(["", "", "a", "", "", "b"]) self._compare(x, None, keepdims=False, zero=np.str_("")) self._compare(x, [], keepdims=False, zero=np.str_("")) self._compare(x, [0], keepdims=False, zero=np.str_("")) self._compare(x, None, keepdims=True, zero=np.str_("")) self._compare(x, [], keepdims=True, zero=np.str_("")) self._compare(x, [0], keepdims=True, zero=np.str_("")) @test_util.run_deprecated_v1 def testStringReduce2D(self): # Create a 2D array of strings x = np.asarray([["", "", "a", "", "", "b"], ["", "c", "", "d", "", ""], ["e", "", "f", "", "", ""]]) self._compare(x, None, keepdims=False, zero=np.str_("")) self._compare(x, [], keepdims=False, zero=np.str_("")) self._compare(x, [0], keepdims=False, zero=np.str_("")) self._compare(x, [1], keepdims=False, zero=np.str_("")) self._compare(x, [0, 1], keepdims=False, zero=np.str_("")) self._compare(x, None, keepdims=True, zero=np.str_("")) self._compare(x, [], keepdims=True, zero=np.str_("")) self._compare(x, [0], keepdims=True, zero=np.str_("")) self._compare(x, [0, 1], keepdims=True, zero=np.str_("")) if __name__ == "__main__": test.main()
apache-2.0
cutecore/futuregadget-lab
magicasakura/src/main/java/com/bilibili/magicasakura/widgets/Tintable.java
761
/* * Copyright (C) 2016 Bilibili * * 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 com.bilibili.magicasakura.widgets; /** * Created by xyczero on 15/9/6. * Email : xyczero@sina.com */ public interface Tintable { void tint(); }
apache-2.0
envoyproxy/envoy-wasm
tools/protoxform/merge_active_shadow_test.py
12052
import unittest import merge_active_shadow from tools.api_proto_plugin import type_context as api_type_context from google.protobuf import descriptor_pb2 from google.protobuf import text_format class MergeActiveShadowTest(unittest.TestCase): # Dummy type context for tests that don't care about this. def fakeTypeContext(self): fake_source_code_info = descriptor_pb2.SourceCodeInfo() source_code_info = api_type_context.SourceCodeInfo('fake', fake_source_code_info) return api_type_context.TypeContext(source_code_info, 'fake_package') # Poor man's text proto equivalence. Tensorflow has better tools for this, # i.e. assertProto2Equal. def assertTextProtoEq(self, lhs, rhs): self.assertMultiLineEqual(lhs.strip(), rhs.strip()) def testAdjustReservedRange(self): """AdjustReservedRange removes specified skip_reserved_numbers.""" desc_pb_text = """ reserved_range { start: 41 end: 41 } reserved_range { start: 42 end: 42 } reserved_range { start: 43 end: 44 } reserved_range { start: 50 end: 51 } """ desc = descriptor_pb2.DescriptorProto() text_format.Merge(desc_pb_text, desc) target = descriptor_pb2.DescriptorProto() merge_active_shadow.AdjustReservedRange(target, desc.reserved_range, [42, 43]) target_pb_text = """ reserved_range { start: 41 end: 41 } reserved_range { start: 50 end: 51 } """ self.assertTextProtoEq(target_pb_text, str(target)) def testMergeActiveShadowEnum(self): """MergeActiveShadowEnum recovers shadow values.""" active_pb_text = """ value { number: 1 name: "foo" } value { number: 0 name: "DEPRECATED_AND_UNAVAILABLE_DO_NOT_USE" } value { number: 3 name: "bar" } reserved_name: "baz" reserved_range { start: 2 end: 3 } """ active_proto = descriptor_pb2.EnumDescriptorProto() text_format.Merge(active_pb_text, active_proto) shadow_pb_text = """ value { number: 1 name: "foo" } value { number: 0 name: "wow" } value { number: 3 name: "bar" } value { number: 2 name: "hidden_envoy_deprecated_baz" } value { number: 4 name: "hidden_envoy_deprecated_huh" } """ shadow_proto = descriptor_pb2.EnumDescriptorProto() text_format.Merge(shadow_pb_text, shadow_proto) target_proto = descriptor_pb2.EnumDescriptorProto() merge_active_shadow.MergeActiveShadowEnum(active_proto, shadow_proto, target_proto) target_pb_text = """ value { name: "foo" number: 1 } value { name: "wow" number: 0 } value { name: "bar" number: 3 } value { name: "hidden_envoy_deprecated_baz" number: 2 } """ self.assertTextProtoEq(target_pb_text, str(target_proto)) def testMergeActiveShadowMessageComments(self): """MergeActiveShadowMessage preserves comment field correspondence.""" active_pb_text = """ field { number: 9 name: "oneof_1_0" oneof_index: 0 } field { number: 1 name: "simple_field_0" } field { number: 0 name: "oneof_2_0" oneof_index: 2 } field { number: 8 name: "oneof_2_1" oneof_index: 2 } field { number: 3 name: "oneof_0_0" oneof_index: 1 } field { number: 4 name: "newbie" } field { number: 7 name: "oneof_3_0" oneof_index: 3 } reserved_name: "missing_oneof_field_0" reserved_name: "missing_oneof_field_1" reserved_name: "missing_oneof_field_2" oneof_decl { name: "oneof_0" } oneof_decl { name: "oneof_1" } oneof_decl { name: "oneof_2" } oneof_decl { name: "oneof_3" } """ active_proto = descriptor_pb2.DescriptorProto() text_format.Merge(active_pb_text, active_proto) active_source_code_info_text = """ location { path: [4, 1, 2, 4] leading_comments: "field_4" } location { path: [4, 1, 2, 5] leading_comments: "field_5" } location { path: [4, 1, 2, 3] leading_comments: "field_3" } location { path: [4, 1, 2, 0] leading_comments: "field_0" } location { path: [4, 1, 2, 1] leading_comments: "field_1" } location { path: [4, 0, 2, 2] leading_comments: "ignore_0" } location { path: [4, 1, 2, 6] leading_comments: "field_6" } location { path: [4, 1, 2, 2] leading_comments: "field_2" } location { path: [3] leading_comments: "ignore_1" } """ active_source_code_info = descriptor_pb2.SourceCodeInfo() text_format.Merge(active_source_code_info_text, active_source_code_info) shadow_pb_text = """ field { number: 10 name: "hidden_envoy_deprecated_missing_oneof_field_0" oneof_index: 0 } field { number: 11 name: "hidden_envoy_deprecated_missing_oneof_field_1" oneof_index: 3 } field { number: 11 name: "hidden_envoy_deprecated_missing_oneof_field_2" oneof_index: 2 } oneof_decl { name: "oneof_0" } oneof_decl { name: "oneof_1" } oneof_decl { name: "oneof_2" } oneof_decl { name: "some_removed_oneof" } oneof_decl { name: "oneof_3" } """ shadow_proto = descriptor_pb2.DescriptorProto() text_format.Merge(shadow_pb_text, shadow_proto) target_proto = descriptor_pb2.DescriptorProto() source_code_info = api_type_context.SourceCodeInfo('fake', active_source_code_info) fake_type_context = api_type_context.TypeContext(source_code_info, 'fake_package') merge_active_shadow.MergeActiveShadowMessage(fake_type_context.ExtendMessage(1, "foo", False), active_proto, shadow_proto, target_proto) target_pb_text = """ field { name: "oneof_1_0" number: 9 oneof_index: 0 } field { name: "hidden_envoy_deprecated_missing_oneof_field_0" number: 10 oneof_index: 0 } field { name: "simple_field_0" number: 1 } field { name: "oneof_2_0" number: 0 oneof_index: 2 } field { name: "oneof_2_1" number: 8 oneof_index: 2 } field { name: "hidden_envoy_deprecated_missing_oneof_field_2" number: 11 oneof_index: 2 } field { name: "oneof_0_0" number: 3 oneof_index: 1 } field { name: "newbie" number: 4 } field { name: "oneof_3_0" number: 7 oneof_index: 3 } field { name: "hidden_envoy_deprecated_missing_oneof_field_1" number: 11 oneof_index: 4 } oneof_decl { name: "oneof_0" } oneof_decl { name: "oneof_1" } oneof_decl { name: "oneof_2" } oneof_decl { name: "oneof_3" } oneof_decl { name: "some_removed_oneof" } """ target_source_code_info_text = """ location { path: 4 path: 1 path: 2 path: 6 leading_comments: "field_4" } location { path: 4 path: 1 path: 2 path: 7 leading_comments: "field_5" } location { path: 4 path: 1 path: 2 path: 4 leading_comments: "field_3" } location { path: 4 path: 1 path: 2 path: 0 leading_comments: "field_0" } location { path: 4 path: 1 path: 2 path: 2 leading_comments: "field_1" } location { path: 4 path: 0 path: 2 path: 2 leading_comments: "ignore_0" } location { path: 4 path: 1 path: 2 path: 8 leading_comments: "field_6" } location { path: 4 path: 1 path: 2 path: 3 leading_comments: "field_2" } location { path: 3 leading_comments: "ignore_1" } """ self.maxDiff = None self.assertTextProtoEq(target_pb_text, str(target_proto)) self.assertTextProtoEq(target_source_code_info_text, str(fake_type_context.source_code_info.proto)) def testMergeActiveShadowMessage(self): """MergeActiveShadowMessage recovers shadow fields with oneofs.""" active_pb_text = """ field { number: 1 name: "foo" } field { number: 0 name: "bar" oneof_index: 2 } field { number: 3 name: "baz" } field { number: 4 name: "newbie" } reserved_name: "wow" reserved_range { start: 2 end: 3 } oneof_decl { name: "ign" } oneof_decl { name: "ign2" } oneof_decl { name: "some_oneof" } """ active_proto = descriptor_pb2.DescriptorProto() text_format.Merge(active_pb_text, active_proto) shadow_pb_text = """ field { number: 1 name: "foo" } field { number: 0 name: "bar" } field { number: 3 name: "baz" } field { number: 2 name: "hidden_envoy_deprecated_wow" oneof_index: 0 } oneof_decl { name: "some_oneof" } """ shadow_proto = descriptor_pb2.DescriptorProto() text_format.Merge(shadow_pb_text, shadow_proto) target_proto = descriptor_pb2.DescriptorProto() merge_active_shadow.MergeActiveShadowMessage(self.fakeTypeContext(), active_proto, shadow_proto, target_proto) target_pb_text = """ field { name: "foo" number: 1 } field { name: "bar" number: 0 oneof_index: 2 } field { name: "hidden_envoy_deprecated_wow" number: 2 oneof_index: 2 } field { name: "baz" number: 3 } field { name: "newbie" number: 4 } oneof_decl { name: "ign" } oneof_decl { name: "ign2" } oneof_decl { name: "some_oneof" } """ self.assertTextProtoEq(target_pb_text, str(target_proto)) def testMergeActiveShadowMessageNoShadowMessage(self): """MergeActiveShadowMessage doesn't require a shadow message for new nested active messages.""" active_proto = descriptor_pb2.DescriptorProto() shadow_proto = descriptor_pb2.DescriptorProto() active_proto.nested_type.add().name = 'foo' target_proto = descriptor_pb2.DescriptorProto() merge_active_shadow.MergeActiveShadowMessage(self.fakeTypeContext(), active_proto, shadow_proto, target_proto) self.assertEqual(target_proto.nested_type[0].name, 'foo') def testMergeActiveShadowMessageNoShadowEnum(self): """MergeActiveShadowMessage doesn't require a shadow enum for new nested active enums.""" active_proto = descriptor_pb2.DescriptorProto() shadow_proto = descriptor_pb2.DescriptorProto() active_proto.enum_type.add().name = 'foo' target_proto = descriptor_pb2.DescriptorProto() merge_active_shadow.MergeActiveShadowMessage(self.fakeTypeContext(), active_proto, shadow_proto, target_proto) self.assertEqual(target_proto.enum_type[0].name, 'foo') def testMergeActiveShadowMessageMissing(self): """MergeActiveShadowMessage recovers missing messages from shadow.""" active_proto = descriptor_pb2.DescriptorProto() shadow_proto = descriptor_pb2.DescriptorProto() shadow_proto.nested_type.add().name = 'foo' target_proto = descriptor_pb2.DescriptorProto() merge_active_shadow.MergeActiveShadowMessage(self.fakeTypeContext(), active_proto, shadow_proto, target_proto) self.assertEqual(target_proto.nested_type[0].name, 'foo') def testMergeActiveShadowFileMissing(self): """MergeActiveShadowFile recovers missing messages from shadow.""" active_proto = descriptor_pb2.FileDescriptorProto() shadow_proto = descriptor_pb2.FileDescriptorProto() shadow_proto.message_type.add().name = 'foo' target_proto = descriptor_pb2.DescriptorProto() target_proto = merge_active_shadow.MergeActiveShadowFile(active_proto, shadow_proto) self.assertEqual(target_proto.message_type[0].name, 'foo') def testMergeActiveShadowFileNoShadowMessage(self): """MergeActiveShadowFile doesn't require a shadow message for new active messages.""" active_proto = descriptor_pb2.FileDescriptorProto() shadow_proto = descriptor_pb2.FileDescriptorProto() active_proto.message_type.add().name = 'foo' target_proto = descriptor_pb2.DescriptorProto() target_proto = merge_active_shadow.MergeActiveShadowFile(active_proto, shadow_proto) self.assertEqual(target_proto.message_type[0].name, 'foo') def testMergeActiveShadowFileNoShadowEnum(self): """MergeActiveShadowFile doesn't require a shadow enum for new active enums.""" active_proto = descriptor_pb2.FileDescriptorProto() shadow_proto = descriptor_pb2.FileDescriptorProto() active_proto.enum_type.add().name = 'foo' target_proto = descriptor_pb2.DescriptorProto() target_proto = merge_active_shadow.MergeActiveShadowFile(active_proto, shadow_proto) self.assertEqual(target_proto.enum_type[0].name, 'foo') # TODO(htuch): add some test for recursion. if __name__ == '__main__': unittest.main()
apache-2.0
shyamjvs/test-infra
prow/tide/tide_test.go
57470
/* 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 tide import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "reflect" "testing" githubql "github.com/shurcooL/githubv4" "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/util/diff" clienttesting "k8s.io/client-go/testing" prowapi "k8s.io/test-infra/prow/apis/prowjobs/v1" "k8s.io/test-infra/prow/client/clientset/versioned/fake" "k8s.io/test-infra/prow/config" "k8s.io/test-infra/prow/git/localgit" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/tide/history" ) func testPullsMatchList(t *testing.T, test string, actual []PullRequest, expected []int) { if len(actual) != len(expected) { t.Errorf("Wrong size for case %s. Got PRs %+v, wanted numbers %v.", test, actual, expected) return } for _, pr := range actual { var found bool n1 := int(pr.Number) for _, n2 := range expected { if n1 == n2 { found = true } } if !found { t.Errorf("For case %s, found PR %d but shouldn't have.", test, n1) } } } func TestAccumulateBatch(t *testing.T) { jobSet := []config.Presubmit{ { Reporter: config.Reporter{Context: "foo"}, }, { Reporter: config.Reporter{Context: "bar"}, }, { Reporter: config.Reporter{Context: "baz"}, }, } type pull struct { number int sha string } type prowjob struct { prs []pull job string state prowapi.ProwJobState } tests := []struct { name string presubmits map[int][]config.Presubmit pulls []pull prowJobs []prowjob merges []int pending bool }{ { name: "no batches running", }, { name: "batch pending", presubmits: map[int][]config.Presubmit{ 1: {{Reporter: config.Reporter{Context: "foo"}}}, 2: {{Reporter: config.Reporter{Context: "foo"}}}, }, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{{job: "foo", state: prowapi.PendingState, prs: []pull{{1, "a"}}}}, pending: true, }, { name: "pending batch missing presubmits is ignored", presubmits: map[int][]config.Presubmit{1: jobSet}, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{{job: "foo", state: prowapi.PendingState, prs: []pull{{1, "a"}}}}, }, { name: "batch pending, successful previous run", presubmits: map[int][]config.Presubmit{1: jobSet, 2: jobSet}, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{ {job: "foo", state: prowapi.PendingState, prs: []pull{{1, "a"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{1, "a"}}}, {job: "baz", state: prowapi.SuccessState, prs: []pull{{1, "a"}}}, {job: "foo", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, {job: "baz", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, }, pending: true, merges: []int{2}, }, { name: "successful run", presubmits: map[int][]config.Presubmit{1: jobSet, 2: jobSet}, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{ {job: "foo", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, {job: "baz", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, }, merges: []int{2}, }, { name: "successful run, multiple PRs", presubmits: map[int][]config.Presubmit{1: jobSet, 2: jobSet}, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{ {job: "foo", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "baz", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, }, merges: []int{1, 2}, }, { name: "successful run, failures in past", presubmits: map[int][]config.Presubmit{1: jobSet, 2: jobSet}, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{ {job: "foo", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "baz", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "foo", state: prowapi.FailureState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "baz", state: prowapi.FailureState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "foo", state: prowapi.FailureState, prs: []pull{{1, "c"}, {2, "b"}}}, }, merges: []int{1, 2}, }, { name: "failures", presubmits: map[int][]config.Presubmit{1: jobSet, 2: jobSet}, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{ {job: "foo", state: prowapi.FailureState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "baz", state: prowapi.FailureState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "foo", state: prowapi.FailureState, prs: []pull{{1, "c"}, {2, "b"}}}, }, }, { name: "missing job required by one PR", presubmits: map[int][]config.Presubmit{1: jobSet, 2: append(jobSet, config.Presubmit{Reporter: config.Reporter{Context: "boo"}})}, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{ {job: "foo", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "baz", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, }, }, { name: "successful run with PR that requires additional job", presubmits: map[int][]config.Presubmit{1: jobSet, 2: append(jobSet, config.Presubmit{Reporter: config.Reporter{Context: "boo"}})}, pulls: []pull{{1, "a"}, {2, "b"}}, prowJobs: []prowjob{ {job: "foo", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "baz", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, {job: "boo", state: prowapi.SuccessState, prs: []pull{{1, "a"}, {2, "b"}}}, }, merges: []int{1, 2}, }, { name: "no presubmits", pulls: []pull{{1, "a"}, {2, "b"}}, pending: false, }, { name: "pending batch with PR that left pool, successful previous run", presubmits: map[int][]config.Presubmit{2: jobSet}, pulls: []pull{{2, "b"}}, prowJobs: []prowjob{ {job: "foo", state: prowapi.PendingState, prs: []pull{{1, "a"}}}, {job: "foo", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, {job: "bar", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, {job: "baz", state: prowapi.SuccessState, prs: []pull{{2, "b"}}}, }, pending: false, merges: []int{2}, }, } for _, test := range tests { var pulls []PullRequest for _, p := range test.pulls { pr := PullRequest{ Number: githubql.Int(p.number), HeadRefOID: githubql.String(p.sha), } pulls = append(pulls, pr) } var pjs []prowapi.ProwJob for _, pj := range test.prowJobs { npj := prowapi.ProwJob{ Spec: prowapi.ProwJobSpec{ Job: pj.job, Context: pj.job, Type: prowapi.BatchJob, Refs: new(prowapi.Refs), }, Status: prowapi.ProwJobStatus{State: pj.state}, } for _, pr := range pj.prs { npj.Spec.Refs.Pulls = append(npj.Spec.Refs.Pulls, prowapi.Pull{ Number: pr.number, SHA: pr.sha, }) } pjs = append(pjs, npj) } merges, pending := accumulateBatch(test.presubmits, pulls, pjs, logrus.NewEntry(logrus.New())) if (len(pending) > 0) != test.pending { t.Errorf("For case \"%s\", got wrong pending.", test.name) } testPullsMatchList(t, test.name, merges, test.merges) } } func TestAccumulate(t *testing.T) { jobSet := []config.Presubmit{ { Reporter: config.Reporter{ Context: "job1", }, }, { Reporter: config.Reporter{ Context: "job2", }, }, } type prowjob struct { prNumber int job string state prowapi.ProwJobState sha string } tests := []struct { presubmits map[int][]config.Presubmit pullRequests map[int]string prowJobs []prowjob successes []int pendings []int none []int }{ { pullRequests: map[int]string{1: "", 2: "", 3: "", 4: "", 5: "", 6: "", 7: ""}, presubmits: map[int][]config.Presubmit{ 1: jobSet, 2: jobSet, 3: jobSet, 4: jobSet, 5: jobSet, 6: jobSet, 7: jobSet, }, prowJobs: []prowjob{ {2, "job1", prowapi.PendingState, ""}, {3, "job1", prowapi.PendingState, ""}, {3, "job2", prowapi.TriggeredState, ""}, {4, "job1", prowapi.FailureState, ""}, {4, "job2", prowapi.PendingState, ""}, {5, "job1", prowapi.PendingState, ""}, {5, "job2", prowapi.FailureState, ""}, {5, "job2", prowapi.PendingState, ""}, {6, "job1", prowapi.SuccessState, ""}, {6, "job2", prowapi.PendingState, ""}, {7, "job1", prowapi.SuccessState, ""}, {7, "job2", prowapi.SuccessState, ""}, {7, "job1", prowapi.FailureState, ""}, }, successes: []int{7}, pendings: []int{3, 5, 6}, none: []int{1, 2, 4}, }, { pullRequests: map[int]string{7: ""}, presubmits: map[int][]config.Presubmit{ 7: { {Reporter: config.Reporter{Context: "job1"}}, {Reporter: config.Reporter{Context: "job2"}}, {Reporter: config.Reporter{Context: "job3"}}, {Reporter: config.Reporter{Context: "job4"}}, }, }, prowJobs: []prowjob{ {7, "job1", prowapi.SuccessState, ""}, {7, "job2", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, {7, "job2", prowapi.SuccessState, ""}, {7, "job3", prowapi.SuccessState, ""}, {7, "job4", prowapi.FailureState, ""}, }, successes: []int{}, pendings: []int{}, none: []int{7}, }, { pullRequests: map[int]string{7: ""}, presubmits: map[int][]config.Presubmit{ 7: { {Reporter: config.Reporter{Context: "job1"}}, {Reporter: config.Reporter{Context: "job2"}}, {Reporter: config.Reporter{Context: "job3"}}, {Reporter: config.Reporter{Context: "job4"}}, }, }, prowJobs: []prowjob{ {7, "job1", prowapi.FailureState, ""}, {7, "job2", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, {7, "job2", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, }, successes: []int{}, pendings: []int{}, none: []int{7}, }, { pullRequests: map[int]string{7: ""}, presubmits: map[int][]config.Presubmit{ 7: { {Reporter: config.Reporter{Context: "job1"}}, {Reporter: config.Reporter{Context: "job2"}}, {Reporter: config.Reporter{Context: "job3"}}, {Reporter: config.Reporter{Context: "job4"}}, }, }, prowJobs: []prowjob{ {7, "job1", prowapi.SuccessState, ""}, {7, "job2", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, {7, "job2", prowapi.SuccessState, ""}, {7, "job3", prowapi.SuccessState, ""}, {7, "job4", prowapi.SuccessState, ""}, {7, "job1", prowapi.FailureState, ""}, }, successes: []int{7}, pendings: []int{}, none: []int{}, }, { pullRequests: map[int]string{7: ""}, presubmits: map[int][]config.Presubmit{ 7: { {Reporter: config.Reporter{Context: "job1"}}, {Reporter: config.Reporter{Context: "job2"}}, {Reporter: config.Reporter{Context: "job3"}}, {Reporter: config.Reporter{Context: "job4"}}, }, }, prowJobs: []prowjob{ {7, "job1", prowapi.SuccessState, ""}, {7, "job2", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, {7, "job3", prowapi.FailureState, ""}, {7, "job4", prowapi.FailureState, ""}, {7, "job2", prowapi.SuccessState, ""}, {7, "job3", prowapi.SuccessState, ""}, {7, "job4", prowapi.PendingState, ""}, {7, "job1", prowapi.FailureState, ""}, }, successes: []int{}, pendings: []int{7}, none: []int{}, }, { presubmits: map[int][]config.Presubmit{ 7: { {Reporter: config.Reporter{Context: "job1"}}, }, }, pullRequests: map[int]string{7: "new", 8: "new"}, prowJobs: []prowjob{ {7, "job1", prowapi.SuccessState, "old"}, {7, "job1", prowapi.FailureState, "new"}, {8, "job1", prowapi.FailureState, "old"}, {8, "job1", prowapi.SuccessState, "new"}, }, successes: []int{8}, pendings: []int{}, none: []int{7}, }, { pullRequests: map[int]string{7: "new", 8: "new"}, prowJobs: []prowjob{}, successes: []int{8, 7}, pendings: []int{}, none: []int{}, }, } for i, test := range tests { var pulls []PullRequest for num, sha := range test.pullRequests { pulls = append( pulls, PullRequest{Number: githubql.Int(num), HeadRefOID: githubql.String(sha)}, ) } var pjs []prowapi.ProwJob for _, pj := range test.prowJobs { pjs = append(pjs, prowapi.ProwJob{ Spec: prowapi.ProwJobSpec{ Job: pj.job, Context: pj.job, Type: prowapi.PresubmitJob, Refs: &prowapi.Refs{Pulls: []prowapi.Pull{{Number: pj.prNumber, SHA: pj.sha}}}, }, Status: prowapi.ProwJobStatus{State: pj.state}, }) } successes, pendings, nones := accumulate(test.presubmits, pulls, pjs, logrus.NewEntry(logrus.New())) t.Logf("test run %d", i) testPullsMatchList(t, "successes", successes, test.successes) testPullsMatchList(t, "pendings", pendings, test.pendings) testPullsMatchList(t, "nones", nones, test.none) } } type fgc struct { prs []PullRequest refs map[string]string merged int setStatus bool expectedSHA string combinedStatus map[string]string } func (f *fgc) GetRef(o, r, ref string) (string, error) { return f.refs[o+"/"+r+" "+ref], nil } func (f *fgc) Query(ctx context.Context, q interface{}, vars map[string]interface{}) error { sq, ok := q.(*searchQuery) if !ok { return errors.New("unexpected query type") } for _, pr := range f.prs { sq.Search.Nodes = append( sq.Search.Nodes, struct { PullRequest PullRequest `graphql:"... on PullRequest"` }{PullRequest: pr}, ) } return nil } func (f *fgc) Merge(org, repo string, number int, details github.MergeDetails) error { if details.SHA == "uh oh" { return errors.New("invalid sha") } f.merged++ return nil } func (f *fgc) CreateStatus(org, repo, ref string, s github.Status) error { switch s.State { case github.StatusSuccess, github.StatusError, github.StatusPending, github.StatusFailure: f.setStatus = true return nil } return fmt.Errorf("invalid 'state' value: %q", s.State) } func (f *fgc) GetCombinedStatus(org, repo, ref string) (*github.CombinedStatus, error) { if f.expectedSHA != ref { return nil, errors.New("bad combined status request: incorrect sha") } var statuses []github.Status for c, s := range f.combinedStatus { statuses = append(statuses, github.Status{Context: c, State: s}) } return &github.CombinedStatus{ Statuses: statuses, }, nil } func (f *fgc) GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error) { if number != 100 { return nil, nil } return []github.PullRequestChange{ { Filename: "CHANGED", }, }, nil } // TestDividePool ensures that subpools returned by dividePool satisfy a few // important invariants. func TestDividePool(t *testing.T) { testPulls := []struct { org string repo string number int branch string }{ { org: "k", repo: "t-i", number: 5, branch: "master", }, { org: "k", repo: "t-i", number: 6, branch: "master", }, { org: "k", repo: "k", number: 123, branch: "master", }, { org: "k", repo: "k", number: 1000, branch: "release-1.6", }, } testPJs := []struct { jobType prowapi.ProwJobType org string repo string baseRef string baseSHA string }{ { jobType: prowapi.PresubmitJob, org: "k", repo: "t-i", baseRef: "master", baseSHA: "123", }, { jobType: prowapi.BatchJob, org: "k", repo: "t-i", baseRef: "master", baseSHA: "123", }, { jobType: prowapi.PeriodicJob, }, { jobType: prowapi.PresubmitJob, org: "k", repo: "t-i", baseRef: "patch", baseSHA: "123", }, { jobType: prowapi.PresubmitJob, org: "k", repo: "t-i", baseRef: "master", baseSHA: "abc", }, { jobType: prowapi.PresubmitJob, org: "o", repo: "t-i", baseRef: "master", baseSHA: "123", }, { jobType: prowapi.PresubmitJob, org: "k", repo: "other", baseRef: "master", baseSHA: "123", }, } fc := &fgc{ refs: map[string]string{"k/t-i heads/master": "123"}, } c := &Controller{ ghc: fc, logger: logrus.WithField("component", "tide"), } pulls := make(map[string]PullRequest) for _, p := range testPulls { npr := PullRequest{Number: githubql.Int(p.number)} npr.BaseRef.Name = githubql.String(p.branch) npr.BaseRef.Prefix = "refs/heads/" npr.Repository.Name = githubql.String(p.repo) npr.Repository.Owner.Login = githubql.String(p.org) pulls[prKey(&npr)] = npr } var pjs []prowapi.ProwJob for _, pj := range testPJs { pjs = append(pjs, prowapi.ProwJob{ Spec: prowapi.ProwJobSpec{ Type: pj.jobType, Refs: &prowapi.Refs{ Org: pj.org, Repo: pj.repo, BaseRef: pj.baseRef, BaseSHA: pj.baseSHA, }, }, }) } sps, err := c.dividePool(pulls, pjs) if err != nil { t.Fatalf("Error dividing pool: %v", err) } if len(sps) == 0 { t.Error("No subpools.") } for _, sp := range sps { name := fmt.Sprintf("%s/%s %s", sp.org, sp.repo, sp.branch) sha := fc.refs[sp.org+"/"+sp.repo+" heads/"+sp.branch] if sp.sha != sha { t.Errorf("For subpool %s, got sha %s, expected %s.", name, sp.sha, sha) } if len(sp.prs) == 0 { t.Errorf("Subpool %s has no PRs.", name) } for _, pr := range sp.prs { if string(pr.Repository.Owner.Login) != sp.org || string(pr.Repository.Name) != sp.repo || string(pr.BaseRef.Name) != sp.branch { t.Errorf("PR in wrong subpool. Got PR %+v in subpool %s.", pr, name) } } for _, pj := range sp.pjs { if pj.Spec.Type != prowapi.PresubmitJob && pj.Spec.Type != prowapi.BatchJob { t.Errorf("PJ with bad type in subpool %s: %+v", name, pj) } if pj.Spec.Refs.Org != sp.org || pj.Spec.Refs.Repo != sp.repo || pj.Spec.Refs.BaseRef != sp.branch || pj.Spec.Refs.BaseSHA != sp.sha { t.Errorf("PJ in wrong subpool. Got PJ %+v in subpool %s.", pj, name) } } } } func TestPickBatch(t *testing.T) { lg, gc, err := localgit.New() if err != nil { t.Fatalf("Error making local git: %v", err) } defer gc.Clean() defer lg.Clean() if err := lg.MakeFakeRepo("o", "r"); err != nil { t.Fatalf("Error making fake repo: %v", err) } if err := lg.AddCommit("o", "r", map[string][]byte{"foo": []byte("foo")}); err != nil { t.Fatalf("Adding initial commit: %v", err) } testprs := []struct { files map[string][]byte success bool number int included bool }{ { files: map[string][]byte{"bar": []byte("ok")}, success: true, number: 0, included: true, }, { files: map[string][]byte{"foo": []byte("ok")}, success: true, number: 1, included: true, }, { files: map[string][]byte{"bar": []byte("conflicts with 0")}, success: true, number: 2, included: false, }, { files: map[string][]byte{"qux": []byte("ok")}, success: false, number: 6, included: false, }, { files: map[string][]byte{"bazel": []byte("ok")}, success: true, number: 7, included: false, // batch of 5 smallest excludes this }, { files: map[string][]byte{"other": []byte("ok")}, success: true, number: 5, included: true, }, { files: map[string][]byte{"changes": []byte("ok")}, success: true, number: 4, included: true, }, { files: map[string][]byte{"something": []byte("ok")}, success: true, number: 3, included: true, }, } sp := subpool{ log: logrus.WithField("component", "tide"), org: "o", repo: "r", branch: "master", sha: "master", } for _, testpr := range testprs { if err := lg.CheckoutNewBranch("o", "r", fmt.Sprintf("pr-%d", testpr.number)); err != nil { t.Fatalf("Error checking out new branch: %v", err) } if err := lg.AddCommit("o", "r", testpr.files); err != nil { t.Fatalf("Error adding commit: %v", err) } if err := lg.Checkout("o", "r", "master"); err != nil { t.Fatalf("Error checking out master: %v", err) } oid := githubql.String(fmt.Sprintf("origin/pr-%d", testpr.number)) var pr PullRequest pr.Number = githubql.Int(testpr.number) pr.HeadRefOID = oid pr.Commits.Nodes = []struct { Commit Commit }{{Commit: Commit{OID: oid}}} pr.Commits.Nodes[0].Commit.Status.Contexts = append(pr.Commits.Nodes[0].Commit.Status.Contexts, Context{State: githubql.StatusStateSuccess}) if !testpr.success { pr.Commits.Nodes[0].Commit.Status.Contexts[0].State = githubql.StatusStateFailure } sp.prs = append(sp.prs, pr) } ca := &config.Agent{} ca.Set(&config.Config{}) c := &Controller{ logger: logrus.WithField("component", "tide"), gc: gc, config: ca.Config, } prs, err := c.pickBatch(sp, &config.TideContextPolicy{}) if err != nil { t.Fatalf("Error from pickBatch: %v", err) } for _, testpr := range testprs { var found bool for _, pr := range prs { if int(pr.Number) == testpr.number { found = true break } } if found && !testpr.included { t.Errorf("PR %d should not be picked.", testpr.number) } else if !found && testpr.included { t.Errorf("PR %d should be picked.", testpr.number) } } } func TestTakeAction(t *testing.T) { // PRs 0-9 exist. All are mergable, and all are passing tests. testcases := []struct { name string batchPending bool successes []int pendings []int nones []int batchMerges []int presubmits map[int][]config.Presubmit merged int triggered int triggeredBatches int action Action }{ { name: "no prs to test, should do nothing", batchPending: true, successes: []int{}, pendings: []int{}, nones: []int{}, batchMerges: []int{}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 0, triggered: 0, action: Wait, }, { name: "pending batch, pending serial, nothing to do", batchPending: true, successes: []int{}, pendings: []int{1}, nones: []int{0, 2}, batchMerges: []int{}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 0, triggered: 0, action: Wait, }, { name: "pending batch, successful serial, nothing to do", batchPending: true, successes: []int{1}, pendings: []int{}, nones: []int{0, 2}, batchMerges: []int{}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 0, triggered: 0, action: Wait, }, { name: "pending batch, should trigger serial", batchPending: true, successes: []int{}, pendings: []int{}, nones: []int{0, 1, 2}, batchMerges: []int{}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 0, triggered: 1, action: Trigger, }, { name: "no pending batch, should trigger batch", batchPending: false, successes: []int{}, pendings: []int{0}, nones: []int{1, 2, 3}, batchMerges: []int{}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 0, triggered: 1, triggeredBatches: 1, action: TriggerBatch, }, { name: "one PR, should not trigger batch", batchPending: false, successes: []int{}, pendings: []int{}, nones: []int{0}, batchMerges: []int{}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 0, triggered: 1, action: Trigger, }, { name: "successful PR, should merge", batchPending: false, successes: []int{0}, pendings: []int{}, nones: []int{1, 2, 3}, batchMerges: []int{}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 1, triggered: 0, action: Merge, }, { name: "successful batch, should merge", batchPending: false, successes: []int{0, 1}, pendings: []int{2, 3}, nones: []int{4, 5}, batchMerges: []int{6, 7, 8}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 3, triggered: 0, action: MergeBatch, }, { name: "one PR that triggers RunIfChangedJob", batchPending: false, successes: []int{}, pendings: []int{}, nones: []int{100}, batchMerges: []int{}, presubmits: map[int][]config.Presubmit{ 100: { {Reporter: config.Reporter{Context: "foo"}}, {Reporter: config.Reporter{Context: "if-changed"}}, }, }, merged: 0, triggered: 2, action: Trigger, }, { name: "no presubmits, merge", batchPending: false, successes: []int{5, 4}, pendings: []int{}, nones: []int{}, batchMerges: []int{}, merged: 1, triggered: 0, action: Merge, }, { name: "no presubmits, wait", batchPending: false, successes: []int{}, pendings: []int{}, nones: []int{}, batchMerges: []int{}, merged: 0, triggered: 0, action: Wait, }, } for _, tc := range testcases { ca := &config.Agent{} cfg := &config.Config{} if err := cfg.SetPresubmits( map[string][]config.Presubmit{ "o/r": { { Reporter: config.Reporter{Context: "foo"}, Trigger: "/test all", RerunCommand: "/test all", AlwaysRun: true, }, { Reporter: config.Reporter{Context: "if-changed"}, Trigger: "/test if-changed", RerunCommand: "/test if-changed", RegexpChangeMatcher: config.RegexpChangeMatcher{ RunIfChanged: "CHANGED", }, }, }, }, ); err != nil { t.Fatalf("failed to set presubmits: %v", err) } ca.Set(cfg) if len(tc.presubmits) > 0 { for i := 0; i <= 8; i++ { tc.presubmits[i] = []config.Presubmit{{Reporter: config.Reporter{Context: "foo"}}} } } lg, gc, err := localgit.New() if err != nil { t.Fatalf("Error making local git: %v", err) } defer gc.Clean() defer lg.Clean() if err := lg.MakeFakeRepo("o", "r"); err != nil { t.Fatalf("Error making fake repo: %v", err) } if err := lg.AddCommit("o", "r", map[string][]byte{"foo": []byte("foo")}); err != nil { t.Fatalf("Adding initial commit: %v", err) } sp := subpool{ log: logrus.WithField("component", "tide"), presubmits: tc.presubmits, cc: &config.TideContextPolicy{}, org: "o", repo: "r", branch: "master", sha: "master", } genPulls := func(nums []int) []PullRequest { var prs []PullRequest for _, i := range nums { if err := lg.CheckoutNewBranch("o", "r", fmt.Sprintf("pr-%d", i)); err != nil { t.Fatalf("Error checking out new branch: %v", err) } if err := lg.AddCommit("o", "r", map[string][]byte{fmt.Sprintf("%d", i): []byte("WOW")}); err != nil { t.Fatalf("Error adding commit: %v", err) } if err := lg.Checkout("o", "r", "master"); err != nil { t.Fatalf("Error checking out master: %v", err) } oid := githubql.String(fmt.Sprintf("origin/pr-%d", i)) var pr PullRequest pr.Number = githubql.Int(i) pr.HeadRefOID = oid pr.Commits.Nodes = []struct { Commit Commit }{{Commit: Commit{OID: oid}}} sp.prs = append(sp.prs, pr) prs = append(prs, pr) } return prs } fakeProwJobClient := fake.NewSimpleClientset() var fgc fgc c := &Controller{ logger: logrus.WithField("controller", "tide"), gc: gc, config: ca.Config, ghc: &fgc, prowJobClient: fakeProwJobClient.ProwV1().ProwJobs("prowjobs"), } var batchPending []PullRequest if tc.batchPending { batchPending = []PullRequest{{}} } t.Logf("Test case: %s", tc.name) if act, _, err := c.takeAction(sp, batchPending, genPulls(tc.successes), genPulls(tc.pendings), genPulls(tc.nones), genPulls(tc.batchMerges)); err != nil { t.Errorf("Error in takeAction: %v", err) continue } else if act != tc.action { t.Errorf("Wrong action. Got %v, wanted %v.", act, tc.action) } numCreated := 0 var batchJobs []*prowapi.ProwJob for _, action := range fakeProwJobClient.Actions() { switch action := action.(type) { case clienttesting.CreateActionImpl: numCreated++ if prowJob, ok := action.Object.(*prowapi.ProwJob); ok && prowJob.Spec.Type == prowapi.BatchJob { batchJobs = append(batchJobs, prowJob) } } } if tc.triggered != numCreated { t.Errorf("Wrong number of jobs triggered. Got %d, expected %d.", numCreated, tc.triggered) } if tc.merged != fgc.merged { t.Errorf("Wrong number of merges. Got %d, expected %d.", fgc.merged, tc.merged) } // Ensure that the correct number of batch jobs were triggered if tc.triggeredBatches != len(batchJobs) { t.Errorf("Wrong number of batches triggered. Got %d, expected %d.", len(batchJobs), tc.triggeredBatches) } for _, job := range batchJobs { if len(job.Spec.Refs.Pulls) <= 1 { t.Error("Found a batch job that doesn't contain multiple pull refs!") } } } } func TestServeHTTP(t *testing.T) { pr1 := PullRequest{} pr1.Commits.Nodes = append(pr1.Commits.Nodes, struct{ Commit Commit }{}) pr1.Commits.Nodes[0].Commit.Status.Contexts = []Context{{ Context: githubql.String("coverage/coveralls"), Description: githubql.String("Coverage increased (+0.1%) to 27.599%"), }} c := &Controller{ pools: []Pool{ { MissingPRs: []PullRequest{pr1}, Action: Merge, }, }, History: history.New(100), } s := httptest.NewServer(c) defer s.Close() resp, err := http.Get(s.URL) if err != nil { t.Errorf("GET error: %v", err) } defer resp.Body.Close() var pools []Pool if err := json.NewDecoder(resp.Body).Decode(&pools); err != nil { t.Fatalf("JSON decoding error: %v", err) } if !reflect.DeepEqual(c.pools, pools) { t.Errorf("Received pools %v do not match original pools %v.", pools, c.pools) } } func TestHeadContexts(t *testing.T) { type commitContext struct { // one context per commit for testing context string sha string } win := "win" lose := "lose" headSHA := "head" testCases := []struct { name string commitContexts []commitContext expectAPICall bool }{ { name: "first commit is head", commitContexts: []commitContext{ {context: win, sha: headSHA}, {context: lose, sha: "other"}, {context: lose, sha: "sha"}, }, }, { name: "last commit is head", commitContexts: []commitContext{ {context: lose, sha: "shaaa"}, {context: lose, sha: "other"}, {context: win, sha: headSHA}, }, }, { name: "no commit is head", commitContexts: []commitContext{ {context: lose, sha: "shaaa"}, {context: lose, sha: "other"}, {context: lose, sha: "sha"}, }, expectAPICall: true, }, } for _, tc := range testCases { t.Logf("Running test case %q", tc.name) fgc := &fgc{combinedStatus: map[string]string{win: string(githubql.StatusStateSuccess)}} if tc.expectAPICall { fgc.expectedSHA = headSHA } pr := &PullRequest{HeadRefOID: githubql.String(headSHA)} for _, ctx := range tc.commitContexts { commit := Commit{ Status: struct{ Contexts []Context }{ Contexts: []Context{ { Context: githubql.String(ctx.context), }, }, }, OID: githubql.String(ctx.sha), } pr.Commits.Nodes = append(pr.Commits.Nodes, struct{ Commit Commit }{commit}) } contexts, err := headContexts(logrus.WithField("component", "tide"), fgc, pr) if err != nil { t.Fatalf("Unexpected error from headContexts: %v", err) } if len(contexts) != 1 || string(contexts[0].Context) != win { t.Errorf("Expected exactly 1 %q context, but got: %#v", win, contexts) } } } func testPR(org, repo, branch string, number int, mergeable githubql.MergeableState) PullRequest { pr := PullRequest{ Number: githubql.Int(number), Mergeable: mergeable, HeadRefOID: githubql.String("SHA"), } pr.Repository.Owner.Login = githubql.String(org) pr.Repository.Name = githubql.String(repo) pr.Repository.NameWithOwner = githubql.String(fmt.Sprintf("%s/%s", org, repo)) pr.BaseRef.Name = githubql.String(branch) pr.Commits.Nodes = append(pr.Commits.Nodes, struct{ Commit Commit }{ Commit{ Status: struct{ Contexts []Context }{ Contexts: []Context{ { Context: githubql.String("context"), State: githubql.StatusStateSuccess, }, }, }, OID: githubql.String("SHA"), }, }) return pr } func TestSync(t *testing.T) { mergeableA := testPR("org", "repo", "A", 5, githubql.MergeableStateMergeable) unmergeableA := testPR("org", "repo", "A", 6, githubql.MergeableStateConflicting) unmergeableB := testPR("org", "repo", "B", 7, githubql.MergeableStateConflicting) unknownA := testPR("org", "repo", "A", 8, githubql.MergeableStateUnknown) testcases := []struct { name string prs []PullRequest expectedPools []Pool }{ { name: "no PRs", prs: []PullRequest{}, expectedPools: []Pool{}, }, { name: "1 mergeable PR", prs: []PullRequest{mergeableA}, expectedPools: []Pool{{ Org: "org", Repo: "repo", Branch: "A", SuccessPRs: []PullRequest{mergeableA}, Action: Merge, Target: []PullRequest{mergeableA}, }}, }, { name: "1 unmergeable PR", prs: []PullRequest{unmergeableA}, expectedPools: []Pool{}, }, { name: "1 unknown PR", prs: []PullRequest{unknownA}, expectedPools: []Pool{{ Org: "org", Repo: "repo", Branch: "A", SuccessPRs: []PullRequest{unknownA}, Action: Merge, Target: []PullRequest{unknownA}, }}, }, { name: "1 mergeable, 1 unmergeable (different pools)", prs: []PullRequest{mergeableA, unmergeableB}, expectedPools: []Pool{{ Org: "org", Repo: "repo", Branch: "A", SuccessPRs: []PullRequest{mergeableA}, Action: Merge, Target: []PullRequest{mergeableA}, }}, }, { name: "1 mergeable, 1 unmergeable (same pool)", prs: []PullRequest{mergeableA, unmergeableA}, expectedPools: []Pool{{ Org: "org", Repo: "repo", Branch: "A", SuccessPRs: []PullRequest{mergeableA}, Action: Merge, Target: []PullRequest{mergeableA}, }}, }, { name: "1 mergeable PR (satisfies multiple queries)", prs: []PullRequest{mergeableA, mergeableA}, expectedPools: []Pool{{ Org: "org", Repo: "repo", Branch: "A", SuccessPRs: []PullRequest{mergeableA}, Action: Merge, Target: []PullRequest{mergeableA}, }}, }, } for _, tc := range testcases { t.Logf("Starting case %q...", tc.name) fgc := &fgc{prs: tc.prs} fakeProwJobClient := fake.NewSimpleClientset() ca := &config.Agent{} ca.Set(&config.Config{ ProwConfig: config.ProwConfig{ Tide: config.Tide{ Queries: []config.TideQuery{{}}, MaxGoroutines: 4, }, }, }) sc := &statusController{ logger: logrus.WithField("controller", "status-update"), ghc: fgc, config: ca.Config, newPoolPending: make(chan bool, 1), shutDown: make(chan bool), } go sc.run() defer sc.shutdown() c := &Controller{ config: ca.Config, ghc: fgc, prowJobClient: fakeProwJobClient.ProwV1().ProwJobs("prowjobs"), logger: logrus.WithField("controller", "sync"), sc: sc, changedFiles: &changedFilesAgent{ ghc: fgc, nextChangeCache: make(map[changeCacheKey][]string), }, History: history.New(100), } if err := c.Sync(); err != nil { t.Errorf("Unexpected error from 'Sync()': %v.", err) continue } if len(tc.expectedPools) != len(c.pools) { t.Errorf("Tide pools did not match expected. Got %#v, expected %#v.", c.pools, tc.expectedPools) continue } for _, expected := range tc.expectedPools { var match *Pool for i, actual := range c.pools { if expected.Org == actual.Org && expected.Repo == actual.Repo && expected.Branch == actual.Branch { match = &c.pools[i] } } if match == nil { t.Errorf("Failed to find expected pool %s/%s %s.", expected.Org, expected.Repo, expected.Branch) } else if !reflect.DeepEqual(*match, expected) { t.Errorf("Expected pool %#v does not match actual pool %#v.", expected, *match) } } } } func TestFilterSubpool(t *testing.T) { presubmits := map[int][]config.Presubmit{ 1: {{Reporter: config.Reporter{Context: "pj-a"}}}, 2: {{Reporter: config.Reporter{Context: "pj-a"}}, {Reporter: config.Reporter{Context: "pj-b"}}}, } trueVar := true cc := &config.TideContextPolicy{ RequiredContexts: []string{"pj-a", "pj-b", "other-a"}, OptionalContexts: []string{"tide", "pj-c"}, SkipUnknownContexts: &trueVar, } type pr struct { number int mergeable bool contexts []Context } tcs := []struct { name string prs []pr expectedPRs []int // Empty indicates no subpool should be returned. }{ { name: "one mergeable passing PR (omitting optional context)", prs: []pr{ { number: 1, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, }, }, }, expectedPRs: []int{1}, }, { name: "one unmergeable passing PR", prs: []pr{ { number: 1, mergeable: false, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, }, }, }, expectedPRs: []int{}, }, { name: "one mergeable PR pending non-PJ context (consider failing)", prs: []pr{ { number: 2, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStatePending, }, }, }, }, expectedPRs: []int{}, }, { name: "one mergeable PR pending PJ context (consider in pool)", prs: []pr{ { number: 2, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStatePending, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, }, }, }, expectedPRs: []int{2}, }, { name: "one mergeable PR failing PJ context (consider failing)", prs: []pr{ { number: 2, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateFailure, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, }, }, }, expectedPRs: []int{}, }, { name: "one mergeable PR missing PJ context (consider failing)", prs: []pr{ { number: 2, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, }, }, }, expectedPRs: []int{}, }, { name: "one mergeable PR failing unknown context (consider in pool)", prs: []pr{ { number: 2, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("unknown"), State: githubql.StatusStateFailure, }, }, }, }, expectedPRs: []int{2}, }, { name: "one PR failing non-PJ required context; one PR successful (should not prune pool)", prs: []pr{ { number: 1, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStateFailure, }, }, }, { number: 2, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("unknown"), State: githubql.StatusStateSuccess, }, }, }, }, expectedPRs: []int{2}, }, { name: "two successful PRs", prs: []pr{ { number: 1, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, }, }, { number: 2, mergeable: true, contexts: []Context{ { Context: githubql.String("pj-a"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("pj-b"), State: githubql.StatusStateSuccess, }, { Context: githubql.String("other-a"), State: githubql.StatusStateSuccess, }, }, }, }, expectedPRs: []int{1, 2}, }, } for _, tc := range tcs { t.Run(tc.name, func(t *testing.T) { sp := &subpool{ org: "org", repo: "repo", branch: "branch", presubmits: presubmits, cc: cc, log: logrus.WithFields(logrus.Fields{"org": "org", "repo": "repo", "branch": "branch"}), } for _, pull := range tc.prs { pr := PullRequest{ Number: githubql.Int(pull.number), } pr.Commits.Nodes = []struct{ Commit Commit }{ { Commit{ Status: struct{ Contexts []Context }{ Contexts: pull.contexts, }, }, }, } if !pull.mergeable { pr.Mergeable = githubql.MergeableStateConflicting } sp.prs = append(sp.prs, pr) } filtered := filterSubpool(nil, sp) if len(tc.expectedPRs) == 0 { if filtered != nil { t.Fatalf("Expected subpool to be pruned, but got: %v", filtered) } return } if filtered == nil { t.Fatalf("Expected subpool to have %d prs, but it was pruned.", len(tc.expectedPRs)) } if got := prNumbers(filtered.prs); !reflect.DeepEqual(got, tc.expectedPRs) { t.Errorf("Expected filtered pool to have PRs %v, but got %v.", tc.expectedPRs, got) } }) } } func TestIsPassing(t *testing.T) { yes := true no := false headSHA := "head" success := string(githubql.StatusStateSuccess) failure := string(githubql.StatusStateFailure) testCases := []struct { name string passing bool config config.TideContextPolicy combinedContexts map[string]string }{ { name: "empty policy - success (trust combined status)", passing: true, combinedContexts: map[string]string{"c1": success, "c2": success, statusContext: failure}, }, { name: "empty policy - failure because of failed context c4 (trust combined status)", passing: false, combinedContexts: map[string]string{"c1": success, "c2": success, "c3": failure, statusContext: failure}, }, { name: "passing (trust combined status)", passing: true, config: config.TideContextPolicy{ RequiredContexts: []string{"c1", "c2", "c3"}, SkipUnknownContexts: &no, }, combinedContexts: map[string]string{"c1": success, "c2": success, "c3": success, statusContext: failure}, }, { name: "failing because of missing required check c3", passing: false, config: config.TideContextPolicy{ RequiredContexts: []string{"c1", "c2", "c3"}, }, combinedContexts: map[string]string{"c1": success, "c2": success, statusContext: failure}, }, { name: "failing because of failed context c2", passing: false, combinedContexts: map[string]string{"c1": success, "c2": failure}, config: config.TideContextPolicy{ RequiredContexts: []string{"c1", "c2", "c3"}, OptionalContexts: []string{"c4"}, }, }, { name: "passing because of failed context c4 is optional", passing: true, combinedContexts: map[string]string{"c1": success, "c2": success, "c3": success, "c4": failure}, config: config.TideContextPolicy{ RequiredContexts: []string{"c1", "c2", "c3"}, OptionalContexts: []string{"c4"}, }, }, { name: "skipping unknown contexts - failing because of missing required context c3", passing: false, config: config.TideContextPolicy{ RequiredContexts: []string{"c1", "c2", "c3"}, SkipUnknownContexts: &yes, }, combinedContexts: map[string]string{"c1": success, "c2": success, statusContext: failure}, }, { name: "skipping unknown contexts - failing because c2 is failing", passing: false, combinedContexts: map[string]string{"c1": success, "c2": failure}, config: config.TideContextPolicy{ RequiredContexts: []string{"c1", "c2"}, OptionalContexts: []string{"c4"}, SkipUnknownContexts: &yes, }, }, { name: "skipping unknown contexts - passing because c4 is optional", passing: true, combinedContexts: map[string]string{"c1": success, "c2": success, "c3": success, "c4": failure}, config: config.TideContextPolicy{ RequiredContexts: []string{"c1", "c3"}, OptionalContexts: []string{"c4"}, SkipUnknownContexts: &yes, }, }, { name: "skipping unknown contexts - passing because c4 is optional and c5 is unknown", passing: true, combinedContexts: map[string]string{"c1": success, "c2": success, "c3": success, "c4": failure, "c5": failure}, config: config.TideContextPolicy{ RequiredContexts: []string{"c1", "c3"}, OptionalContexts: []string{"c4"}, SkipUnknownContexts: &yes, }, }, } for _, tc := range testCases { ghc := &fgc{ combinedStatus: tc.combinedContexts, expectedSHA: headSHA} log := logrus.WithField("component", "tide") _, err := log.String() if err != nil { t.Errorf("Failed to get log output before testing: %v", err) t.FailNow() } pr := PullRequest{HeadRefOID: githubql.String(headSHA)} passing := isPassingTests(log, ghc, pr, &tc.config) if passing != tc.passing { t.Errorf("%s: Expected %t got %t", tc.name, tc.passing, passing) } } } func TestPresubmitsByPull(t *testing.T) { samplePR := PullRequest{ Number: githubql.Int(100), HeadRefOID: githubql.String("sha"), } testcases := []struct { name string initialChangeCache map[changeCacheKey][]string presubmits []config.Presubmit expectedPresubmits map[int][]config.Presubmit expectedChangeCache map[changeCacheKey][]string }{ { name: "no matching presubmits", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "always"}, RegexpChangeMatcher: config.RegexpChangeMatcher{ RunIfChanged: "foo", }, }, { Reporter: config.Reporter{Context: "never"}, }, }, expectedChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"CHANGED"}}, expectedPresubmits: map[int][]config.Presubmit{}, }, { name: "no presubmits", presubmits: []config.Presubmit{}, expectedPresubmits: map[int][]config.Presubmit{}, }, { name: "no matching presubmits (check cache eviction)", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "never"}, }, }, initialChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"FILE"}}, expectedPresubmits: map[int][]config.Presubmit{}, }, { name: "no matching presubmits (check cache retention)", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "always"}, RegexpChangeMatcher: config.RegexpChangeMatcher{ RunIfChanged: "foo", }, }, { Reporter: config.Reporter{Context: "never"}, }, }, initialChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"FILE"}}, expectedChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"FILE"}}, expectedPresubmits: map[int][]config.Presubmit{}, }, { name: "always_run", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }, { Reporter: config.Reporter{Context: "never"}, }, }, expectedPresubmits: map[int][]config.Presubmit{100: {{ Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }}}, }, { name: "runs against branch", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "presubmit"}, AlwaysRun: true, Brancher: config.Brancher{ Branches: []string{"master", "dev"}, }, }, { Reporter: config.Reporter{Context: "never"}, }, }, expectedPresubmits: map[int][]config.Presubmit{100: {{ Reporter: config.Reporter{Context: "presubmit"}, AlwaysRun: true, Brancher: config.Brancher{ Branches: []string{"master", "dev"}, }, }}}, }, { name: "doesn't run against branch", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "presubmit"}, AlwaysRun: true, Brancher: config.Brancher{ Branches: []string{"release", "dev"}, }, }, { Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }, { Reporter: config.Reporter{Context: "never"}, }, }, expectedPresubmits: map[int][]config.Presubmit{100: {{ Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }}}, }, { name: "run_if_changed (uncached)", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "presubmit"}, RegexpChangeMatcher: config.RegexpChangeMatcher{ RunIfChanged: "^CHANGE.$", }, }, { Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }, { Reporter: config.Reporter{Context: "never"}, }, }, expectedPresubmits: map[int][]config.Presubmit{100: {{ Reporter: config.Reporter{Context: "presubmit"}, RegexpChangeMatcher: config.RegexpChangeMatcher{ RunIfChanged: "^CHANGE.$", }, }, { Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }}}, expectedChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"CHANGED"}}, }, { name: "run_if_changed (cached)", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "presubmit"}, RegexpChangeMatcher: config.RegexpChangeMatcher{ RunIfChanged: "^FIL.$", }, }, { Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }, { Reporter: config.Reporter{Context: "never"}, }, }, initialChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"FILE"}}, expectedPresubmits: map[int][]config.Presubmit{100: {{ Reporter: config.Reporter{Context: "presubmit"}, RegexpChangeMatcher: config.RegexpChangeMatcher{ RunIfChanged: "^FIL.$", }, }, { Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }}}, expectedChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"FILE"}}, }, { name: "run_if_changed (cached) (skippable)", presubmits: []config.Presubmit{ { Reporter: config.Reporter{Context: "presubmit"}, RegexpChangeMatcher: config.RegexpChangeMatcher{ RunIfChanged: "^CHANGE.$", }, }, { Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }, { Reporter: config.Reporter{Context: "never"}, }, }, initialChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"FILE"}}, expectedPresubmits: map[int][]config.Presubmit{100: {{ Reporter: config.Reporter{Context: "always"}, AlwaysRun: true, }}}, expectedChangeCache: map[changeCacheKey][]string{{number: 100, sha: "sha"}: {"FILE"}}, }, } for _, tc := range testcases { t.Logf("Starting test case: %q", tc.name) if tc.initialChangeCache == nil { tc.initialChangeCache = map[changeCacheKey][]string{} } if tc.expectedChangeCache == nil { tc.expectedChangeCache = map[changeCacheKey][]string{} } cfg := &config.Config{} cfg.SetPresubmits(map[string][]config.Presubmit{ "/": tc.presubmits, "foo/bar": {{Reporter: config.Reporter{Context: "wrong-repo"}, AlwaysRun: true}}, }) cfgAgent := &config.Agent{} cfgAgent.Set(cfg) sp := &subpool{ branch: "master", prs: []PullRequest{samplePR}, } c := &Controller{ config: cfgAgent.Config, ghc: &fgc{}, changedFiles: &changedFilesAgent{ ghc: &fgc{}, changeCache: tc.initialChangeCache, nextChangeCache: make(map[changeCacheKey][]string), }, } presubmits, err := c.presubmitsByPull(sp) if err != nil { t.Fatalf("unexpected error from presubmitsByPull: %v", err) } c.changedFiles.prune() // for equality we need to clear the compiled regexes for _, jobs := range presubmits { config.ClearCompiledRegexes(jobs) } if !equality.Semantic.DeepEqual(presubmits, tc.expectedPresubmits) { t.Errorf("got incorrect presubmit mapping: %v\n", diff.ObjectReflectDiff(tc.expectedPresubmits, presubmits)) } if got := c.changedFiles.changeCache; !reflect.DeepEqual(got, tc.expectedChangeCache) { t.Errorf("got incorrect file change cache: %v", diff.ObjectReflectDiff(tc.expectedChangeCache, got)) } } }
apache-2.0
sergecodd/FireFox-OS
B2G/gecko/browser/devtools/debugger/test/browser_dbg_stack-01.js
1374
/* vim:set ts=2 sw=2 sts=2 et: */ /* * Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ var gPane = null; var gTab = null; var gDebuggee = null; var gDebugger = null; function test() { debug_tab_pane(STACK_URL, function(aTab, aDebuggee, aPane) { gTab = aTab; gDebuggee = aDebuggee; gPane = aPane; gDebugger = gPane.contentWindow; testSimpleCall(); }); } function testSimpleCall() { gDebugger.DebuggerController.activeThread.addOneTimeListener("framesadded", function() { Services.tm.currentThread.dispatch({ run: function() { let frames = gDebugger.DebuggerView.StackFrames._frames; let childNodes = frames.childNodes; is(gDebugger.DebuggerController.activeThread.state, "paused", "Should only be getting stack frames while paused."); is(frames.querySelectorAll(".dbg-stackframe").length, 1, "Should have only one frame."); is(childNodes.length, frames.querySelectorAll(".dbg-stackframe").length, "All children should be frames."); gDebugger.DebuggerController.activeThread.resume(function() { closeDebuggerAndFinish(); }); }}, 0); }); gDebuggee.simpleCall(); } registerCleanupFunction(function() { removeTab(gTab); gPane = null; gTab = null; gDebuggee = null; gDebugger = null; });
apache-2.0
AnqaFalak/JapKatsuyou
docs/jpconj/search/variables_3.js
125
var searchData= [ ['jap',['jap',['../struct_tatoeba_1_1_exp.html#a6aedde568a43468dcd805cbb54b116d5',1,'Tatoeba::Exp']]] ];
apache-2.0
porcelli-forks/uberfire-extensions
uberfire-metadata/uberfire-metadata-commons-io/src/test/java/org/uberfire/ext/metadata/io/IOServiceIndexedGitImplTest.java
7399
/* * Copyright 2015 JBoss, by 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. */ package org.uberfire.ext.metadata.io; import java.io.IOException; import java.util.Collections; import java.util.Date; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopScoreDocCollector; import org.junit.Test; import org.uberfire.ext.metadata.backend.lucene.index.LuceneIndex; import org.uberfire.ext.metadata.engine.Index; import org.uberfire.ext.metadata.model.KObject; import org.uberfire.java.nio.file.OpenOption; import org.uberfire.java.nio.file.Path; import org.uberfire.java.nio.file.attribute.FileAttribute; import static org.junit.Assert.*; import static org.uberfire.ext.metadata.backend.lucene.util.KObjectUtil.toKObject; import static org.uberfire.ext.metadata.io.KObjectUtil.*; public class IOServiceIndexedGitImplTest extends BaseIndexTest { protected final Date dateValue = new Date(); @Override protected String[] getRepositoryNames() { return new String[]{ this.getClass().getSimpleName() }; } @Test public void testIndexedFile() throws IOException, InterruptedException { final Path path1 = getBasePath( this.getClass().getSimpleName() ).resolve( "myIndexedFile.txt" ); ioService().write( path1, "ooooo!", Collections.<OpenOption>emptySet(), new FileAttribute<Object>() { @Override public String name() { return "custom"; } @Override public Object value() { return dateValue; } }, new FileAttribute<String>() { @Override public String name() { return "int.hello"; } @Override public String value() { return "hello some world jhere"; } }, new FileAttribute<Integer>() { @Override public String name() { return "int"; } @Override public Integer value() { return 10; } } ); final Path path2 = getBasePath( this.getClass().getSimpleName() ).resolve( "myOtherIndexedFile.txt" ); ioService().write( path2, "ooooo!", Collections.<OpenOption>emptySet(), new FileAttribute<String>() { @Override public String name() { return "int.hello"; } @Override public String value() { return "jhere"; } } ); Thread.sleep( 5000 ); //wait for events to be consumed from jgit -> (notify changes -> watcher -> index) -> lucene index assertNotNull( config.getMetaModelStore().getMetaObject( Path.class.getName() ) ); assertNotNull( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "int" ) ); assertNotNull( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "int.hello" ) ); assertNotNull( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "custom" ) ); assertNotNull( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "int" ) ); assertNotNull( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "int.hello" ) ); assertNotNull( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "custom" ) ); assertEquals( 1, config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "int" ).getTypes().size() ); assertEquals( 1, config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "int.hello" ).getTypes().size() ); assertEquals( 1, config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "custom" ).getTypes().size() ); assertTrue( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "int" ).getTypes().contains( Integer.class ) ); assertTrue( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "int.hello" ).getTypes().contains( String.class ) ); assertTrue( config.getMetaModelStore().getMetaObject( Path.class.getName() ).getProperty( "custom" ).getTypes().contains( Date.class ) ); final Index index = config.getIndexManager().get( toKCluster( path2.getFileSystem() ) ); final IndexSearcher searcher = ( (LuceneIndex) index ).nrtSearcher(); { final TopScoreDocCollector collector = TopScoreDocCollector.create( 10, true ); searcher.search( new TermQuery( new Term( "int.hello", "world" ) ), collector ); final ScoreDoc[] hits = collector.topDocs().scoreDocs; listHitPaths( searcher, hits ); assertEquals( 1, hits.length ); } { final TopScoreDocCollector collector = TopScoreDocCollector.create( 10, true ); searcher.search( new TermQuery( new Term( "int.hello", "jhere" ) ), collector ); final ScoreDoc[] hits = collector.topDocs().scoreDocs; listHitPaths( searcher, hits ); assertEquals( 2, hits.length ); } { final TopScoreDocCollector collector = TopScoreDocCollector.create( 10, true ); searcher.search( new MatchAllDocsQuery(), collector ); final ScoreDoc[] hits = collector.topDocs().scoreDocs; listHitPaths( searcher, hits ); assertEquals( 2, hits.length ); } ( (LuceneIndex) index ).nrtRelease( searcher ); } }
apache-2.0
4Giedrius/boxbilling
src/bb-library/Registrar/Exception.php
53
<?php class Registrar_Exception extends Exception {}
apache-2.0
blstream/StudyBox_FE
src/app/decks/decks.route.js
991
(function() { 'use strict'; angular .module('decks') .config(routerConfig); /** @ngInject */ function routerConfig($stateProvider, $urlRouterProvider) { $stateProvider .state('decks', { parent: 'navbar', url: '/decks', templateUrl: 'app/decks/decks.html', controller: 'DecksController', controllerAs: 'decks', params: { access: 'private' } }) .state('decks-search', { parent: 'navbar', url: '/decks-search', templateUrl: 'app/decks/decks.html', controller: 'DecksController', controllerAs: 'decks', params: { access: 'public' }, onExit: tryClosingSearchBar }); $urlRouterProvider.otherwise('/'); function tryClosingSearchBar(NavbarService, $timeout) { var ctrl = NavbarService.controller; if(ctrl && ctrl.inputVisible) { $timeout(function(){ ctrl.inputVisible = false; }); } } } })();
apache-2.0
solimant/druid
server/src/test/java/io/druid/server/coordinator/DruidClusterTest.java
6810
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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. */ package io.druid.server.coordinator; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.MinMaxPriorityQueue; import com.google.common.collect.Ordering; import io.druid.client.ImmutableDruidDataSource; import io.druid.client.ImmutableDruidServer; import io.druid.server.coordination.DruidServerMetadata; import io.druid.server.coordination.ServerType; import io.druid.timeline.DataSegment; import io.druid.timeline.partition.NoneShardSpec; import org.joda.time.Interval; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class DruidClusterTest { private static final List<DataSegment> segments = ImmutableList.of( new DataSegment( "test", new Interval("2015-04-12/2015-04-13"), "1", ImmutableMap.of("containerName", "container1", "blobPath", "blobPath1"), null, null, NoneShardSpec.instance(), 0, 1 ), new DataSegment( "test", new Interval("2015-04-12/2015-04-13"), "1", ImmutableMap.of("containerName", "container2", "blobPath", "blobPath2"), null, null, NoneShardSpec.instance(), 0, 1 ) ); private static final Map<String, ImmutableDruidDataSource> dataSources = ImmutableMap.of( "src1", new ImmutableDruidDataSource( "src1", ImmutableMap.of(), ImmutableMap.of(), ImmutableSet.of() ), "src2", new ImmutableDruidDataSource( "src2", ImmutableMap.of(), ImmutableMap.of(), ImmutableSet.of() ) ); private static final ServerHolder newRealtime = new ServerHolder( new ImmutableDruidServer( new DruidServerMetadata("name1", "host2", null, 100L, ServerType.REALTIME, "tier1", 0), 0L, ImmutableMap.of( "src1", dataSources.get("src1") ), ImmutableMap.of( "segment1", segments.get(0) ) ), new LoadQueuePeonTester() ); private static final ServerHolder newHistorical = new ServerHolder( new ImmutableDruidServer( new DruidServerMetadata("name1", "host2", null, 100L, ServerType.HISTORICAL, "tier1", 0), 0L, ImmutableMap.of( "src1", dataSources.get("src1") ), ImmutableMap.of( "segment1", segments.get(0) ) ), new LoadQueuePeonTester() ); private DruidCluster cluster; @Before public void setup() { cluster = new DruidCluster( ImmutableSet.of( new ServerHolder( new ImmutableDruidServer( new DruidServerMetadata("name1", "host1", null, 100L, ServerType.REALTIME, "tier1", 0), 0L, ImmutableMap.of( "src1", dataSources.get("src1") ), ImmutableMap.of( "segment1", segments.get(0) ) ), new LoadQueuePeonTester() ) ), ImmutableMap.of( "tier1", MinMaxPriorityQueue.orderedBy(Ordering.natural().reverse()).create( ImmutableList.of( new ServerHolder( new ImmutableDruidServer( new DruidServerMetadata("name1", "host1", null, 100L, ServerType.HISTORICAL, "tier1", 0), 0L, ImmutableMap.of( "src1", dataSources.get("src1") ), ImmutableMap.of( "segment1", segments.get(0) ) ), new LoadQueuePeonTester() ) ) ) ) ); } @Test public void testAdd() { Assert.assertEquals(1, cluster.getHistoricals().values().stream().mapToInt(Collection::size).sum()); Assert.assertEquals(1, cluster.getRealtimes().size()); cluster.add(newRealtime); Assert.assertEquals(1, cluster.getHistoricals().values().stream().mapToInt(Collection::size).sum()); Assert.assertEquals(2, cluster.getRealtimes().size()); cluster.add(newHistorical); Assert.assertEquals(2, cluster.getHistoricals().values().stream().mapToInt(Collection::size).sum()); Assert.assertEquals(2, cluster.getRealtimes().size()); } @Test public void testGetAllServers() { cluster.add(newRealtime); cluster.add(newHistorical); final Set<ServerHolder> expectedRealtimes = cluster.getRealtimes(); final Map<String, MinMaxPriorityQueue<ServerHolder>> expectedHistoricals = cluster.getHistoricals(); final Collection<ServerHolder> allServers = cluster.getAllServers(); Assert.assertEquals(4, allServers.size()); Assert.assertTrue(allServers.containsAll(cluster.getRealtimes())); Assert.assertTrue( allServers.containsAll( cluster.getHistoricals().values().stream().flatMap(Collection::stream).collect(Collectors.toList()) ) ); Assert.assertEquals(expectedHistoricals, cluster.getHistoricals()); Assert.assertEquals(expectedRealtimes, cluster.getRealtimes()); } @Test public void testIsEmpty() { final DruidCluster emptyCluster = new DruidCluster(); Assert.assertFalse(cluster.isEmpty()); Assert.assertTrue(emptyCluster.isEmpty()); } }
apache-2.0
cdapio/tephra
tephra-core/src/test/java/co/cask/tephra/TransactionContextTest.java
23040
/* * Copyright © 2012-2014 Cask Data, 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. */ package co.cask.tephra; import co.cask.tephra.inmemory.InMemoryTxSystemClient; import co.cask.tephra.runtime.ConfigModule; import co.cask.tephra.runtime.DiscoveryModules; import co.cask.tephra.runtime.TransactionModules; import co.cask.tephra.snapshot.SnapshotCodecV4; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.google.inject.util.Modules; import org.apache.hadoop.conf.Configuration; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.util.Collection; import java.util.List; /** * Tests the transaction executor. */ public class TransactionContextTest { private static DummyTxClient txClient; @ClassRule public static TemporaryFolder tmpFolder = new TemporaryFolder(); @BeforeClass public static void setup() throws IOException { final Configuration conf = new Configuration(); conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, SnapshotCodecV4.class.getName()); conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath()); Injector injector = Guice.createInjector( new ConfigModule(conf), new DiscoveryModules().getInMemoryModules(), Modules.override( new TransactionModules().getInMemoryModules()).with(new AbstractModule() { @Override protected void configure() { TransactionManager txManager = new TransactionManager(conf); txManager.startAndWait(); bind(TransactionManager.class).toInstance(txManager); bind(TransactionSystemClient.class).to(DummyTxClient.class).in(Singleton.class); } })); txClient = (DummyTxClient) injector.getInstance(TransactionSystemClient.class); } final DummyTxAware ds1 = new DummyTxAware(), ds2 = new DummyTxAware(); static final byte[] A = { 'a' }; static final byte[] B = { 'b' }; private static TransactionContext newTransactionContext(TransactionAware... txAwares) { return new TransactionContext(txClient, txAwares); } @Before public void resetTxAwares() { ds1.reset(); ds2.reset(); } @Test public void testSuccessful() throws TransactionFailureException, InterruptedException { TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction context.finish(); // verify both are committed and post-committed Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertTrue(ds2.committed); Assert.assertTrue(ds1.postCommitted); Assert.assertTrue(ds2.postCommitted); Assert.assertFalse(ds1.rolledBack); Assert.assertFalse(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Committed); } @Test public void testPostCommitFailure() throws TransactionFailureException, InterruptedException { ds1.failPostCommitTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction should fail but without rollback as the failure happens post-commit try { context.finish(); Assert.fail("post commit failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertEquals("post failure", e.getCause().getMessage()); } // verify both are committed and post-committed Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertTrue(ds2.committed); Assert.assertTrue(ds1.postCommitted); Assert.assertTrue(ds2.postCommitted); Assert.assertFalse(ds1.rolledBack); Assert.assertFalse(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Committed); } @Test public void testPersistFailure() throws TransactionFailureException, InterruptedException { ds1.failCommitTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction should fail and cause rollback try { context.finish(); Assert.fail("Persist should have failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertEquals("persist failure", e.getCause().getMessage()); } // verify both are rolled back and tx is aborted Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertFalse(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertTrue(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); } @Test public void testPersistFalse() throws TransactionFailureException, InterruptedException { ds1.failCommitTxOnce = InduceFailure.ReturnFalse; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction should fail and cause rollback try { context.finish(); Assert.fail("Persist should have failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertNull(e.getCause()); // in this case, the ds simply returned false } // verify both are rolled back and tx is aborted Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertFalse(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertTrue(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); } @Test public void testPersistAndRollbackFailure() throws TransactionFailureException, InterruptedException { ds1.failCommitTxOnce = InduceFailure.ThrowException; ds1.failRollbackTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction should fail and cause rollback try { context.finish(); Assert.fail("Persist should have failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertEquals("persist failure", e.getCause().getMessage()); } // verify both are rolled back and tx is invalidated Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertFalse(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertTrue(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Invalidated); } @Test public void testPersistAndRollbackFalse() throws TransactionFailureException, InterruptedException { ds1.failCommitTxOnce = InduceFailure.ReturnFalse; ds1.failRollbackTxOnce = InduceFailure.ReturnFalse; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction should fail and cause rollback try { context.finish(); Assert.fail("Persist should have failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertNull(e.getCause()); // in this case, the ds simply returned false } // verify both are rolled back and tx is invalidated Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertFalse(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertTrue(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Invalidated); } @Test public void testCommitFalse() throws TransactionFailureException, InterruptedException { txClient.failCommits = 1; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction should fail and cause rollback try { context.finish(); Assert.fail("commit failed - exception should be thrown"); } catch (TransactionConflictException e) { Assert.assertNull(e.getCause()); } // verify both are rolled back and tx is aborted Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertTrue(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertTrue(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); } @Test public void testCanCommitFalse() throws TransactionFailureException, InterruptedException { txClient.failCanCommitOnce = true; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction should fail and cause rollback try { context.finish(); Assert.fail("commit failed - exception should be thrown"); } catch (TransactionConflictException e) { Assert.assertNull(e.getCause()); } // verify both are rolled back and tx is aborted Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertFalse(ds1.committed); Assert.assertFalse(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertTrue(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); } @Test public void testChangesAndRollbackFailure() throws TransactionFailureException, InterruptedException { ds1.failChangesTxOnce = InduceFailure.ThrowException; ds1.failRollbackTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction context.start(); // add a change to ds1 and ds2 ds1.addChange(A); ds2.addChange(B); // commit transaction should fail and cause rollback try { context.finish(); Assert.fail("get changes failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertEquals("changes failure", e.getCause().getMessage()); } // verify both are rolled back and tx is invalidated Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertFalse(ds2.checked); Assert.assertFalse(ds1.committed); Assert.assertFalse(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertTrue(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Invalidated); } @Test public void testStartAndRollbackFailure() throws TransactionFailureException, InterruptedException { ds1.failStartTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(ds1, ds2); // start transaction try { context.start(); Assert.fail("start failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertEquals("start failure", e.getCause().getMessage()); } // verify both are not rolled back and tx is aborted Assert.assertTrue(ds1.started); Assert.assertFalse(ds2.started); Assert.assertFalse(ds1.checked); Assert.assertFalse(ds2.checked); Assert.assertFalse(ds1.committed); Assert.assertFalse(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertFalse(ds1.rolledBack); Assert.assertFalse(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); } @Test public void testAddThenSuccess() throws TransactionFailureException, InterruptedException { TransactionContext context = newTransactionContext(ds1); // start transaction context.start(); // add a change to ds1 ds1.addChange(A); // add ds2 to the tx context.addTransactionAware(ds2); // add a change to ds2 ds2.addChange(B); // commit transaction context.finish(); // verify both are committed and post-committed Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertTrue(ds2.committed); Assert.assertTrue(ds1.postCommitted); Assert.assertTrue(ds2.postCommitted); Assert.assertFalse(ds1.rolledBack); Assert.assertFalse(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Committed); } @Test public void testAddThenFailure() throws TransactionFailureException, InterruptedException { ds2.failCommitTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(ds1); // start transaction context.start(); // add a change to ds1 ds1.addChange(A); // add ds2 to the tx context.addTransactionAware(ds2); // add a change to ds2 ds2.addChange(B); // commit transaction should fail and cause rollback try { context.finish(); Assert.fail("Persist should have failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertEquals("persist failure", e.getCause().getMessage()); } // verify both are rolled back and tx is aborted Assert.assertTrue(ds1.started); Assert.assertTrue(ds2.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds2.checked); Assert.assertTrue(ds1.committed); Assert.assertTrue(ds2.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertFalse(ds2.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertTrue(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); } @Test public void testAddThenRemoveSuccess() throws TransactionFailureException { TransactionContext context = newTransactionContext(); context.start(); Assert.assertTrue(context.addTransactionAware(ds1)); ds1.addChange(A); try { context.removeTransactionAware(ds1); Assert.fail("Removal of TransactionAware should fails when there is active transaction."); } catch (IllegalStateException e) { // Expected } context.finish(); Assert.assertTrue(context.removeTransactionAware(ds1)); // Removing a TransactionAware not added before should returns false Assert.assertFalse(context.removeTransactionAware(ds2)); // Verify ds1 is committed and post-committed Assert.assertTrue(ds1.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds1.committed); Assert.assertTrue(ds1.postCommitted); Assert.assertFalse(ds1.rolledBack); // Verify nothing happen to ds2 Assert.assertFalse(ds2.started); Assert.assertFalse(ds2.checked); Assert.assertFalse(ds2.committed); Assert.assertFalse(ds2.postCommitted); Assert.assertFalse(ds2.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Committed); } @Test public void testAndThenRemoveOnFailure() throws TransactionFailureException { ds1.failCommitTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(); context.start(); Assert.assertTrue(context.addTransactionAware(ds1)); ds1.addChange(A); try { context.finish(); Assert.fail("Persist should have failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertEquals("persist failure", e.getCause().getMessage()); } Assert.assertTrue(context.removeTransactionAware(ds1)); // Verify ds1 is rolled back Assert.assertTrue(ds1.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds1.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); } enum InduceFailure { NoFailure, ReturnFalse, ThrowException } static class DummyTxAware implements TransactionAware { Transaction tx; boolean started = false; boolean committed = false; boolean checked = false; boolean rolledBack = false; boolean postCommitted = false; List<byte[]> changes = Lists.newArrayList(); InduceFailure failStartTxOnce = InduceFailure.NoFailure; InduceFailure failChangesTxOnce = InduceFailure.NoFailure; InduceFailure failCommitTxOnce = InduceFailure.NoFailure; InduceFailure failPostCommitTxOnce = InduceFailure.NoFailure; InduceFailure failRollbackTxOnce = InduceFailure.NoFailure; void addChange(byte[] key) { changes.add(key); } void reset() { tx = null; started = false; checked = false; committed = false; rolledBack = false; postCommitted = false; changes.clear(); } @Override public void startTx(Transaction tx) { reset(); started = true; this.tx = tx; if (failStartTxOnce == InduceFailure.ThrowException) { failStartTxOnce = InduceFailure.NoFailure; throw new RuntimeException("start failure"); } } @Override public void updateTx(Transaction tx) { this.tx = tx; } @Override public Collection<byte[]> getTxChanges() { checked = true; if (failChangesTxOnce == InduceFailure.ThrowException) { failChangesTxOnce = InduceFailure.NoFailure; throw new RuntimeException("changes failure"); } return ImmutableList.copyOf(changes); } @Override public boolean commitTx() throws Exception { committed = true; if (failCommitTxOnce == InduceFailure.ThrowException) { failCommitTxOnce = InduceFailure.NoFailure; throw new RuntimeException("persist failure"); } if (failCommitTxOnce == InduceFailure.ReturnFalse) { failCommitTxOnce = InduceFailure.NoFailure; return false; } return true; } @Override public void postTxCommit() { postCommitted = true; if (failPostCommitTxOnce == InduceFailure.ThrowException) { failPostCommitTxOnce = InduceFailure.NoFailure; throw new RuntimeException("post failure"); } } @Override public boolean rollbackTx() throws Exception { rolledBack = true; if (failRollbackTxOnce == InduceFailure.ThrowException) { failRollbackTxOnce = InduceFailure.NoFailure; throw new RuntimeException("rollback failure"); } if (failRollbackTxOnce == InduceFailure.ReturnFalse) { failRollbackTxOnce = InduceFailure.NoFailure; return false; } return true; } @Override public String getTransactionAwareName() { return "dummy"; } } static class DummyTxClient extends InMemoryTxSystemClient { boolean failCanCommitOnce = false; int failCommits = 0; enum CommitState { Started, Committed, Aborted, Invalidated } CommitState state = CommitState.Started; @Inject DummyTxClient(TransactionManager txmgr) { super(txmgr); } @Override public boolean canCommit(Transaction tx, Collection<byte[]> changeIds) throws TransactionNotInProgressException { if (failCanCommitOnce) { failCanCommitOnce = false; return false; } else { return super.canCommit(tx, changeIds); } } @Override public boolean commit(Transaction tx) throws TransactionNotInProgressException { if (failCommits-- > 0) { return false; } else { state = CommitState.Committed; return super.commit(tx); } } @Override public Transaction startLong() { state = CommitState.Started; return super.startLong(); } @Override public Transaction startShort() { state = CommitState.Started; return super.startShort(); } @Override public Transaction startShort(int timeout) { state = CommitState.Started; return super.startShort(timeout); } @Override public void abort(Transaction tx) { state = CommitState.Aborted; super.abort(tx); } @Override public boolean invalidate(long tx) { state = CommitState.Invalidated; return super.invalidate(tx); } } }
apache-2.0
xingwu1/azure-sdk-for-node
lib/services/serviceFabric/lib/operations/index.js
880
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /* jshint latedef:false */ /* jshint forin:false */ /* jshint noempty:false */ 'use strict'; exports.MeshSecret = require('./meshSecret'); exports.MeshSecretValue = require('./meshSecretValue'); exports.MeshVolume = require('./meshVolume'); exports.MeshNetwork = require('./meshNetwork'); exports.MeshApplication = require('./meshApplication'); exports.MeshService = require('./meshService'); exports.MeshCodePackage = require('./meshCodePackage'); exports.MeshServiceReplica = require('./meshServiceReplica'); exports.MeshGateway = require('./meshGateway');
apache-2.0
hanm/zookeeper
zookeeper-server/src/test/java/org/apache/zookeeper/server/embedded/ZookeeperServerClusterMutualAuthTest.java
6304
/** * 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. */ package org.apache.zookeeper.server.embedded; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties; import javax.security.auth.login.Configuration; import org.apache.zookeeper.PortAssignment; import org.apache.zookeeper.test.ClientBase; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; /** * Test Quorum Mutual Auth with ZooKeeperEmbedded. */ public class ZookeeperServerClusterMutualAuthTest { @BeforeAll public static void setUpEnvironment() { System.setProperty("java.security.auth.login.config", new File("src/test/resources/embedded/test_jaas_server_auth.conf") .getAbsolutePath()); Configuration.getConfiguration().refresh(); System.setProperty("zookeeper.admin.enableServer", "false"); System.setProperty("zookeeper.4lw.commands.whitelist", "*"); } @AfterAll public static void cleanUpEnvironment() throws InterruptedException, IOException { System.clearProperty("zookeeper.admin.enableServer"); System.clearProperty("zookeeper.4lw.commands.whitelist"); System.clearProperty("java.security.auth.login.config"); Configuration.getConfiguration().refresh(); } @TempDir public Path baseDir; @Test public void testStart() throws Exception { Path baseDir1 = baseDir.resolve("server1"); Path baseDir2 = baseDir.resolve("server2"); Path baseDir3 = baseDir.resolve("server3"); int clientport1 = PortAssignment.unique(); int clientport2 = PortAssignment.unique(); int clientport3 = PortAssignment.unique(); int port4 = PortAssignment.unique(); int port5 = PortAssignment.unique(); int port6 = PortAssignment.unique(); int port7 = PortAssignment.unique(); int port8 = PortAssignment.unique(); int port9 = PortAssignment.unique(); Properties config = new Properties(); config.put("host", "localhost"); config.put("ticktime", "10"); config.put("initLimit", "4000"); config.put("syncLimit", "5"); config.put("server.1", "localhost:" + port4 + ":" + port7); config.put("server.2", "localhost:" + port5 + ":" + port8); config.put("server.3", "localhost:" + port6 + ":" + port9); config.put("quorum.auth.enableSasl", "true"); config.put("quorum.auth.learnerRequireSasl", "true"); config.put("quorum.auth.serverRequireSasl", "true"); config.put("quorum.auth.learner.loginContext", "QuorumLearner"); config.put("quorum.auth.server.loginContext", "QuorumServer"); config.put("quorum.auth.kerberos.servicePrincipal", "servicename/_HOST"); config.put("quorum.cnxn.threads.size", "20"); final Properties configZookeeper1 = new Properties(); configZookeeper1.putAll(config); configZookeeper1.put("clientPort", clientport1 + ""); final Properties configZookeeper2 = new Properties(); configZookeeper2.putAll(config); configZookeeper2.put("clientPort", clientport2 + ""); final Properties configZookeeper3 = new Properties(); configZookeeper3.putAll(config); configZookeeper3.put("clientPort", clientport3 + ""); Files.createDirectories(baseDir1.resolve("data")); Files.write(baseDir1.resolve("data").resolve("myid"), "1".getBytes("ASCII")); Files.createDirectories(baseDir2.resolve("data")); Files.write(baseDir2.resolve("data").resolve("myid"), "2".getBytes("ASCII")); Files.createDirectories(baseDir3.resolve("data")); Files.write(baseDir3.resolve("data").resolve("myid"), "3".getBytes("ASCII")); try (ZooKeeperServerEmbedded zkServer1 = ZooKeeperServerEmbedded.builder().configuration(configZookeeper1).baseDir(baseDir1).exitHandler(ExitHandler.LOG_ONLY).build(); ZooKeeperServerEmbedded zkServer2 = ZooKeeperServerEmbedded.builder().configuration(configZookeeper2).baseDir(baseDir2).exitHandler(ExitHandler.LOG_ONLY).build(); ZooKeeperServerEmbedded zkServer3 = ZooKeeperServerEmbedded.builder().configuration(configZookeeper3).baseDir(baseDir3).exitHandler(ExitHandler.LOG_ONLY).build();) { zkServer1.start(); zkServer2.start(); zkServer3.start(); assertTrue(ClientBase.waitForServerUp("localhost:" + clientport1, 60000)); assertTrue(ClientBase.waitForServerUp("localhost:" + clientport2, 60000)); assertTrue(ClientBase.waitForServerUp("localhost:" + clientport3, 60000)); for (int i = 0; i < 100; i++) { ZookeeperServeInfo.ServerInfo status = ZookeeperServeInfo.getStatus("ReplicatedServer*"); System.out.println("status:" + status); if (status.isLeader() && !status.isStandaloneMode() && status.getPeers().size() == 3) { break; } Thread.sleep(100); } ZookeeperServeInfo.ServerInfo status = ZookeeperServeInfo.getStatus("ReplicatedServer*"); assertTrue(status.isLeader()); assertTrue(!status.isStandaloneMode()); assertEquals(3, status.getPeers().size()); } } }
apache-2.0
tdreitz/bloc-jams-responsive
app/scripts/min/landing-min.js
361
var animatePoints=function(){"use strict";var t=function(){$(this).css({opacity:1,transform:"scaleX(1) translateY(0)"})};$.each($(".point"),t)};$(window).load(function(){"use strict";$(window).height()>950&&animatePoints();var t=$(".selling-points").offset().top-$(window).height()+200;$(window).scroll(function(i){$(window).scrollTop()>=t&&animatePoints()})});
apache-2.0
yangyang0425/zabbix
js/chkbxrange.js
9293
/* ** Zabbix ** Copyright (C) 2001-2016 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ /* * Automatic checkbox range selection */ var chkbxRange = { startbox: null, // start checkbox obj chkboxes: {}, // ckbx list prefix: null, // prefix for cookie name pageGoName: null, // which checkboxes should be counted by Go button and saved to cookies selectedIds: {}, // ids of selected objects footerButtons: {}, // action buttons at the bottom of page cookieName: null, init: function() { // cookie name var path = new Curl(); var filename = basename(path.getPath(), '.php'); this.cookieName = 'cb_' + filename + (this.prefix ? '_' + this.prefix : ''); this.resetOtherPageCookies(); // initialize checkboxes var chkboxes = jQuery('.list-table input[type=checkbox]:not(:disabled)'); if (chkboxes.length > 0) { for (var i = 0; i < chkboxes.length; i++) { this.implement(chkboxes[i]); } } // load selected checkboxes from cookies or cache if (this.pageGoName != null) { this.selectedIds = cookie.readJSON(this.cookieName); // check if checkboxes should be selected from cookies if (!jQuery.isEmptyObject(this.selectedIds)) { var objectIds = jQuery.map(this.selectedIds, function(id) { return id }); } // no checkboxes selected from cookies, check browser cache if checkboxes are still checked and update state else { var checkedFromCache = jQuery('.list-table tr:not(.header) input[type=checkbox]:checked:not(:disabled)'); var objectIds = jQuery.map(checkedFromCache, jQuery.proxy(function(checkbox) { return this.getObjectIdFromName(checkbox.name); }, this)); } this.checkObjects(this.pageGoName, objectIds, true); this.update(this.pageGoName); } this.footerButtons = jQuery('#action_buttons button'); var thisChkbxRange = this; this.footerButtons.each(function() { addListener(this, 'click', thisChkbxRange.submitFooterButton.bindAsEventListener(thisChkbxRange), false); }); }, implement: function(obj) { // skip the "select all" checkbox if (obj.name.indexOf('all_') > -1) { return; } var objName = this.getObjectFromName(obj.name); if (typeof(this.chkboxes[objName]) === 'undefined') { this.chkboxes[objName] = []; } this.chkboxes[objName].push(obj); addListener(obj, 'click', this.handleClick.bindAsEventListener(this), false); if (objName == this.pageGoName) { var objId = jQuery(obj).val(); if (isset(objId, this.selectedIds)) { obj.checked = true; } } }, /** * Handles a click on one of the checkboxes. * * @param e */ handleClick: function(e) { e = e || window.event; var checkbox = Event.element(e); PageRefresh.restart(); var object = this.getObjectFromName(checkbox.name); var objectId = this.getObjectIdFromName(checkbox.name); // range selection if ((e.ctrlKey || e.shiftKey) && this.startbox != null) { this.checkObjectRange(object, this.startbox, checkbox, this.startbox.checked); } // an individual checkbox else { this.checkObjects(object, [objectId], checkbox.checked); } this.update(object); this.saveCookies(object); this.startbox = checkbox; }, /** * Extracts the name of an object from the name of a checkbox. * * @param {string} name * * @returns {string} */ getObjectFromName: function(name) { return name.split('[')[0]; }, /** * Extracts the ID of an object from the name of a checkbox. * * @param {string} name * * @returns {string} */ getObjectIdFromName: function(name) { var id = name.split('[')[1]; id = id.substring(0, id.lastIndexOf(']')); return id; }, /** * Returns the checkboxes in an object group. * * @param string object * * @returns {Array} */ getObjectCheckboxes: function(object) { return this.chkboxes[object] || []; }, /** * Toggle all checkboxes of the given objects. * * Checks all of the checkboxes that belong to these objects and highlights the table row. * * @param {string} object * @param {Array} objectIds array of objects IDs as integers * @param {bool} checked */ checkObjects: function(object, objectIds, checked) { jQuery.each(this.getObjectCheckboxes(object), jQuery.proxy(function(i, checkbox) { var objectId = this.getObjectIdFromName(checkbox.name); if (objectIds.indexOf(objectId) > -1) { checkbox.checked = checked; jQuery(checkbox).closest('tr').toggleClass('row-selected', checked); // Remove class attribute if it's empty jQuery(checkbox).closest('tr').filter('*[class=""]').removeAttr('class'); if (checked) { this.selectedIds[objectId] = objectId; } else { delete this.selectedIds[objectId]; } } }, this)); }, /** * Toggle all objects between the two checkboxes. * * @param {string} object * @param {object} startCheckbox * @param {object} endCheckbox * @param {bool} checked */ checkObjectRange: function(object, startCheckbox, endCheckbox, checked) { var checkboxes = this.getObjectCheckboxes(object); var startCheckboxIndex = checkboxes.indexOf(startCheckbox); var endCheckboxIndex = checkboxes.indexOf(endCheckbox); var start = Math.min(startCheckboxIndex, endCheckboxIndex); var end = Math.max(startCheckboxIndex, endCheckboxIndex); var objectIds = []; for (var i = start; i <= end; i++) { objectIds.push(this.getObjectIdFromName(checkboxes[i].name)); } this.checkObjects(object, objectIds, checked); }, /** * Toggle all of the checkboxes belonging to the given object group. * * @param {string} object * * @param {bool} checked */ checkObjectAll: function(object, checked) { // main checkbox exists and is clickable, but other checkboxes may not exist and object may be empty var objectIds = jQuery.map(this.getObjectCheckboxes(object), jQuery.proxy(function(checkbox) { return this.getObjectIdFromName(checkbox.name); }, this)); this.checkObjects(object, objectIds, checked); }, /** * Update the general state after toggling a checkbox. * * @param {string} object */ update: function(object) { // update main checkbox state this.updateMainCheckbox(); if (this.pageGoName == object) { this.updateGoButton(); } }, /** * Update the state of the "Go" controls. */ updateGoButton: function() { var count = 0; jQuery.each(this.selectedIds, function() { count++; }); var selectedCountSpan = jQuery('#selected_count'); selectedCountSpan.text(count + ' ' + selectedCountSpan.text().split(' ')[1]); jQuery('#action_buttons button').prop('disabled', count == 0); }, // check if all checkboxes are selected and select main checkbox, else disable checkbox, select options and button updateMainCheckbox: function() { var mainCheckbox = jQuery('.list-table .header input[type=checkbox]:not(:disabled)'); if (!mainCheckbox.length) { return; } var countAvailable = jQuery('.list-table tr:not(.header) input[type=checkbox]:not(:disabled)').length; if (countAvailable > 0) { var countChecked = jQuery('.list-table tr:not(.header) input[type=checkbox]:not(:disabled):checked').length; mainCheckbox = mainCheckbox[0]; mainCheckbox.checked = (countChecked == countAvailable); if (mainCheckbox.checked) { jQuery('.list-table .header').addClass('selectedMain'); } else { jQuery('.list-table .header').removeClass('selectedMain'); } } else { mainCheckbox.disabled = true; } }, /** * Save the state of the checkboxes belonging to the given object group in cookies. * * @param {string} object */ saveCookies: function(object) { if (this.pageGoName == object) { cookie.createJSON(this.cookieName, this.selectedIds); } }, clearSelectedOnFilterChange: function() { cookie.eraseArray(this.cookieName); }, /** * Reset all selections on other pages. */ resetOtherPageCookies: function() { for (var key in cookie.cookies) { var cookiePair = key.split('='); if (cookiePair[0].indexOf('cb_') > -1 && cookiePair[0].indexOf(this.cookieName) == -1) { cookie.erase(key); } } }, submitFooterButton: function(e) { e = e || window.event; var footerButton = jQuery(e.target), form = footerButton.closest('form'), confirmText = footerButton.attr('confirm'); if (confirmText && !confirm(confirmText)) { Event.stop(e); return false; } for (var key in this.selectedIds) { if (this.selectedIds.hasOwnProperty(key) && this.selectedIds[key] !== null) { create_var(form.attr('name'), this.pageGoName + '[' + key + ']', key, false); } } return true; } };
apache-2.0
sekikn/ambari
ambari-common/src/main/python/resource_management/core/resources/packaging.py
2243
#!/usr/bin/env python """ 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. Ambari Agent """ __all__ = ["Package"] from resource_management.core.base import Resource, ForcedListArgument, ResourceArgument, BooleanArgument class Package(Resource): action = ForcedListArgument(default="install") package_name = ResourceArgument(default=lambda obj: obj.name) location = ResourceArgument(default=lambda obj: obj.package_name) """ Dictionary of repositories (repo ID => repo file name) to allow using only a specific list of repositories when performing action. (APT requires repo file names while other providers can filter by repo ID, hence the need to pass both.) """ use_repos = ResourceArgument(default={}) """ List of repositories to avoid using (currently only respected by YUM provider) """ skip_repos = ResourceArgument(default=[]) """ True - log it in INFO mode False - never log it None (default) - log it in DEBUG mode """ logoutput = ResourceArgument(default=None) """ Retry if package manager is locked or unavailable. Note that retry_on_lock works only for apt-get and zypper, while yum manages lock retries itself. """ retry_count = ResourceArgument(default=4) retry_sleep = ResourceArgument(default=30) retry_on_repo_unavailability = BooleanArgument(default=False) retry_on_locked = BooleanArgument(default=True) version = ResourceArgument() actions = ["install", "upgrade", "remove"] build_vars = ForcedListArgument(default=[])
apache-2.0
brosander/big-data-plugin
legacy/src/main/java/org/pentaho/amazon/s3/S3FileOutputMeta.java
7305
/******************************************************************************* * * Pentaho Big Data * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * 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 org.pentaho.amazon.s3; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.pentaho.di.core.Const; import org.pentaho.di.core.annotations.Step; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.injection.Injection; import org.pentaho.di.core.injection.InjectionSupported; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.textfileoutput.TextFileOutputMeta; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; @Step( id = "S3FileOutputPlugin", image = "S3O.svg", name = "S3FileOutput.Name", description = "S3FileOutput.Description", categoryDescription = "i18n:org.pentaho.di.trans.step:BaseStep.Category.Output", i18nPackageName = "org.pentaho.amazon.s3" ) @InjectionSupported( localizationPrefix = "S3FileOutput.Injection.", groups = { "OUTPUT_FIELDS" } ) public class S3FileOutputMeta extends TextFileOutputMeta { private static final String ACCESS_KEY_TAG = "access_key"; private static final String SECRET_KEY_TAG = "secret_key"; private static final String FILE_TAG = "file"; private static final String NAME_TAG = "name"; private static final Pattern OLD_STYLE_FILENAME = Pattern.compile( "^[s|S]3:\\/\\/([0-9a-zA-Z]{20}):(.+)@(.+)$" ); @Injection( name = "AWS_ACCESS_KEY" ) private String accessKey = null; @Injection( name = "AWS_SECRET_KEY" ) private String secretKey = null; public String getAccessKey() { return accessKey; } public void setAccessKey( String accessKey ) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey( String secretKey ) { this.secretKey = secretKey; } @Override public void setDefault() { // call the base classes method super.setDefault(); // now set the default for the // filename to an empty string setFileName( "" ); } @Override public String getXML() { StringBuffer retval = new StringBuffer( 1000 ); retval.append( super.getXML() ); retval.append( " " ).append( XMLHandler.addTagValue( ACCESS_KEY_TAG, Encr.encryptPasswordIfNotUsingVariables( accessKey ) ) ); retval.append( " " ).append( XMLHandler.addTagValue( SECRET_KEY_TAG, Encr.encryptPasswordIfNotUsingVariables( secretKey ) ) ); return retval.toString(); } @Override public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException { try { super.saveRep( rep, metaStore, id_transformation, id_step ); rep.saveStepAttribute( id_transformation, id_step, ACCESS_KEY_TAG, Encr .encryptPasswordIfNotUsingVariables( accessKey ) ); rep.saveStepAttribute( id_transformation, id_step, SECRET_KEY_TAG, Encr .encryptPasswordIfNotUsingVariables( secretKey ) ); } catch ( Exception e ) { throw new KettleException( "Unable to save step information to the repository for id_step=" + id_step, e ); } } @Override public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException { try { super.readRep( rep, metaStore, id_step, databases ); setAccessKey( Encr.decryptPasswordOptionallyEncrypted( rep.getStepAttributeString( id_step, ACCESS_KEY_TAG ) ) ); setSecretKey( Encr.decryptPasswordOptionallyEncrypted( rep.getStepAttributeString( id_step, SECRET_KEY_TAG ) ) ); setFileAsCommand( false ); // commands cannot be executed in S3 file system; PDI-4707, 4655 String filename = rep.getStepAttributeString( id_step, "file_name" ); processFilename( filename ); } catch ( Exception e ) { throw new KettleException( "Unexpected error reading step information from the repository", e ); } } public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException { readData( stepnode ); } @Override public void readData( Node stepnode ) throws KettleXMLException { try { super.readData( stepnode ); accessKey = Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue( stepnode, ACCESS_KEY_TAG ) ); secretKey = Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue( stepnode, SECRET_KEY_TAG ) ); setFileAsCommand( false ); // command cannot be executed in S3 file system; PDI-4707, 4655 String filename = XMLHandler.getTagValue( stepnode, FILE_TAG, NAME_TAG ); processFilename( filename ); } catch ( Exception e ) { throw new KettleXMLException( "Unable to load step info from XML", e ); } } @Override public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans ) { return new S3FileOutput( stepMeta, stepDataInterface, cnr, transMeta, trans ); } /** * New filenames obey the rule s3://<any_string>/<s3_bucket_name>/<path>. However, we maintain old filenames * s3://<access_key>:<secret_key>@s3/<s3_bucket_name>/<path> * * @param filename * @return */ protected void processFilename( String filename ) throws Exception { if ( Const.isEmpty( filename ) ) { setFileName( filename ); return; } // it it's an old-style filename - use and then remove keys from the filename Matcher matcher = OLD_STYLE_FILENAME.matcher( filename ); if ( matcher.matches() ) { // old style filename is URL encoded accessKey = decodeAccessKey( matcher.group( 1 ) ); secretKey = decodeAccessKey( matcher.group( 2 ) ); setFileName( "s3://" + matcher.group( 3 ) ); } else { setFileName( filename ); } } protected String decodeAccessKey( String key ) { if ( Const.isEmpty( key ) ) { return key; } return key.replaceAll( "%2B", "\\+" ).replaceAll( "%2F", "/" ); } }
apache-2.0
JYBESSON/camel
components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelEnvironment.java
2925
/** * 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. */ package org.apache.camel.cdi; import javax.enterprise.inject.spi.Annotated; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.InjectionTarget; import javax.enterprise.inject.spi.Producer; import org.apache.camel.CamelContext; import org.apache.camel.core.osgi.utils.BundleContextUtils; @Vetoed final class CdiCamelEnvironment { private final boolean hasBundleContext; CdiCamelEnvironment() { hasBundleContext = isCamelCoreOsgiPresent() && hasBundleContext(CdiCamelExtension.class); } <T extends CamelContext> Producer<T> camelContextProducer(Producer<T> delegate, Annotated annotated, BeanManager manager, CdiCamelExtension extension) { CamelContextProducer<T> producer = new CamelContextProducer<>(delegate, annotated, manager, extension); return hasBundleContext ? new CamelContextOsgiProducer<>(producer) : producer; } <T extends CamelContext> InjectionTarget<T> camelContextInjectionTarget(InjectionTarget<T> delegate, Annotated annotated, BeanManager manager, CdiCamelExtension extension) { CamelContextProducer<T> producer = new CamelContextProducer<>(delegate, annotated, manager, extension); return new CamelContextInjectionTarget<>(delegate, hasBundleContext ? new CamelContextOsgiProducer<>(producer) : producer); } private static boolean isCamelCoreOsgiPresent() { try { getClassLoader(CdiCamelExtension.class).loadClass("org.apache.camel.core.osgi.OsgiCamelContextHelper"); return true; } catch (ClassNotFoundException cause) { return false; } catch (NoClassDefFoundError cause) { return false; } } private static boolean hasBundleContext(Class clazz) { return BundleContextUtils.getBundleContext(clazz) != null; } private static ClassLoader getClassLoader(Class<?> clazz) { if (Thread.currentThread().getContextClassLoader() != null) { return Thread.currentThread().getContextClassLoader(); } else { return clazz.getClassLoader(); } } }
apache-2.0
jbartece/pnc
ui/app/common/directives/pnc-infinite-select-items/pncInfiniteSelectItems.js
7276
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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. */ (function () { 'use strict'; var module = angular.module('pnc.common.directives'); /** * @ngdoc directive * @name pnc.common.directives:pncInfiniteSelectSingle * @restrict E * @param {string@} singleItem * Indicates if the list of selected items is single (selecting a new item will replace the existing one, if any). Defaults to 'false' * @param {array=} selected-items * An array on the in scope controller that will hold the items selected by * the user. The array can be pre-populated to show items that are already * selected. * @param {string@} display-property * The name of the property on the item to search against and display. Defaults to 'name' * @param {string=} additional-display-items-by-id * The name of the additional property to display * @param {array=} items * The items to display * @param {string=} item-id * The ui id of the items (for UI validation) * @param {string@} placeholder * The placeholder to show in the search text. Defaults to 'Scroll & Filter' * @param {string@} infinite-select-id * The ui id of the infiniteSelect directive (for UI validation) * @param {string@} infinite-select-name * The ui name of the infiniteSelect directive (for UI validation) * @param {string@} infinite-select-required * Indicates if the infinite select value is required (for UI validation). Defaults to 'false' * @description * A directive that allows users to select multiple options from a list of * possible types, using the infinite scroll. The user finds possible items by typing into a input box. * The selected items are presented to the user in a list (one-item list if 'singleItem' is true) * The user is given the option to remove items from the list by pressing a * cross button next to the selected item. * @example * <pnc-infinite-select-list ng-show="configurationForm.$visible" selected-items="detailCtrl.buildgroupconfigs.selected" infinite-select-required="false" infinite-select-id="input-build-group-configs" infinite-select-name="bgConfigId" placeholder="Scroll & Filter Build Group Configs..." items="detailCtrl.configurationSetList"> </pnc-infinite-select-list> * @author Andrea Vibelli */ module.directive('pncInfiniteSelectItems', function() { return { restrict: 'E', scope: { singleItem: '@', selectedItems: '=', displayProperty: '@', additionalDisplayItemsById: '=', items: '=', itemId: '=', placeholder: '@', infiniteSelectId: '@', infiniteSelectRequired: '@' }, templateUrl: 'common/directives/pnc-infinite-select-items/pnc-infinite-select-items.html', controller: [ '$log', '$scope', function($log, $scope) { var findInArray = function(obj, array) { for (var i = 0; i < array.length; i++) { if (angular.equals(obj.id, array[i].id)) { return i; } } return -1; }; var PLACEHOLDER = 'Scroll & Filter'; $scope.placeholder = _.isUndefined($scope.placeholder) ? PLACEHOLDER : $scope.placeholder; $scope.infiniteSelectRequired = _.isUndefined($scope.infiniteSelectRequired) ? false : $scope.infiniteSelectRequired; $scope.singleItem = convertToBooleanString($scope.singleItem); var DEFAULT_DISPLAY_PROPERTY = 'name'; $scope.displayProperty = _.isUndefined($scope.displayProperty) ? DEFAULT_DISPLAY_PROPERTY : $scope.displayProperty; // If selectedItems is not empty, populate the $scope.itemId and $scope.searchText, otherwise // if 'infiniteSelectRequired' is true, the form would be invalid if ($scope.singleItem === 'true' && !_.isUndefined($scope.selectedItems) && !_.isEmpty($scope.selectedItems)) { $scope.itemId = $scope.selectedItems[0].id; $scope.searchText = $scope.selectedItems[0][$scope.displayProperty]; } $scope.removeItem = function(item) { // Remove from selected items list var i = findInArray(item, $scope.selectedItems); if (i >= 0) { $scope.selectedItems.splice(i, 1); if ($scope.singleItem === 'true') { $scope.itemId = undefined; $scope.searchText = undefined; } } }; $scope.shouldShowList = function() { return ($scope.selectedItems && $scope.selectedItems.length > 0); }; $scope.shouldShowSelection = function() { return !($scope.singleItem === 'true' && $scope.shouldShowList()); }; $scope.loadOptions = function() { if (!$scope.searchText) { $scope.items.loadMore(); } }; /* * Mousedown event handler */ $scope.selectItem = function(item) { if ($scope.singleItem === 'false') { $scope.itemId = undefined; $scope.searchText = undefined; } else { $scope.itemId = item.id; $scope.searchText = item[$scope.displayProperty]; } $scope.items.search(undefined); if (findInArray(item, $scope.selectedItems) < 0) { // If single item, clear the $scope.selectedItems if ($scope.singleItem === 'true') { $scope.selectedItems.splice(0, $scope.selectedItems.length); } // Add to selected items list $scope.selectedItems.push(item); } }; $scope.viewDropdown = function(isDropdown) { $scope.isDropdown = isDropdown; }; $scope.search = _.throttle(function() { $scope.items.search($scope.searchText); }, 1000); // When resetting the forms, itemId is reset because it's bound in the form via the 'item-id' property, but 'searchText' is not. // This makes sure the 'searchText' is reset also, to avoid refreshing problems $scope.$watch('itemId', function(newValue) { if (_.isUndefined(newValue)) { $scope.searchText = undefined; } }); } ] }; }); function convertToBooleanString(value) { if (_.isUndefined(value) || value !== 'true') { return 'false'; } return 'true'; } })();
apache-2.0
Talend/ui
packages/components/src/DateTimePickers/LegacyDateTimePickers/views/HeaderTitle/index.js
80
import HeaderTitle from './HeaderTitle.component'; export default HeaderTitle;
apache-2.0
Forexware/quickfixj
src/main/java/quickfix/JdbcUtil.java
5084
/******************************************************************************* * Copyright (c) quickfixengine.org All rights reserved. * * This file is part of the QuickFIX FIX Engine * * This file may be distributed under the terms of the quickfixengine.org * license as defined by quickfixengine.org and appearing in the file * LICENSE included in the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.quickfixengine.org/LICENSE for licensing information. * * Contact ask@quickfixengine.org if any conditions of this licensing * are not clear to you. ******************************************************************************/ package quickfix; import javax.sql.DataSource; import java.sql.*; class JdbcUtil { static void close(SessionID sessionID, Connection connection) { if (connection != null) { try { connection.close(); } catch (SQLException e) { LogUtil.logThrowable(sessionID, e.getMessage(), e); } } } static void close(SessionID sessionID, PreparedStatement statement) { if (statement != null) { try { statement.close(); } catch (SQLException e) { LogUtil.logThrowable(sessionID, e.getMessage(), e); } } } static void close(SessionID sessionID, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LogUtil.logThrowable(sessionID, e.getMessage(), e); } } } static boolean determineSessionIdSupport(DataSource dataSource, String tableName) throws SQLException { Connection connection = dataSource.getConnection(); try { DatabaseMetaData metaData = connection.getMetaData(); String columnName = "sendersubid"; return isColumn(metaData, tableName.toUpperCase(), columnName.toUpperCase()) || isColumn(metaData, tableName, columnName); } finally { connection.close(); } } private static boolean isColumn(DatabaseMetaData metaData, String tableName, String columnName) throws SQLException { ResultSet columns = metaData.getColumns(null, null, tableName, columnName); try { return columns.next(); } finally { columns.close(); } } static String getIDWhereClause(boolean isExtendedSessionID) { return isExtendedSessionID ? ("beginstring=? and sendercompid=? and sendersubid=? and senderlocid=? and " + "targetcompid=? and targetsubid=? and targetlocid=? and session_qualifier=? ") : "beginstring=? and sendercompid=? and targetcompid=? and session_qualifier=? "; } static String getIDColumns(boolean isExtendedSessionID) { return isExtendedSessionID ? "beginstring,sendercompid,sendersubid,senderlocid,targetcompid,targetsubid,targetlocid,session_qualifier" : "beginstring,sendercompid,targetcompid,session_qualifier"; } static String getIDPlaceholders(boolean isExtendedSessionID) { return isExtendedSessionID ? "?,?,?,?,?,?,?,?" : "?,?,?,?"; } static int setSessionIdParameters(SessionID sessionID, PreparedStatement query, int offset, boolean isExtendedSessionID, String defaultSqlValue) throws SQLException { if (isExtendedSessionID) { query.setString(offset++, getSqlValue(sessionID.getBeginString(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getSenderCompID(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getSenderSubID(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getSenderLocationID(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getTargetCompID(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getTargetSubID(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getTargetLocationID(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getSessionQualifier(), defaultSqlValue)); } else { query.setString(offset++, getSqlValue(sessionID.getBeginString(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getSenderCompID(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getTargetCompID(), defaultSqlValue)); query.setString(offset++, getSqlValue(sessionID.getSessionQualifier(), defaultSqlValue)); } return offset; } private static String getSqlValue(String javaValue, String defaultSqlValue) { return !SessionID.NOT_SET.equals(javaValue) ? javaValue : defaultSqlValue; } }
apache-2.0
botunge/hapi-fhir
hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Appointment.java
112216
package org.hl7.fhir.dstu3.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0 import java.util.*; import org.hl7.fhir.utilities.Utilities; import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.api.annotation.SearchParamDefinition; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.ChildOrder; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.Block; import org.hl7.fhir.instance.model.api.*; import org.hl7.fhir.exceptions.FHIRException; /** * A booking of a healthcare event among patient(s), practitioner(s), related person(s) and/or device(s) for a specific date/time. This may result in one or more Encounter(s). */ @ResourceDef(name="Appointment", profile="http://hl7.org/fhir/Profile/Appointment") public class Appointment extends DomainResource { public enum AppointmentStatus { /** * None of the participant(s) have finalized their acceptance of the appointment request, and the start/end time may not be set yet. */ PROPOSED, /** * Some or all of the participant(s) have not finalized their acceptance of the appointment request. */ PENDING, /** * All participant(s) have been considered and the appointment is confirmed to go ahead at the date/times specified. */ BOOKED, /** * Some of the patients have arrived. */ ARRIVED, /** * This appointment has completed and may have resulted in an encounter. */ FULFILLED, /** * The appointment has been cancelled. */ CANCELLED, /** * Some or all of the participant(s) have not/did not appear for the appointment (usually the patient). */ NOSHOW, /** * This instance should not have been part of this patient's medical record. */ ENTEREDINERROR, /** * added to help the parsers with the generic types */ NULL; public static AppointmentStatus fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("proposed".equals(codeString)) return PROPOSED; if ("pending".equals(codeString)) return PENDING; if ("booked".equals(codeString)) return BOOKED; if ("arrived".equals(codeString)) return ARRIVED; if ("fulfilled".equals(codeString)) return FULFILLED; if ("cancelled".equals(codeString)) return CANCELLED; if ("noshow".equals(codeString)) return NOSHOW; if ("entered-in-error".equals(codeString)) return ENTEREDINERROR; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown AppointmentStatus code '"+codeString+"'"); } public String toCode() { switch (this) { case PROPOSED: return "proposed"; case PENDING: return "pending"; case BOOKED: return "booked"; case ARRIVED: return "arrived"; case FULFILLED: return "fulfilled"; case CANCELLED: return "cancelled"; case NOSHOW: return "noshow"; case ENTEREDINERROR: return "entered-in-error"; default: return "?"; } } public String getSystem() { switch (this) { case PROPOSED: return "http://hl7.org/fhir/appointmentstatus"; case PENDING: return "http://hl7.org/fhir/appointmentstatus"; case BOOKED: return "http://hl7.org/fhir/appointmentstatus"; case ARRIVED: return "http://hl7.org/fhir/appointmentstatus"; case FULFILLED: return "http://hl7.org/fhir/appointmentstatus"; case CANCELLED: return "http://hl7.org/fhir/appointmentstatus"; case NOSHOW: return "http://hl7.org/fhir/appointmentstatus"; case ENTEREDINERROR: return "http://hl7.org/fhir/appointmentstatus"; default: return "?"; } } public String getDefinition() { switch (this) { case PROPOSED: return "None of the participant(s) have finalized their acceptance of the appointment request, and the start/end time may not be set yet."; case PENDING: return "Some or all of the participant(s) have not finalized their acceptance of the appointment request."; case BOOKED: return "All participant(s) have been considered and the appointment is confirmed to go ahead at the date/times specified."; case ARRIVED: return "Some of the patients have arrived."; case FULFILLED: return "This appointment has completed and may have resulted in an encounter."; case CANCELLED: return "The appointment has been cancelled."; case NOSHOW: return "Some or all of the participant(s) have not/did not appear for the appointment (usually the patient)."; case ENTEREDINERROR: return "This instance should not have been part of this patient's medical record."; default: return "?"; } } public String getDisplay() { switch (this) { case PROPOSED: return "Proposed"; case PENDING: return "Pending"; case BOOKED: return "Booked"; case ARRIVED: return "Arrived"; case FULFILLED: return "Fulfilled"; case CANCELLED: return "Cancelled"; case NOSHOW: return "No Show"; case ENTEREDINERROR: return "Entered in error"; default: return "?"; } } } public static class AppointmentStatusEnumFactory implements EnumFactory<AppointmentStatus> { public AppointmentStatus fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("proposed".equals(codeString)) return AppointmentStatus.PROPOSED; if ("pending".equals(codeString)) return AppointmentStatus.PENDING; if ("booked".equals(codeString)) return AppointmentStatus.BOOKED; if ("arrived".equals(codeString)) return AppointmentStatus.ARRIVED; if ("fulfilled".equals(codeString)) return AppointmentStatus.FULFILLED; if ("cancelled".equals(codeString)) return AppointmentStatus.CANCELLED; if ("noshow".equals(codeString)) return AppointmentStatus.NOSHOW; if ("entered-in-error".equals(codeString)) return AppointmentStatus.ENTEREDINERROR; throw new IllegalArgumentException("Unknown AppointmentStatus code '"+codeString+"'"); } public Enumeration<AppointmentStatus> fromType(Base code) throws FHIRException { if (code == null || code.isEmpty()) return null; String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("proposed".equals(codeString)) return new Enumeration<AppointmentStatus>(this, AppointmentStatus.PROPOSED); if ("pending".equals(codeString)) return new Enumeration<AppointmentStatus>(this, AppointmentStatus.PENDING); if ("booked".equals(codeString)) return new Enumeration<AppointmentStatus>(this, AppointmentStatus.BOOKED); if ("arrived".equals(codeString)) return new Enumeration<AppointmentStatus>(this, AppointmentStatus.ARRIVED); if ("fulfilled".equals(codeString)) return new Enumeration<AppointmentStatus>(this, AppointmentStatus.FULFILLED); if ("cancelled".equals(codeString)) return new Enumeration<AppointmentStatus>(this, AppointmentStatus.CANCELLED); if ("noshow".equals(codeString)) return new Enumeration<AppointmentStatus>(this, AppointmentStatus.NOSHOW); if ("entered-in-error".equals(codeString)) return new Enumeration<AppointmentStatus>(this, AppointmentStatus.ENTEREDINERROR); throw new FHIRException("Unknown AppointmentStatus code '"+codeString+"'"); } public String toCode(AppointmentStatus code) { if (code == AppointmentStatus.PROPOSED) return "proposed"; if (code == AppointmentStatus.PENDING) return "pending"; if (code == AppointmentStatus.BOOKED) return "booked"; if (code == AppointmentStatus.ARRIVED) return "arrived"; if (code == AppointmentStatus.FULFILLED) return "fulfilled"; if (code == AppointmentStatus.CANCELLED) return "cancelled"; if (code == AppointmentStatus.NOSHOW) return "noshow"; if (code == AppointmentStatus.ENTEREDINERROR) return "entered-in-error"; return "?"; } public String toSystem(AppointmentStatus code) { return code.getSystem(); } } public enum ParticipantRequired { /** * The participant is required to attend the appointment. */ REQUIRED, /** * The participant may optionally attend the appointment. */ OPTIONAL, /** * The participant is excluded from the appointment, and may not be informed of the appointment taking place. (Appointment is about them, not for them - such as 2 doctors discussing results about a patient's test). */ INFORMATIONONLY, /** * added to help the parsers with the generic types */ NULL; public static ParticipantRequired fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("required".equals(codeString)) return REQUIRED; if ("optional".equals(codeString)) return OPTIONAL; if ("information-only".equals(codeString)) return INFORMATIONONLY; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown ParticipantRequired code '"+codeString+"'"); } public String toCode() { switch (this) { case REQUIRED: return "required"; case OPTIONAL: return "optional"; case INFORMATIONONLY: return "information-only"; default: return "?"; } } public String getSystem() { switch (this) { case REQUIRED: return "http://hl7.org/fhir/participantrequired"; case OPTIONAL: return "http://hl7.org/fhir/participantrequired"; case INFORMATIONONLY: return "http://hl7.org/fhir/participantrequired"; default: return "?"; } } public String getDefinition() { switch (this) { case REQUIRED: return "The participant is required to attend the appointment."; case OPTIONAL: return "The participant may optionally attend the appointment."; case INFORMATIONONLY: return "The participant is excluded from the appointment, and may not be informed of the appointment taking place. (Appointment is about them, not for them - such as 2 doctors discussing results about a patient's test)."; default: return "?"; } } public String getDisplay() { switch (this) { case REQUIRED: return "Required"; case OPTIONAL: return "Optional"; case INFORMATIONONLY: return "Information Only"; default: return "?"; } } } public static class ParticipantRequiredEnumFactory implements EnumFactory<ParticipantRequired> { public ParticipantRequired fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("required".equals(codeString)) return ParticipantRequired.REQUIRED; if ("optional".equals(codeString)) return ParticipantRequired.OPTIONAL; if ("information-only".equals(codeString)) return ParticipantRequired.INFORMATIONONLY; throw new IllegalArgumentException("Unknown ParticipantRequired code '"+codeString+"'"); } public Enumeration<ParticipantRequired> fromType(Base code) throws FHIRException { if (code == null || code.isEmpty()) return null; String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("required".equals(codeString)) return new Enumeration<ParticipantRequired>(this, ParticipantRequired.REQUIRED); if ("optional".equals(codeString)) return new Enumeration<ParticipantRequired>(this, ParticipantRequired.OPTIONAL); if ("information-only".equals(codeString)) return new Enumeration<ParticipantRequired>(this, ParticipantRequired.INFORMATIONONLY); throw new FHIRException("Unknown ParticipantRequired code '"+codeString+"'"); } public String toCode(ParticipantRequired code) { if (code == ParticipantRequired.REQUIRED) return "required"; if (code == ParticipantRequired.OPTIONAL) return "optional"; if (code == ParticipantRequired.INFORMATIONONLY) return "information-only"; return "?"; } public String toSystem(ParticipantRequired code) { return code.getSystem(); } } public enum ParticipationStatus { /** * The participant has accepted the appointment. */ ACCEPTED, /** * The participant has declined the appointment and will not participate in the appointment. */ DECLINED, /** * The participant has tentatively accepted the appointment. This could be automatically created by a system and requires further processing before it can be accepted. There is no commitment that attendance will occur. */ TENTATIVE, /** * The participant needs to indicate if they accept the appointment by changing this status to one of the other statuses. */ NEEDSACTION, /** * added to help the parsers with the generic types */ NULL; public static ParticipationStatus fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("accepted".equals(codeString)) return ACCEPTED; if ("declined".equals(codeString)) return DECLINED; if ("tentative".equals(codeString)) return TENTATIVE; if ("needs-action".equals(codeString)) return NEEDSACTION; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown ParticipationStatus code '"+codeString+"'"); } public String toCode() { switch (this) { case ACCEPTED: return "accepted"; case DECLINED: return "declined"; case TENTATIVE: return "tentative"; case NEEDSACTION: return "needs-action"; default: return "?"; } } public String getSystem() { switch (this) { case ACCEPTED: return "http://hl7.org/fhir/participationstatus"; case DECLINED: return "http://hl7.org/fhir/participationstatus"; case TENTATIVE: return "http://hl7.org/fhir/participationstatus"; case NEEDSACTION: return "http://hl7.org/fhir/participationstatus"; default: return "?"; } } public String getDefinition() { switch (this) { case ACCEPTED: return "The participant has accepted the appointment."; case DECLINED: return "The participant has declined the appointment and will not participate in the appointment."; case TENTATIVE: return "The participant has tentatively accepted the appointment. This could be automatically created by a system and requires further processing before it can be accepted. There is no commitment that attendance will occur."; case NEEDSACTION: return "The participant needs to indicate if they accept the appointment by changing this status to one of the other statuses."; default: return "?"; } } public String getDisplay() { switch (this) { case ACCEPTED: return "Accepted"; case DECLINED: return "Declined"; case TENTATIVE: return "Tentative"; case NEEDSACTION: return "Needs Action"; default: return "?"; } } } public static class ParticipationStatusEnumFactory implements EnumFactory<ParticipationStatus> { public ParticipationStatus fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("accepted".equals(codeString)) return ParticipationStatus.ACCEPTED; if ("declined".equals(codeString)) return ParticipationStatus.DECLINED; if ("tentative".equals(codeString)) return ParticipationStatus.TENTATIVE; if ("needs-action".equals(codeString)) return ParticipationStatus.NEEDSACTION; throw new IllegalArgumentException("Unknown ParticipationStatus code '"+codeString+"'"); } public Enumeration<ParticipationStatus> fromType(Base code) throws FHIRException { if (code == null || code.isEmpty()) return null; String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("accepted".equals(codeString)) return new Enumeration<ParticipationStatus>(this, ParticipationStatus.ACCEPTED); if ("declined".equals(codeString)) return new Enumeration<ParticipationStatus>(this, ParticipationStatus.DECLINED); if ("tentative".equals(codeString)) return new Enumeration<ParticipationStatus>(this, ParticipationStatus.TENTATIVE); if ("needs-action".equals(codeString)) return new Enumeration<ParticipationStatus>(this, ParticipationStatus.NEEDSACTION); throw new FHIRException("Unknown ParticipationStatus code '"+codeString+"'"); } public String toCode(ParticipationStatus code) { if (code == ParticipationStatus.ACCEPTED) return "accepted"; if (code == ParticipationStatus.DECLINED) return "declined"; if (code == ParticipationStatus.TENTATIVE) return "tentative"; if (code == ParticipationStatus.NEEDSACTION) return "needs-action"; return "?"; } public String toSystem(ParticipationStatus code) { return code.getSystem(); } } @Block() public static class AppointmentParticipantComponent extends BackboneElement implements IBaseBackboneElement { /** * Role of participant in the appointment. */ @Child(name = "type", type = {CodeableConcept.class}, order=1, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Role of participant in the appointment", formalDefinition="Role of participant in the appointment." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/encounter-participant-type") protected List<CodeableConcept> type; /** * A Person, Location/HealthcareService or Device that is participating in the appointment. */ @Child(name = "actor", type = {Patient.class, Practitioner.class, RelatedPerson.class, Device.class, HealthcareService.class, Location.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Person, Location/HealthcareService or Device", formalDefinition="A Person, Location/HealthcareService or Device that is participating in the appointment." ) protected Reference actor; /** * The actual object that is the target of the reference (A Person, Location/HealthcareService or Device that is participating in the appointment.) */ protected Resource actorTarget; /** * Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet to discuss the results for a specific patient, and the patient is not required to be present. */ @Child(name = "required", type = {CodeType.class}, order=3, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="required | optional | information-only", formalDefinition="Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet to discuss the results for a specific patient, and the patient is not required to be present." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/participantrequired") protected Enumeration<ParticipantRequired> required; /** * Participation status of the Patient. */ @Child(name = "status", type = {CodeType.class}, order=4, min=1, max=1, modifier=false, summary=false) @Description(shortDefinition="accepted | declined | tentative | needs-action", formalDefinition="Participation status of the Patient." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/participationstatus") protected Enumeration<ParticipationStatus> status; private static final long serialVersionUID = -1620552507L; /** * Constructor */ public AppointmentParticipantComponent() { super(); } /** * Constructor */ public AppointmentParticipantComponent(Enumeration<ParticipationStatus> status) { super(); this.status = status; } /** * @return {@link #type} (Role of participant in the appointment.) */ public List<CodeableConcept> getType() { if (this.type == null) this.type = new ArrayList<CodeableConcept>(); return this.type; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public AppointmentParticipantComponent setType(List<CodeableConcept> theType) { this.type = theType; return this; } public boolean hasType() { if (this.type == null) return false; for (CodeableConcept item : this.type) if (!item.isEmpty()) return true; return false; } public CodeableConcept addType() { //3 CodeableConcept t = new CodeableConcept(); if (this.type == null) this.type = new ArrayList<CodeableConcept>(); this.type.add(t); return t; } public AppointmentParticipantComponent addType(CodeableConcept t) { //3 if (t == null) return this; if (this.type == null) this.type = new ArrayList<CodeableConcept>(); this.type.add(t); return this; } /** * @return The first repetition of repeating field {@link #type}, creating it if it does not already exist */ public CodeableConcept getTypeFirstRep() { if (getType().isEmpty()) { addType(); } return getType().get(0); } /** * @return {@link #actor} (A Person, Location/HealthcareService or Device that is participating in the appointment.) */ public Reference getActor() { if (this.actor == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create AppointmentParticipantComponent.actor"); else if (Configuration.doAutoCreate()) this.actor = new Reference(); // cc return this.actor; } public boolean hasActor() { return this.actor != null && !this.actor.isEmpty(); } /** * @param value {@link #actor} (A Person, Location/HealthcareService or Device that is participating in the appointment.) */ public AppointmentParticipantComponent setActor(Reference value) { this.actor = value; return this; } /** * @return {@link #actor} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (A Person, Location/HealthcareService or Device that is participating in the appointment.) */ public Resource getActorTarget() { return this.actorTarget; } /** * @param value {@link #actor} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (A Person, Location/HealthcareService or Device that is participating in the appointment.) */ public AppointmentParticipantComponent setActorTarget(Resource value) { this.actorTarget = value; return this; } /** * @return {@link #required} (Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet to discuss the results for a specific patient, and the patient is not required to be present.). This is the underlying object with id, value and extensions. The accessor "getRequired" gives direct access to the value */ public Enumeration<ParticipantRequired> getRequiredElement() { if (this.required == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create AppointmentParticipantComponent.required"); else if (Configuration.doAutoCreate()) this.required = new Enumeration<ParticipantRequired>(new ParticipantRequiredEnumFactory()); // bb return this.required; } public boolean hasRequiredElement() { return this.required != null && !this.required.isEmpty(); } public boolean hasRequired() { return this.required != null && !this.required.isEmpty(); } /** * @param value {@link #required} (Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet to discuss the results for a specific patient, and the patient is not required to be present.). This is the underlying object with id, value and extensions. The accessor "getRequired" gives direct access to the value */ public AppointmentParticipantComponent setRequiredElement(Enumeration<ParticipantRequired> value) { this.required = value; return this; } /** * @return Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet to discuss the results for a specific patient, and the patient is not required to be present. */ public ParticipantRequired getRequired() { return this.required == null ? null : this.required.getValue(); } /** * @param value Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet to discuss the results for a specific patient, and the patient is not required to be present. */ public AppointmentParticipantComponent setRequired(ParticipantRequired value) { if (value == null) this.required = null; else { if (this.required == null) this.required = new Enumeration<ParticipantRequired>(new ParticipantRequiredEnumFactory()); this.required.setValue(value); } return this; } /** * @return {@link #status} (Participation status of the Patient.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public Enumeration<ParticipationStatus> getStatusElement() { if (this.status == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create AppointmentParticipantComponent.status"); else if (Configuration.doAutoCreate()) this.status = new Enumeration<ParticipationStatus>(new ParticipationStatusEnumFactory()); // bb return this.status; } public boolean hasStatusElement() { return this.status != null && !this.status.isEmpty(); } public boolean hasStatus() { return this.status != null && !this.status.isEmpty(); } /** * @param value {@link #status} (Participation status of the Patient.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public AppointmentParticipantComponent setStatusElement(Enumeration<ParticipationStatus> value) { this.status = value; return this; } /** * @return Participation status of the Patient. */ public ParticipationStatus getStatus() { return this.status == null ? null : this.status.getValue(); } /** * @param value Participation status of the Patient. */ public AppointmentParticipantComponent setStatus(ParticipationStatus value) { if (this.status == null) this.status = new Enumeration<ParticipationStatus>(new ParticipationStatusEnumFactory()); this.status.setValue(value); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("type", "CodeableConcept", "Role of participant in the appointment.", 0, java.lang.Integer.MAX_VALUE, type)); childrenList.add(new Property("actor", "Reference(Patient|Practitioner|RelatedPerson|Device|HealthcareService|Location)", "A Person, Location/HealthcareService or Device that is participating in the appointment.", 0, java.lang.Integer.MAX_VALUE, actor)); childrenList.add(new Property("required", "code", "Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet to discuss the results for a specific patient, and the patient is not required to be present.", 0, java.lang.Integer.MAX_VALUE, required)); childrenList.add(new Property("status", "code", "Participation status of the Patient.", 0, java.lang.Integer.MAX_VALUE, status)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case 3575610: /*type*/ return this.type == null ? new Base[0] : this.type.toArray(new Base[this.type.size()]); // CodeableConcept case 92645877: /*actor*/ return this.actor == null ? new Base[0] : new Base[] {this.actor}; // Reference case -393139297: /*required*/ return this.required == null ? new Base[0] : new Base[] {this.required}; // Enumeration<ParticipantRequired> case -892481550: /*status*/ return this.status == null ? new Base[0] : new Base[] {this.status}; // Enumeration<ParticipationStatus> default: return super.getProperty(hash, name, checkValid); } } @Override public void setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case 3575610: // type this.getType().add(castToCodeableConcept(value)); // CodeableConcept break; case 92645877: // actor this.actor = castToReference(value); // Reference break; case -393139297: // required this.required = new ParticipantRequiredEnumFactory().fromType(value); // Enumeration<ParticipantRequired> break; case -892481550: // status this.status = new ParticipationStatusEnumFactory().fromType(value); // Enumeration<ParticipationStatus> break; default: super.setProperty(hash, name, value); } } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("type")) this.getType().add(castToCodeableConcept(value)); else if (name.equals("actor")) this.actor = castToReference(value); // Reference else if (name.equals("required")) this.required = new ParticipantRequiredEnumFactory().fromType(value); // Enumeration<ParticipantRequired> else if (name.equals("status")) this.status = new ParticipationStatusEnumFactory().fromType(value); // Enumeration<ParticipationStatus> else super.setProperty(name, value); } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case 3575610: return addType(); // CodeableConcept case 92645877: return getActor(); // Reference case -393139297: throw new FHIRException("Cannot make property required as it is not a complex type"); // Enumeration<ParticipantRequired> case -892481550: throw new FHIRException("Cannot make property status as it is not a complex type"); // Enumeration<ParticipationStatus> default: return super.makeProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("type")) { return addType(); } else if (name.equals("actor")) { this.actor = new Reference(); return this.actor; } else if (name.equals("required")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.required"); } else if (name.equals("status")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.status"); } else return super.addChild(name); } public AppointmentParticipantComponent copy() { AppointmentParticipantComponent dst = new AppointmentParticipantComponent(); copyValues(dst); if (type != null) { dst.type = new ArrayList<CodeableConcept>(); for (CodeableConcept i : type) dst.type.add(i.copy()); }; dst.actor = actor == null ? null : actor.copy(); dst.required = required == null ? null : required.copy(); dst.status = status == null ? null : status.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof AppointmentParticipantComponent)) return false; AppointmentParticipantComponent o = (AppointmentParticipantComponent) other; return compareDeep(type, o.type, true) && compareDeep(actor, o.actor, true) && compareDeep(required, o.required, true) && compareDeep(status, o.status, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof AppointmentParticipantComponent)) return false; AppointmentParticipantComponent o = (AppointmentParticipantComponent) other; return compareValues(required, o.required, true) && compareValues(status, o.status, true); } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(type, actor, required, status ); } public String fhirType() { return "Appointment.participant"; } } /** * This records identifiers associated with this appointment concern that are defined by business processes and/or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). */ @Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="External Ids for this item", formalDefinition="This records identifiers associated with this appointment concern that are defined by business processes and/or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation)." ) protected List<Identifier> identifier; /** * The overall status of the Appointment. Each of the participants has their own participation status which indicates their involvement in the process, however this status indicates the shared status. */ @Child(name = "status", type = {CodeType.class}, order=1, min=1, max=1, modifier=true, summary=true) @Description(shortDefinition="proposed | pending | booked | arrived | fulfilled | cancelled | noshow | entered-in-error", formalDefinition="The overall status of the Appointment. Each of the participants has their own participation status which indicates their involvement in the process, however this status indicates the shared status." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/appointmentstatus") protected Enumeration<AppointmentStatus> status; /** * A broad categorisation of the service that is to be performed during this appointment. */ @Child(name = "serviceCategory", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="A broad categorisation of the service that is to be performed during this appointment", formalDefinition="A broad categorisation of the service that is to be performed during this appointment." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/service-category") protected CodeableConcept serviceCategory; /** * The specific service that is to be performed during this appointment. */ @Child(name = "serviceType", type = {CodeableConcept.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="The specific service that is to be performed during this appointment", formalDefinition="The specific service that is to be performed during this appointment." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/service-type") protected List<CodeableConcept> serviceType; /** * The specialty of a practitioner that would be required to perform the service requested in this appointment. */ @Child(name = "specialty", type = {CodeableConcept.class}, order=4, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="The specialty of a practitioner that would be required to perform the service requested in this appointment", formalDefinition="The specialty of a practitioner that would be required to perform the service requested in this appointment." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/c80-practice-codes") protected List<CodeableConcept> specialty; /** * The style of appointment or patient that has been booked in the slot (not service type). */ @Child(name = "appointmentType", type = {CodeableConcept.class}, order=5, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="The style of appointment or patient that has been booked in the slot (not service type)", formalDefinition="The style of appointment or patient that has been booked in the slot (not service type)." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/v2-0276") protected CodeableConcept appointmentType; /** * The reason that this appointment is being scheduled. This is more clinical than administrative. */ @Child(name = "reason", type = {CodeableConcept.class}, order=6, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Reason this appointment is scheduled", formalDefinition="The reason that this appointment is being scheduled. This is more clinical than administrative." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/encounter-reason") protected CodeableConcept reason; /** * The priority of the appointment. Can be used to make informed decisions if needing to re-prioritize appointments. (The iCal Standard specifies 0 as undefined, 1 as highest, 9 as lowest priority). */ @Child(name = "priority", type = {UnsignedIntType.class}, order=7, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Used to make informed decisions if needing to re-prioritize", formalDefinition="The priority of the appointment. Can be used to make informed decisions if needing to re-prioritize appointments. (The iCal Standard specifies 0 as undefined, 1 as highest, 9 as lowest priority)." ) protected UnsignedIntType priority; /** * The brief description of the appointment as would be shown on a subject line in a meeting request, or appointment list. Detailed or expanded information should be put in the comment field. */ @Child(name = "description", type = {StringType.class}, order=8, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Shown on a subject line in a meeting request, or appointment list", formalDefinition="The brief description of the appointment as would be shown on a subject line in a meeting request, or appointment list. Detailed or expanded information should be put in the comment field." ) protected StringType description; /** * Date/Time that the appointment is to take place. */ @Child(name = "start", type = {InstantType.class}, order=9, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="When appointment is to take place", formalDefinition="Date/Time that the appointment is to take place." ) protected InstantType start; /** * Date/Time that the appointment is to conclude. */ @Child(name = "end", type = {InstantType.class}, order=10, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="When appointment is to conclude", formalDefinition="Date/Time that the appointment is to conclude." ) protected InstantType end; /** * Number of minutes that the appointment is to take. This can be less than the duration between the start and end times (where actual time of appointment is only an estimate or is a planned appointment request). */ @Child(name = "minutesDuration", type = {PositiveIntType.class}, order=11, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Can be less than start/end (e.g. estimate)", formalDefinition="Number of minutes that the appointment is to take. This can be less than the duration between the start and end times (where actual time of appointment is only an estimate or is a planned appointment request)." ) protected PositiveIntType minutesDuration; /** * The slot that this appointment is filling. If provided then the schedule will not be provided as slots are not recursive, and the start/end values MUST be the same as from the slot. */ @Child(name = "slot", type = {Slot.class}, order=12, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="If provided, then no schedule and start/end values MUST match slot", formalDefinition="The slot that this appointment is filling. If provided then the schedule will not be provided as slots are not recursive, and the start/end values MUST be the same as from the slot." ) protected List<Reference> slot; /** * The actual objects that are the target of the reference (The slot that this appointment is filling. If provided then the schedule will not be provided as slots are not recursive, and the start/end values MUST be the same as from the slot.) */ protected List<Slot> slotTarget; /** * The date that this appointment was initially created. This could be different to the meta.lastModified value on the initial entry, as this could have been before the resource was created on the FHIR server, and should remain unchanged over the lifespan of the appointment. */ @Child(name = "created", type = {DateTimeType.class}, order=13, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="The date that this appointment was initially created", formalDefinition="The date that this appointment was initially created. This could be different to the meta.lastModified value on the initial entry, as this could have been before the resource was created on the FHIR server, and should remain unchanged over the lifespan of the appointment." ) protected DateTimeType created; /** * Additional comments about the appointment. */ @Child(name = "comment", type = {StringType.class}, order=14, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Additional comments", formalDefinition="Additional comments about the appointment." ) protected StringType comment; /** * List of participants involved in the appointment. */ @Child(name = "participant", type = {}, order=15, min=1, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Participants involved in appointment", formalDefinition="List of participants involved in the appointment." ) protected List<AppointmentParticipantComponent> participant; /** * A set of date ranges (potentially including times) that the appointment is preferred to be scheduled. When using these values, the minutes duration should be provided to indicate the length of the appointment to fill and populate the start/end times for the actual allocated time. */ @Child(name = "requestedPeriod", type = {Period.class}, order=16, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Potential date/time interval(s) requested to allocate the appointment during", formalDefinition="A set of date ranges (potentially including times) that the appointment is preferred to be scheduled. When using these values, the minutes duration should be provided to indicate the length of the appointment to fill and populate the start/end times for the actual allocated time." ) protected List<Period> requestedPeriod; private static final long serialVersionUID = -1430302122L; /** * Constructor */ public Appointment() { super(); } /** * Constructor */ public Appointment(Enumeration<AppointmentStatus> status) { super(); this.status = status; } /** * @return {@link #identifier} (This records identifiers associated with this appointment concern that are defined by business processes and/or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).) */ public List<Identifier> getIdentifier() { if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); return this.identifier; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Appointment setIdentifier(List<Identifier> theIdentifier) { this.identifier = theIdentifier; return this; } public boolean hasIdentifier() { if (this.identifier == null) return false; for (Identifier item : this.identifier) if (!item.isEmpty()) return true; return false; } public Identifier addIdentifier() { //3 Identifier t = new Identifier(); if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return t; } public Appointment addIdentifier(Identifier t) { //3 if (t == null) return this; if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return this; } /** * @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist */ public Identifier getIdentifierFirstRep() { if (getIdentifier().isEmpty()) { addIdentifier(); } return getIdentifier().get(0); } /** * @return {@link #status} (The overall status of the Appointment. Each of the participants has their own participation status which indicates their involvement in the process, however this status indicates the shared status.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public Enumeration<AppointmentStatus> getStatusElement() { if (this.status == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.status"); else if (Configuration.doAutoCreate()) this.status = new Enumeration<AppointmentStatus>(new AppointmentStatusEnumFactory()); // bb return this.status; } public boolean hasStatusElement() { return this.status != null && !this.status.isEmpty(); } public boolean hasStatus() { return this.status != null && !this.status.isEmpty(); } /** * @param value {@link #status} (The overall status of the Appointment. Each of the participants has their own participation status which indicates their involvement in the process, however this status indicates the shared status.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public Appointment setStatusElement(Enumeration<AppointmentStatus> value) { this.status = value; return this; } /** * @return The overall status of the Appointment. Each of the participants has their own participation status which indicates their involvement in the process, however this status indicates the shared status. */ public AppointmentStatus getStatus() { return this.status == null ? null : this.status.getValue(); } /** * @param value The overall status of the Appointment. Each of the participants has their own participation status which indicates their involvement in the process, however this status indicates the shared status. */ public Appointment setStatus(AppointmentStatus value) { if (this.status == null) this.status = new Enumeration<AppointmentStatus>(new AppointmentStatusEnumFactory()); this.status.setValue(value); return this; } /** * @return {@link #serviceCategory} (A broad categorisation of the service that is to be performed during this appointment.) */ public CodeableConcept getServiceCategory() { if (this.serviceCategory == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.serviceCategory"); else if (Configuration.doAutoCreate()) this.serviceCategory = new CodeableConcept(); // cc return this.serviceCategory; } public boolean hasServiceCategory() { return this.serviceCategory != null && !this.serviceCategory.isEmpty(); } /** * @param value {@link #serviceCategory} (A broad categorisation of the service that is to be performed during this appointment.) */ public Appointment setServiceCategory(CodeableConcept value) { this.serviceCategory = value; return this; } /** * @return {@link #serviceType} (The specific service that is to be performed during this appointment.) */ public List<CodeableConcept> getServiceType() { if (this.serviceType == null) this.serviceType = new ArrayList<CodeableConcept>(); return this.serviceType; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Appointment setServiceType(List<CodeableConcept> theServiceType) { this.serviceType = theServiceType; return this; } public boolean hasServiceType() { if (this.serviceType == null) return false; for (CodeableConcept item : this.serviceType) if (!item.isEmpty()) return true; return false; } public CodeableConcept addServiceType() { //3 CodeableConcept t = new CodeableConcept(); if (this.serviceType == null) this.serviceType = new ArrayList<CodeableConcept>(); this.serviceType.add(t); return t; } public Appointment addServiceType(CodeableConcept t) { //3 if (t == null) return this; if (this.serviceType == null) this.serviceType = new ArrayList<CodeableConcept>(); this.serviceType.add(t); return this; } /** * @return The first repetition of repeating field {@link #serviceType}, creating it if it does not already exist */ public CodeableConcept getServiceTypeFirstRep() { if (getServiceType().isEmpty()) { addServiceType(); } return getServiceType().get(0); } /** * @return {@link #specialty} (The specialty of a practitioner that would be required to perform the service requested in this appointment.) */ public List<CodeableConcept> getSpecialty() { if (this.specialty == null) this.specialty = new ArrayList<CodeableConcept>(); return this.specialty; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Appointment setSpecialty(List<CodeableConcept> theSpecialty) { this.specialty = theSpecialty; return this; } public boolean hasSpecialty() { if (this.specialty == null) return false; for (CodeableConcept item : this.specialty) if (!item.isEmpty()) return true; return false; } public CodeableConcept addSpecialty() { //3 CodeableConcept t = new CodeableConcept(); if (this.specialty == null) this.specialty = new ArrayList<CodeableConcept>(); this.specialty.add(t); return t; } public Appointment addSpecialty(CodeableConcept t) { //3 if (t == null) return this; if (this.specialty == null) this.specialty = new ArrayList<CodeableConcept>(); this.specialty.add(t); return this; } /** * @return The first repetition of repeating field {@link #specialty}, creating it if it does not already exist */ public CodeableConcept getSpecialtyFirstRep() { if (getSpecialty().isEmpty()) { addSpecialty(); } return getSpecialty().get(0); } /** * @return {@link #appointmentType} (The style of appointment or patient that has been booked in the slot (not service type).) */ public CodeableConcept getAppointmentType() { if (this.appointmentType == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.appointmentType"); else if (Configuration.doAutoCreate()) this.appointmentType = new CodeableConcept(); // cc return this.appointmentType; } public boolean hasAppointmentType() { return this.appointmentType != null && !this.appointmentType.isEmpty(); } /** * @param value {@link #appointmentType} (The style of appointment or patient that has been booked in the slot (not service type).) */ public Appointment setAppointmentType(CodeableConcept value) { this.appointmentType = value; return this; } /** * @return {@link #reason} (The reason that this appointment is being scheduled. This is more clinical than administrative.) */ public CodeableConcept getReason() { if (this.reason == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.reason"); else if (Configuration.doAutoCreate()) this.reason = new CodeableConcept(); // cc return this.reason; } public boolean hasReason() { return this.reason != null && !this.reason.isEmpty(); } /** * @param value {@link #reason} (The reason that this appointment is being scheduled. This is more clinical than administrative.) */ public Appointment setReason(CodeableConcept value) { this.reason = value; return this; } /** * @return {@link #priority} (The priority of the appointment. Can be used to make informed decisions if needing to re-prioritize appointments. (The iCal Standard specifies 0 as undefined, 1 as highest, 9 as lowest priority).). This is the underlying object with id, value and extensions. The accessor "getPriority" gives direct access to the value */ public UnsignedIntType getPriorityElement() { if (this.priority == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.priority"); else if (Configuration.doAutoCreate()) this.priority = new UnsignedIntType(); // bb return this.priority; } public boolean hasPriorityElement() { return this.priority != null && !this.priority.isEmpty(); } public boolean hasPriority() { return this.priority != null && !this.priority.isEmpty(); } /** * @param value {@link #priority} (The priority of the appointment. Can be used to make informed decisions if needing to re-prioritize appointments. (The iCal Standard specifies 0 as undefined, 1 as highest, 9 as lowest priority).). This is the underlying object with id, value and extensions. The accessor "getPriority" gives direct access to the value */ public Appointment setPriorityElement(UnsignedIntType value) { this.priority = value; return this; } /** * @return The priority of the appointment. Can be used to make informed decisions if needing to re-prioritize appointments. (The iCal Standard specifies 0 as undefined, 1 as highest, 9 as lowest priority). */ public int getPriority() { return this.priority == null || this.priority.isEmpty() ? 0 : this.priority.getValue(); } /** * @param value The priority of the appointment. Can be used to make informed decisions if needing to re-prioritize appointments. (The iCal Standard specifies 0 as undefined, 1 as highest, 9 as lowest priority). */ public Appointment setPriority(int value) { if (this.priority == null) this.priority = new UnsignedIntType(); this.priority.setValue(value); return this; } /** * @return {@link #description} (The brief description of the appointment as would be shown on a subject line in a meeting request, or appointment list. Detailed or expanded information should be put in the comment field.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public StringType getDescriptionElement() { if (this.description == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.description"); else if (Configuration.doAutoCreate()) this.description = new StringType(); // bb return this.description; } public boolean hasDescriptionElement() { return this.description != null && !this.description.isEmpty(); } public boolean hasDescription() { return this.description != null && !this.description.isEmpty(); } /** * @param value {@link #description} (The brief description of the appointment as would be shown on a subject line in a meeting request, or appointment list. Detailed or expanded information should be put in the comment field.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public Appointment setDescriptionElement(StringType value) { this.description = value; return this; } /** * @return The brief description of the appointment as would be shown on a subject line in a meeting request, or appointment list. Detailed or expanded information should be put in the comment field. */ public String getDescription() { return this.description == null ? null : this.description.getValue(); } /** * @param value The brief description of the appointment as would be shown on a subject line in a meeting request, or appointment list. Detailed or expanded information should be put in the comment field. */ public Appointment setDescription(String value) { if (Utilities.noString(value)) this.description = null; else { if (this.description == null) this.description = new StringType(); this.description.setValue(value); } return this; } /** * @return {@link #start} (Date/Time that the appointment is to take place.). This is the underlying object with id, value and extensions. The accessor "getStart" gives direct access to the value */ public InstantType getStartElement() { if (this.start == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.start"); else if (Configuration.doAutoCreate()) this.start = new InstantType(); // bb return this.start; } public boolean hasStartElement() { return this.start != null && !this.start.isEmpty(); } public boolean hasStart() { return this.start != null && !this.start.isEmpty(); } /** * @param value {@link #start} (Date/Time that the appointment is to take place.). This is the underlying object with id, value and extensions. The accessor "getStart" gives direct access to the value */ public Appointment setStartElement(InstantType value) { this.start = value; return this; } /** * @return Date/Time that the appointment is to take place. */ public Date getStart() { return this.start == null ? null : this.start.getValue(); } /** * @param value Date/Time that the appointment is to take place. */ public Appointment setStart(Date value) { if (value == null) this.start = null; else { if (this.start == null) this.start = new InstantType(); this.start.setValue(value); } return this; } /** * @return {@link #end} (Date/Time that the appointment is to conclude.). This is the underlying object with id, value and extensions. The accessor "getEnd" gives direct access to the value */ public InstantType getEndElement() { if (this.end == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.end"); else if (Configuration.doAutoCreate()) this.end = new InstantType(); // bb return this.end; } public boolean hasEndElement() { return this.end != null && !this.end.isEmpty(); } public boolean hasEnd() { return this.end != null && !this.end.isEmpty(); } /** * @param value {@link #end} (Date/Time that the appointment is to conclude.). This is the underlying object with id, value and extensions. The accessor "getEnd" gives direct access to the value */ public Appointment setEndElement(InstantType value) { this.end = value; return this; } /** * @return Date/Time that the appointment is to conclude. */ public Date getEnd() { return this.end == null ? null : this.end.getValue(); } /** * @param value Date/Time that the appointment is to conclude. */ public Appointment setEnd(Date value) { if (value == null) this.end = null; else { if (this.end == null) this.end = new InstantType(); this.end.setValue(value); } return this; } /** * @return {@link #minutesDuration} (Number of minutes that the appointment is to take. This can be less than the duration between the start and end times (where actual time of appointment is only an estimate or is a planned appointment request).). This is the underlying object with id, value and extensions. The accessor "getMinutesDuration" gives direct access to the value */ public PositiveIntType getMinutesDurationElement() { if (this.minutesDuration == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.minutesDuration"); else if (Configuration.doAutoCreate()) this.minutesDuration = new PositiveIntType(); // bb return this.minutesDuration; } public boolean hasMinutesDurationElement() { return this.minutesDuration != null && !this.minutesDuration.isEmpty(); } public boolean hasMinutesDuration() { return this.minutesDuration != null && !this.minutesDuration.isEmpty(); } /** * @param value {@link #minutesDuration} (Number of minutes that the appointment is to take. This can be less than the duration between the start and end times (where actual time of appointment is only an estimate or is a planned appointment request).). This is the underlying object with id, value and extensions. The accessor "getMinutesDuration" gives direct access to the value */ public Appointment setMinutesDurationElement(PositiveIntType value) { this.minutesDuration = value; return this; } /** * @return Number of minutes that the appointment is to take. This can be less than the duration between the start and end times (where actual time of appointment is only an estimate or is a planned appointment request). */ public int getMinutesDuration() { return this.minutesDuration == null || this.minutesDuration.isEmpty() ? 0 : this.minutesDuration.getValue(); } /** * @param value Number of minutes that the appointment is to take. This can be less than the duration between the start and end times (where actual time of appointment is only an estimate or is a planned appointment request). */ public Appointment setMinutesDuration(int value) { if (this.minutesDuration == null) this.minutesDuration = new PositiveIntType(); this.minutesDuration.setValue(value); return this; } /** * @return {@link #slot} (The slot that this appointment is filling. If provided then the schedule will not be provided as slots are not recursive, and the start/end values MUST be the same as from the slot.) */ public List<Reference> getSlot() { if (this.slot == null) this.slot = new ArrayList<Reference>(); return this.slot; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Appointment setSlot(List<Reference> theSlot) { this.slot = theSlot; return this; } public boolean hasSlot() { if (this.slot == null) return false; for (Reference item : this.slot) if (!item.isEmpty()) return true; return false; } public Reference addSlot() { //3 Reference t = new Reference(); if (this.slot == null) this.slot = new ArrayList<Reference>(); this.slot.add(t); return t; } public Appointment addSlot(Reference t) { //3 if (t == null) return this; if (this.slot == null) this.slot = new ArrayList<Reference>(); this.slot.add(t); return this; } /** * @return The first repetition of repeating field {@link #slot}, creating it if it does not already exist */ public Reference getSlotFirstRep() { if (getSlot().isEmpty()) { addSlot(); } return getSlot().get(0); } /** * @deprecated Use Reference#setResource(IBaseResource) instead */ @Deprecated public List<Slot> getSlotTarget() { if (this.slotTarget == null) this.slotTarget = new ArrayList<Slot>(); return this.slotTarget; } /** * @deprecated Use Reference#setResource(IBaseResource) instead */ @Deprecated public Slot addSlotTarget() { Slot r = new Slot(); if (this.slotTarget == null) this.slotTarget = new ArrayList<Slot>(); this.slotTarget.add(r); return r; } /** * @return {@link #created} (The date that this appointment was initially created. This could be different to the meta.lastModified value on the initial entry, as this could have been before the resource was created on the FHIR server, and should remain unchanged over the lifespan of the appointment.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value */ public DateTimeType getCreatedElement() { if (this.created == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.created"); else if (Configuration.doAutoCreate()) this.created = new DateTimeType(); // bb return this.created; } public boolean hasCreatedElement() { return this.created != null && !this.created.isEmpty(); } public boolean hasCreated() { return this.created != null && !this.created.isEmpty(); } /** * @param value {@link #created} (The date that this appointment was initially created. This could be different to the meta.lastModified value on the initial entry, as this could have been before the resource was created on the FHIR server, and should remain unchanged over the lifespan of the appointment.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value */ public Appointment setCreatedElement(DateTimeType value) { this.created = value; return this; } /** * @return The date that this appointment was initially created. This could be different to the meta.lastModified value on the initial entry, as this could have been before the resource was created on the FHIR server, and should remain unchanged over the lifespan of the appointment. */ public Date getCreated() { return this.created == null ? null : this.created.getValue(); } /** * @param value The date that this appointment was initially created. This could be different to the meta.lastModified value on the initial entry, as this could have been before the resource was created on the FHIR server, and should remain unchanged over the lifespan of the appointment. */ public Appointment setCreated(Date value) { if (value == null) this.created = null; else { if (this.created == null) this.created = new DateTimeType(); this.created.setValue(value); } return this; } /** * @return {@link #comment} (Additional comments about the appointment.). This is the underlying object with id, value and extensions. The accessor "getComment" gives direct access to the value */ public StringType getCommentElement() { if (this.comment == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Appointment.comment"); else if (Configuration.doAutoCreate()) this.comment = new StringType(); // bb return this.comment; } public boolean hasCommentElement() { return this.comment != null && !this.comment.isEmpty(); } public boolean hasComment() { return this.comment != null && !this.comment.isEmpty(); } /** * @param value {@link #comment} (Additional comments about the appointment.). This is the underlying object with id, value and extensions. The accessor "getComment" gives direct access to the value */ public Appointment setCommentElement(StringType value) { this.comment = value; return this; } /** * @return Additional comments about the appointment. */ public String getComment() { return this.comment == null ? null : this.comment.getValue(); } /** * @param value Additional comments about the appointment. */ public Appointment setComment(String value) { if (Utilities.noString(value)) this.comment = null; else { if (this.comment == null) this.comment = new StringType(); this.comment.setValue(value); } return this; } /** * @return {@link #participant} (List of participants involved in the appointment.) */ public List<AppointmentParticipantComponent> getParticipant() { if (this.participant == null) this.participant = new ArrayList<AppointmentParticipantComponent>(); return this.participant; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Appointment setParticipant(List<AppointmentParticipantComponent> theParticipant) { this.participant = theParticipant; return this; } public boolean hasParticipant() { if (this.participant == null) return false; for (AppointmentParticipantComponent item : this.participant) if (!item.isEmpty()) return true; return false; } public AppointmentParticipantComponent addParticipant() { //3 AppointmentParticipantComponent t = new AppointmentParticipantComponent(); if (this.participant == null) this.participant = new ArrayList<AppointmentParticipantComponent>(); this.participant.add(t); return t; } public Appointment addParticipant(AppointmentParticipantComponent t) { //3 if (t == null) return this; if (this.participant == null) this.participant = new ArrayList<AppointmentParticipantComponent>(); this.participant.add(t); return this; } /** * @return The first repetition of repeating field {@link #participant}, creating it if it does not already exist */ public AppointmentParticipantComponent getParticipantFirstRep() { if (getParticipant().isEmpty()) { addParticipant(); } return getParticipant().get(0); } /** * @return {@link #requestedPeriod} (A set of date ranges (potentially including times) that the appointment is preferred to be scheduled. When using these values, the minutes duration should be provided to indicate the length of the appointment to fill and populate the start/end times for the actual allocated time.) */ public List<Period> getRequestedPeriod() { if (this.requestedPeriod == null) this.requestedPeriod = new ArrayList<Period>(); return this.requestedPeriod; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Appointment setRequestedPeriod(List<Period> theRequestedPeriod) { this.requestedPeriod = theRequestedPeriod; return this; } public boolean hasRequestedPeriod() { if (this.requestedPeriod == null) return false; for (Period item : this.requestedPeriod) if (!item.isEmpty()) return true; return false; } public Period addRequestedPeriod() { //3 Period t = new Period(); if (this.requestedPeriod == null) this.requestedPeriod = new ArrayList<Period>(); this.requestedPeriod.add(t); return t; } public Appointment addRequestedPeriod(Period t) { //3 if (t == null) return this; if (this.requestedPeriod == null) this.requestedPeriod = new ArrayList<Period>(); this.requestedPeriod.add(t); return this; } /** * @return The first repetition of repeating field {@link #requestedPeriod}, creating it if it does not already exist */ public Period getRequestedPeriodFirstRep() { if (getRequestedPeriod().isEmpty()) { addRequestedPeriod(); } return getRequestedPeriod().get(0); } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "Identifier", "This records identifiers associated with this appointment concern that are defined by business processes and/or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("status", "code", "The overall status of the Appointment. Each of the participants has their own participation status which indicates their involvement in the process, however this status indicates the shared status.", 0, java.lang.Integer.MAX_VALUE, status)); childrenList.add(new Property("serviceCategory", "CodeableConcept", "A broad categorisation of the service that is to be performed during this appointment.", 0, java.lang.Integer.MAX_VALUE, serviceCategory)); childrenList.add(new Property("serviceType", "CodeableConcept", "The specific service that is to be performed during this appointment.", 0, java.lang.Integer.MAX_VALUE, serviceType)); childrenList.add(new Property("specialty", "CodeableConcept", "The specialty of a practitioner that would be required to perform the service requested in this appointment.", 0, java.lang.Integer.MAX_VALUE, specialty)); childrenList.add(new Property("appointmentType", "CodeableConcept", "The style of appointment or patient that has been booked in the slot (not service type).", 0, java.lang.Integer.MAX_VALUE, appointmentType)); childrenList.add(new Property("reason", "CodeableConcept", "The reason that this appointment is being scheduled. This is more clinical than administrative.", 0, java.lang.Integer.MAX_VALUE, reason)); childrenList.add(new Property("priority", "unsignedInt", "The priority of the appointment. Can be used to make informed decisions if needing to re-prioritize appointments. (The iCal Standard specifies 0 as undefined, 1 as highest, 9 as lowest priority).", 0, java.lang.Integer.MAX_VALUE, priority)); childrenList.add(new Property("description", "string", "The brief description of the appointment as would be shown on a subject line in a meeting request, or appointment list. Detailed or expanded information should be put in the comment field.", 0, java.lang.Integer.MAX_VALUE, description)); childrenList.add(new Property("start", "instant", "Date/Time that the appointment is to take place.", 0, java.lang.Integer.MAX_VALUE, start)); childrenList.add(new Property("end", "instant", "Date/Time that the appointment is to conclude.", 0, java.lang.Integer.MAX_VALUE, end)); childrenList.add(new Property("minutesDuration", "positiveInt", "Number of minutes that the appointment is to take. This can be less than the duration between the start and end times (where actual time of appointment is only an estimate or is a planned appointment request).", 0, java.lang.Integer.MAX_VALUE, minutesDuration)); childrenList.add(new Property("slot", "Reference(Slot)", "The slot that this appointment is filling. If provided then the schedule will not be provided as slots are not recursive, and the start/end values MUST be the same as from the slot.", 0, java.lang.Integer.MAX_VALUE, slot)); childrenList.add(new Property("created", "dateTime", "The date that this appointment was initially created. This could be different to the meta.lastModified value on the initial entry, as this could have been before the resource was created on the FHIR server, and should remain unchanged over the lifespan of the appointment.", 0, java.lang.Integer.MAX_VALUE, created)); childrenList.add(new Property("comment", "string", "Additional comments about the appointment.", 0, java.lang.Integer.MAX_VALUE, comment)); childrenList.add(new Property("participant", "", "List of participants involved in the appointment.", 0, java.lang.Integer.MAX_VALUE, participant)); childrenList.add(new Property("requestedPeriod", "Period", "A set of date ranges (potentially including times) that the appointment is preferred to be scheduled. When using these values, the minutes duration should be provided to indicate the length of the appointment to fill and populate the start/end times for the actual allocated time.", 0, java.lang.Integer.MAX_VALUE, requestedPeriod)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier case -892481550: /*status*/ return this.status == null ? new Base[0] : new Base[] {this.status}; // Enumeration<AppointmentStatus> case 1281188563: /*serviceCategory*/ return this.serviceCategory == null ? new Base[0] : new Base[] {this.serviceCategory}; // CodeableConcept case -1928370289: /*serviceType*/ return this.serviceType == null ? new Base[0] : this.serviceType.toArray(new Base[this.serviceType.size()]); // CodeableConcept case -1694759682: /*specialty*/ return this.specialty == null ? new Base[0] : this.specialty.toArray(new Base[this.specialty.size()]); // CodeableConcept case -1596426375: /*appointmentType*/ return this.appointmentType == null ? new Base[0] : new Base[] {this.appointmentType}; // CodeableConcept case -934964668: /*reason*/ return this.reason == null ? new Base[0] : new Base[] {this.reason}; // CodeableConcept case -1165461084: /*priority*/ return this.priority == null ? new Base[0] : new Base[] {this.priority}; // UnsignedIntType case -1724546052: /*description*/ return this.description == null ? new Base[0] : new Base[] {this.description}; // StringType case 109757538: /*start*/ return this.start == null ? new Base[0] : new Base[] {this.start}; // InstantType case 100571: /*end*/ return this.end == null ? new Base[0] : new Base[] {this.end}; // InstantType case -413630573: /*minutesDuration*/ return this.minutesDuration == null ? new Base[0] : new Base[] {this.minutesDuration}; // PositiveIntType case 3533310: /*slot*/ return this.slot == null ? new Base[0] : this.slot.toArray(new Base[this.slot.size()]); // Reference case 1028554472: /*created*/ return this.created == null ? new Base[0] : new Base[] {this.created}; // DateTimeType case 950398559: /*comment*/ return this.comment == null ? new Base[0] : new Base[] {this.comment}; // StringType case 767422259: /*participant*/ return this.participant == null ? new Base[0] : this.participant.toArray(new Base[this.participant.size()]); // AppointmentParticipantComponent case -897241393: /*requestedPeriod*/ return this.requestedPeriod == null ? new Base[0] : this.requestedPeriod.toArray(new Base[this.requestedPeriod.size()]); // Period default: return super.getProperty(hash, name, checkValid); } } @Override public void setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1618432855: // identifier this.getIdentifier().add(castToIdentifier(value)); // Identifier break; case -892481550: // status this.status = new AppointmentStatusEnumFactory().fromType(value); // Enumeration<AppointmentStatus> break; case 1281188563: // serviceCategory this.serviceCategory = castToCodeableConcept(value); // CodeableConcept break; case -1928370289: // serviceType this.getServiceType().add(castToCodeableConcept(value)); // CodeableConcept break; case -1694759682: // specialty this.getSpecialty().add(castToCodeableConcept(value)); // CodeableConcept break; case -1596426375: // appointmentType this.appointmentType = castToCodeableConcept(value); // CodeableConcept break; case -934964668: // reason this.reason = castToCodeableConcept(value); // CodeableConcept break; case -1165461084: // priority this.priority = castToUnsignedInt(value); // UnsignedIntType break; case -1724546052: // description this.description = castToString(value); // StringType break; case 109757538: // start this.start = castToInstant(value); // InstantType break; case 100571: // end this.end = castToInstant(value); // InstantType break; case -413630573: // minutesDuration this.minutesDuration = castToPositiveInt(value); // PositiveIntType break; case 3533310: // slot this.getSlot().add(castToReference(value)); // Reference break; case 1028554472: // created this.created = castToDateTime(value); // DateTimeType break; case 950398559: // comment this.comment = castToString(value); // StringType break; case 767422259: // participant this.getParticipant().add((AppointmentParticipantComponent) value); // AppointmentParticipantComponent break; case -897241393: // requestedPeriod this.getRequestedPeriod().add(castToPeriod(value)); // Period break; default: super.setProperty(hash, name, value); } } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("identifier")) this.getIdentifier().add(castToIdentifier(value)); else if (name.equals("status")) this.status = new AppointmentStatusEnumFactory().fromType(value); // Enumeration<AppointmentStatus> else if (name.equals("serviceCategory")) this.serviceCategory = castToCodeableConcept(value); // CodeableConcept else if (name.equals("serviceType")) this.getServiceType().add(castToCodeableConcept(value)); else if (name.equals("specialty")) this.getSpecialty().add(castToCodeableConcept(value)); else if (name.equals("appointmentType")) this.appointmentType = castToCodeableConcept(value); // CodeableConcept else if (name.equals("reason")) this.reason = castToCodeableConcept(value); // CodeableConcept else if (name.equals("priority")) this.priority = castToUnsignedInt(value); // UnsignedIntType else if (name.equals("description")) this.description = castToString(value); // StringType else if (name.equals("start")) this.start = castToInstant(value); // InstantType else if (name.equals("end")) this.end = castToInstant(value); // InstantType else if (name.equals("minutesDuration")) this.minutesDuration = castToPositiveInt(value); // PositiveIntType else if (name.equals("slot")) this.getSlot().add(castToReference(value)); else if (name.equals("created")) this.created = castToDateTime(value); // DateTimeType else if (name.equals("comment")) this.comment = castToString(value); // StringType else if (name.equals("participant")) this.getParticipant().add((AppointmentParticipantComponent) value); else if (name.equals("requestedPeriod")) this.getRequestedPeriod().add(castToPeriod(value)); else super.setProperty(name, value); } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: return addIdentifier(); // Identifier case -892481550: throw new FHIRException("Cannot make property status as it is not a complex type"); // Enumeration<AppointmentStatus> case 1281188563: return getServiceCategory(); // CodeableConcept case -1928370289: return addServiceType(); // CodeableConcept case -1694759682: return addSpecialty(); // CodeableConcept case -1596426375: return getAppointmentType(); // CodeableConcept case -934964668: return getReason(); // CodeableConcept case -1165461084: throw new FHIRException("Cannot make property priority as it is not a complex type"); // UnsignedIntType case -1724546052: throw new FHIRException("Cannot make property description as it is not a complex type"); // StringType case 109757538: throw new FHIRException("Cannot make property start as it is not a complex type"); // InstantType case 100571: throw new FHIRException("Cannot make property end as it is not a complex type"); // InstantType case -413630573: throw new FHIRException("Cannot make property minutesDuration as it is not a complex type"); // PositiveIntType case 3533310: return addSlot(); // Reference case 1028554472: throw new FHIRException("Cannot make property created as it is not a complex type"); // DateTimeType case 950398559: throw new FHIRException("Cannot make property comment as it is not a complex type"); // StringType case 767422259: return addParticipant(); // AppointmentParticipantComponent case -897241393: return addRequestedPeriod(); // Period default: return super.makeProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("identifier")) { return addIdentifier(); } else if (name.equals("status")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.status"); } else if (name.equals("serviceCategory")) { this.serviceCategory = new CodeableConcept(); return this.serviceCategory; } else if (name.equals("serviceType")) { return addServiceType(); } else if (name.equals("specialty")) { return addSpecialty(); } else if (name.equals("appointmentType")) { this.appointmentType = new CodeableConcept(); return this.appointmentType; } else if (name.equals("reason")) { this.reason = new CodeableConcept(); return this.reason; } else if (name.equals("priority")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.priority"); } else if (name.equals("description")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.description"); } else if (name.equals("start")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.start"); } else if (name.equals("end")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.end"); } else if (name.equals("minutesDuration")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.minutesDuration"); } else if (name.equals("slot")) { return addSlot(); } else if (name.equals("created")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.created"); } else if (name.equals("comment")) { throw new FHIRException("Cannot call addChild on a primitive type Appointment.comment"); } else if (name.equals("participant")) { return addParticipant(); } else if (name.equals("requestedPeriod")) { return addRequestedPeriod(); } else return super.addChild(name); } public String fhirType() { return "Appointment"; } public Appointment copy() { Appointment dst = new Appointment(); copyValues(dst); if (identifier != null) { dst.identifier = new ArrayList<Identifier>(); for (Identifier i : identifier) dst.identifier.add(i.copy()); }; dst.status = status == null ? null : status.copy(); dst.serviceCategory = serviceCategory == null ? null : serviceCategory.copy(); if (serviceType != null) { dst.serviceType = new ArrayList<CodeableConcept>(); for (CodeableConcept i : serviceType) dst.serviceType.add(i.copy()); }; if (specialty != null) { dst.specialty = new ArrayList<CodeableConcept>(); for (CodeableConcept i : specialty) dst.specialty.add(i.copy()); }; dst.appointmentType = appointmentType == null ? null : appointmentType.copy(); dst.reason = reason == null ? null : reason.copy(); dst.priority = priority == null ? null : priority.copy(); dst.description = description == null ? null : description.copy(); dst.start = start == null ? null : start.copy(); dst.end = end == null ? null : end.copy(); dst.minutesDuration = minutesDuration == null ? null : minutesDuration.copy(); if (slot != null) { dst.slot = new ArrayList<Reference>(); for (Reference i : slot) dst.slot.add(i.copy()); }; dst.created = created == null ? null : created.copy(); dst.comment = comment == null ? null : comment.copy(); if (participant != null) { dst.participant = new ArrayList<AppointmentParticipantComponent>(); for (AppointmentParticipantComponent i : participant) dst.participant.add(i.copy()); }; if (requestedPeriod != null) { dst.requestedPeriod = new ArrayList<Period>(); for (Period i : requestedPeriod) dst.requestedPeriod.add(i.copy()); }; return dst; } protected Appointment typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof Appointment)) return false; Appointment o = (Appointment) other; return compareDeep(identifier, o.identifier, true) && compareDeep(status, o.status, true) && compareDeep(serviceCategory, o.serviceCategory, true) && compareDeep(serviceType, o.serviceType, true) && compareDeep(specialty, o.specialty, true) && compareDeep(appointmentType, o.appointmentType, true) && compareDeep(reason, o.reason, true) && compareDeep(priority, o.priority, true) && compareDeep(description, o.description, true) && compareDeep(start, o.start, true) && compareDeep(end, o.end, true) && compareDeep(minutesDuration, o.minutesDuration, true) && compareDeep(slot, o.slot, true) && compareDeep(created, o.created, true) && compareDeep(comment, o.comment, true) && compareDeep(participant, o.participant, true) && compareDeep(requestedPeriod, o.requestedPeriod, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof Appointment)) return false; Appointment o = (Appointment) other; return compareValues(status, o.status, true) && compareValues(priority, o.priority, true) && compareValues(description, o.description, true) && compareValues(start, o.start, true) && compareValues(end, o.end, true) && compareValues(minutesDuration, o.minutesDuration, true) && compareValues(created, o.created, true) && compareValues(comment, o.comment, true); } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, status, serviceCategory , serviceType, specialty, appointmentType, reason, priority, description, start , end, minutesDuration, slot, created, comment, participant, requestedPeriod); } @Override public ResourceType getResourceType() { return ResourceType.Appointment; } /** * Search parameter: <b>date</b> * <p> * Description: <b>Appointment date/time.</b><br> * Type: <b>date</b><br> * Path: <b>Appointment.start</b><br> * </p> */ @SearchParamDefinition(name="date", path="Appointment.start", description="Appointment date/time.", type="date" ) public static final String SP_DATE = "date"; /** * <b>Fluent Client</b> search parameter constant for <b>date</b> * <p> * Description: <b>Appointment date/time.</b><br> * Type: <b>date</b><br> * Path: <b>Appointment.start</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.DateClientParam DATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_DATE); /** * Search parameter: <b>actor</b> * <p> * Description: <b>Any one of the individuals participating in the appointment</b><br> * Type: <b>reference</b><br> * Path: <b>Appointment.participant.actor</b><br> * </p> */ @SearchParamDefinition(name="actor", path="Appointment.participant.actor", description="Any one of the individuals participating in the appointment", type="reference", providesMembershipIn={ @ca.uhn.fhir.model.api.annotation.Compartment(name="Device"), @ca.uhn.fhir.model.api.annotation.Compartment(name="Patient"), @ca.uhn.fhir.model.api.annotation.Compartment(name="Practitioner"), @ca.uhn.fhir.model.api.annotation.Compartment(name="RelatedPerson") }, target={Device.class, HealthcareService.class, Location.class, Patient.class, Practitioner.class, RelatedPerson.class } ) public static final String SP_ACTOR = "actor"; /** * <b>Fluent Client</b> search parameter constant for <b>actor</b> * <p> * Description: <b>Any one of the individuals participating in the appointment</b><br> * Type: <b>reference</b><br> * Path: <b>Appointment.participant.actor</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam ACTOR = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_ACTOR); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>Appointment:actor</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_ACTOR = new ca.uhn.fhir.model.api.Include("Appointment:actor").toLocked(); /** * Search parameter: <b>identifier</b> * <p> * Description: <b>An Identifier of the Appointment</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.identifier</b><br> * </p> */ @SearchParamDefinition(name="identifier", path="Appointment.identifier", description="An Identifier of the Appointment", type="token" ) public static final String SP_IDENTIFIER = "identifier"; /** * <b>Fluent Client</b> search parameter constant for <b>identifier</b> * <p> * Description: <b>An Identifier of the Appointment</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.identifier</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER); /** * Search parameter: <b>practitioner</b> * <p> * Description: <b>One of the individuals of the appointment is this practitioner</b><br> * Type: <b>reference</b><br> * Path: <b>Appointment.participant.actor</b><br> * </p> */ @SearchParamDefinition(name="practitioner", path="Appointment.participant.actor", description="One of the individuals of the appointment is this practitioner", type="reference", target={Practitioner.class } ) public static final String SP_PRACTITIONER = "practitioner"; /** * <b>Fluent Client</b> search parameter constant for <b>practitioner</b> * <p> * Description: <b>One of the individuals of the appointment is this practitioner</b><br> * Type: <b>reference</b><br> * Path: <b>Appointment.participant.actor</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam PRACTITIONER = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_PRACTITIONER); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>Appointment:practitioner</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_PRACTITIONER = new ca.uhn.fhir.model.api.Include("Appointment:practitioner").toLocked(); /** * Search parameter: <b>part-status</b> * <p> * Description: <b>The Participation status of the subject, or other participant on the appointment. Can be used to locate participants that have not responded to meeting requests.</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.participant.status</b><br> * </p> */ @SearchParamDefinition(name="part-status", path="Appointment.participant.status", description="The Participation status of the subject, or other participant on the appointment. Can be used to locate participants that have not responded to meeting requests.", type="token" ) public static final String SP_PART_STATUS = "part-status"; /** * <b>Fluent Client</b> search parameter constant for <b>part-status</b> * <p> * Description: <b>The Participation status of the subject, or other participant on the appointment. Can be used to locate participants that have not responded to meeting requests.</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.participant.status</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam PART_STATUS = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_PART_STATUS); /** * Search parameter: <b>patient</b> * <p> * Description: <b>One of the individuals of the appointment is this patient</b><br> * Type: <b>reference</b><br> * Path: <b>Appointment.participant.actor</b><br> * </p> */ @SearchParamDefinition(name="patient", path="Appointment.participant.actor", description="One of the individuals of the appointment is this patient", type="reference", target={Patient.class } ) public static final String SP_PATIENT = "patient"; /** * <b>Fluent Client</b> search parameter constant for <b>patient</b> * <p> * Description: <b>One of the individuals of the appointment is this patient</b><br> * Type: <b>reference</b><br> * Path: <b>Appointment.participant.actor</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam PATIENT = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_PATIENT); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>Appointment:patient</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_PATIENT = new ca.uhn.fhir.model.api.Include("Appointment:patient").toLocked(); /** * Search parameter: <b>appointment-type</b> * <p> * Description: <b>The style of appointment or patient that has been booked in the slot (not service type)</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.appointmentType</b><br> * </p> */ @SearchParamDefinition(name="appointment-type", path="Appointment.appointmentType", description="The style of appointment or patient that has been booked in the slot (not service type)", type="token" ) public static final String SP_APPOINTMENT_TYPE = "appointment-type"; /** * <b>Fluent Client</b> search parameter constant for <b>appointment-type</b> * <p> * Description: <b>The style of appointment or patient that has been booked in the slot (not service type)</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.appointmentType</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam APPOINTMENT_TYPE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_APPOINTMENT_TYPE); /** * Search parameter: <b>service-type</b> * <p> * Description: <b>The specific service that is to be performed during this appointment</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.serviceType</b><br> * </p> */ @SearchParamDefinition(name="service-type", path="Appointment.serviceType", description="The specific service that is to be performed during this appointment", type="token" ) public static final String SP_SERVICE_TYPE = "service-type"; /** * <b>Fluent Client</b> search parameter constant for <b>service-type</b> * <p> * Description: <b>The specific service that is to be performed during this appointment</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.serviceType</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam SERVICE_TYPE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_SERVICE_TYPE); /** * Search parameter: <b>location</b> * <p> * Description: <b>This location is listed in the participants of the appointment</b><br> * Type: <b>reference</b><br> * Path: <b>Appointment.participant.actor</b><br> * </p> */ @SearchParamDefinition(name="location", path="Appointment.participant.actor", description="This location is listed in the participants of the appointment", type="reference", target={Location.class } ) public static final String SP_LOCATION = "location"; /** * <b>Fluent Client</b> search parameter constant for <b>location</b> * <p> * Description: <b>This location is listed in the participants of the appointment</b><br> * Type: <b>reference</b><br> * Path: <b>Appointment.participant.actor</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam LOCATION = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_LOCATION); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>Appointment:location</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_LOCATION = new ca.uhn.fhir.model.api.Include("Appointment:location").toLocked(); /** * Search parameter: <b>status</b> * <p> * Description: <b>The overall status of the appointment</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.status</b><br> * </p> */ @SearchParamDefinition(name="status", path="Appointment.status", description="The overall status of the appointment", type="token" ) public static final String SP_STATUS = "status"; /** * <b>Fluent Client</b> search parameter constant for <b>status</b> * <p> * Description: <b>The overall status of the appointment</b><br> * Type: <b>token</b><br> * Path: <b>Appointment.status</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam STATUS = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_STATUS); }
apache-2.0
googlearchive/big-rig
app/src/scripts/components/Spinner.js
3890
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Class constructor for Spinner MDL component. * Implements MDL component design pattern defined at: * https://github.com/jasonmayes/mdl-component-design-pattern * @param {HTMLElement} element The element that will be upgraded. * @constructor */ class MaterialSpinner { constructor (element) { this.element_ = element; // Initialize instance. this.init(); } /** * Store constants in one place so they can be updated easily. * @enum {string | number} * @private */ get Constant_ () { return { MDL_SPINNER_LAYER_COUNT: 4 }; } /** * Store strings for class names defined by this component that are used in * JavaScript. This allows us to simply change it in one place should we * decide to modify at a later date. * @enum {string} * @private */ get CssClasses_ () { return { MDL_SPINNER_LAYER: 'mdl-spinner__layer', MDL_SPINNER_CIRCLE_CLIPPER: 'mdl-spinner__circle-clipper', MDL_SPINNER_CIRCLE: 'mdl-spinner__circle', MDL_SPINNER_GAP_PATCH: 'mdl-spinner__gap-patch', MDL_SPINNER_LEFT: 'mdl-spinner__left', MDL_SPINNER_RIGHT: 'mdl-spinner__right' }; } /** * Auxiliary method to create a spinner layer. */ createLayer (index) { var layer = document.createElement('div'); layer.classList.add(this.CssClasses_.MDL_SPINNER_LAYER); layer.classList.add(this.CssClasses_.MDL_SPINNER_LAYER + '-' + index); var leftClipper = document.createElement('div'); leftClipper.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE_CLIPPER); leftClipper.classList.add(this.CssClasses_.MDL_SPINNER_LEFT); var gapPatch = document.createElement('div'); gapPatch.classList.add(this.CssClasses_.MDL_SPINNER_GAP_PATCH); var rightClipper = document.createElement('div'); rightClipper.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE_CLIPPER); rightClipper.classList.add(this.CssClasses_.MDL_SPINNER_RIGHT); var circleOwners = [leftClipper, gapPatch, rightClipper]; for (var i = 0; i < circleOwners.length; i++) { var circle = document.createElement('div'); circle.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE); circleOwners[i].appendChild(circle); } layer.appendChild(leftClipper); layer.appendChild(gapPatch); layer.appendChild(rightClipper); this.element_.appendChild(layer); } /** * Stops the spinner animation. * Public method for users who need to stop the spinner for any reason. * @public */ stop () { this.element_.classList.remove('is-active'); } /** * Starts the spinner animation. * Public method for users who need to manually start the spinner for any reason * (instead of just adding the 'is-active' class to their markup). * @public */ start () { this.element_.classList.add('is-active'); } /** * Initialize element. */ init () { if (this.element_) { for (var i = 1; i <= this.Constant_.MDL_SPINNER_LAYER_COUNT; i++) { this.createLayer(i); } this.element_.classList.add('is-upgraded'); } } } var spinners = document.querySelectorAll('.mdl-js-spinner'); for (var s = 0; s < spinners.length; s++) { new MaterialSpinner(spinners[s]); }
apache-2.0
NeelumAyub/Tutorials
SimpleServlet/src/main/java/net/javatutorial/tutorials/SimpleServlet.java
823
package net.javatutorial.tutorials; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = -4751096228274971485L; @Override protected void doGet(HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("Hello World!"); } @Override public void init() throws ServletException { System.out.println("Servlet " + this.getServletName() + " has started"); } @Override public void destroy() { System.out.println("Servlet " + this.getServletName() + " has stopped"); } }
apache-2.0
goodwinnk/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/ui/ToolbarClicksUsagesCollector.java
1559
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.collectors.fus.ui; import com.intellij.internal.statistic.beans.UsageDescriptor; import com.intellij.internal.statistic.collectors.fus.ui.persistence.ToolbarClicksCollector; import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector; import com.intellij.internal.statistic.service.fus.collectors.FUSUsageContext; import com.intellij.internal.statistic.service.fus.collectors.FUStatisticsDifferenceSender; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Set; import static com.intellij.internal.statistic.service.fus.collectors.UsageDescriptorKeyValidator.ensureProperKey; public final class ToolbarClicksUsagesCollector extends ApplicationUsagesCollector implements FUStatisticsDifferenceSender { public static final String GROUP_ID = "statistics.ui.toolbar.clicks"; @Override @NotNull public Set<UsageDescriptor> getUsages() { ToolbarClicksCollector.ClicksState state = ToolbarClicksCollector.getInstance().getState(); assert state != null; return ContainerUtil.map2Set(state.myValues.entrySet(), e -> new UsageDescriptor(ensureProperKey(e.getKey()), e.getValue())); } @Override @NotNull public String getGroupId() { return GROUP_ID; } @NotNull @Override public FUSUsageContext getContext() { return FUSUsageContext.OS_CONTEXT; } }
apache-2.0
SpreeGorilla/Prebid.js
modules/nasmediaAdmixerBidAdapter.js
2224
import * as utils from 'src/utils'; import {registerBidder} from 'src/adapters/bidderFactory'; import find from 'core-js/library/fn/array/find'; const ADMIXER_ENDPOINT = 'https://adn.admixer.co.kr:10443/prebid'; const DEFAULT_BID_TTL = 360; const DEFAULT_CURRENCY = 'USD'; const DEFAULT_REVENUE = false; export const spec = { code: 'nasmediaAdmixer', isBidRequestValid: function (bid) { return !!(bid && bid.params && bid.params.ax_key); }, buildRequests: function (validBidRequests) { return validBidRequests.map(bid => { let adSize = getSize(bid.sizes); return { method: 'GET', url: ADMIXER_ENDPOINT, data: { ax_key: utils.getBidIdParameter('ax_key', bid.params), req_id: bid.bidId, width: adSize.width, height: adSize.height, referrer: utils.getTopWindowUrl(), os: getOsType() } } }) }, interpretResponse: function (serverResponse, bidRequest) { const serverBody = serverResponse.body; const bidResponses = []; if (serverBody && serverBody.error_code === 0 && serverBody.body && serverBody.body.length > 0) { let bidData = serverBody.body[0]; const bidResponse = { ad: bidData.ad, requestId: serverBody.req_id, creativeId: bidData.ad_id, cpm: bidData.cpm, width: bidData.width, height: bidData.height, currency: bidData.currency ? bidData.currency : DEFAULT_CURRENCY, netRevenue: DEFAULT_REVENUE, ttl: DEFAULT_BID_TTL }; bidResponses.push(bidResponse); } return bidResponses; } } function getOsType() { let ua = navigator.userAgent.toLowerCase(); let os = ['android', 'ios', 'mac', 'linux', 'window']; let regexp_os = [/android/i, /iphone|ipad/i, /mac/i, /linux/i, /window/i]; return find(os, (tos, idx) => { if (ua.match(regexp_os[idx])) { return os[idx]; } }) || 'etc'; } function getSize(sizes) { let parsedSizes = utils.parseSizesInput(sizes); let [width, height] = parsedSizes.length ? parsedSizes[0].split('x') : []; return { width: parseInt(width, 10), height: parseInt(height, 10) }; } registerBidder(spec);
apache-2.0
fujitsu-cf/cli
integration/helpers/route.go
1622
package helpers import ( "fmt" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" . "github.com/onsi/gomega/gexec" ) type Route struct { Space string Host string Domain string Path string } func NewRoute(space string, domain string, hostname string, path string) Route { return Route{ Space: space, Domain: domain, Host: hostname, Path: path, } } func (r Route) Create() { Eventually(CF("create-route", r.Space, r.Domain, "--hostname", r.Host, "--path", r.Path)).Should(Exit(0)) } func (r Route) Delete() { Eventually(CF("delete-route", r.Domain, "--hostname", r.Host, "--path", r.Path, "-f")).Should(Exit(0)) } func DomainName(prefix ...string) string { if len(prefix) > 0 { return fmt.Sprintf("integration-%s.com", PrefixedRandomName(prefix[0])) } return fmt.Sprintf("integration%s.com", PrefixedRandomName("")) } type Domain struct { Org string Name string } func NewDomain(org string, name string) Domain { return Domain{ Org: org, Name: name, } } func (d Domain) Create() { Eventually(CF("create-domain", d.Org, d.Name)).Should(Exit(0)) Eventually(CF("domains")).Should(And(Exit(0), Say(d.Name))) } func (d Domain) CreateShared() { Eventually(CF("create-shared-domain", d.Name)).Should(Exit(0)) } func (d Domain) CreateWithRouterGroup(routerGroup string) { Eventually(CF("create-shared-domain", d.Name, "--router-group", routerGroup)).Should(Exit(0)) } func (d Domain) Share() { Eventually(CF("share-private-domain", d.Org, d.Name)).Should(Exit(0)) } func (d Domain) Delete() { Eventually(CF("delete-domain", d.Name, "-f")).Should(Exit(0)) }
apache-2.0
bp117/ChaincodePOC
src/main/java/com/makotojava/learn/blockchain/chaincode/ChaincodeLog.java
2879
/* * Copyright 2017 Makoto Consulting Group, 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. */ package com.makotojava.learn.blockchain.chaincode; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.java.shim.ChaincodeStub; /** * * @author jstevenperry * */ public class ChaincodeLog extends AbstractChaincode { private static final Log log = LogFactory.getLog(ChaincodeLog.class); public static final String CONTRACT_ID = "ChaincodeLogSmartContract"; public static final String FUNCTION_LOG = "log"; public static final String KEY_PREFIX = CONTRACT_ID + "-CLSC-"; /** * The driver method. Every chaincode program must have one. * This is invoked to start the chaincode running, and register * it with the Fabric. * * @param args */ public static void main(String[] args) { new ChaincodeLog().start(args); } /** * Returns the unique chaincode ID for this chaincode program. */ @Override public String getChaincodeID() { return null; } /** * Handles initializing this chaincode program. * <br/> * Caller expects this method to: * <ol> * <li>Use args[0] as the key for logging.</li> * <li>Use args[1] as the log message.</li> * <li>Return the logged message.</li> * </ol> */ @Override protected String handleInit(ChaincodeStub stub, String[] args) { return null; } /** * Handles querying the ledger. * <br/> * Caller expects this method to: * <ol> * <li>Use args[0] as the key for ledger query.</li> * <li>Return the ledger value matching the specified key * (which should be the message that was logged using that key).</li> * </ol> */ @Override protected String handleQuery(ChaincodeStub stub, String[] args) { return null; } /** * Handles other methods applied to the ledger. * Currently, that functionality is limited to these functions: * <ul> * <li>log</li> * </ul> * <br/> * Caller expects this method to: * <ol> * <li>Use args[0] as the key for logging.</li> * <li>Use args[1] as the log message.</li> * <li>Return the logged message.</li> * </ol> */ @Override protected String handleOther(ChaincodeStub stub, String function, String[] args) { // TODO Auto-generated method stub return null; } }
apache-2.0
ranraj/code-godown
java/akka-actor-java-pi/src/main/java/akka/tutorial/first/java/Calculate.java
59
package akka.tutorial.first.java; public class Calculate {}
apache-2.0
Kri-Ol/LCG-PLE63
main.cpp
5077
#include <cassert> #include <cstdint> #include <cmath> #include <algorithm> #include <utility> #include "LCG_PLE63.hpp" #include "std_LCG_PLE63.hpp" #include "uniform_distribution.hpp" static uint64_t find_period(uint64_t N, std::ostream& os) { constexpr uint32_t BILLION = 1024U*1024U*1024U; std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> ugen; auto seed = ugen.get_seed(); N /= BILLION; // number of billions for( auto i = 0ULL; i != N; ++i ) { for( auto k = 0U; k != BILLION; ++k) { auto s = ugen(); if (s == seed) { return i*BILLION + uint64_t(k); } } os << "Passed: " << i << std::endl; } // skip the leftover return 0ULL; } static inline std::pair<float,float> kahan_summation(std::pair<float,float> s, float r) { float y = r - s.second; float t = s.first + y; return std::pair<float,float>{t, (t - s.first) - y}; } static std::pair<float,float> test_mean_sigma(uint64_t n) { std::pair<float,float> s{0.0f, 0.0f}; std::pair<float,float> d{0.0f, 0.0f}; std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> ugen; std::uniform_distribution<float> rng; for(uint64_t k = 0ULL; k != n; ++k) { float r = rng(ugen); s = kahan_summation(s, r); d = kahan_summation(d, r*r); } s.first /= float(n); d.first /= float(n); d.first = sqrt(d.first); d.first = (d.first - s.first)*(d.first + s.first); if (d.first < 0.0f) d.first = 0.0f; return std::pair<float,float>{s.first, d.first}; } static bool test_skip_ahead(int64_t ns) { assert( ns > 0LL); std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> ugen; std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> ugens{ugen}; ugens.discard(ns); // manual skip ahead uint64_t sum{0ULL}; for(int64_t k = 0; k != ns; ++k) { auto r = ugen(); sum += r; } // compare manual and fast skip return (ugen.get_seed() == ugens.get_seed()); } static bool test_skip_ahead_and_back(int64_t ns) { assert( ns > 0LL); std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> ugen; auto seed = ugen.get_seed(); ugen.discard(ns); ugen.discard(-ns); return (ugen.get_seed() == seed); } static bool test_skip_zero() { std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> ugen; auto seed = ugen.get_seed(); ugen.discard(0LL); return (ugen.get_seed() == seed); } static bool test_skip_backward(int64_t ns) { assert( ns < 0LL); std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> ugen; auto seed = ugen.get_seed(); // internal skip-ahead ugen.discard(ns); // manual skip-ahead by same number of steps uint64_t fns = abs(ns); uint64_t sum{0ULL}; for(uint64_t k = 0ULL; k != fns; ++k) { auto q = ugen(); sum += q; } return (ugen.get_seed() == seed); } static bool test_skip_backward_and_back(int64_t ns) { assert( ns < 0LL); std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> ugen; auto seed = ugen.get_seed(); ugen.discard(ns); ugen.discard(-ns); return (ugen.get_seed() == seed); } static bool test_custom_vs_std(uint64_t ns) { OTI::lcg_PLE63 rng; std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> rng_std; for(uint64_t k = 0; k != ns; ++k) { rng.sample(); auto rseed = rng.seed(); auto sseed = rng_std(); if (rseed != sseed) return false; } return true; } static bool test_skip_custom_vs_std(int64_t ns) { OTI::lcg_PLE63 rng; std::linear_congruential_engine<uint64_t, 2806196910506780709ULL, 1ULL, (1ULL<<63ULL)> rng_std; rng.skip(ns); OTI::lcg_PLE63::seed_type rseed = rng.seed(); rng_std.discard(ns); OTI::lcg_PLE63::seed_type sseed = rng_std.get_seed(); return (rseed == sseed); } int main(int argc, char* argv[]) { OTI::lcg_PLE63::result_type period = find_period(2500000000ULL, std::cout); std::cout << "Found period: " << period << std::endl; std::pair<float,float> r = test_mean_sigma(50000000ULL); std::cout << "Mean, Sigma " << r.first*2.0f << " " << r.second*12.0f << std::endl; bool q; q = test_skip_ahead(777777LL); assert(q); q = test_skip_ahead_and_back(12391LL); assert(q); test_skip_zero(); assert(q); q = test_skip_backward(-7788991LL); assert(q); q = test_skip_backward_and_back(-12391LL); assert(q); q = test_custom_vs_std(10ULL); assert(q); q = test_skip_custom_vs_std(1336789ULL); assert(q); q = test_skip_custom_vs_std(-123987LL); assert(q); return 0; }
apache-2.0
robinpercy/kops
dns-controller/pkg/watchers/pod.go
5320
/* Copyright 2019 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 watchers import ( "fmt" "time" "k8s.io/klog" "strings" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" "k8s.io/kops/dns-controller/pkg/dns" "k8s.io/kops/dns-controller/pkg/util" ) // PodController watches for Pods with dns annotations type PodController struct { util.Stoppable client kubernetes.Interface namespace string scope dns.Scope } // NewPodController creates a podController func NewPodController(client kubernetes.Interface, dns dns.Context, namespace string) (*PodController, error) { scope, err := dns.CreateScope("pod") if err != nil { return nil, fmt.Errorf("error building dns scope: %v", err) } c := &PodController{ client: client, scope: scope, namespace: namespace, } return c, nil } // Run starts the PodController. func (c *PodController) Run() { klog.Infof("starting pod controller") stopCh := c.StopChannel() go c.runWatcher(stopCh) <-stopCh klog.Infof("shutting down pod controller") } func (c *PodController) runWatcher(stopCh <-chan struct{}) { runOnce := func() (bool, error) { var listOpts metav1.ListOptions klog.V(4).Infof("querying without label filter") allKeys := c.scope.AllKeys() podList, err := c.client.CoreV1().Pods(c.namespace).List(listOpts) if err != nil { return false, fmt.Errorf("error listing pods: %v", err) } foundKeys := make(map[string]bool) for i := range podList.Items { pod := &podList.Items[i] klog.V(4).Infof("found pod: %v", pod.Name) key := c.updatePodRecords(pod) foundKeys[key] = true } for _, key := range allKeys { if !foundKeys[key] { // The pod previous existed, but no longer exists; delete it from the scope klog.V(2).Infof("removing pod not found in list: %s", key) c.scope.Replace(key, nil) } } c.scope.MarkReady() listOpts.Watch = true listOpts.ResourceVersion = podList.ResourceVersion watcher, err := c.client.CoreV1().Pods(c.namespace).Watch(listOpts) if err != nil { return false, fmt.Errorf("error watching pods: %v", err) } ch := watcher.ResultChan() for { select { case <-stopCh: klog.Infof("Got stop signal") return true, nil case event, ok := <-ch: if !ok { klog.Infof("pod watch channel closed") return false, nil } pod := event.Object.(*v1.Pod) klog.V(4).Infof("pod changed: %s %v", event.Type, pod.Name) switch event.Type { case watch.Added, watch.Modified: c.updatePodRecords(pod) case watch.Deleted: c.scope.Replace(pod.Namespace+"/"+pod.Name, nil) default: klog.Warningf("Unknown event type: %v", event.Type) } } } } for { stop, err := runOnce() if stop { return } if err != nil { klog.Warningf("Unexpected error in event watch, will retry: %v", err) time.Sleep(10 * time.Second) } } } // updatePodRecords will apply the records for the specified pod. It returns the key that was set. func (c *PodController) updatePodRecords(pod *v1.Pod) string { var records []dns.Record specExternal := pod.Annotations[AnnotationNameDNSExternal] if specExternal != "" { var aliases []string if pod.Spec.HostNetwork { if pod.Spec.NodeName != "" { aliases = append(aliases, "node/"+pod.Spec.NodeName+"/external") } } else { klog.V(4).Infof("Pod %q had %s=%s, but was not HostNetwork", pod.Name, AnnotationNameDNSExternal, specExternal) } tokens := strings.Split(specExternal, ",") for _, token := range tokens { token = strings.TrimSpace(token) fqdn := dns.EnsureDotSuffix(token) for _, alias := range aliases { records = append(records, dns.Record{ RecordType: dns.RecordTypeAlias, FQDN: fqdn, Value: alias, }) } } } else { klog.V(4).Infof("Pod %q did not have %s annotation", pod.Name, AnnotationNameDNSExternal) } specInternal := pod.Annotations[AnnotationNameDNSInternal] if specInternal != "" { var ips []string if pod.Spec.HostNetwork { if pod.Status.PodIP != "" { ips = append(ips, pod.Status.PodIP) } } else { klog.V(4).Infof("Pod %q had %s=%s, but was not HostNetwork", pod.Name, AnnotationNameDNSInternal, specInternal) } tokens := strings.Split(specInternal, ",") for _, token := range tokens { token = strings.TrimSpace(token) fqdn := dns.EnsureDotSuffix(token) for _, ip := range ips { records = append(records, dns.Record{ RecordType: dns.RecordTypeA, FQDN: fqdn, Value: ip, }) } } } else { klog.V(4).Infof("Pod %q did not have %s label", pod.Name, AnnotationNameDNSInternal) } key := pod.Namespace + "/" + pod.Name c.scope.Replace(key, records) return key }
apache-2.0
sscdotopen/giraph-compensations
src/main/java/org/apache/giraph/examples/SimpleSuperstepVertex.java
6312
/* * 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. */ package org.apache.giraph.examples; import com.google.common.collect.Maps; import org.apache.giraph.graph.BasicVertex; import org.apache.giraph.graph.BspUtils; import org.apache.giraph.graph.EdgeListVertex; import org.apache.giraph.graph.VertexReader; import org.apache.giraph.graph.VertexWriter; import org.apache.giraph.lib.TextVertexOutputFormat; import org.apache.giraph.lib.TextVertexOutputFormat.TextVertexWriter; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.log4j.Logger; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * Just a simple Vertex compute implementation that executes 3 supersteps, then * finishes. */ public class SimpleSuperstepVertex extends EdgeListVertex<LongWritable, IntWritable, FloatWritable, IntWritable> { @Override public void compute(Iterator<IntWritable> msgIterator) { if (getSuperstep() > 3) { voteToHalt(); } } /** * Simple VertexReader that supports {@link SimpleSuperstepVertex} */ public static class SimpleSuperstepVertexReader extends GeneratedVertexReader<LongWritable, IntWritable, FloatWritable, IntWritable> { /** Class logger */ private static final Logger LOG = Logger.getLogger(SimpleSuperstepVertexReader.class); @Override public boolean nextVertex() throws IOException, InterruptedException { return totalRecords > recordsRead; } public SimpleSuperstepVertexReader() { super(); } @Override public BasicVertex<LongWritable, IntWritable, FloatWritable, IntWritable> getCurrentVertex() throws IOException, InterruptedException { BasicVertex<LongWritable, IntWritable, FloatWritable, IntWritable> vertex = BspUtils.<LongWritable, IntWritable, FloatWritable, IntWritable>createVertex( configuration); long tmpId = reverseIdOrder ? ((inputSplit.getSplitIndex() + 1) * totalRecords) - recordsRead - 1 : (inputSplit.getSplitIndex() * totalRecords) + recordsRead; LongWritable vertexId = new LongWritable(tmpId); IntWritable vertexValue = new IntWritable((int) (vertexId.get() * 10)); Map<LongWritable, FloatWritable> edgeMap = Maps.newHashMap(); long destVertexId = (vertexId.get() + 1) % (inputSplit.getNumSplits() * totalRecords); float edgeValue = vertexId.get() * 100f; edgeMap.put(new LongWritable(destVertexId), new FloatWritable(edgeValue)); vertex.initialize(vertexId, vertexValue, edgeMap, null); ++recordsRead; if (LOG.isInfoEnabled()) { LOG.info("next: Return vertexId=" + vertex.getVertexId().get() + ", vertexValue=" + vertex.getVertexValue() + ", destinationId=" + destVertexId + ", edgeValue=" + edgeValue); } return vertex; } } /** * Simple VertexInputFormat that supports {@link SimpleSuperstepVertex} */ public static class SimpleSuperstepVertexInputFormat extends GeneratedVertexInputFormat<LongWritable, IntWritable, FloatWritable, IntWritable> { @Override public VertexReader<LongWritable, IntWritable, FloatWritable, IntWritable> createVertexReader(InputSplit split, TaskAttemptContext context) throws IOException { return new SimpleSuperstepVertexReader(); } } /** * Simple VertexWriter that supports {@link SimpleSuperstepVertex} */ public static class SimpleSuperstepVertexWriter extends TextVertexWriter<LongWritable, IntWritable, FloatWritable> { public SimpleSuperstepVertexWriter( RecordWriter<Text, Text> lineRecordWriter) { super(lineRecordWriter); } @Override public void writeVertex( BasicVertex<LongWritable, IntWritable, FloatWritable, ?> vertex) throws IOException, InterruptedException { getRecordWriter().write( new Text(vertex.getVertexId().toString()), new Text(vertex.getVertexValue().toString())); } } /** * Simple VertexOutputFormat that supports {@link SimpleSuperstepVertex} */ public static class SimpleSuperstepVertexOutputFormat extends TextVertexOutputFormat<LongWritable, IntWritable, FloatWritable> { @Override public VertexWriter<LongWritable, IntWritable, FloatWritable> createVertexWriter(TaskAttemptContext context) throws IOException, InterruptedException { RecordWriter<Text, Text> recordWriter = textOutputFormat.getRecordWriter(context); return new SimpleSuperstepVertexWriter(recordWriter); } } }
apache-2.0
openstack/magnum
magnum/tests/unit/api/controllers/v1/test_federation.py
18016
# 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 datetime from unittest import mock from oslo_config import cfg from oslo_utils import uuidutils from magnum.api.controllers.v1 import federation as api_federation from magnum.conductor import api as rpcapi import magnum.conf from magnum import objects from magnum.tests import base from magnum.tests.unit.api import base as api_base from magnum.tests.unit.api import utils as apiutils from magnum.tests.unit.objects import utils as obj_utils CONF = magnum.conf.CONF class TestFederationObject(base.TestCase): def test_federation_init(self): fed_dict = apiutils.federation_post_data() fed_dict['uuid'] = uuidutils.generate_uuid() federation = api_federation.Federation(**fed_dict) self.assertEqual(fed_dict['uuid'], federation.uuid) class TestListFederation(api_base.FunctionalTest): def setUp(self): super(TestListFederation, self).setUp() def test_empty(self): response = self.get_json('/federations') self.assertEqual(response['federations'], []) def test_one(self): federation = obj_utils.create_test_federation( self.context, uuid=uuidutils.generate_uuid()) response = self.get_json('/federations') self.assertEqual(federation.uuid, response['federations'][0]['uuid']) def test_get_one(self): federation = obj_utils.create_test_federation( self.context, uuid=uuidutils.generate_uuid()) response = self.get_json('/federations/%s' % federation['uuid']) self.assertTrue(response['uuid'], federation.uuid) def test_get_one_by_name(self): federation = obj_utils.create_test_federation( self.context, uuid=uuidutils.generate_uuid()) response = self.get_json('/federations/%s' % federation['name']) self.assertTrue(response['uuid'], federation.uuid) def test_get_one_by_name_not_found(self): response = self.get_json('/federations/not_found', expect_errors=True) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['errors']) def test_get_one_by_uuid(self): temp_uuid = uuidutils.generate_uuid() federation = obj_utils.create_test_federation(self.context, uuid=temp_uuid) response = self.get_json('/federations/%s' % temp_uuid) self.assertTrue(response['uuid'], federation.uuid) def test_get_one_by_uuid_not_found(self): temp_uuid = uuidutils.generate_uuid() response = self.get_json('/federations/%s' % temp_uuid, expect_errors=True) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['errors']) def test_get_one_by_name_multiple_federation(self): obj_utils.create_test_federation(self.context, name='test_federation', uuid=uuidutils.generate_uuid()) obj_utils.create_test_federation(self.context, name='test_federation', uuid=uuidutils.generate_uuid()) response = self.get_json('/federations/test_federation', expect_errors=True) self.assertEqual(409, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['errors']) def test_get_all_with_pagination_marker(self): federation_list = [] for id_ in range(4): federation = obj_utils.create_test_federation( self.context, id=id_, uuid=uuidutils.generate_uuid()) federation_list.append(federation) response = self.get_json( '/federations?limit=3&marker=%s' % federation_list[2].uuid) self.assertEqual(1, len(response['federations'])) self.assertEqual(federation_list[-1].uuid, response['federations'][0]['uuid']) def test_detail(self): federation = obj_utils.create_test_federation( self.context, uuid=uuidutils.generate_uuid()) response = self.get_json('/federations/detail') self.assertEqual(federation.uuid, response['federations'][0]["uuid"]) def test_detail_with_pagination_marker(self): federation_list = [] for id_ in range(4): federation = obj_utils.create_test_federation( self.context, id=id_, uuid=uuidutils.generate_uuid()) federation_list.append(federation) response = self.get_json( '/federations/detail?limit=3&marker=%s' % federation_list[2].uuid) self.assertEqual(1, len(response['federations'])) self.assertEqual(federation_list[-1].uuid, response['federations'][0]['uuid']) def test_detail_against_single(self): federation = obj_utils.create_test_federation( self.context, uuid=uuidutils.generate_uuid()) response = self.get_json( '/federations/%s/detail' % federation['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['errors']) def test_many(self): federation_list = [] for id_ in range(5): temp_uuid = uuidutils.generate_uuid() federation = obj_utils.create_test_federation( self.context, id=id_, uuid=temp_uuid) federation_list.append(federation.uuid) response = self.get_json('/federations') self.assertEqual(len(federation_list), len(response['federations'])) uuids = [f['uuid'] for f in response['federations']] self.assertEqual(sorted(federation_list), sorted(uuids)) def test_links(self): uuid = uuidutils.generate_uuid() obj_utils.create_test_federation(self.context, id=1, uuid=uuid) response = self.get_json('/federations/%s' % uuid) self.assertIn('links', response.keys()) self.assertEqual(2, len(response['links'])) self.assertIn(uuid, response['links'][0]['href']) for link in response['links']: bookmark = link['rel'] == 'bookmark' self.assertTrue(self.validate_link(link['href'], bookmark=bookmark)) def test_collection_links(self): for id_ in range(5): obj_utils.create_test_federation(self.context, id=id_, uuid=uuidutils.generate_uuid()) response = self.get_json('/federations/?limit=3') next_marker = response['federations'][-1]['uuid'] self.assertIn(next_marker, response['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') for id_ in range(5): obj_utils.create_test_federation(self.context, id=id_, uuid=uuidutils.generate_uuid()) response = self.get_json('/federations') self.assertEqual(3, len(response['federations'])) next_marker = response['federations'][-1]['uuid'] self.assertIn(next_marker, response['next']) class TestPatch(api_base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() p = mock.patch.object(rpcapi.API, 'federation_update_async') self.mock_federation_update = p.start() self.mock_federation_update.side_effect = \ self._sim_rpc_federation_update self.addCleanup(p.stop) def _sim_rpc_federation_update(self, federation, rollback=False): federation.save() return federation def test_member_join(self): f = obj_utils.create_test_federation( self.context, name='federation-example', uuid=uuidutils.generate_uuid(), member_ids=[]) new_member = obj_utils.create_test_cluster(self.context) response = self.patch_json( '/federations/%s' % f.uuid, [{'path': '/member_ids', 'value': new_member.uuid, 'op': 'add'}]) self.assertEqual(202, response.status_int) # make sure it was added: fed = self.get_json('/federations/%s' % f.uuid) self.assertTrue(new_member.uuid in fed['member_ids']) def test_member_unjoin(self): member = obj_utils.create_test_cluster(self.context) federation = obj_utils.create_test_federation( self.context, name='federation-example', uuid=uuidutils.generate_uuid(), member_ids=[member.uuid]) response = self.patch_json( '/federations/%s' % federation.uuid, [{'path': '/member_ids', 'value': member.uuid, 'op': 'remove'}]) self.assertEqual(202, response.status_int) # make sure it was deleted: fed = self.get_json('/federations/%s' % federation.uuid) self.assertFalse(member.uuid in fed['member_ids']) def test_join_non_existent_cluster(self): foo_uuid = uuidutils.generate_uuid() f = obj_utils.create_test_federation( self.context, name='federation-example', uuid=uuidutils.generate_uuid(), member_ids=[]) response = self.patch_json( '/federations/%s' % f.uuid, [{'path': '/member_ids', 'value': foo_uuid, 'op': 'add'}], expect_errors=True) self.assertEqual(404, response.status_int) def test_unjoin_non_existent_cluster(self): foo_uuid = uuidutils.generate_uuid() f = obj_utils.create_test_federation( self.context, name='federation-example', uuid=uuidutils.generate_uuid(), member_ids=[]) response = self.patch_json( '/federations/%s' % f.uuid, [{'path': '/member_ids', 'value': foo_uuid, 'op': 'remove'}], expect_errors=True) self.assertEqual(404, response.status_int) def test_join_cluster_already_member(self): cluster = obj_utils.create_test_cluster(self.context) f = obj_utils.create_test_federation( self.context, name='federation-example', uuid=uuidutils.generate_uuid(), member_ids=[cluster.uuid]) response = self.patch_json( '/federations/%s' % f.uuid, [{'path': '/member_ids', 'value': cluster.uuid, 'op': 'add'}], expect_errors=True) self.assertEqual(409, response.status_int) def test_unjoin_non_member_cluster(self): cluster = obj_utils.create_test_cluster(self.context) f = obj_utils.create_test_federation( self.context, name='federation-example', uuid=uuidutils.generate_uuid(), member_ids=[]) response = self.patch_json( '/federations/%s' % f.uuid, [{'path': '/member_ids', 'value': cluster.uuid, 'op': 'remove'}], expect_errors=True) self.assertEqual(404, response.status_int) class TestPost(api_base.FunctionalTest): def setUp(self): super(TestPost, self).setUp() p = mock.patch.object(rpcapi.API, 'federation_create_async') self.mock_fed_create = p.start() self.mock_fed_create.side_effect = self._simulate_federation_create self.addCleanup(p.stop) self.hostcluster = obj_utils.create_test_cluster(self.context) def _simulate_federation_create(self, federation, create_timeout): federation.create() return federation @mock.patch('oslo_utils.timeutils.utcnow') def test_create_federation(self, mock_utcnow): bdict = apiutils.federation_post_data( uuid=uuidutils.generate_uuid(), hostcluster_id=self.hostcluster.uuid) test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time response = self.post_json('/federations', bdict) self.assertEqual('application/json', response.content_type) self.assertEqual(202, response.status_int) self.assertTrue(uuidutils.is_uuid_like(response.json['uuid'])) def test_create_federation_no_hostcluster_id(self): bdict = apiutils.federation_post_data(uuid=uuidutils.generate_uuid()) del bdict['hostcluster_id'] response = self.post_json('/federations', bdict, expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['errors']) def test_create_federation_hostcluster_does_not_exist(self): bdict = apiutils.federation_post_data( uuid=uuidutils.generate_uuid(), hostcluster_id=uuidutils.generate_uuid()) response = self.post_json('/federations', bdict, expect_errors=True) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['errors']) def test_create_federation_no_dns_zone_name(self): bdict = apiutils.federation_post_data( uuid=uuidutils.generate_uuid(), hostcluster_id=self.hostcluster.uuid) del bdict['properties'] response = self.post_json('/federations', bdict, expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['errors']) def test_create_federation_generate_uuid(self): bdict = apiutils.federation_post_data( hostcluster_id=self.hostcluster.uuid) del bdict['uuid'] response = self.post_json('/federations', bdict) self.assertEqual(202, response.status_int) def test_create_federation_with_invalid_name(self): invalid_names = [ 'x' * 243, '123456', '123456test_federation', '-test_federation', '.test_federation', '_test_federation', '' ] for value in invalid_names: bdict = apiutils.federation_post_data( uuid=uuidutils.generate_uuid(), name=value, hostcluster_id=self.hostcluster.uuid) response = self.post_json('/federations', bdict, expect_errors=True) self.assertEqual('application/json', response.content_type) self.assertEqual(400, response.status_int) self.assertTrue(response.json['errors']) def test_create_federation_with_valid_name(self): valid_names = [ 'test_federation123456', 'test-federation', 'test.federation', 'testfederation.', 'testfederation-', 'testfederation_', 'test.-_federation', 'Testfederation' ] for value in valid_names: bdict = apiutils.federation_post_data( name=value, hostcluster_id=self.hostcluster.uuid) bdict['uuid'] = uuidutils.generate_uuid() response = self.post_json('/federations', bdict) self.assertEqual(202, response.status_int) def test_create_federation_without_name(self): bdict = apiutils.federation_post_data( uuid=uuidutils.generate_uuid(), hostcluster_id=self.hostcluster.uuid) del bdict['name'] response = self.post_json('/federations', bdict) self.assertEqual(202, response.status_int) class TestDelete(api_base.FunctionalTest): def setUp(self): super(TestDelete, self).setUp() self.federation = obj_utils.create_test_federation( self.context, name='federation-example', uuid=uuidutils.generate_uuid()) p = mock.patch.object(rpcapi.API, 'federation_delete_async') self.mock_federation_delete = p.start() self.mock_federation_delete.side_effect = \ self._simulate_federation_delete self.addCleanup(p.stop) def _simulate_federation_delete(self, federation_uuid): federation = objects.Federation.get_by_uuid(self.context, federation_uuid) federation.destroy() def test_delete_federation(self): self.delete('/federations/%s' % self.federation.uuid) response = self.get_json('/federations/%s' % self.federation.uuid, expect_errors=True) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['errors']) def test_delete_federation_not_found(self): delete = self.delete('/federations/%s' % uuidutils.generate_uuid(), expect_errors=True) self.assertEqual(404, delete.status_int) self.assertEqual('application/json', delete.content_type) self.assertTrue(delete.json['errors']) def test_delete_federation_with_name(self): delete = self.delete('/federations/%s' % self.federation.name) self.assertEqual(204, delete.status_int) def test_delete_federation_with_name_not_found(self): delete = self.delete('/federations/%s' % 'foo', expect_errors=True) self.assertEqual(404, delete.status_int) self.assertEqual('application/json', delete.content_type) self.assertTrue(delete.json['errors'])
apache-2.0
evgrud/TypeScript
src/lib/dom.generated.d.ts
533162
///////////////////////////// /// IE DOM APIs ///////////////////////////// interface Algorithm { name?: string; } interface AriaRequestEventInit extends EventInit { attributeName?: string; attributeValue?: string; } interface ClipboardEventInit extends EventInit { data?: string; dataType?: string; } interface CommandEventInit extends EventInit { commandName?: string; detail?: string; } interface CompositionEventInit extends UIEventInit { data?: string; } interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { arrayOfDomainStrings?: string[]; } interface CustomEventInit extends EventInit { detail?: any; } interface DeviceAccelerationDict { x?: number; y?: number; z?: number; } interface DeviceRotationRateDict { alpha?: number; beta?: number; gamma?: number; } interface EventInit { bubbles?: boolean; cancelable?: boolean; } interface ExceptionInformation { domain?: string; } interface FocusEventInit extends UIEventInit { relatedTarget?: EventTarget; } interface HashChangeEventInit extends EventInit { newURL?: string; oldURL?: string; } interface KeyAlgorithm { name?: string; } interface KeyboardEventInit extends SharedKeyboardAndMouseEventInit { key?: string; location?: number; repeat?: boolean; } interface MouseEventInit extends SharedKeyboardAndMouseEventInit { screenX?: number; screenY?: number; clientX?: number; clientY?: number; button?: number; buttons?: number; relatedTarget?: EventTarget; } interface MsZoomToOptions { contentX?: number; contentY?: number; viewportX?: string; viewportY?: string; scaleFactor?: number; animate?: string; } interface MutationObserverInit { childList?: boolean; attributes?: boolean; characterData?: boolean; subtree?: boolean; attributeOldValue?: boolean; characterDataOldValue?: boolean; attributeFilter?: string[]; } interface ObjectURLOptions { oneTimeOnly?: boolean; } interface PointerEventInit extends MouseEventInit { pointerId?: number; width?: number; height?: number; pressure?: number; tiltX?: number; tiltY?: number; pointerType?: string; isPrimary?: boolean; } interface PositionOptions { enableHighAccuracy?: boolean; timeout?: number; maximumAge?: number; } interface SharedKeyboardAndMouseEventInit extends UIEventInit { ctrlKey?: boolean; shiftKey?: boolean; altKey?: boolean; metaKey?: boolean; keyModifierStateAltGraph?: boolean; keyModifierStateCapsLock?: boolean; keyModifierStateFn?: boolean; keyModifierStateFnLock?: boolean; keyModifierStateHyper?: boolean; keyModifierStateNumLock?: boolean; keyModifierStateOS?: boolean; keyModifierStateScrollLock?: boolean; keyModifierStateSuper?: boolean; keyModifierStateSymbol?: boolean; keyModifierStateSymbolLock?: boolean; } interface StoreExceptionsInformation extends ExceptionInformation { siteName?: string; explanationString?: string; detailURI?: string; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { arrayOfDomainStrings?: string[]; } interface UIEventInit extends EventInit { view?: Window; detail?: number; } interface WebGLContextAttributes { alpha?: boolean; depth?: boolean; stencil?: boolean; antialias?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; } interface WebGLContextEventInit extends EventInit { statusMessage?: string; } interface WheelEventInit extends MouseEventInit { deltaX?: number; deltaY?: number; deltaZ?: number; deltaMode?: number; } interface EventListener { (evt: Event): void; } interface ANGLE_instanced_arrays { drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; vertexAttribDivisorANGLE(index: number, divisor: number): void; VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } declare var ANGLE_instanced_arrays: { prototype: ANGLE_instanced_arrays; new(): ANGLE_instanced_arrays; VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; } interface AnalyserNode extends AudioNode { fftSize: number; frequencyBinCount: number; maxDecibels: number; minDecibels: number; smoothingTimeConstant: number; getByteFrequencyData(array: Uint8Array): void; getByteTimeDomainData(array: Uint8Array): void; getFloatFrequencyData(array: Float32Array): void; getFloatTimeDomainData(array: Float32Array): void; } declare var AnalyserNode: { prototype: AnalyserNode; new(): AnalyserNode; } interface AnimationEvent extends Event { animationName: string; elapsedTime: number; initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; } declare var AnimationEvent: { prototype: AnimationEvent; new(): AnimationEvent; } interface ApplicationCache extends EventTarget { oncached: (ev: Event) => any; onchecking: (ev: Event) => any; ondownloading: (ev: Event) => any; onerror: (ev: Event) => any; onnoupdate: (ev: Event) => any; onobsolete: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; onupdateready: (ev: Event) => any; status: number; abort(): void; swapCache(): void; update(): void; CHECKING: number; DOWNLOADING: number; IDLE: number; OBSOLETE: number; UNCACHED: number; UPDATEREADY: number; addEventListener(type: "cached", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "checking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "downloading", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "noupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "obsolete", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "updateready", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var ApplicationCache: { prototype: ApplicationCache; new(): ApplicationCache; CHECKING: number; DOWNLOADING: number; IDLE: number; OBSOLETE: number; UNCACHED: number; UPDATEREADY: number; } interface AriaRequestEvent extends Event { attributeName: string; attributeValue: string; } declare var AriaRequestEvent: { prototype: AriaRequestEvent; new(type: string, eventInitDict?: AriaRequestEventInit): AriaRequestEvent; } interface Attr extends Node { name: string; ownerElement: Element; specified: boolean; value: string; } declare var Attr: { prototype: Attr; new(): Attr; } interface AudioBuffer { duration: number; length: number; numberOfChannels: number; sampleRate: number; getChannelData(channel: number): Float32Array; } declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; } interface AudioBufferSourceNode extends AudioNode { buffer: AudioBuffer; loop: boolean; loopEnd: number; loopStart: number; onended: (ev: Event) => any; playbackRate: AudioParam; start(when?: number, offset?: number, duration?: number): void; stop(when?: number): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; } interface AudioContext extends EventTarget { currentTime: number; destination: AudioDestinationNode; listener: AudioListener; sampleRate: number; state: string; createAnalyser(): AnalyserNode; createBiquadFilter(): BiquadFilterNode; createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; createBufferSource(): AudioBufferSourceNode; createChannelMerger(numberOfInputs?: number): ChannelMergerNode; createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; createConvolver(): ConvolverNode; createDelay(maxDelayTime?: number): DelayNode; createDynamicsCompressor(): DynamicsCompressorNode; createGain(): GainNode; createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; createOscillator(): OscillatorNode; createPanner(): PannerNode; createPeriodicWave(real: Float32Array, imag: Float32Array): PeriodicWave; createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; createStereoPanner(): StereoPannerNode; createWaveShaper(): WaveShaperNode; decodeAudioData(audioData: ArrayBuffer, successCallback: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): void; } declare var AudioContext: { prototype: AudioContext; new(): AudioContext; } interface AudioDestinationNode extends AudioNode { maxChannelCount: number; } declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; } interface AudioListener { dopplerFactor: number; speedOfSound: number; setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; setPosition(x: number, y: number, z: number): void; setVelocity(x: number, y: number, z: number): void; } declare var AudioListener: { prototype: AudioListener; new(): AudioListener; } interface AudioNode extends EventTarget { channelCount: number; channelCountMode: string; channelInterpretation: string; context: AudioContext; numberOfInputs: number; numberOfOutputs: number; connect(destination: AudioNode, output?: number, input?: number): void; disconnect(output?: number): void; disconnect(destination: AudioNode, output?: number, input?: number): void; disconnect(destination: AudioParam, output?: number): void; } declare var AudioNode: { prototype: AudioNode; new(): AudioNode; } interface AudioParam { defaultValue: number; value: number; cancelScheduledValues(startTime: number): void; exponentialRampToValueAtTime(value: number, endTime: number): void; linearRampToValueAtTime(value: number, endTime: number): void; setTargetAtTime(target: number, startTime: number, timeConstant: number): void; setValueAtTime(value: number, startTime: number): void; setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; } declare var AudioParam: { prototype: AudioParam; new(): AudioParam; } interface AudioProcessingEvent extends Event { inputBuffer: AudioBuffer; outputBuffer: AudioBuffer; playbackTime: number; } declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; } interface AudioTrack { enabled: boolean; id: string; kind: string; label: string; language: string; sourceBuffer: SourceBuffer; } declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; } interface AudioTrackList extends EventTarget { length: number; onaddtrack: (ev: TrackEvent) => any; onchange: (ev: Event) => any; onremovetrack: (ev: TrackEvent) => any; getTrackById(id: string): AudioTrack; item(index: number): AudioTrack; addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "removetrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [index: number]: AudioTrack; } declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; } interface BarProp { visible: boolean; } declare var BarProp: { prototype: BarProp; new(): BarProp; } interface BeforeUnloadEvent extends Event { returnValue: any; } declare var BeforeUnloadEvent: { prototype: BeforeUnloadEvent; new(): BeforeUnloadEvent; } interface BiquadFilterNode extends AudioNode { Q: AudioParam; detune: AudioParam; frequency: AudioParam; gain: AudioParam; type: string; getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; } declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; } interface Blob { size: number; type: string; msClose(): void; msDetachStream(): any; slice(start?: number, end?: number, contentType?: string): Blob; } declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; } interface CDATASection extends Text { } declare var CDATASection: { prototype: CDATASection; new(): CDATASection; } interface CSS { supports(property: string, value?: string): boolean; } declare var CSS: CSS; interface CSSConditionRule extends CSSGroupingRule { conditionText: string; } declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; } interface CSSFontFaceRule extends CSSRule { style: CSSStyleDeclaration; } declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; } interface CSSGroupingRule extends CSSRule { cssRules: CSSRuleList; deleteRule(index?: number): void; insertRule(rule: string, index?: number): number; } declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; } interface CSSImportRule extends CSSRule { href: string; media: MediaList; styleSheet: CSSStyleSheet; } declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; } interface CSSKeyframeRule extends CSSRule { keyText: string; style: CSSStyleDeclaration; } declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; } interface CSSKeyframesRule extends CSSRule { cssRules: CSSRuleList; name: string; appendRule(rule: string): void; deleteRule(rule: string): void; findRule(rule: string): CSSKeyframeRule; } declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; } interface CSSMediaRule extends CSSConditionRule { media: MediaList; } declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; } interface CSSNamespaceRule extends CSSRule { namespaceURI: string; prefix: string; } declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; } interface CSSPageRule extends CSSRule { pseudoClass: string; selector: string; selectorText: string; style: CSSStyleDeclaration; } declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; } interface CSSRule { cssText: string; parentRule: CSSRule; parentStyleSheet: CSSStyleSheet; type: number; CHARSET_RULE: number; FONT_FACE_RULE: number; IMPORT_RULE: number; KEYFRAMES_RULE: number; KEYFRAME_RULE: number; MEDIA_RULE: number; NAMESPACE_RULE: number; PAGE_RULE: number; STYLE_RULE: number; SUPPORTS_RULE: number; UNKNOWN_RULE: number; VIEWPORT_RULE: number; } declare var CSSRule: { prototype: CSSRule; new(): CSSRule; CHARSET_RULE: number; FONT_FACE_RULE: number; IMPORT_RULE: number; KEYFRAMES_RULE: number; KEYFRAME_RULE: number; MEDIA_RULE: number; NAMESPACE_RULE: number; PAGE_RULE: number; STYLE_RULE: number; SUPPORTS_RULE: number; UNKNOWN_RULE: number; VIEWPORT_RULE: number; } interface CSSRuleList { length: number; item(index: number): CSSRule; [index: number]: CSSRule; } declare var CSSRuleList: { prototype: CSSRuleList; new(): CSSRuleList; } interface CSSStyleDeclaration { alignContent: string; alignItems: string; alignSelf: string; alignmentBaseline: string; animation: string; animationDelay: string; animationDirection: string; animationDuration: string; animationFillMode: string; animationIterationCount: string; animationName: string; animationPlayState: string; animationTimingFunction: string; backfaceVisibility: string; background: string; backgroundAttachment: string; backgroundClip: string; backgroundColor: string; backgroundImage: string; backgroundOrigin: string; backgroundPosition: string; backgroundPositionX: string; backgroundPositionY: string; backgroundRepeat: string; backgroundSize: string; baselineShift: string; border: string; borderBottom: string; borderBottomColor: string; borderBottomLeftRadius: string; borderBottomRightRadius: string; borderBottomStyle: string; borderBottomWidth: string; borderCollapse: string; borderColor: string; borderImage: string; borderImageOutset: string; borderImageRepeat: string; borderImageSlice: string; borderImageSource: string; borderImageWidth: string; borderLeft: string; borderLeftColor: string; borderLeftStyle: string; borderLeftWidth: string; borderRadius: string; borderRight: string; borderRightColor: string; borderRightStyle: string; borderRightWidth: string; borderSpacing: string; borderStyle: string; borderTop: string; borderTopColor: string; borderTopLeftRadius: string; borderTopRightRadius: string; borderTopStyle: string; borderTopWidth: string; borderWidth: string; bottom: string; boxShadow: string; boxSizing: string; breakAfter: string; breakBefore: string; breakInside: string; captionSide: string; clear: string; clip: string; clipPath: string; clipRule: string; color: string; colorInterpolationFilters: string; columnCount: any; columnFill: string; columnGap: any; columnRule: string; columnRuleColor: any; columnRuleStyle: string; columnRuleWidth: any; columnSpan: string; columnWidth: any; columns: string; content: string; counterIncrement: string; counterReset: string; cssFloat: string; cssText: string; cursor: string; direction: string; display: string; dominantBaseline: string; emptyCells: string; enableBackground: string; fill: string; fillOpacity: string; fillRule: string; filter: string; flex: string; flexBasis: string; flexDirection: string; flexFlow: string; flexGrow: string; flexShrink: string; flexWrap: string; floodColor: string; floodOpacity: string; font: string; fontFamily: string; fontFeatureSettings: string; fontSize: string; fontSizeAdjust: string; fontStretch: string; fontStyle: string; fontVariant: string; fontWeight: string; glyphOrientationHorizontal: string; glyphOrientationVertical: string; height: string; imeMode: string; justifyContent: string; kerning: string; left: string; length: number; letterSpacing: string; lightingColor: string; lineHeight: string; listStyle: string; listStyleImage: string; listStylePosition: string; listStyleType: string; margin: string; marginBottom: string; marginLeft: string; marginRight: string; marginTop: string; marker: string; markerEnd: string; markerMid: string; markerStart: string; mask: string; maxHeight: string; maxWidth: string; minHeight: string; minWidth: string; msContentZoomChaining: string; msContentZoomLimit: string; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: string; msContentZoomSnapPoints: string; msContentZoomSnapType: string; msContentZooming: string; msFlowFrom: string; msFlowInto: string; msFontFeatureSettings: string; msGridColumn: any; msGridColumnAlign: string; msGridColumnSpan: any; msGridColumns: string; msGridRow: any; msGridRowAlign: string; msGridRowSpan: any; msGridRows: string; msHighContrastAdjust: string; msHyphenateLimitChars: string; msHyphenateLimitLines: any; msHyphenateLimitZone: any; msHyphens: string; msImeAlign: string; msOverflowStyle: string; msScrollChaining: string; msScrollLimit: string; msScrollLimitXMax: any; msScrollLimitXMin: any; msScrollLimitYMax: any; msScrollLimitYMin: any; msScrollRails: string; msScrollSnapPointsX: string; msScrollSnapPointsY: string; msScrollSnapType: string; msScrollSnapX: string; msScrollSnapY: string; msScrollTranslation: string; msTextCombineHorizontal: string; msTextSizeAdjust: any; msTouchAction: string; msTouchSelect: string; msUserSelect: string; msWrapFlow: string; msWrapMargin: any; msWrapThrough: string; opacity: string; order: string; orphans: string; outline: string; outlineColor: string; outlineStyle: string; outlineWidth: string; overflow: string; overflowX: string; overflowY: string; padding: string; paddingBottom: string; paddingLeft: string; paddingRight: string; paddingTop: string; pageBreakAfter: string; pageBreakBefore: string; pageBreakInside: string; parentRule: CSSRule; perspective: string; perspectiveOrigin: string; pointerEvents: string; position: string; quotes: string; right: string; rubyAlign: string; rubyOverhang: string; rubyPosition: string; stopColor: string; stopOpacity: string; stroke: string; strokeDasharray: string; strokeDashoffset: string; strokeLinecap: string; strokeLinejoin: string; strokeMiterlimit: string; strokeOpacity: string; strokeWidth: string; tableLayout: string; textAlign: string; textAlignLast: string; textAnchor: string; textDecoration: string; textFillColor: string; textIndent: string; textJustify: string; textKashida: string; textKashidaSpace: string; textOverflow: string; textShadow: string; textTransform: string; textUnderlinePosition: string; top: string; touchAction: string; transform: string; transformOrigin: string; transformStyle: string; transition: string; transitionDelay: string; transitionDuration: string; transitionProperty: string; transitionTimingFunction: string; unicodeBidi: string; verticalAlign: string; visibility: string; webkitAlignContent: string; webkitAlignItems: string; webkitAlignSelf: string; webkitAnimation: string; webkitAnimationDelay: string; webkitAnimationDirection: string; webkitAnimationDuration: string; webkitAnimationFillMode: string; webkitAnimationIterationCount: string; webkitAnimationName: string; webkitAnimationPlayState: string; webkitAnimationTimingFunction: string; webkitAppearance: string; webkitBackfaceVisibility: string; webkitBackground: string; webkitBackgroundAttachment: string; webkitBackgroundClip: string; webkitBackgroundColor: string; webkitBackgroundImage: string; webkitBackgroundOrigin: string; webkitBackgroundPosition: string; webkitBackgroundPositionX: string; webkitBackgroundPositionY: string; webkitBackgroundRepeat: string; webkitBackgroundSize: string; webkitBorderBottomLeftRadius: string; webkitBorderBottomRightRadius: string; webkitBorderImage: string; webkitBorderImageOutset: string; webkitBorderImageRepeat: string; webkitBorderImageSlice: string; webkitBorderImageSource: string; webkitBorderImageWidth: string; webkitBorderRadius: string; webkitBorderTopLeftRadius: string; webkitBorderTopRightRadius: string; webkitBoxAlign: string; webkitBoxDirection: string; webkitBoxFlex: string; webkitBoxOrdinalGroup: string; webkitBoxOrient: string; webkitBoxPack: string; webkitBoxSizing: string; webkitColumnBreakAfter: string; webkitColumnBreakBefore: string; webkitColumnBreakInside: string; webkitColumnCount: any; webkitColumnGap: any; webkitColumnRule: string; webkitColumnRuleColor: any; webkitColumnRuleStyle: string; webkitColumnRuleWidth: any; webkitColumnSpan: string; webkitColumnWidth: any; webkitColumns: string; webkitFilter: string; webkitFlex: string; webkitFlexBasis: string; webkitFlexDirection: string; webkitFlexFlow: string; webkitFlexGrow: string; webkitFlexShrink: string; webkitFlexWrap: string; webkitJustifyContent: string; webkitOrder: string; webkitPerspective: string; webkitPerspectiveOrigin: string; webkitTapHighlightColor: string; webkitTextFillColor: string; webkitTextSizeAdjust: any; webkitTransform: string; webkitTransformOrigin: string; webkitTransformStyle: string; webkitTransition: string; webkitTransitionDelay: string; webkitTransitionDuration: string; webkitTransitionProperty: string; webkitTransitionTimingFunction: string; webkitUserSelect: string; webkitWritingMode: string; whiteSpace: string; widows: string; width: string; wordBreak: string; wordSpacing: string; wordWrap: string; writingMode: string; zIndex: string; zoom: string; getPropertyPriority(propertyName: string): string; getPropertyValue(propertyName: string): string; item(index: number): string; removeProperty(propertyName: string): string; setProperty(propertyName: string, value: string, priority?: string): void; [index: number]: string; } declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; } interface CSSStyleRule extends CSSRule { readOnly: boolean; selectorText: string; style: CSSStyleDeclaration; } declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; } interface CSSStyleSheet extends StyleSheet { cssRules: CSSRuleList; cssText: string; href: string; id: string; imports: StyleSheetList; isAlternate: boolean; isPrefAlternate: boolean; ownerRule: CSSRule; owningElement: Element; pages: StyleSheetPageList; readOnly: boolean; rules: CSSRuleList; addImport(bstrURL: string, lIndex?: number): number; addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; deleteRule(index?: number): void; insertRule(rule: string, index?: number): number; removeImport(lIndex: number): void; removeRule(lIndex: number): void; } declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; } interface CSSSupportsRule extends CSSConditionRule { } declare var CSSSupportsRule: { prototype: CSSSupportsRule; new(): CSSSupportsRule; } interface CanvasGradient { addColorStop(offset: number, color: string): void; } declare var CanvasGradient: { prototype: CanvasGradient; new(): CanvasGradient; } interface CanvasPattern { } declare var CanvasPattern: { prototype: CanvasPattern; new(): CanvasPattern; } interface CanvasRenderingContext2D { canvas: HTMLCanvasElement; fillStyle: string | CanvasGradient | CanvasPattern; font: string; globalAlpha: number; globalCompositeOperation: string; lineCap: string; lineDashOffset: number; lineJoin: string; lineWidth: number; miterLimit: number; msFillRule: string; msImageSmoothingEnabled: boolean; shadowBlur: number; shadowColor: string; shadowOffsetX: number; shadowOffsetY: number; strokeStyle: string | CanvasGradient | CanvasPattern; textAlign: string; textBaseline: string; arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; beginPath(): void; bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; clearRect(x: number, y: number, w: number, h: number): void; clip(fillRule?: string): void; closePath(): void; createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; fill(fillRule?: string): void; fillRect(x: number, y: number, w: number, h: number): void; fillText(text: string, x: number, y: number, maxWidth?: number): void; getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; getLineDash(): number[]; isPointInPath(x: number, y: number, fillRule?: string): boolean; lineTo(x: number, y: number): void; measureText(text: string): TextMetrics; moveTo(x: number, y: number): void; putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; rect(x: number, y: number, w: number, h: number): void; restore(): void; rotate(angle: number): void; save(): void; scale(x: number, y: number): void; setLineDash(segments: number[]): void; setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; stroke(): void; strokeRect(x: number, y: number, w: number, h: number): void; strokeText(text: string, x: number, y: number, maxWidth?: number): void; transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; translate(x: number, y: number): void; } declare var CanvasRenderingContext2D: { prototype: CanvasRenderingContext2D; new(): CanvasRenderingContext2D; } interface ChannelMergerNode extends AudioNode { } declare var ChannelMergerNode: { prototype: ChannelMergerNode; new(): ChannelMergerNode; } interface ChannelSplitterNode extends AudioNode { } declare var ChannelSplitterNode: { prototype: ChannelSplitterNode; new(): ChannelSplitterNode; } interface CharacterData extends Node, ChildNode { data: string; length: number; appendData(arg: string): void; deleteData(offset: number, count: number): void; insertData(offset: number, arg: string): void; replaceData(offset: number, count: number, arg: string): void; substringData(offset: number, count: number): string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var CharacterData: { prototype: CharacterData; new(): CharacterData; } interface ClientRect { bottom: number; height: number; left: number; right: number; top: number; width: number; } declare var ClientRect: { prototype: ClientRect; new(): ClientRect; } interface ClientRectList { length: number; item(index: number): ClientRect; [index: number]: ClientRect; } declare var ClientRectList: { prototype: ClientRectList; new(): ClientRectList; } interface ClipboardEvent extends Event { clipboardData: DataTransfer; } declare var ClipboardEvent: { prototype: ClipboardEvent; new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; } interface CloseEvent extends Event { code: number; reason: string; wasClean: boolean; initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; } declare var CloseEvent: { prototype: CloseEvent; new(): CloseEvent; } interface CommandEvent extends Event { commandName: string; detail: string; } declare var CommandEvent: { prototype: CommandEvent; new(type: string, eventInitDict?: CommandEventInit): CommandEvent; } interface Comment extends CharacterData { text: string; } declare var Comment: { prototype: Comment; new(): Comment; } interface CompositionEvent extends UIEvent { data: string; locale: string; initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; } declare var CompositionEvent: { prototype: CompositionEvent; new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; } interface Console { assert(test?: boolean, message?: string, ...optionalParams: any[]): void; clear(): void; count(countTitle?: string): void; debug(message?: string, ...optionalParams: any[]): void; dir(value?: any, ...optionalParams: any[]): void; dirxml(value: any): void; error(message?: any, ...optionalParams: any[]): void; group(groupTitle?: string): void; groupCollapsed(groupTitle?: string): void; groupEnd(): void; info(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; msIsIndependentlyComposed(element: Element): boolean; profile(reportName?: string): void; profileEnd(): void; select(element: Element): void; time(timerName?: string): void; timeEnd(timerName?: string): void; trace(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; } declare var Console: { prototype: Console; new(): Console; } interface ConvolverNode extends AudioNode { buffer: AudioBuffer; normalize: boolean; } declare var ConvolverNode: { prototype: ConvolverNode; new(): ConvolverNode; } interface Coordinates { accuracy: number; altitude: number; altitudeAccuracy: number; heading: number; latitude: number; longitude: number; speed: number; } declare var Coordinates: { prototype: Coordinates; new(): Coordinates; } interface Crypto extends Object, RandomSource { subtle: SubtleCrypto; } declare var Crypto: { prototype: Crypto; new(): Crypto; } interface CryptoKey { algorithm: KeyAlgorithm; extractable: boolean; type: string; usages: string[]; } declare var CryptoKey: { prototype: CryptoKey; new(): CryptoKey; } interface CryptoKeyPair { privateKey: CryptoKey; publicKey: CryptoKey; } declare var CryptoKeyPair: { prototype: CryptoKeyPair; new(): CryptoKeyPair; } interface CustomEvent extends Event { detail: any; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; } declare var CustomEvent: { prototype: CustomEvent; new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; } interface DOMError { name: string; toString(): string; } declare var DOMError: { prototype: DOMError; new(): DOMError; } interface DOMException { code: number; message: string; name: string; toString(): string; ABORT_ERR: number; DATA_CLONE_ERR: number; DOMSTRING_SIZE_ERR: number; HIERARCHY_REQUEST_ERR: number; INDEX_SIZE_ERR: number; INUSE_ATTRIBUTE_ERR: number; INVALID_ACCESS_ERR: number; INVALID_CHARACTER_ERR: number; INVALID_MODIFICATION_ERR: number; INVALID_NODE_TYPE_ERR: number; INVALID_STATE_ERR: number; NAMESPACE_ERR: number; NETWORK_ERR: number; NOT_FOUND_ERR: number; NOT_SUPPORTED_ERR: number; NO_DATA_ALLOWED_ERR: number; NO_MODIFICATION_ALLOWED_ERR: number; PARSE_ERR: number; QUOTA_EXCEEDED_ERR: number; SECURITY_ERR: number; SERIALIZE_ERR: number; SYNTAX_ERR: number; TIMEOUT_ERR: number; TYPE_MISMATCH_ERR: number; URL_MISMATCH_ERR: number; VALIDATION_ERR: number; WRONG_DOCUMENT_ERR: number; } declare var DOMException: { prototype: DOMException; new(): DOMException; ABORT_ERR: number; DATA_CLONE_ERR: number; DOMSTRING_SIZE_ERR: number; HIERARCHY_REQUEST_ERR: number; INDEX_SIZE_ERR: number; INUSE_ATTRIBUTE_ERR: number; INVALID_ACCESS_ERR: number; INVALID_CHARACTER_ERR: number; INVALID_MODIFICATION_ERR: number; INVALID_NODE_TYPE_ERR: number; INVALID_STATE_ERR: number; NAMESPACE_ERR: number; NETWORK_ERR: number; NOT_FOUND_ERR: number; NOT_SUPPORTED_ERR: number; NO_DATA_ALLOWED_ERR: number; NO_MODIFICATION_ALLOWED_ERR: number; PARSE_ERR: number; QUOTA_EXCEEDED_ERR: number; SECURITY_ERR: number; SERIALIZE_ERR: number; SYNTAX_ERR: number; TIMEOUT_ERR: number; TYPE_MISMATCH_ERR: number; URL_MISMATCH_ERR: number; VALIDATION_ERR: number; WRONG_DOCUMENT_ERR: number; } interface DOMImplementation { createDocument(namespaceURI: string, qualifiedName: string, doctype: DocumentType): Document; createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; createHTMLDocument(title: string): Document; hasFeature(feature: string, version: string): boolean; } declare var DOMImplementation: { prototype: DOMImplementation; new(): DOMImplementation; } interface DOMParser { parseFromString(source: string, mimeType: string): Document; } declare var DOMParser: { prototype: DOMParser; new(): DOMParser; } interface DOMSettableTokenList extends DOMTokenList { value: string; } declare var DOMSettableTokenList: { prototype: DOMSettableTokenList; new(): DOMSettableTokenList; } interface DOMStringList { length: number; contains(str: string): boolean; item(index: number): string; [index: number]: string; } declare var DOMStringList: { prototype: DOMStringList; new(): DOMStringList; } interface DOMStringMap { [name: string]: string; } declare var DOMStringMap: { prototype: DOMStringMap; new(): DOMStringMap; } interface DOMTokenList { length: number; add(...token: string[]): void; contains(token: string): boolean; item(index: number): string; remove(...token: string[]): void; toString(): string; toggle(token: string, force?: boolean): boolean; [index: number]: string; } declare var DOMTokenList: { prototype: DOMTokenList; new(): DOMTokenList; } interface DataCue extends TextTrackCue { data: ArrayBuffer; } declare var DataCue: { prototype: DataCue; new(): DataCue; } interface DataTransfer { dropEffect: string; effectAllowed: string; files: FileList; items: DataTransferItemList; types: DOMStringList; clearData(format?: string): boolean; getData(format: string): string; setData(format: string, data: string): boolean; } declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; } interface DataTransferItem { kind: string; type: string; getAsFile(): File; getAsString(_callback: FunctionStringCallback): void; } declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; } interface DataTransferItemList { length: number; add(data: File): DataTransferItem; clear(): void; item(index: number): DataTransferItem; remove(index: number): void; [index: number]: DataTransferItem; } declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; } interface DeferredPermissionRequest { id: number; type: string; uri: string; allow(): void; deny(): void; } declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; } interface DelayNode extends AudioNode { delayTime: AudioParam; } declare var DelayNode: { prototype: DelayNode; new(): DelayNode; } interface DeviceAcceleration { x: number; y: number; z: number; } declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; } interface DeviceMotionEvent extends Event { acceleration: DeviceAcceleration; accelerationIncludingGravity: DeviceAcceleration; interval: number; rotationRate: DeviceRotationRate; initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict, accelerationIncludingGravity: DeviceAccelerationDict, rotationRate: DeviceRotationRateDict, interval: number): void; } declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(): DeviceMotionEvent; } interface DeviceOrientationEvent extends Event { absolute: boolean; alpha: number; beta: number; gamma: number; initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number, beta: number, gamma: number, absolute: boolean): void; } declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(): DeviceOrientationEvent; } interface DeviceRotationRate { alpha: number; beta: number; gamma: number; } declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; } interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { /** * Sets or gets the URL for the current document. */ URL: string; /** * Gets the URL for the document, stripped of any character encoding. */ URLUnencoded: string; /** * Gets the object that has the focus when the parent document has focus. */ activeElement: Element; /** * Sets or gets the color of all active links in the document. */ alinkColor: string; /** * Returns a reference to the collection of elements contained by the object. */ all: HTMLCollection; /** * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. */ anchors: HTMLCollection; /** * Retrieves a collection of all applet objects in the document. */ applets: HTMLCollection; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ bgColor: string; /** * Specifies the beginning and end of the document body. */ body: HTMLElement; characterSet: string; /** * Gets or sets the character set used to encode the object. */ charset: string; /** * Gets a value that indicates whether standards-compliant mode is switched on for the object. */ compatMode: string; cookie: string; /** * Gets the default character set from the current regional language settings. */ defaultCharset: string; defaultView: Window; /** * Sets or gets a value that indicates whether the document can be edited. */ designMode: string; /** * Sets or retrieves a value that indicates the reading order of the object. */ dir: string; /** * Gets an object representing the document type declaration associated with the current document. */ doctype: DocumentType; /** * Gets a reference to the root node of the document. */ documentElement: HTMLElement; /** * Sets or gets the security domain of the document. */ domain: string; /** * Retrieves a collection of all embed objects in the document. */ embeds: HTMLCollection; /** * Sets or gets the foreground (text) color of the document. */ fgColor: string; /** * Retrieves a collection, in source order, of all form objects in the document. */ forms: HTMLCollection; fullscreenElement: Element; fullscreenEnabled: boolean; head: HTMLHeadElement; hidden: boolean; /** * Retrieves a collection, in source order, of img objects in the document. */ images: HTMLCollection; /** * Gets the implementation object of the current document. */ implementation: DOMImplementation; /** * Returns the character encoding used to create the webpage that is loaded into the document object. */ inputEncoding: string; /** * Gets the date that the page was last modified, if the page supplies one. */ lastModified: string; /** * Sets or gets the color of the document links. */ linkColor: string; /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. */ links: HTMLCollection; /** * Contains information about the current URL. */ location: Location; media: string; msCSSOMElementFloatMetrics: boolean; msCapsLockWarningOff: boolean; msHidden: boolean; msVisibilityState: string; /** * Fires when the user aborts the download. * @param ev The event. */ onabort: (ev: Event) => any; /** * Fires when the object is set as the active element. * @param ev The event. */ onactivate: (ev: UIEvent) => any; /** * Fires immediately before the object is set as the active element. * @param ev The event. */ onbeforeactivate: (ev: UIEvent) => any; /** * Fires immediately before the activeElement is changed from the current object to another object in the parent document. * @param ev The event. */ onbeforedeactivate: (ev: UIEvent) => any; /** * Fires when the object loses the input focus. * @param ev The focus event. */ onblur: (ev: FocusEvent) => any; /** * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ onchange: (ev: Event) => any; /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ onclick: (ev: MouseEvent) => any; /** * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ oncontextmenu: (ev: PointerEvent) => any; /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ ondblclick: (ev: MouseEvent) => any; /** * Fires when the activeElement is changed from the current object to another object in the parent document. * @param ev The UI Event */ ondeactivate: (ev: UIEvent) => any; /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ ondrag: (ev: DragEvent) => any; /** * Fires on the source object when the user releases the mouse at the close of a drag operation. * @param ev The event. */ ondragend: (ev: DragEvent) => any; /** * Fires on the target element when the user drags the object to a valid drop target. * @param ev The drag event. */ ondragenter: (ev: DragEvent) => any; /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ ondragleave: (ev: DragEvent) => any; /** * Fires on the target element continuously while the user drags the object over a valid drop target. * @param ev The event. */ ondragover: (ev: DragEvent) => any; /** * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; /** * Occurs when the duration attribute is updated. * @param ev The event. */ ondurationchange: (ev: Event) => any; /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ onemptied: (ev: Event) => any; /** * Occurs when the end of playback is reached. * @param ev The event */ onended: (ev: Event) => any; /** * Fires when an error occurs during object loading. * @param ev The event. */ onerror: (ev: Event) => any; /** * Fires when the object receives focus. * @param ev The event. */ onfocus: (ev: FocusEvent) => any; onfullscreenchange: (ev: Event) => any; onfullscreenerror: (ev: Event) => any; oninput: (ev: Event) => any; /** * Fires when the user presses a key. * @param ev The keyboard event */ onkeydown: (ev: KeyboardEvent) => any; /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ onkeypress: (ev: KeyboardEvent) => any; /** * Fires when the user releases a key. * @param ev The keyboard event */ onkeyup: (ev: KeyboardEvent) => any; /** * Fires immediately after the browser loads the object. * @param ev The event. */ onload: (ev: Event) => any; /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ onloadeddata: (ev: Event) => any; /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ onloadedmetadata: (ev: Event) => any; /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ onloadstart: (ev: Event) => any; /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ onmousedown: (ev: MouseEvent) => any; /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ onmousemove: (ev: MouseEvent) => any; /** * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ onmouseout: (ev: MouseEvent) => any; /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ onmouseover: (ev: MouseEvent) => any; /** * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ onmouseup: (ev: MouseEvent) => any; /** * Fires when the wheel button is rotated. * @param ev The mouse event */ onmousewheel: (ev: MouseWheelEvent) => any; onmscontentzoom: (ev: UIEvent) => any; onmsgesturechange: (ev: MSGestureEvent) => any; onmsgesturedoubletap: (ev: MSGestureEvent) => any; onmsgestureend: (ev: MSGestureEvent) => any; onmsgesturehold: (ev: MSGestureEvent) => any; onmsgesturestart: (ev: MSGestureEvent) => any; onmsgesturetap: (ev: MSGestureEvent) => any; onmsinertiastart: (ev: MSGestureEvent) => any; onmsmanipulationstatechanged: (ev: MSManipulationEvent) => any; onmspointercancel: (ev: MSPointerEvent) => any; onmspointerdown: (ev: MSPointerEvent) => any; onmspointerenter: (ev: MSPointerEvent) => any; onmspointerleave: (ev: MSPointerEvent) => any; onmspointermove: (ev: MSPointerEvent) => any; onmspointerout: (ev: MSPointerEvent) => any; onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; /** * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. * @param ev The event. */ onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; /** * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. * @param ev The event. */ onmsthumbnailclick: (ev: MSSiteModeEvent) => any; /** * Occurs when playback is paused. * @param ev The event. */ onpause: (ev: Event) => any; /** * Occurs when the play method is requested. * @param ev The event. */ onplay: (ev: Event) => any; /** * Occurs when the audio or video has started playing. * @param ev The event. */ onplaying: (ev: Event) => any; onpointerlockchange: (ev: Event) => any; onpointerlockerror: (ev: Event) => any; /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ onprogress: (ev: ProgressEvent) => any; /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ onratechange: (ev: Event) => any; /** * Fires when the state of the object has changed. * @param ev The event */ onreadystatechange: (ev: ProgressEvent) => any; /** * Fires when the user resets a form. * @param ev The event. */ onreset: (ev: Event) => any; /** * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ onscroll: (ev: UIEvent) => any; /** * Occurs when the seek operation ends. * @param ev The event. */ onseeked: (ev: Event) => any; /** * Occurs when the current playback position is moved. * @param ev The event. */ onseeking: (ev: Event) => any; /** * Fires when the current selection changes. * @param ev The event. */ onselect: (ev: UIEvent) => any; onselectstart: (ev: Event) => any; /** * Occurs when the download has stopped. * @param ev The event. */ onstalled: (ev: Event) => any; /** * Fires when the user clicks the Stop button or leaves the Web page. * @param ev The event. */ onstop: (ev: Event) => any; onsubmit: (ev: Event) => any; /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ onsuspend: (ev: Event) => any; /** * Occurs to indicate the current playback position. * @param ev The event. */ ontimeupdate: (ev: Event) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ onvolumechange: (ev: Event) => any; /** * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ onwaiting: (ev: Event) => any; onwebkitfullscreenchange: (ev: Event) => any; onwebkitfullscreenerror: (ev: Event) => any; plugins: HTMLCollection; pointerLockElement: Element; /** * Retrieves a value that indicates the current state of the object. */ readyState: string; /** * Gets the URL of the location that referred the user to the current page. */ referrer: string; /** * Gets the root svg element in the document hierarchy. */ rootElement: SVGSVGElement; /** * Retrieves a collection of all script objects in the document. */ scripts: HTMLCollection; security: string; /** * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. */ styleSheets: StyleSheetList; /** * Contains the title of the document. */ title: string; visibilityState: string; /** * Sets or gets the color of the links that the user has visited. */ vlinkColor: string; webkitCurrentFullScreenElement: Element; webkitFullscreenElement: Element; webkitFullscreenEnabled: boolean; webkitIsFullScreen: boolean; xmlEncoding: string; xmlStandalone: boolean; /** * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string; currentScript: HTMLScriptElement; adoptNode(source: Node): Node; captureEvents(): void; clear(): void; /** * Closes an output stream and forces the sent data to display. */ close(): void; /** * Creates an attribute object with a specified name. * @param name String that sets the attribute object's name. */ createAttribute(name: string): Attr; createAttributeNS(namespaceURI: string, qualifiedName: string): Attr; createCDATASection(data: string): CDATASection; /** * Creates a comment object with the specified data. * @param data Sets the comment object's data. */ createComment(data: string): Comment; /** * Creates a new document. */ createDocumentFragment(): DocumentFragment; /** * Creates an instance of the element for the specified tag. * @param tagName The name of an element. */ createElement(tagName: "a"): HTMLAnchorElement; createElement(tagName: "abbr"): HTMLPhraseElement; createElement(tagName: "acronym"): HTMLPhraseElement; createElement(tagName: "address"): HTMLBlockElement; createElement(tagName: "applet"): HTMLAppletElement; createElement(tagName: "area"): HTMLAreaElement; createElement(tagName: "audio"): HTMLAudioElement; createElement(tagName: "b"): HTMLPhraseElement; createElement(tagName: "base"): HTMLBaseElement; createElement(tagName: "basefont"): HTMLBaseFontElement; createElement(tagName: "bdo"): HTMLPhraseElement; createElement(tagName: "big"): HTMLPhraseElement; createElement(tagName: "blockquote"): HTMLBlockElement; createElement(tagName: "body"): HTMLBodyElement; createElement(tagName: "br"): HTMLBRElement; createElement(tagName: "button"): HTMLButtonElement; createElement(tagName: "canvas"): HTMLCanvasElement; createElement(tagName: "caption"): HTMLTableCaptionElement; createElement(tagName: "center"): HTMLBlockElement; createElement(tagName: "cite"): HTMLPhraseElement; createElement(tagName: "code"): HTMLPhraseElement; createElement(tagName: "col"): HTMLTableColElement; createElement(tagName: "colgroup"): HTMLTableColElement; createElement(tagName: "datalist"): HTMLDataListElement; createElement(tagName: "dd"): HTMLDDElement; createElement(tagName: "del"): HTMLModElement; createElement(tagName: "dfn"): HTMLPhraseElement; createElement(tagName: "dir"): HTMLDirectoryElement; createElement(tagName: "div"): HTMLDivElement; createElement(tagName: "dl"): HTMLDListElement; createElement(tagName: "dt"): HTMLDTElement; createElement(tagName: "em"): HTMLPhraseElement; createElement(tagName: "embed"): HTMLEmbedElement; createElement(tagName: "fieldset"): HTMLFieldSetElement; createElement(tagName: "font"): HTMLFontElement; createElement(tagName: "form"): HTMLFormElement; createElement(tagName: "frame"): HTMLFrameElement; createElement(tagName: "frameset"): HTMLFrameSetElement; createElement(tagName: "h1"): HTMLHeadingElement; createElement(tagName: "h2"): HTMLHeadingElement; createElement(tagName: "h3"): HTMLHeadingElement; createElement(tagName: "h4"): HTMLHeadingElement; createElement(tagName: "h5"): HTMLHeadingElement; createElement(tagName: "h6"): HTMLHeadingElement; createElement(tagName: "head"): HTMLHeadElement; createElement(tagName: "hr"): HTMLHRElement; createElement(tagName: "html"): HTMLHtmlElement; createElement(tagName: "i"): HTMLPhraseElement; createElement(tagName: "iframe"): HTMLIFrameElement; createElement(tagName: "img"): HTMLImageElement; createElement(tagName: "input"): HTMLInputElement; createElement(tagName: "ins"): HTMLModElement; createElement(tagName: "isindex"): HTMLIsIndexElement; createElement(tagName: "kbd"): HTMLPhraseElement; createElement(tagName: "keygen"): HTMLBlockElement; createElement(tagName: "label"): HTMLLabelElement; createElement(tagName: "legend"): HTMLLegendElement; createElement(tagName: "li"): HTMLLIElement; createElement(tagName: "link"): HTMLLinkElement; createElement(tagName: "listing"): HTMLBlockElement; createElement(tagName: "map"): HTMLMapElement; createElement(tagName: "marquee"): HTMLMarqueeElement; createElement(tagName: "menu"): HTMLMenuElement; createElement(tagName: "meta"): HTMLMetaElement; createElement(tagName: "nextid"): HTMLNextIdElement; createElement(tagName: "nobr"): HTMLPhraseElement; createElement(tagName: "object"): HTMLObjectElement; createElement(tagName: "ol"): HTMLOListElement; createElement(tagName: "optgroup"): HTMLOptGroupElement; createElement(tagName: "option"): HTMLOptionElement; createElement(tagName: "p"): HTMLParagraphElement; createElement(tagName: "param"): HTMLParamElement; createElement(tagName: "plaintext"): HTMLBlockElement; createElement(tagName: "pre"): HTMLPreElement; createElement(tagName: "progress"): HTMLProgressElement; createElement(tagName: "q"): HTMLQuoteElement; createElement(tagName: "rt"): HTMLPhraseElement; createElement(tagName: "ruby"): HTMLPhraseElement; createElement(tagName: "s"): HTMLPhraseElement; createElement(tagName: "samp"): HTMLPhraseElement; createElement(tagName: "script"): HTMLScriptElement; createElement(tagName: "select"): HTMLSelectElement; createElement(tagName: "small"): HTMLPhraseElement; createElement(tagName: "source"): HTMLSourceElement; createElement(tagName: "span"): HTMLSpanElement; createElement(tagName: "strike"): HTMLPhraseElement; createElement(tagName: "strong"): HTMLPhraseElement; createElement(tagName: "style"): HTMLStyleElement; createElement(tagName: "sub"): HTMLPhraseElement; createElement(tagName: "sup"): HTMLPhraseElement; createElement(tagName: "table"): HTMLTableElement; createElement(tagName: "tbody"): HTMLTableSectionElement; createElement(tagName: "td"): HTMLTableDataCellElement; createElement(tagName: "textarea"): HTMLTextAreaElement; createElement(tagName: "tfoot"): HTMLTableSectionElement; createElement(tagName: "th"): HTMLTableHeaderCellElement; createElement(tagName: "thead"): HTMLTableSectionElement; createElement(tagName: "title"): HTMLTitleElement; createElement(tagName: "tr"): HTMLTableRowElement; createElement(tagName: "track"): HTMLTrackElement; createElement(tagName: "tt"): HTMLPhraseElement; createElement(tagName: "u"): HTMLPhraseElement; createElement(tagName: "ul"): HTMLUListElement; createElement(tagName: "var"): HTMLPhraseElement; createElement(tagName: "video"): HTMLVideoElement; createElement(tagName: "x-ms-webview"): MSHTMLWebViewElement; createElement(tagName: "xmp"): HTMLBlockElement; createElement(tagName: string): HTMLElement; createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement createElementNS(namespaceURI: string, qualifiedName: string): Element; createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver: Node): XPathNSResolver; /** * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. * @param whatToShow The type of nodes or elements to appear in the node list * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. */ createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. */ createRange(): Range; /** * Creates a text string from the specified value. * @param data String that specifies the nodeValue property of the text node. */ createTextNode(data: string): Text; createTouch(view: any, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. * @param filter A custom NodeFilter function to use. * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset * @param y The y-offset */ elementFromPoint(x: number, y: number): Element; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; /** * Executes a command on the current document, current selection, or the given range. * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. * @param showUI Display the user interface, defaults to false. * @param value Value to assign. */ execCommand(commandId: string, showUI?: boolean, value?: any): boolean; /** * Displays help information for the given command identifier. * @param commandId Displays help information for the given command identifier. */ execCommandShowHelp(commandId: string): boolean; exitFullscreen(): void; exitPointerLock(): void; /** * Causes the element to receive the focus and executes the code specified by the onfocus event. */ focus(): void; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. * @param elementId String that specifies the ID value. Case-insensitive. */ getElementById(elementId: string): HTMLElement; getElementsByClassName(classNames: string): NodeListOf<Element>; /** * Gets a collection of objects based on the value of the NAME or ID attribute. * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. */ getElementsByName(elementName: string): NodeListOf<Element>; /** * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ getElementsByTagName(tagname: "a"): NodeListOf<HTMLAnchorElement>; getElementsByTagName(tagname: "abbr"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "acronym"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "address"): NodeListOf<HTMLBlockElement>; getElementsByTagName(tagname: "applet"): NodeListOf<HTMLAppletElement>; getElementsByTagName(tagname: "area"): NodeListOf<HTMLAreaElement>; getElementsByTagName(tagname: "article"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "aside"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "audio"): NodeListOf<HTMLAudioElement>; getElementsByTagName(tagname: "b"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "base"): NodeListOf<HTMLBaseElement>; getElementsByTagName(tagname: "basefont"): NodeListOf<HTMLBaseFontElement>; getElementsByTagName(tagname: "bdo"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "big"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "blockquote"): NodeListOf<HTMLBlockElement>; getElementsByTagName(tagname: "body"): NodeListOf<HTMLBodyElement>; getElementsByTagName(tagname: "br"): NodeListOf<HTMLBRElement>; getElementsByTagName(tagname: "button"): NodeListOf<HTMLButtonElement>; getElementsByTagName(tagname: "canvas"): NodeListOf<HTMLCanvasElement>; getElementsByTagName(tagname: "caption"): NodeListOf<HTMLTableCaptionElement>; getElementsByTagName(tagname: "center"): NodeListOf<HTMLBlockElement>; getElementsByTagName(tagname: "circle"): NodeListOf<SVGCircleElement>; getElementsByTagName(tagname: "cite"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "clippath"): NodeListOf<SVGClipPathElement>; getElementsByTagName(tagname: "code"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "col"): NodeListOf<HTMLTableColElement>; getElementsByTagName(tagname: "colgroup"): NodeListOf<HTMLTableColElement>; getElementsByTagName(tagname: "datalist"): NodeListOf<HTMLDataListElement>; getElementsByTagName(tagname: "dd"): NodeListOf<HTMLDDElement>; getElementsByTagName(tagname: "defs"): NodeListOf<SVGDefsElement>; getElementsByTagName(tagname: "del"): NodeListOf<HTMLModElement>; getElementsByTagName(tagname: "desc"): NodeListOf<SVGDescElement>; getElementsByTagName(tagname: "dfn"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "dir"): NodeListOf<HTMLDirectoryElement>; getElementsByTagName(tagname: "div"): NodeListOf<HTMLDivElement>; getElementsByTagName(tagname: "dl"): NodeListOf<HTMLDListElement>; getElementsByTagName(tagname: "dt"): NodeListOf<HTMLDTElement>; getElementsByTagName(tagname: "ellipse"): NodeListOf<SVGEllipseElement>; getElementsByTagName(tagname: "em"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "embed"): NodeListOf<HTMLEmbedElement>; getElementsByTagName(tagname: "feblend"): NodeListOf<SVGFEBlendElement>; getElementsByTagName(tagname: "fecolormatrix"): NodeListOf<SVGFEColorMatrixElement>; getElementsByTagName(tagname: "fecomponenttransfer"): NodeListOf<SVGFEComponentTransferElement>; getElementsByTagName(tagname: "fecomposite"): NodeListOf<SVGFECompositeElement>; getElementsByTagName(tagname: "feconvolvematrix"): NodeListOf<SVGFEConvolveMatrixElement>; getElementsByTagName(tagname: "fediffuselighting"): NodeListOf<SVGFEDiffuseLightingElement>; getElementsByTagName(tagname: "fedisplacementmap"): NodeListOf<SVGFEDisplacementMapElement>; getElementsByTagName(tagname: "fedistantlight"): NodeListOf<SVGFEDistantLightElement>; getElementsByTagName(tagname: "feflood"): NodeListOf<SVGFEFloodElement>; getElementsByTagName(tagname: "fefunca"): NodeListOf<SVGFEFuncAElement>; getElementsByTagName(tagname: "fefuncb"): NodeListOf<SVGFEFuncBElement>; getElementsByTagName(tagname: "fefuncg"): NodeListOf<SVGFEFuncGElement>; getElementsByTagName(tagname: "fefuncr"): NodeListOf<SVGFEFuncRElement>; getElementsByTagName(tagname: "fegaussianblur"): NodeListOf<SVGFEGaussianBlurElement>; getElementsByTagName(tagname: "feimage"): NodeListOf<SVGFEImageElement>; getElementsByTagName(tagname: "femerge"): NodeListOf<SVGFEMergeElement>; getElementsByTagName(tagname: "femergenode"): NodeListOf<SVGFEMergeNodeElement>; getElementsByTagName(tagname: "femorphology"): NodeListOf<SVGFEMorphologyElement>; getElementsByTagName(tagname: "feoffset"): NodeListOf<SVGFEOffsetElement>; getElementsByTagName(tagname: "fepointlight"): NodeListOf<SVGFEPointLightElement>; getElementsByTagName(tagname: "fespecularlighting"): NodeListOf<SVGFESpecularLightingElement>; getElementsByTagName(tagname: "fespotlight"): NodeListOf<SVGFESpotLightElement>; getElementsByTagName(tagname: "fetile"): NodeListOf<SVGFETileElement>; getElementsByTagName(tagname: "feturbulence"): NodeListOf<SVGFETurbulenceElement>; getElementsByTagName(tagname: "fieldset"): NodeListOf<HTMLFieldSetElement>; getElementsByTagName(tagname: "figcaption"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "figure"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "filter"): NodeListOf<SVGFilterElement>; getElementsByTagName(tagname: "font"): NodeListOf<HTMLFontElement>; getElementsByTagName(tagname: "footer"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "foreignobject"): NodeListOf<SVGForeignObjectElement>; getElementsByTagName(tagname: "form"): NodeListOf<HTMLFormElement>; getElementsByTagName(tagname: "frame"): NodeListOf<HTMLFrameElement>; getElementsByTagName(tagname: "frameset"): NodeListOf<HTMLFrameSetElement>; getElementsByTagName(tagname: "g"): NodeListOf<SVGGElement>; getElementsByTagName(tagname: "h1"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(tagname: "h2"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(tagname: "h3"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(tagname: "h4"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(tagname: "h5"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(tagname: "h6"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(tagname: "head"): NodeListOf<HTMLHeadElement>; getElementsByTagName(tagname: "header"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "hgroup"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "hr"): NodeListOf<HTMLHRElement>; getElementsByTagName(tagname: "html"): NodeListOf<HTMLHtmlElement>; getElementsByTagName(tagname: "i"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "iframe"): NodeListOf<HTMLIFrameElement>; getElementsByTagName(tagname: "image"): NodeListOf<SVGImageElement>; getElementsByTagName(tagname: "img"): NodeListOf<HTMLImageElement>; getElementsByTagName(tagname: "input"): NodeListOf<HTMLInputElement>; getElementsByTagName(tagname: "ins"): NodeListOf<HTMLModElement>; getElementsByTagName(tagname: "isindex"): NodeListOf<HTMLIsIndexElement>; getElementsByTagName(tagname: "kbd"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "keygen"): NodeListOf<HTMLBlockElement>; getElementsByTagName(tagname: "label"): NodeListOf<HTMLLabelElement>; getElementsByTagName(tagname: "legend"): NodeListOf<HTMLLegendElement>; getElementsByTagName(tagname: "li"): NodeListOf<HTMLLIElement>; getElementsByTagName(tagname: "line"): NodeListOf<SVGLineElement>; getElementsByTagName(tagname: "lineargradient"): NodeListOf<SVGLinearGradientElement>; getElementsByTagName(tagname: "link"): NodeListOf<HTMLLinkElement>; getElementsByTagName(tagname: "listing"): NodeListOf<HTMLBlockElement>; getElementsByTagName(tagname: "map"): NodeListOf<HTMLMapElement>; getElementsByTagName(tagname: "mark"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "marker"): NodeListOf<SVGMarkerElement>; getElementsByTagName(tagname: "marquee"): NodeListOf<HTMLMarqueeElement>; getElementsByTagName(tagname: "mask"): NodeListOf<SVGMaskElement>; getElementsByTagName(tagname: "menu"): NodeListOf<HTMLMenuElement>; getElementsByTagName(tagname: "meta"): NodeListOf<HTMLMetaElement>; getElementsByTagName(tagname: "metadata"): NodeListOf<SVGMetadataElement>; getElementsByTagName(tagname: "nav"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "nextid"): NodeListOf<HTMLNextIdElement>; getElementsByTagName(tagname: "nobr"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "noframes"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "noscript"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "object"): NodeListOf<HTMLObjectElement>; getElementsByTagName(tagname: "ol"): NodeListOf<HTMLOListElement>; getElementsByTagName(tagname: "optgroup"): NodeListOf<HTMLOptGroupElement>; getElementsByTagName(tagname: "option"): NodeListOf<HTMLOptionElement>; getElementsByTagName(tagname: "p"): NodeListOf<HTMLParagraphElement>; getElementsByTagName(tagname: "param"): NodeListOf<HTMLParamElement>; getElementsByTagName(tagname: "path"): NodeListOf<SVGPathElement>; getElementsByTagName(tagname: "pattern"): NodeListOf<SVGPatternElement>; getElementsByTagName(tagname: "plaintext"): NodeListOf<HTMLBlockElement>; getElementsByTagName(tagname: "polygon"): NodeListOf<SVGPolygonElement>; getElementsByTagName(tagname: "polyline"): NodeListOf<SVGPolylineElement>; getElementsByTagName(tagname: "pre"): NodeListOf<HTMLPreElement>; getElementsByTagName(tagname: "progress"): NodeListOf<HTMLProgressElement>; getElementsByTagName(tagname: "q"): NodeListOf<HTMLQuoteElement>; getElementsByTagName(tagname: "radialgradient"): NodeListOf<SVGRadialGradientElement>; getElementsByTagName(tagname: "rect"): NodeListOf<SVGRectElement>; getElementsByTagName(tagname: "rt"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "ruby"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "s"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "samp"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "script"): NodeListOf<HTMLScriptElement>; getElementsByTagName(tagname: "section"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "select"): NodeListOf<HTMLSelectElement>; getElementsByTagName(tagname: "small"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "source"): NodeListOf<HTMLSourceElement>; getElementsByTagName(tagname: "span"): NodeListOf<HTMLSpanElement>; getElementsByTagName(tagname: "stop"): NodeListOf<SVGStopElement>; getElementsByTagName(tagname: "strike"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "strong"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "style"): NodeListOf<HTMLStyleElement>; getElementsByTagName(tagname: "sub"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "sup"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "svg"): NodeListOf<SVGSVGElement>; getElementsByTagName(tagname: "switch"): NodeListOf<SVGSwitchElement>; getElementsByTagName(tagname: "symbol"): NodeListOf<SVGSymbolElement>; getElementsByTagName(tagname: "table"): NodeListOf<HTMLTableElement>; getElementsByTagName(tagname: "tbody"): NodeListOf<HTMLTableSectionElement>; getElementsByTagName(tagname: "td"): NodeListOf<HTMLTableDataCellElement>; getElementsByTagName(tagname: "text"): NodeListOf<SVGTextElement>; getElementsByTagName(tagname: "textpath"): NodeListOf<SVGTextPathElement>; getElementsByTagName(tagname: "textarea"): NodeListOf<HTMLTextAreaElement>; getElementsByTagName(tagname: "tfoot"): NodeListOf<HTMLTableSectionElement>; getElementsByTagName(tagname: "th"): NodeListOf<HTMLTableHeaderCellElement>; getElementsByTagName(tagname: "thead"): NodeListOf<HTMLTableSectionElement>; getElementsByTagName(tagname: "title"): NodeListOf<HTMLTitleElement>; getElementsByTagName(tagname: "tr"): NodeListOf<HTMLTableRowElement>; getElementsByTagName(tagname: "track"): NodeListOf<HTMLTrackElement>; getElementsByTagName(tagname: "tspan"): NodeListOf<SVGTSpanElement>; getElementsByTagName(tagname: "tt"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "u"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "ul"): NodeListOf<HTMLUListElement>; getElementsByTagName(tagname: "use"): NodeListOf<SVGUseElement>; getElementsByTagName(tagname: "var"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(tagname: "video"): NodeListOf<HTMLVideoElement>; getElementsByTagName(tagname: "view"): NodeListOf<SVGViewElement>; getElementsByTagName(tagname: "wbr"): NodeListOf<HTMLElement>; getElementsByTagName(tagname: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>; getElementsByTagName(tagname: "xmp"): NodeListOf<HTMLBlockElement>; getElementsByTagName(tagname: string): NodeListOf<Element>; getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>; /** * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. */ getSelection(): Selection; /** * Gets a value indicating whether the object currently has focus. */ hasFocus(): boolean; importNode(importedNode: Node, deep: boolean): Node; msElementsFromPoint(x: number, y: number): NodeList; msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; /** * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. * @param url Specifies a MIME type for the document. * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. * @param replace Specifies whether the existing entry for the document is replaced in the history list. */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; /** * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. * @param commandId Specifies a command identifier. */ queryCommandEnabled(commandId: string): boolean; /** * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. * @param commandId String that specifies a command identifier. */ queryCommandIndeterm(commandId: string): boolean; /** * Returns a Boolean value that indicates the current state of the command. * @param commandId String that specifies a command identifier. */ queryCommandState(commandId: string): boolean; /** * Returns a Boolean value that indicates whether the current command is supported on the current range. * @param commandId Specifies a command identifier. */ queryCommandSupported(commandId: string): boolean; /** * Retrieves the string associated with a command. * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. */ queryCommandText(commandId: string): string; /** * Returns the current value of the document, range, or current selection for the given command. * @param commandId String that specifies a command identifier. */ queryCommandValue(commandId: string): string; releaseEvents(): void; /** * Allows updating the print settings for the page. */ updateSettings(): void; webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ write(...content: string[]): void; /** * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; createElement(tagName: "picture"): HTMLPictureElement; getElementsByTagName(tagname: "picture"): NodeListOf<HTMLPictureElement>; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "fullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "fullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "mssitemodejumplistitemremoved", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; addEventListener(type: "msthumbnailclick", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerlockchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointerlockerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stop", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Document: { prototype: Document; new(): Document; } interface DocumentFragment extends Node, NodeSelector { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; } interface DocumentType extends Node, ChildNode { entities: NamedNodeMap; internalSubset: string; name: string; notations: NamedNodeMap; publicId: string; systemId: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var DocumentType: { prototype: DocumentType; new(): DocumentType; } interface DragEvent extends MouseEvent { dataTransfer: DataTransfer; initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; msConvertURL(file: File, targetType: string, targetURL?: string): void; } declare var DragEvent: { prototype: DragEvent; new(): DragEvent; } interface DynamicsCompressorNode extends AudioNode { attack: AudioParam; knee: AudioParam; ratio: AudioParam; reduction: AudioParam; release: AudioParam; threshold: AudioParam; } declare var DynamicsCompressorNode: { prototype: DynamicsCompressorNode; new(): DynamicsCompressorNode; } interface EXT_texture_filter_anisotropic { MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; TEXTURE_MAX_ANISOTROPY_EXT: number; } declare var EXT_texture_filter_anisotropic: { prototype: EXT_texture_filter_anisotropic; new(): EXT_texture_filter_anisotropic; MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; TEXTURE_MAX_ANISOTROPY_EXT: number; } interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode { classList: DOMTokenList; clientHeight: number; clientLeft: number; clientTop: number; clientWidth: number; msContentZoomFactor: number; msRegionOverflow: string; onariarequest: (ev: AriaRequestEvent) => any; oncommand: (ev: CommandEvent) => any; ongotpointercapture: (ev: PointerEvent) => any; onlostpointercapture: (ev: PointerEvent) => any; onmsgesturechange: (ev: MSGestureEvent) => any; onmsgesturedoubletap: (ev: MSGestureEvent) => any; onmsgestureend: (ev: MSGestureEvent) => any; onmsgesturehold: (ev: MSGestureEvent) => any; onmsgesturestart: (ev: MSGestureEvent) => any; onmsgesturetap: (ev: MSGestureEvent) => any; onmsgotpointercapture: (ev: MSPointerEvent) => any; onmsinertiastart: (ev: MSGestureEvent) => any; onmslostpointercapture: (ev: MSPointerEvent) => any; onmspointercancel: (ev: MSPointerEvent) => any; onmspointerdown: (ev: MSPointerEvent) => any; onmspointerenter: (ev: MSPointerEvent) => any; onmspointerleave: (ev: MSPointerEvent) => any; onmspointermove: (ev: MSPointerEvent) => any; onmspointerout: (ev: MSPointerEvent) => any; onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; ontouchcancel: (ev: TouchEvent) => any; ontouchend: (ev: TouchEvent) => any; ontouchmove: (ev: TouchEvent) => any; ontouchstart: (ev: TouchEvent) => any; onwebkitfullscreenchange: (ev: Event) => any; onwebkitfullscreenerror: (ev: Event) => any; scrollHeight: number; scrollLeft: number; scrollTop: number; scrollWidth: number; tagName: string; id: string; className: string; innerHTML: string; getAttribute(name?: string): string; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; getElementsByTagName(name: "a"): NodeListOf<HTMLAnchorElement>; getElementsByTagName(name: "abbr"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "acronym"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "address"): NodeListOf<HTMLBlockElement>; getElementsByTagName(name: "applet"): NodeListOf<HTMLAppletElement>; getElementsByTagName(name: "area"): NodeListOf<HTMLAreaElement>; getElementsByTagName(name: "article"): NodeListOf<HTMLElement>; getElementsByTagName(name: "aside"): NodeListOf<HTMLElement>; getElementsByTagName(name: "audio"): NodeListOf<HTMLAudioElement>; getElementsByTagName(name: "b"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "base"): NodeListOf<HTMLBaseElement>; getElementsByTagName(name: "basefont"): NodeListOf<HTMLBaseFontElement>; getElementsByTagName(name: "bdo"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "big"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "blockquote"): NodeListOf<HTMLBlockElement>; getElementsByTagName(name: "body"): NodeListOf<HTMLBodyElement>; getElementsByTagName(name: "br"): NodeListOf<HTMLBRElement>; getElementsByTagName(name: "button"): NodeListOf<HTMLButtonElement>; getElementsByTagName(name: "canvas"): NodeListOf<HTMLCanvasElement>; getElementsByTagName(name: "caption"): NodeListOf<HTMLTableCaptionElement>; getElementsByTagName(name: "center"): NodeListOf<HTMLBlockElement>; getElementsByTagName(name: "circle"): NodeListOf<SVGCircleElement>; getElementsByTagName(name: "cite"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "clippath"): NodeListOf<SVGClipPathElement>; getElementsByTagName(name: "code"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "col"): NodeListOf<HTMLTableColElement>; getElementsByTagName(name: "colgroup"): NodeListOf<HTMLTableColElement>; getElementsByTagName(name: "datalist"): NodeListOf<HTMLDataListElement>; getElementsByTagName(name: "dd"): NodeListOf<HTMLDDElement>; getElementsByTagName(name: "defs"): NodeListOf<SVGDefsElement>; getElementsByTagName(name: "del"): NodeListOf<HTMLModElement>; getElementsByTagName(name: "desc"): NodeListOf<SVGDescElement>; getElementsByTagName(name: "dfn"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "dir"): NodeListOf<HTMLDirectoryElement>; getElementsByTagName(name: "div"): NodeListOf<HTMLDivElement>; getElementsByTagName(name: "dl"): NodeListOf<HTMLDListElement>; getElementsByTagName(name: "dt"): NodeListOf<HTMLDTElement>; getElementsByTagName(name: "ellipse"): NodeListOf<SVGEllipseElement>; getElementsByTagName(name: "em"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "embed"): NodeListOf<HTMLEmbedElement>; getElementsByTagName(name: "feblend"): NodeListOf<SVGFEBlendElement>; getElementsByTagName(name: "fecolormatrix"): NodeListOf<SVGFEColorMatrixElement>; getElementsByTagName(name: "fecomponenttransfer"): NodeListOf<SVGFEComponentTransferElement>; getElementsByTagName(name: "fecomposite"): NodeListOf<SVGFECompositeElement>; getElementsByTagName(name: "feconvolvematrix"): NodeListOf<SVGFEConvolveMatrixElement>; getElementsByTagName(name: "fediffuselighting"): NodeListOf<SVGFEDiffuseLightingElement>; getElementsByTagName(name: "fedisplacementmap"): NodeListOf<SVGFEDisplacementMapElement>; getElementsByTagName(name: "fedistantlight"): NodeListOf<SVGFEDistantLightElement>; getElementsByTagName(name: "feflood"): NodeListOf<SVGFEFloodElement>; getElementsByTagName(name: "fefunca"): NodeListOf<SVGFEFuncAElement>; getElementsByTagName(name: "fefuncb"): NodeListOf<SVGFEFuncBElement>; getElementsByTagName(name: "fefuncg"): NodeListOf<SVGFEFuncGElement>; getElementsByTagName(name: "fefuncr"): NodeListOf<SVGFEFuncRElement>; getElementsByTagName(name: "fegaussianblur"): NodeListOf<SVGFEGaussianBlurElement>; getElementsByTagName(name: "feimage"): NodeListOf<SVGFEImageElement>; getElementsByTagName(name: "femerge"): NodeListOf<SVGFEMergeElement>; getElementsByTagName(name: "femergenode"): NodeListOf<SVGFEMergeNodeElement>; getElementsByTagName(name: "femorphology"): NodeListOf<SVGFEMorphologyElement>; getElementsByTagName(name: "feoffset"): NodeListOf<SVGFEOffsetElement>; getElementsByTagName(name: "fepointlight"): NodeListOf<SVGFEPointLightElement>; getElementsByTagName(name: "fespecularlighting"): NodeListOf<SVGFESpecularLightingElement>; getElementsByTagName(name: "fespotlight"): NodeListOf<SVGFESpotLightElement>; getElementsByTagName(name: "fetile"): NodeListOf<SVGFETileElement>; getElementsByTagName(name: "feturbulence"): NodeListOf<SVGFETurbulenceElement>; getElementsByTagName(name: "fieldset"): NodeListOf<HTMLFieldSetElement>; getElementsByTagName(name: "figcaption"): NodeListOf<HTMLElement>; getElementsByTagName(name: "figure"): NodeListOf<HTMLElement>; getElementsByTagName(name: "filter"): NodeListOf<SVGFilterElement>; getElementsByTagName(name: "font"): NodeListOf<HTMLFontElement>; getElementsByTagName(name: "footer"): NodeListOf<HTMLElement>; getElementsByTagName(name: "foreignobject"): NodeListOf<SVGForeignObjectElement>; getElementsByTagName(name: "form"): NodeListOf<HTMLFormElement>; getElementsByTagName(name: "frame"): NodeListOf<HTMLFrameElement>; getElementsByTagName(name: "frameset"): NodeListOf<HTMLFrameSetElement>; getElementsByTagName(name: "g"): NodeListOf<SVGGElement>; getElementsByTagName(name: "h1"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(name: "h2"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(name: "h3"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(name: "h4"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(name: "h5"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(name: "h6"): NodeListOf<HTMLHeadingElement>; getElementsByTagName(name: "head"): NodeListOf<HTMLHeadElement>; getElementsByTagName(name: "header"): NodeListOf<HTMLElement>; getElementsByTagName(name: "hgroup"): NodeListOf<HTMLElement>; getElementsByTagName(name: "hr"): NodeListOf<HTMLHRElement>; getElementsByTagName(name: "html"): NodeListOf<HTMLHtmlElement>; getElementsByTagName(name: "i"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "iframe"): NodeListOf<HTMLIFrameElement>; getElementsByTagName(name: "image"): NodeListOf<SVGImageElement>; getElementsByTagName(name: "img"): NodeListOf<HTMLImageElement>; getElementsByTagName(name: "input"): NodeListOf<HTMLInputElement>; getElementsByTagName(name: "ins"): NodeListOf<HTMLModElement>; getElementsByTagName(name: "isindex"): NodeListOf<HTMLIsIndexElement>; getElementsByTagName(name: "kbd"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "keygen"): NodeListOf<HTMLBlockElement>; getElementsByTagName(name: "label"): NodeListOf<HTMLLabelElement>; getElementsByTagName(name: "legend"): NodeListOf<HTMLLegendElement>; getElementsByTagName(name: "li"): NodeListOf<HTMLLIElement>; getElementsByTagName(name: "line"): NodeListOf<SVGLineElement>; getElementsByTagName(name: "lineargradient"): NodeListOf<SVGLinearGradientElement>; getElementsByTagName(name: "link"): NodeListOf<HTMLLinkElement>; getElementsByTagName(name: "listing"): NodeListOf<HTMLBlockElement>; getElementsByTagName(name: "map"): NodeListOf<HTMLMapElement>; getElementsByTagName(name: "mark"): NodeListOf<HTMLElement>; getElementsByTagName(name: "marker"): NodeListOf<SVGMarkerElement>; getElementsByTagName(name: "marquee"): NodeListOf<HTMLMarqueeElement>; getElementsByTagName(name: "mask"): NodeListOf<SVGMaskElement>; getElementsByTagName(name: "menu"): NodeListOf<HTMLMenuElement>; getElementsByTagName(name: "meta"): NodeListOf<HTMLMetaElement>; getElementsByTagName(name: "metadata"): NodeListOf<SVGMetadataElement>; getElementsByTagName(name: "nav"): NodeListOf<HTMLElement>; getElementsByTagName(name: "nextid"): NodeListOf<HTMLNextIdElement>; getElementsByTagName(name: "nobr"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "noframes"): NodeListOf<HTMLElement>; getElementsByTagName(name: "noscript"): NodeListOf<HTMLElement>; getElementsByTagName(name: "object"): NodeListOf<HTMLObjectElement>; getElementsByTagName(name: "ol"): NodeListOf<HTMLOListElement>; getElementsByTagName(name: "optgroup"): NodeListOf<HTMLOptGroupElement>; getElementsByTagName(name: "option"): NodeListOf<HTMLOptionElement>; getElementsByTagName(name: "p"): NodeListOf<HTMLParagraphElement>; getElementsByTagName(name: "param"): NodeListOf<HTMLParamElement>; getElementsByTagName(name: "path"): NodeListOf<SVGPathElement>; getElementsByTagName(name: "pattern"): NodeListOf<SVGPatternElement>; getElementsByTagName(name: "plaintext"): NodeListOf<HTMLBlockElement>; getElementsByTagName(name: "polygon"): NodeListOf<SVGPolygonElement>; getElementsByTagName(name: "polyline"): NodeListOf<SVGPolylineElement>; getElementsByTagName(name: "pre"): NodeListOf<HTMLPreElement>; getElementsByTagName(name: "progress"): NodeListOf<HTMLProgressElement>; getElementsByTagName(name: "q"): NodeListOf<HTMLQuoteElement>; getElementsByTagName(name: "radialgradient"): NodeListOf<SVGRadialGradientElement>; getElementsByTagName(name: "rect"): NodeListOf<SVGRectElement>; getElementsByTagName(name: "rt"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "ruby"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "s"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "samp"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "script"): NodeListOf<HTMLScriptElement>; getElementsByTagName(name: "section"): NodeListOf<HTMLElement>; getElementsByTagName(name: "select"): NodeListOf<HTMLSelectElement>; getElementsByTagName(name: "small"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "source"): NodeListOf<HTMLSourceElement>; getElementsByTagName(name: "span"): NodeListOf<HTMLSpanElement>; getElementsByTagName(name: "stop"): NodeListOf<SVGStopElement>; getElementsByTagName(name: "strike"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "strong"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "style"): NodeListOf<HTMLStyleElement>; getElementsByTagName(name: "sub"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "sup"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "svg"): NodeListOf<SVGSVGElement>; getElementsByTagName(name: "switch"): NodeListOf<SVGSwitchElement>; getElementsByTagName(name: "symbol"): NodeListOf<SVGSymbolElement>; getElementsByTagName(name: "table"): NodeListOf<HTMLTableElement>; getElementsByTagName(name: "tbody"): NodeListOf<HTMLTableSectionElement>; getElementsByTagName(name: "td"): NodeListOf<HTMLTableDataCellElement>; getElementsByTagName(name: "text"): NodeListOf<SVGTextElement>; getElementsByTagName(name: "textpath"): NodeListOf<SVGTextPathElement>; getElementsByTagName(name: "textarea"): NodeListOf<HTMLTextAreaElement>; getElementsByTagName(name: "tfoot"): NodeListOf<HTMLTableSectionElement>; getElementsByTagName(name: "th"): NodeListOf<HTMLTableHeaderCellElement>; getElementsByTagName(name: "thead"): NodeListOf<HTMLTableSectionElement>; getElementsByTagName(name: "title"): NodeListOf<HTMLTitleElement>; getElementsByTagName(name: "tr"): NodeListOf<HTMLTableRowElement>; getElementsByTagName(name: "track"): NodeListOf<HTMLTrackElement>; getElementsByTagName(name: "tspan"): NodeListOf<SVGTSpanElement>; getElementsByTagName(name: "tt"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "u"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "ul"): NodeListOf<HTMLUListElement>; getElementsByTagName(name: "use"): NodeListOf<SVGUseElement>; getElementsByTagName(name: "var"): NodeListOf<HTMLPhraseElement>; getElementsByTagName(name: "video"): NodeListOf<HTMLVideoElement>; getElementsByTagName(name: "view"): NodeListOf<SVGViewElement>; getElementsByTagName(name: "wbr"): NodeListOf<HTMLElement>; getElementsByTagName(name: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>; getElementsByTagName(name: "xmp"): NodeListOf<HTMLBlockElement>; getElementsByTagName(name: string): NodeListOf<Element>; getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>; hasAttribute(name: string): boolean; hasAttributeNS(namespaceURI: string, localName: string): boolean; msGetRegionContent(): MSRangeCollection; msGetUntransformedBounds(): ClientRect; msMatchesSelector(selectors: string): boolean; msReleasePointerCapture(pointerId: number): void; msSetPointerCapture(pointerId: number): void; msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; removeAttribute(name?: string): void; removeAttributeNS(namespaceURI: string, localName: string): void; removeAttributeNode(oldAttr: Attr): Attr; requestFullscreen(): void; requestPointerLock(): void; setAttribute(name: string, value: string): void; setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; setPointerCapture(pointerId: number): void; webkitMatchesSelector(selectors: string): boolean; webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf<Element>; matches(selector: string): boolean; getElementsByTagName(tagname: "picture"): NodeListOf<HTMLPictureElement>; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Element: { prototype: Element; new(): Element; } interface ErrorEvent extends Event { colno: number; error: any; filename: string; lineno: number; message: string; initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; } declare var ErrorEvent: { prototype: ErrorEvent; new(): ErrorEvent; } interface Event { bubbles: boolean; cancelBubble: boolean; cancelable: boolean; currentTarget: EventTarget; defaultPrevented: boolean; eventPhase: number; isTrusted: boolean; returnValue: boolean; srcElement: Element; target: EventTarget; timeStamp: number; type: string; initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; preventDefault(): void; stopImmediatePropagation(): void; stopPropagation(): void; AT_TARGET: number; BUBBLING_PHASE: number; CAPTURING_PHASE: number; } declare var Event: { prototype: Event; new(type: string, eventInitDict?: EventInit): Event; AT_TARGET: number; BUBBLING_PHASE: number; CAPTURING_PHASE: number; } interface EventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; dispatchEvent(evt: Event): boolean; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var EventTarget: { prototype: EventTarget; new(): EventTarget; } interface External { } declare var External: { prototype: External; new(): External; } interface File extends Blob { lastModifiedDate: any; name: string; } declare var File: { prototype: File; new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; } interface FileList { length: number; item(index: number): File; [index: number]: File; } declare var FileList: { prototype: FileList; new(): FileList; } interface FileReader extends EventTarget, MSBaseReader { error: DOMError; readAsArrayBuffer(blob: Blob): void; readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; } interface FocusEvent extends UIEvent { relatedTarget: EventTarget; initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; } declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; } interface FormData { append(name: any, value: any, blobName?: string): void; } declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; } interface GainNode extends AudioNode { gain: AudioParam; } declare var GainNode: { prototype: GainNode; new(): GainNode; } interface Gamepad { axes: number[]; buttons: GamepadButton[]; connected: boolean; id: string; index: number; mapping: string; timestamp: number; } declare var Gamepad: { prototype: Gamepad; new(): Gamepad; } interface GamepadButton { pressed: boolean; value: number; } declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; } interface GamepadEvent extends Event { gamepad: Gamepad; } declare var GamepadEvent: { prototype: GamepadEvent; new(): GamepadEvent; } interface Geolocation { clearWatch(watchId: number): void; getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; } declare var Geolocation: { prototype: Geolocation; new(): Geolocation; } interface HTMLAllCollection extends HTMLCollection { namedItem(name: string): Element; } declare var HTMLAllCollection: { prototype: HTMLAllCollection; new(): HTMLAllCollection; } interface HTMLAnchorElement extends HTMLElement { Methods: string; /** * Sets or retrieves the character set used to encode the object. */ charset: string; /** * Sets or retrieves the coordinates of the object. */ coords: string; /** * Contains the anchor portion of the URL including the hash sign (#). */ hash: string; /** * Contains the hostname and port values of the URL. */ host: string; /** * Contains the hostname of a URL. */ hostname: string; /** * Sets or retrieves a destination URL or an anchor point. */ href: string; /** * Sets or retrieves the language code of the object. */ hreflang: string; mimeType: string; /** * Sets or retrieves the shape of the object. */ name: string; nameProp: string; /** * Contains the pathname of the URL. */ pathname: string; /** * Sets or retrieves the port number associated with a URL. */ port: string; /** * Contains the protocol of the URL. */ protocol: string; protocolLong: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ rel: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ rev: string; /** * Sets or retrieves the substring of the href property that follows the question mark. */ search: string; /** * Sets or retrieves the shape of the object. */ shape: string; /** * Sets or retrieves the window or frame at which to target content. */ target: string; /** * Retrieves or sets the text of the object as a string. */ text: string; type: string; urn: string; /** * Returns a string representation of an object. */ toString(): string; } declare var HTMLAnchorElement: { prototype: HTMLAnchorElement; new(): HTMLAnchorElement; } interface HTMLAppletElement extends HTMLElement { /** * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. */ BaseHref: string; align: string; /** * Sets or retrieves a text alternative to the graphic. */ alt: string; /** * Gets or sets the optional alternative HTML script to execute if the object fails to load. */ altHtml: string; /** * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. */ archive: string; border: string; code: string; /** * Sets or retrieves the URL of the component. */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ codeType: string; /** * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. */ contentDocument: Document; /** * Sets or retrieves the URL that references the data of the object. */ data: string; /** * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. */ declare: boolean; form: HTMLFormElement; /** * Sets or retrieves the height of the object. */ height: string; hspace: number; /** * Sets or retrieves the shape of the object. */ name: string; object: string; /** * Sets or retrieves a message to be displayed while an object is loading. */ standby: string; /** * Returns the content type of the object. */ type: string; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ useMap: string; vspace: number; width: number; } declare var HTMLAppletElement: { prototype: HTMLAppletElement; new(): HTMLAppletElement; } interface HTMLAreaElement extends HTMLElement { /** * Sets or retrieves a text alternative to the graphic. */ alt: string; /** * Sets or retrieves the coordinates of the object. */ coords: string; /** * Sets or retrieves the subsection of the href property that follows the number sign (#). */ hash: string; /** * Sets or retrieves the hostname and port number of the location or URL. */ host: string; /** * Sets or retrieves the host name part of the location or URL. */ hostname: string; /** * Sets or retrieves a destination URL or an anchor point. */ href: string; /** * Sets or gets whether clicks in this region cause action. */ noHref: boolean; /** * Sets or retrieves the file name or path specified by the object. */ pathname: string; /** * Sets or retrieves the port number associated with a URL. */ port: string; /** * Sets or retrieves the protocol portion of a URL. */ protocol: string; rel: string; /** * Sets or retrieves the substring of the href property that follows the question mark. */ search: string; /** * Sets or retrieves the shape of the object. */ shape: string; /** * Sets or retrieves the window or frame at which to target content. */ target: string; /** * Returns a string representation of an object. */ toString(): string; } declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; } interface HTMLAreasCollection extends HTMLCollection { /** * Adds an element to the areas, controlRange, or options collection. */ add(element: HTMLElement, before?: HTMLElement | number): void; /** * Removes an element from the collection. */ remove(index?: number): void; } declare var HTMLAreasCollection: { prototype: HTMLAreasCollection; new(): HTMLAreasCollection; } interface HTMLAudioElement extends HTMLMediaElement { } declare var HTMLAudioElement: { prototype: HTMLAudioElement; new(): HTMLAudioElement; } interface HTMLBRElement extends HTMLElement { /** * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. */ clear: string; } declare var HTMLBRElement: { prototype: HTMLBRElement; new(): HTMLBRElement; } interface HTMLBaseElement extends HTMLElement { /** * Gets or sets the baseline URL on which relative links are based. */ href: string; /** * Sets or retrieves the window or frame at which to target content. */ target: string; } declare var HTMLBaseElement: { prototype: HTMLBaseElement; new(): HTMLBaseElement; } interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { /** * Sets or retrieves the current typeface family. */ face: string; /** * Sets or retrieves the font size of the object. */ size: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; } interface HTMLBlockElement extends HTMLElement { /** * Sets or retrieves reference information about the object. */ cite: string; clear: string; /** * Sets or retrieves the width of the object. */ width: number; } declare var HTMLBlockElement: { prototype: HTMLBlockElement; new(): HTMLBlockElement; } interface HTMLBodyElement extends HTMLElement { aLink: any; background: string; bgColor: any; bgProperties: string; link: any; noWrap: boolean; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; onblur: (ev: FocusEvent) => any; onerror: (ev: Event) => any; onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; onload: (ev: Event) => any; onmessage: (ev: MessageEvent) => any; onoffline: (ev: Event) => any; ononline: (ev: Event) => any; onorientationchange: (ev: Event) => any; onpagehide: (ev: PageTransitionEvent) => any; onpageshow: (ev: PageTransitionEvent) => any; onpopstate: (ev: PopStateEvent) => any; onresize: (ev: UIEvent) => any; onstorage: (ev: StorageEvent) => any; onunload: (ev: Event) => any; text: any; vLink: any; createTextRange(): TextRange; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "hashchange", listener: (ev: HashChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLBodyElement: { prototype: HTMLBodyElement; new(): HTMLBodyElement; } interface HTMLButtonElement extends HTMLElement { /** * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. */ autofocus: boolean; disabled: boolean; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ formAction: string; /** * Used to override the encoding (formEnctype attribute) specified on the form element. */ formEnctype: string; /** * Overrides the submit method attribute previously specified on a form element. */ formMethod: string; /** * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. */ formNoValidate: string; /** * Overrides the target attribute on a form element. */ formTarget: string; /** * Sets or retrieves the name of the object. */ name: string; status: any; /** * Gets the classification and default behavior of the button. */ type: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ validationMessage: string; /** * Returns a ValidityState object that represents the validity states of an element. */ validity: ValidityState; /** * Sets or retrieves the default or selected value of the control. */ value: string; /** * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; /** * Creates a TextRange object for the element. */ createTextRange(): TextRange; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; } declare var HTMLButtonElement: { prototype: HTMLButtonElement; new(): HTMLButtonElement; } interface HTMLCanvasElement extends HTMLElement { /** * Gets or sets the height of a canvas element on a document. */ height: number; /** * Gets or sets the width of a canvas element on a document. */ width: number; /** * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ getContext(contextId: "2d"): CanvasRenderingContext2D; getContext(contextId: "experimental-webgl"): WebGLRenderingContext; getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext; /** * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ msToBlob(): Blob; /** * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; toBlob(): Blob; } declare var HTMLCanvasElement: { prototype: HTMLCanvasElement; new(): HTMLCanvasElement; } interface HTMLCollection { /** * Sets or retrieves the number of objects in a collection. */ length: number; /** * Retrieves an object from various collections. */ item(nameOrIndex?: any, optionalIndex?: any): Element; /** * Retrieves a select object or an object from an options collection. */ namedItem(name: string): Element; [index: number]: Element; } declare var HTMLCollection: { prototype: HTMLCollection; new(): HTMLCollection; } interface HTMLDDElement extends HTMLElement { /** * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; } declare var HTMLDDElement: { prototype: HTMLDDElement; new(): HTMLDDElement; } interface HTMLDListElement extends HTMLElement { compact: boolean; } declare var HTMLDListElement: { prototype: HTMLDListElement; new(): HTMLDListElement; } interface HTMLDTElement extends HTMLElement { /** * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; } declare var HTMLDTElement: { prototype: HTMLDTElement; new(): HTMLDTElement; } interface HTMLDataListElement extends HTMLElement { options: HTMLCollection; } declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; } interface HTMLDirectoryElement extends HTMLElement { compact: boolean; } declare var HTMLDirectoryElement: { prototype: HTMLDirectoryElement; new(): HTMLDirectoryElement; } interface HTMLDivElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; } declare var HTMLDivElement: { prototype: HTMLDivElement; new(): HTMLDivElement; } interface HTMLDocument extends Document { } declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; } interface HTMLElement extends Element { accessKey: string; children: HTMLCollection; contentEditable: string; dataset: DOMStringMap; dir: string; draggable: boolean; hidden: boolean; hideFocus: boolean; innerHTML: string; innerText: string; isContentEditable: boolean; lang: string; offsetHeight: number; offsetLeft: number; offsetParent: Element; offsetTop: number; offsetWidth: number; onabort: (ev: Event) => any; onactivate: (ev: UIEvent) => any; onbeforeactivate: (ev: UIEvent) => any; onbeforecopy: (ev: DragEvent) => any; onbeforecut: (ev: DragEvent) => any; onbeforedeactivate: (ev: UIEvent) => any; onbeforepaste: (ev: DragEvent) => any; onblur: (ev: FocusEvent) => any; oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; onchange: (ev: Event) => any; onclick: (ev: MouseEvent) => any; oncontextmenu: (ev: PointerEvent) => any; oncopy: (ev: DragEvent) => any; oncuechange: (ev: Event) => any; oncut: (ev: DragEvent) => any; ondblclick: (ev: MouseEvent) => any; ondeactivate: (ev: UIEvent) => any; ondrag: (ev: DragEvent) => any; ondragend: (ev: DragEvent) => any; ondragenter: (ev: DragEvent) => any; ondragleave: (ev: DragEvent) => any; ondragover: (ev: DragEvent) => any; ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; ondurationchange: (ev: Event) => any; onemptied: (ev: Event) => any; onended: (ev: Event) => any; onerror: (ev: Event) => any; onfocus: (ev: FocusEvent) => any; oninput: (ev: Event) => any; onkeydown: (ev: KeyboardEvent) => any; onkeypress: (ev: KeyboardEvent) => any; onkeyup: (ev: KeyboardEvent) => any; onload: (ev: Event) => any; onloadeddata: (ev: Event) => any; onloadedmetadata: (ev: Event) => any; onloadstart: (ev: Event) => any; onmousedown: (ev: MouseEvent) => any; onmouseenter: (ev: MouseEvent) => any; onmouseleave: (ev: MouseEvent) => any; onmousemove: (ev: MouseEvent) => any; onmouseout: (ev: MouseEvent) => any; onmouseover: (ev: MouseEvent) => any; onmouseup: (ev: MouseEvent) => any; onmousewheel: (ev: MouseWheelEvent) => any; onmscontentzoom: (ev: UIEvent) => any; onmsmanipulationstatechanged: (ev: MSManipulationEvent) => any; onpaste: (ev: DragEvent) => any; onpause: (ev: Event) => any; onplay: (ev: Event) => any; onplaying: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; onratechange: (ev: Event) => any; onreset: (ev: Event) => any; onscroll: (ev: UIEvent) => any; onseeked: (ev: Event) => any; onseeking: (ev: Event) => any; onselect: (ev: UIEvent) => any; onselectstart: (ev: Event) => any; onstalled: (ev: Event) => any; onsubmit: (ev: Event) => any; onsuspend: (ev: Event) => any; ontimeupdate: (ev: Event) => any; onvolumechange: (ev: Event) => any; onwaiting: (ev: Event) => any; outerHTML: string; outerText: string; spellcheck: boolean; style: CSSStyleDeclaration; tabIndex: number; title: string; blur(): void; click(): void; dragDrop(): boolean; focus(): void; insertAdjacentElement(position: string, insertedElement: Element): Element; insertAdjacentHTML(where: string, html: string): void; insertAdjacentText(where: string, text: string): void; msGetInputContext(): MSInputMethodContext; scrollIntoView(top?: boolean): void; setActive(): void; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLElement: { prototype: HTMLElement; new(): HTMLElement; } interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves the height of the object. */ height: string; hidden: any; /** * Gets or sets whether the DLNA PlayTo device is available. */ msPlayToDisabled: boolean; /** * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. */ msPlayToPreferredSourceUri: string; /** * Gets or sets the primary DLNA PlayTo device. */ msPlayToPrimary: boolean; /** * Gets the source associated with the media element for use by the PlayToManager. */ msPlayToSource: any; /** * Sets or retrieves the name of the object. */ name: string; /** * Retrieves the palette used for the embedded document. */ palette: string; /** * Retrieves the URL of the plug-in used to view an embedded document. */ pluginspage: string; readyState: string; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** * Sets or retrieves the height and width units of the embed object. */ units: string; /** * Sets or retrieves the width of the object. */ width: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLEmbedElement: { prototype: HTMLEmbedElement; new(): HTMLEmbedElement; } interface HTMLFieldSetElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; disabled: boolean; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ validationMessage: string; /** * Returns a ValidityState object that represents the validity states of an element. */ validity: ValidityState; /** * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; } declare var HTMLFieldSetElement: { prototype: HTMLFieldSetElement; new(): HTMLFieldSetElement; } interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** * Sets or retrieves the current typeface family. */ face: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; } interface HTMLFormElement extends HTMLElement { /** * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. */ acceptCharset: string; /** * Sets or retrieves the URL to which the form content is sent for processing. */ action: string; /** * Specifies whether autocomplete is applied to an editable text field. */ autocomplete: string; /** * Retrieves a collection, in source order, of all controls in a given form. */ elements: HTMLCollection; /** * Sets or retrieves the MIME encoding for the form. */ encoding: string; /** * Sets or retrieves the encoding type for the form. */ enctype: string; /** * Sets or retrieves the number of objects in a collection. */ length: number; /** * Sets or retrieves how to send the form data to the server. */ method: string; /** * Sets or retrieves the name of the object. */ name: string; /** * Designates a form that is not validated when submitted. */ noValidate: boolean; /** * Sets or retrieves the window or frame at which to target content. */ target: string; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; /** * Retrieves a form object or an object from an elements collection. * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. */ item(name?: any, index?: any): any; /** * Retrieves a form object or an object from an elements collection. */ namedItem(name: string): any; /** * Fires when the user resets a form. */ reset(): void; /** * Fires when a FORM is about to be submitted. */ submit(): void; [name: string]: any; } declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; } interface HTMLFrameElement extends HTMLElement, GetSVGDocument { /** * Specifies the properties of a border drawn around an object. */ border: string; /** * Sets or retrieves the border color of the object. */ borderColor: any; /** * Retrieves the document object of the page or frame. */ contentDocument: Document; /** * Retrieves the object of the specified. */ contentWindow: Window; /** * Sets or retrieves whether to display a border for the frame. */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. */ frameSpacing: any; /** * Sets or retrieves the height of the object. */ height: string | number; /** * Sets or retrieves a URI to a long description of the object. */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ marginWidth: string; /** * Sets or retrieves the frame name. */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; /** * Raised when the object has been completely received from the server. */ onload: (ev: Event) => any; /** * Sets or retrieves whether the frame can be scrolled. */ scrolling: string; /** * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. */ security: any; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** * Sets or retrieves the width of the object. */ width: string | number; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; } interface HTMLFrameSetElement extends HTMLElement { border: string; /** * Sets or retrieves the border color of the object. */ borderColor: any; /** * Sets or retrieves the frame widths of the object. */ cols: string; /** * Sets or retrieves whether to display a border for the frame. */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. */ frameSpacing: any; name: string; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; /** * Fires when the object loses the input focus. */ onblur: (ev: FocusEvent) => any; onerror: (ev: Event) => any; /** * Fires when the object receives focus. */ onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; onload: (ev: Event) => any; onmessage: (ev: MessageEvent) => any; onoffline: (ev: Event) => any; ononline: (ev: Event) => any; onorientationchange: (ev: Event) => any; onpagehide: (ev: PageTransitionEvent) => any; onpageshow: (ev: PageTransitionEvent) => any; onresize: (ev: UIEvent) => any; onstorage: (ev: StorageEvent) => any; onunload: (ev: Event) => any; /** * Sets or retrieves the frame heights of the object. */ rows: string; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "hashchange", listener: (ev: HashChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; new(): HTMLFrameSetElement; } interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. */ noShade: boolean; /** * Sets or retrieves the width of the object. */ width: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLHRElement: { prototype: HTMLHRElement; new(): HTMLHRElement; } interface HTMLHeadElement extends HTMLElement { profile: string; } declare var HTMLHeadElement: { prototype: HTMLHeadElement; new(): HTMLHeadElement; } interface HTMLHeadingElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ align: string; clear: string; } declare var HTMLHeadingElement: { prototype: HTMLHeadingElement; new(): HTMLHeadingElement; } interface HTMLHtmlElement extends HTMLElement { /** * Sets or retrieves the DTD version that governs the current document. */ version: string; } declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; } interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; allowFullscreen: boolean; /** * Specifies the properties of a border drawn around an object. */ border: string; /** * Retrieves the document object of the page or frame. */ contentDocument: Document; /** * Retrieves the object of the specified. */ contentWindow: Window; /** * Sets or retrieves whether to display a border for the frame. */ frameBorder: string; /** * Sets or retrieves the amount of additional space between the frames. */ frameSpacing: any; /** * Sets or retrieves the height of the object. */ height: string; /** * Sets or retrieves the horizontal margin for the object. */ hspace: number; /** * Sets or retrieves a URI to a long description of the object. */ longDesc: string; /** * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. */ marginHeight: string; /** * Sets or retrieves the left and right margin widths before displaying the text in a frame. */ marginWidth: string; /** * Sets or retrieves the frame name. */ name: string; /** * Sets or retrieves whether the user can resize the frame. */ noResize: boolean; /** * Raised when the object has been completely received from the server. */ onload: (ev: Event) => any; sandbox: DOMSettableTokenList; /** * Sets or retrieves whether the frame can be scrolled. */ scrolling: string; /** * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. */ security: any; /** * Sets or retrieves a URL to be loaded by the object. */ src: string; /** * Sets or retrieves the vertical margin for the object. */ vspace: number; /** * Sets or retrieves the width of the object. */ width: string; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; new(): HTMLIFrameElement; } interface HTMLImageElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ alt: string; /** * Specifies the properties of a border drawn around an object. */ border: string; /** * Retrieves whether the object is fully loaded. */ complete: boolean; crossOrigin: string; currentSrc: string; /** * Sets or retrieves the height of the object. */ height: number; /** * Sets or retrieves the width of the border to draw around the object. */ hspace: number; /** * Sets or retrieves whether the image is a server-side image map. */ isMap: boolean; /** * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. */ longDesc: string; /** * Gets or sets whether the DLNA PlayTo device is available. */ msPlayToDisabled: boolean; msPlayToPreferredSourceUri: string; /** * Gets or sets the primary DLNA PlayTo device. */ msPlayToPrimary: boolean; /** * Gets the source associated with the media element for use by the PlayToManager. */ msPlayToSource: any; /** * Sets or retrieves the name of the object. */ name: string; /** * The original height of the image resource before sizing. */ naturalHeight: number; /** * The original width of the image resource before sizing. */ naturalWidth: number; /** * The address or URL of the a media resource that is to be considered. */ src: string; srcset: string; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ useMap: string; /** * Sets or retrieves the vertical margin for the object. */ vspace: number; /** * Sets or retrieves the width of the object. */ width: number; x: number; y: number; msGetAsCastingSource(): any; } declare var HTMLImageElement: { prototype: HTMLImageElement; new(): HTMLImageElement; create(): HTMLImageElement; } interface HTMLInputElement extends HTMLElement { /** * Sets or retrieves a comma-separated list of content types. */ accept: string; /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** * Sets or retrieves a text alternative to the graphic. */ alt: string; /** * Specifies whether autocomplete is applied to an editable text field. */ autocomplete: string; /** * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. */ autofocus: boolean; /** * Sets or retrieves the width of the border to draw around the object. */ border: string; /** * Sets or retrieves the state of the check box or radio button. */ checked: boolean; /** * Retrieves whether the object is fully loaded. */ complete: boolean; /** * Sets or retrieves the state of the check box or radio button. */ defaultChecked: boolean; /** * Sets or retrieves the initial contents of the object. */ defaultValue: string; disabled: boolean; /** * Returns a FileList object on a file type input object. */ files: FileList; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ formAction: string; /** * Used to override the encoding (formEnctype attribute) specified on the form element. */ formEnctype: string; /** * Overrides the submit method attribute previously specified on a form element. */ formMethod: string; /** * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. */ formNoValidate: string; /** * Overrides the target attribute on a form element. */ formTarget: string; /** * Sets or retrieves the height of the object. */ height: string; /** * Sets or retrieves the width of the border to draw around the object. */ hspace: number; indeterminate: boolean; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ list: HTMLElement; /** * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. */ max: string; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; /** * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. */ min: string; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ multiple: boolean; /** * Sets or retrieves the name of the object. */ name: string; /** * Gets or sets a string containing a regular expression that the user's input must match. */ pattern: string; /** * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. */ placeholder: string; readOnly: boolean; /** * When present, marks an element that can't be submitted without a value. */ required: boolean; /** * Gets or sets the end position or offset of a text selection. */ selectionEnd: number; /** * Gets or sets the starting position or offset of a text selection. */ selectionStart: number; size: number; /** * The address or URL of the a media resource that is to be considered. */ src: string; status: boolean; /** * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. */ step: string; /** * Returns the content type of the object. */ type: string; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ useMap: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ validationMessage: string; /** * Returns a ValidityState object that represents the validity states of an element. */ validity: ValidityState; /** * Returns the value of the data at the cursor's current position. */ value: string; valueAsDate: Date; /** * Returns the input field value as a number. */ valueAsNumber: number; /** * Sets or retrieves the vertical margin for the object. */ vspace: number; /** * Sets or retrieves the width of the object. */ width: string; /** * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; /** * Creates a TextRange object for the element. */ createTextRange(): TextRange; /** * Makes the selection equal to the current object. */ select(): void; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; /** * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. */ stepDown(n?: number): void; /** * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. * @param n Value to increment the value by. */ stepUp(n?: number): void; } declare var HTMLInputElement: { prototype: HTMLInputElement; new(): HTMLInputElement; } interface HTMLIsIndexElement extends HTMLElement { /** * Sets or retrieves the URL to which the form content is sent for processing. */ action: string; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; prompt: string; } declare var HTMLIsIndexElement: { prototype: HTMLIsIndexElement; new(): HTMLIsIndexElement; } interface HTMLLIElement extends HTMLElement { type: string; /** * Sets or retrieves the value of a list item. */ value: number; } declare var HTMLLIElement: { prototype: HTMLLIElement; new(): HTMLLIElement; } interface HTMLLabelElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Sets or retrieves the object to which the given label object is assigned. */ htmlFor: string; } declare var HTMLLabelElement: { prototype: HTMLLabelElement; new(): HTMLLabelElement; } interface HTMLLegendElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ align: string; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; } declare var HTMLLegendElement: { prototype: HTMLLegendElement; new(): HTMLLegendElement; } interface HTMLLinkElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the character set used to encode the object. */ charset: string; disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. */ href: string; /** * Sets or retrieves the language code of the object. */ hreflang: string; /** * Sets or retrieves the media type. */ media: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ rel: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ rev: string; /** * Sets or retrieves the window or frame at which to target content. */ target: string; /** * Sets or retrieves the MIME type of the object. */ type: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLLinkElement: { prototype: HTMLLinkElement; new(): HTMLLinkElement; } interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. */ areas: HTMLAreasCollection; /** * Sets or retrieves the name of the object. */ name: string; } declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; } interface HTMLMarqueeElement extends HTMLElement { behavior: string; bgColor: any; direction: string; height: string; hspace: number; loop: number; onbounce: (ev: Event) => any; onfinish: (ev: Event) => any; onstart: (ev: Event) => any; scrollAmount: number; scrollDelay: number; trueSpeed: boolean; vspace: number; width: string; start(): void; stop(): void; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "bounce", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "finish", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "start", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; } interface HTMLMediaElement extends HTMLElement { /** * Returns an AudioTrackList object with the audio tracks for a given video element. */ audioTracks: AudioTrackList; /** * Gets or sets a value that indicates whether to start playing the media automatically. */ autoplay: boolean; /** * Gets a collection of buffered time ranges. */ buffered: TimeRanges; /** * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). */ controls: boolean; /** * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. */ currentSrc: string; /** * Gets or sets the current playback position, in seconds. */ currentTime: number; defaultMuted: boolean; /** * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. */ defaultPlaybackRate: number; /** * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. */ duration: number; /** * Gets information about whether the playback has ended or not. */ ended: boolean; /** * Returns an object representing the current error state of the audio or video element. */ error: MediaError; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ loop: boolean; /** * Specifies the purpose of the audio or video media, such as background audio or alerts. */ msAudioCategory: string; /** * Specifies the output device id that the audio will be sent to. */ msAudioDeviceType: string; msGraphicsTrustStatus: MSGraphicsTrust; /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ msKeys: MSMediaKeys; /** * Gets or sets whether the DLNA PlayTo device is available. */ msPlayToDisabled: boolean; /** * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. */ msPlayToPreferredSourceUri: string; /** * Gets or sets the primary DLNA PlayTo device. */ msPlayToPrimary: boolean; /** * Gets the source associated with the media element for use by the PlayToManager. */ msPlayToSource: any; /** * Specifies whether or not to enable low-latency playback on the media element. */ msRealTime: boolean; /** * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. */ muted: boolean; /** * Gets the current network activity for the element. */ networkState: number; onmsneedkey: (ev: MSMediaKeyNeededEvent) => any; /** * Gets a flag that specifies whether playback is paused. */ paused: boolean; /** * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. */ playbackRate: number; /** * Gets TimeRanges for the current media resource that has been played. */ played: TimeRanges; /** * Gets or sets the current playback position, in seconds. */ preload: string; readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ seekable: TimeRanges; /** * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. */ seeking: boolean; /** * The address or URL of the a media resource that is to be considered. */ src: string; textTracks: TextTrackList; videoTracks: VideoTrackList; /** * Gets or sets the volume level for audio portions of the media element. */ volume: number; addTextTrack(kind: string, label?: string, language?: string): TextTrack; /** * Returns a string that specifies whether the client can play a given media resource type. */ canPlayType(type: string): string; /** * Fires immediately after the client loads the object. */ load(): void; /** * Clears all effects from the media pipeline. */ msClearEffects(): void; msGetAsCastingSource(): any; /** * Inserts the specified audio effect into media pipeline. */ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Specifies the media protection manager for a given media pipeline. */ msSetMediaProtectionManager(mediaProtectionManager?: any): void; /** * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. */ pause(): void; /** * Loads and starts playback of a media resource. */ play(): void; HAVE_CURRENT_DATA: number; HAVE_ENOUGH_DATA: number; HAVE_FUTURE_DATA: number; HAVE_METADATA: number; HAVE_NOTHING: number; NETWORK_EMPTY: number; NETWORK_IDLE: number; NETWORK_LOADING: number; NETWORK_NO_SOURCE: number; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLMediaElement: { prototype: HTMLMediaElement; new(): HTMLMediaElement; HAVE_CURRENT_DATA: number; HAVE_ENOUGH_DATA: number; HAVE_FUTURE_DATA: number; HAVE_METADATA: number; HAVE_NOTHING: number; NETWORK_EMPTY: number; NETWORK_IDLE: number; NETWORK_LOADING: number; NETWORK_NO_SOURCE: number; } interface HTMLMenuElement extends HTMLElement { compact: boolean; type: string; } declare var HTMLMenuElement: { prototype: HTMLMenuElement; new(): HTMLMenuElement; } interface HTMLMetaElement extends HTMLElement { /** * Sets or retrieves the character set used to encode the object. */ charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. */ content: string; /** * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. */ httpEquiv: string; /** * Sets or retrieves the value specified in the content attribute of the meta object. */ name: string; /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ scheme: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; } declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; } interface HTMLModElement extends HTMLElement { /** * Sets or retrieves reference information about the object. */ cite: string; /** * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; } declare var HTMLModElement: { prototype: HTMLModElement; new(): HTMLModElement; } interface HTMLNextIdElement extends HTMLElement { n: string; } declare var HTMLNextIdElement: { prototype: HTMLNextIdElement; new(): HTMLNextIdElement; } interface HTMLOListElement extends HTMLElement { compact: boolean; /** * The starting number. */ start: number; type: string; } declare var HTMLOListElement: { prototype: HTMLOListElement; new(): HTMLOListElement; } interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. */ BaseHref: string; align: string; /** * Sets or retrieves a text alternative to the graphic. */ alt: string; /** * Gets or sets the optional alternative HTML script to execute if the object fails to load. */ altHtml: string; /** * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. */ archive: string; border: string; /** * Sets or retrieves the URL of the file containing the compiled Java class. */ code: string; /** * Sets or retrieves the URL of the component. */ codeBase: string; /** * Sets or retrieves the Internet media type for the code associated with the object. */ codeType: string; /** * Retrieves the document object of the page or frame. */ contentDocument: Document; /** * Sets or retrieves the URL that references the data of the object. */ data: string; declare: boolean; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Sets or retrieves the height of the object. */ height: string; hspace: number; /** * Gets or sets whether the DLNA PlayTo device is available. */ msPlayToDisabled: boolean; /** * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. */ msPlayToPreferredSourceUri: string; /** * Gets or sets the primary DLNA PlayTo device. */ msPlayToPrimary: boolean; /** * Gets the source associated with the media element for use by the PlayToManager. */ msPlayToSource: any; /** * Sets or retrieves the name of the object. */ name: string; /** * Retrieves the contained object. */ object: any; readyState: number; /** * Sets or retrieves a message to be displayed while an object is loading. */ standby: string; /** * Sets or retrieves the MIME type of the object. */ type: string; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ useMap: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ validationMessage: string; /** * Returns a ValidityState object that represents the validity states of an element. */ validity: ValidityState; vspace: number; /** * Sets or retrieves the width of the object. */ width: string; /** * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLObjectElement: { prototype: HTMLObjectElement; new(): HTMLObjectElement; } interface HTMLOptGroupElement extends HTMLElement { /** * Sets or retrieves the status of an option. */ defaultSelected: boolean; disabled: boolean; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Sets or retrieves the ordinal position of an option in a list box. */ index: number; /** * Sets or retrieves a value that you can use to implement your own label functionality for the object. */ label: string; /** * Sets or retrieves whether the option in the list box is the default item. */ selected: boolean; /** * Sets or retrieves the text string specified by the option tag. */ text: string; /** * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; } declare var HTMLOptGroupElement: { prototype: HTMLOptGroupElement; new(): HTMLOptGroupElement; } interface HTMLOptionElement extends HTMLElement { /** * Sets or retrieves the status of an option. */ defaultSelected: boolean; disabled: boolean; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Sets or retrieves the ordinal position of an option in a list box. */ index: number; /** * Sets or retrieves a value that you can use to implement your own label functionality for the object. */ label: string; /** * Sets or retrieves whether the option in the list box is the default item. */ selected: boolean; /** * Sets or retrieves the text string specified by the option tag. */ text: string; /** * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; } declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; create(): HTMLOptionElement; } interface HTMLParagraphElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; clear: string; } declare var HTMLParagraphElement: { prototype: HTMLParagraphElement; new(): HTMLParagraphElement; } interface HTMLParamElement extends HTMLElement { /** * Sets or retrieves the name of an input parameter for an element. */ name: string; /** * Sets or retrieves the content type of the resource designated by the value attribute. */ type: string; /** * Sets or retrieves the value of an input parameter for an element. */ value: string; /** * Sets or retrieves the data type of the value attribute. */ valueType: string; } declare var HTMLParamElement: { prototype: HTMLParamElement; new(): HTMLParamElement; } interface HTMLPhraseElement extends HTMLElement { /** * Sets or retrieves reference information about the object. */ cite: string; /** * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; } declare var HTMLPhraseElement: { prototype: HTMLPhraseElement; new(): HTMLPhraseElement; } interface HTMLPreElement extends HTMLElement { /** * Indicates a citation by rendering text in italic type. */ cite: string; clear: string; /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ width: number; } declare var HTMLPreElement: { prototype: HTMLPreElement; new(): HTMLPreElement; } interface HTMLProgressElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Defines the maximum, or "done" value for a progress element. */ max: number; /** * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). */ position: number; /** * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. */ value: number; } declare var HTMLProgressElement: { prototype: HTMLProgressElement; new(): HTMLProgressElement; } interface HTMLQuoteElement extends HTMLElement { /** * Sets or retrieves reference information about the object. */ cite: string; /** * Sets or retrieves the date and time of a modification to the object. */ dateTime: string; } declare var HTMLQuoteElement: { prototype: HTMLQuoteElement; new(): HTMLQuoteElement; } interface HTMLScriptElement extends HTMLElement { async: boolean; /** * Sets or retrieves the character set used to encode the object. */ charset: string; /** * Sets or retrieves the status of the script. */ defer: boolean; /** * Sets or retrieves the event for which the script is written. */ event: string; /** * Sets or retrieves the object that is bound to the event script. */ htmlFor: string; /** * Retrieves the URL to an external file that contains the source code or data. */ src: string; /** * Retrieves or sets the text of the object as a string. */ text: string; /** * Sets or retrieves the MIME type for the associated scripting engine. */ type: string; } declare var HTMLScriptElement: { prototype: HTMLScriptElement; new(): HTMLScriptElement; } interface HTMLSelectElement extends HTMLElement { /** * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. */ autofocus: boolean; disabled: boolean; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Sets or retrieves the number of objects in a collection. */ length: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ multiple: boolean; /** * Sets or retrieves the name of the object. */ name: string; options: HTMLCollection; /** * When present, marks an element that can't be submitted without a value. */ required: boolean; /** * Sets or retrieves the index of the selected option in a select object. */ selectedIndex: number; /** * Sets or retrieves the number of rows in the list box. */ size: number; /** * Retrieves the type of select control based on the value of the MULTIPLE attribute. */ type: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ validationMessage: string; /** * Returns a ValidityState object that represents the validity states of an element. */ validity: ValidityState; /** * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value: string; /** * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; selectedOptions: HTMLCollection; /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. */ add(element: HTMLElement, before?: HTMLElement | number): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; /** * Retrieves a select object or an object from an options collection. * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. */ item(name?: any, index?: any): any; /** * Retrieves a select object or an object from an options collection. * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. */ namedItem(name: string): any; /** * Removes an element from the collection. * @param index Number that specifies the zero-based index of the element to remove from the collection. */ remove(index?: number): void; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; [name: string]: any; } declare var HTMLSelectElement: { prototype: HTMLSelectElement; new(): HTMLSelectElement; } interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; msKeySystem: string; /** * The address or URL of the a media resource that is to be considered. */ src: string; /** * Gets or sets the MIME type of a media resource. */ type: string; } declare var HTMLSourceElement: { prototype: HTMLSourceElement; new(): HTMLSourceElement; } interface HTMLSpanElement extends HTMLElement { } declare var HTMLSpanElement: { prototype: HTMLSpanElement; new(): HTMLSpanElement; } interface HTMLStyleElement extends HTMLElement, LinkStyle { /** * Sets or retrieves the media type. */ media: string; /** * Retrieves the CSS language in which the style sheet is written. */ type: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLStyleElement: { prototype: HTMLStyleElement; new(): HTMLStyleElement; } interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. */ align: string; /** * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign: string; } declare var HTMLTableCaptionElement: { prototype: HTMLTableCaptionElement; new(): HTMLTableCaptionElement; } interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves abbreviated text for the object. */ abbr: string; /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. */ axis: string; bgColor: any; /** * Retrieves the position of the object in the cells collection of a row. */ cellIndex: number; /** * Sets or retrieves the number columns in the table that the object should span. */ colSpan: number; /** * Sets or retrieves a list of header cells that provide information for the object. */ headers: string; /** * Sets or retrieves the height of the object. */ height: any; /** * Sets or retrieves whether the browser automatically performs wordwrap. */ noWrap: boolean; /** * Sets or retrieves how many rows in a table the cell should span. */ rowSpan: number; /** * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; /** * Sets or retrieves the width of the object. */ width: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTableCellElement: { prototype: HTMLTableCellElement; new(): HTMLTableCellElement; } interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves the alignment of the object relative to the display or table. */ align: string; /** * Sets or retrieves the number of columns in the group. */ span: number; /** * Sets or retrieves the width of the object. */ width: any; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTableColElement: { prototype: HTMLTableColElement; new(): HTMLTableColElement; } interface HTMLTableDataCellElement extends HTMLTableCellElement { } declare var HTMLTableDataCellElement: { prototype: HTMLTableDataCellElement; new(): HTMLTableDataCellElement; } interface HTMLTableElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. */ align: string; bgColor: any; /** * Sets or retrieves the width of the border to draw around the object. */ border: string; /** * Sets or retrieves the border color of the object. */ borderColor: any; /** * Retrieves the caption object of a table. */ caption: HTMLTableCaptionElement; /** * Sets or retrieves the amount of space between the border of the cell and the content of the cell. */ cellPadding: string; /** * Sets or retrieves the amount of space between cells in a table. */ cellSpacing: string; /** * Sets or retrieves the number of columns in the table. */ cols: number; /** * Sets or retrieves the way the border frame around the table is displayed. */ frame: string; /** * Sets or retrieves the height of the object. */ height: any; /** * Sets or retrieves the number of horizontal rows contained in the object. */ rows: HTMLCollection; /** * Sets or retrieves which dividing lines (inner borders) are displayed. */ rules: string; /** * Sets or retrieves a description and/or structure of the object. */ summary: string; /** * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. */ tBodies: HTMLCollection; /** * Retrieves the tFoot object of the table. */ tFoot: HTMLTableSectionElement; /** * Retrieves the tHead object of the table. */ tHead: HTMLTableSectionElement; /** * Sets or retrieves the width of the object. */ width: string; /** * Creates an empty caption element in the table. */ createCaption(): HTMLTableCaptionElement; /** * Creates an empty tBody element in the table. */ createTBody(): HTMLTableSectionElement; /** * Creates an empty tFoot element in the table. */ createTFoot(): HTMLTableSectionElement; /** * Returns the tHead element object if successful, or null otherwise. */ createTHead(): HTMLTableSectionElement; /** * Deletes the caption element and its contents from the table. */ deleteCaption(): void; /** * Removes the specified row (tr) from the element and from the rows collection. * @param index Number that specifies the zero-based position in the rows collection of the row to remove. */ deleteRow(index?: number): void; /** * Deletes the tFoot element and its contents from the table. */ deleteTFoot(): void; /** * Deletes the tHead element and its contents from the table. */ deleteTHead(): void; /** * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; } declare var HTMLTableElement: { prototype: HTMLTableElement; new(): HTMLTableElement; } interface HTMLTableHeaderCellElement extends HTMLTableCellElement { /** * Sets or retrieves the group of cells in a table to which the object's information applies. */ scope: string; } declare var HTMLTableHeaderCellElement: { prototype: HTMLTableHeaderCellElement; new(): HTMLTableHeaderCellElement; } interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves how the object is aligned with adjacent text. */ align: string; bgColor: any; /** * Retrieves a collection of all cells in the table row. */ cells: HTMLCollection; /** * Sets or retrieves the height of the object. */ height: any; /** * Retrieves the position of the object in the rows collection for the table. */ rowIndex: number; /** * Retrieves the position of the object in the collection. */ sectionRowIndex: number; /** * Removes the specified cell from the table row, as well as from the cells collection. * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. */ deleteCell(index?: number): void; /** * Creates a new cell in the table row, and adds the cell to the cells collection. * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ insertCell(index?: number): HTMLTableCellElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTableRowElement: { prototype: HTMLTableRowElement; new(): HTMLTableRowElement; } interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { /** * Sets or retrieves a value that indicates the table alignment. */ align: string; /** * Sets or retrieves the number of horizontal rows contained in the object. */ rows: HTMLCollection; /** * Removes the specified row (tr) from the element and from the rows collection. * @param index Number that specifies the zero-based position in the rows collection of the row to remove. */ deleteRow(index?: number): void; /** * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ insertRow(index?: number): HTMLTableRowElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; } interface HTMLTextAreaElement extends HTMLElement { /** * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. */ autofocus: boolean; /** * Sets or retrieves the width of the object. */ cols: number; /** * Sets or retrieves the initial contents of the object. */ defaultValue: string; disabled: boolean; /** * Retrieves a reference to the form that the object is embedded in. */ form: HTMLFormElement; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength: number; /** * Sets or retrieves the name of the object. */ name: string; /** * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. */ placeholder: string; /** * Sets or retrieves the value indicated whether the content of the object is read-only. */ readOnly: boolean; /** * When present, marks an element that can't be submitted without a value. */ required: boolean; /** * Sets or retrieves the number of horizontal rows contained in the object. */ rows: number; /** * Gets or sets the end position or offset of a text selection. */ selectionEnd: number; /** * Gets or sets the starting position or offset of a text selection. */ selectionStart: number; /** * Sets or retrieves the value indicating whether the control is selected. */ status: any; /** * Retrieves the type of control. */ type: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ validationMessage: string; /** * Returns a ValidityState object that represents the validity states of an element. */ validity: ValidityState; /** * Retrieves or sets the text in the entry field of the textArea element. */ value: string; /** * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; /** * Sets or retrieves how to handle wordwrapping in the object. */ wrap: string; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; /** * Creates a TextRange object for the element. */ createTextRange(): TextRange; /** * Highlights the input area of a form element. */ select(): void; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; /** * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. */ setSelectionRange(start: number, end: number): void; } declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; } interface HTMLTitleElement extends HTMLElement { /** * Retrieves or sets the text of the object as a string. */ text: string; } declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; } interface HTMLTrackElement extends HTMLElement { default: boolean; kind: string; label: string; readyState: number; src: string; srclang: string; track: TextTrack; ERROR: number; LOADED: number; LOADING: number; NONE: number; } declare var HTMLTrackElement: { prototype: HTMLTrackElement; new(): HTMLTrackElement; ERROR: number; LOADED: number; LOADING: number; NONE: number; } interface HTMLUListElement extends HTMLElement { compact: boolean; type: string; } declare var HTMLUListElement: { prototype: HTMLUListElement; new(): HTMLUListElement; } interface HTMLUnknownElement extends HTMLElement { } declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; } interface HTMLVideoElement extends HTMLMediaElement { /** * Gets or sets the height of the video element. */ height: number; msHorizontalMirror: boolean; msIsLayoutOptimalForPlayback: boolean; msIsStereo3D: boolean; msStereo3DPackingMode: string; msStereo3DRenderMode: string; msZoom: boolean; onMSVideoFormatChanged: (ev: Event) => any; onMSVideoFrameStepCompleted: (ev: Event) => any; onMSVideoOptimalLayoutChanged: (ev: Event) => any; /** * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. */ poster: string; /** * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. */ videoHeight: number; /** * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. */ videoWidth: number; webkitDisplayingFullscreen: boolean; webkitSupportsFullscreen: boolean; /** * Gets or sets the width of the video element. */ width: number; getVideoPlaybackQuality(): VideoPlaybackQuality; msFrameStep(forward: boolean): void; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; webkitEnterFullScreen(): void; webkitEnterFullscreen(): void; webkitExitFullScreen(): void; webkitExitFullscreen(): void; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSVideoFormatChanged", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "MSVideoFrameStepCompleted", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var HTMLVideoElement: { prototype: HTMLVideoElement; new(): HTMLVideoElement; } interface HashChangeEvent extends Event { newURL: string; oldURL: string; } declare var HashChangeEvent: { prototype: HashChangeEvent; new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; } interface History { length: number; state: any; back(distance?: any): void; forward(distance?: any): void; go(delta?: any): void; pushState(statedata: any, title?: string, url?: string): void; replaceState(statedata: any, title?: string, url?: string): void; } declare var History: { prototype: History; new(): History; } interface IDBCursor { direction: string; key: any; primaryKey: any; source: IDBObjectStore | IDBIndex; advance(count: number): void; continue(key?: any): void; delete(): IDBRequest; update(value: any): IDBRequest; NEXT: string; NEXT_NO_DUPLICATE: string; PREV: string; PREV_NO_DUPLICATE: string; } declare var IDBCursor: { prototype: IDBCursor; new(): IDBCursor; NEXT: string; NEXT_NO_DUPLICATE: string; PREV: string; PREV_NO_DUPLICATE: string; } interface IDBCursorWithValue extends IDBCursor { value: any; } declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; } interface IDBDatabase extends EventTarget { name: string; objectStoreNames: DOMStringList; onabort: (ev: Event) => any; onerror: (ev: Event) => any; version: number; close(): void; createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: string | string[], mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; } interface IDBFactory { cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; open(name: string, version?: number): IDBOpenDBRequest; } declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; } interface IDBIndex { keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; openCursor(range?: IDBKeyRange, direction?: string): IDBRequest; openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; } interface IDBKeyRange { lower: any; lowerOpen: boolean; upper: any; upperOpen: boolean; } declare var IDBKeyRange: { prototype: IDBKeyRange; new(): IDBKeyRange; bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; lowerBound(bound: any, open?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; upperBound(bound: any, open?: boolean): IDBKeyRange; } interface IDBObjectStore { indexNames: DOMStringList; keyPath: string | string[]; name: string; transaction: IDBTransaction; autoIncrement: boolean; add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; index(name: string): IDBIndex; openCursor(range?: any, direction?: string): IDBRequest; put(value: any, key?: any): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; } interface IDBOpenDBRequest extends IDBRequest { onblocked: (ev: Event) => any; onupgradeneeded: (ev: IDBVersionChangeEvent) => any; addEventListener(type: "blocked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "upgradeneeded", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; } interface IDBRequest extends EventTarget { error: DOMError; onerror: (ev: Event) => any; onsuccess: (ev: Event) => any; readyState: string; result: any; source: IDBObjectStore | IDBIndex | IDBCursor; transaction: IDBTransaction; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; } interface IDBTransaction extends EventTarget { db: IDBDatabase; error: DOMError; mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; onerror: (ev: Event) => any; abort(): void; objectStore(name: string): IDBObjectStore; READ_ONLY: string; READ_WRITE: string; VERSION_CHANGE: string; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var IDBTransaction: { prototype: IDBTransaction; new(): IDBTransaction; READ_ONLY: string; READ_WRITE: string; VERSION_CHANGE: string; } interface IDBVersionChangeEvent extends Event { newVersion: number; oldVersion: number; } declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; } interface ImageData { data: Uint8ClampedArray; height: number; width: number; } declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; new(array: Uint8ClampedArray, width: number, height: number): ImageData; } interface KeyboardEvent extends UIEvent { altKey: boolean; char: string; charCode: number; ctrlKey: boolean; key: string; keyCode: number; locale: string; location: number; metaKey: boolean; repeat: boolean; shiftKey: boolean; which: number; getModifierState(keyArg: string): boolean; initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; DOM_KEY_LOCATION_JOYSTICK: number; DOM_KEY_LOCATION_LEFT: number; DOM_KEY_LOCATION_MOBILE: number; DOM_KEY_LOCATION_NUMPAD: number; DOM_KEY_LOCATION_RIGHT: number; DOM_KEY_LOCATION_STANDARD: number; } declare var KeyboardEvent: { prototype: KeyboardEvent; new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; DOM_KEY_LOCATION_JOYSTICK: number; DOM_KEY_LOCATION_LEFT: number; DOM_KEY_LOCATION_MOBILE: number; DOM_KEY_LOCATION_NUMPAD: number; DOM_KEY_LOCATION_RIGHT: number; DOM_KEY_LOCATION_STANDARD: number; } interface Location { hash: string; host: string; hostname: string; href: string; origin: string; pathname: string; port: string; protocol: string; search: string; assign(url: string): void; reload(forcedReload?: boolean): void; replace(url: string): void; toString(): string; } declare var Location: { prototype: Location; new(): Location; } interface LongRunningScriptDetectedEvent extends Event { executionTime: number; stopPageScriptExecution: boolean; } declare var LongRunningScriptDetectedEvent: { prototype: LongRunningScriptDetectedEvent; new(): LongRunningScriptDetectedEvent; } interface MSApp { clearTemporaryWebDataAsync(): MSAppAsyncOperation; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; createDataPackage(object: any): any; createDataPackageFromSelection(): any; createFileFromStorageFile(storageFile: any): File; createStreamFromInputStream(type: string, inputStream: any): MSStream; execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; getCurrentPriority(): string; getHtmlPrintDocumentSourceAsync(htmlDoc: any): any; getViewId(view: any): any; isTaskScheduledAtPriorityOrHigher(priority: string): boolean; pageHandlesAllApplicationActivations(enabled: boolean): void; suppressSubdownloadCredentialPrompts(suppress: boolean): void; terminateApp(exceptionObject: any): void; CURRENT: string; HIGH: string; IDLE: string; NORMAL: string; } declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { error: DOMError; oncomplete: (ev: Event) => any; onerror: (ev: Event) => any; readyState: number; result: any; start(): void; COMPLETED: number; ERROR: number; STARTED: number; addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var MSAppAsyncOperation: { prototype: MSAppAsyncOperation; new(): MSAppAsyncOperation; COMPLETED: number; ERROR: number; STARTED: number; } interface MSBlobBuilder { append(data: any, endings?: string): void; getBlob(contentType?: string): Blob; } declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; } interface MSCSSMatrix { a: number; b: number; c: number; d: number; e: number; f: number; m11: number; m12: number; m13: number; m14: number; m21: number; m22: number; m23: number; m24: number; m31: number; m32: number; m33: number; m34: number; m41: number; m42: number; m43: number; m44: number; inverse(): MSCSSMatrix; multiply(secondMatrix: MSCSSMatrix): MSCSSMatrix; rotate(angleX: number, angleY?: number, angleZ?: number): MSCSSMatrix; rotateAxisAngle(x: number, y: number, z: number, angle: number): MSCSSMatrix; scale(scaleX: number, scaleY?: number, scaleZ?: number): MSCSSMatrix; setMatrixValue(value: string): void; skewX(angle: number): MSCSSMatrix; skewY(angle: number): MSCSSMatrix; toString(): string; translate(x: number, y: number, z?: number): MSCSSMatrix; } declare var MSCSSMatrix: { prototype: MSCSSMatrix; new(text?: string): MSCSSMatrix; } interface MSGesture { target: Element; addPointer(pointerId: number): void; stop(): void; } declare var MSGesture: { prototype: MSGesture; new(): MSGesture; } interface MSGestureEvent extends UIEvent { clientX: number; clientY: number; expansion: number; gestureObject: any; hwTimestamp: number; offsetX: number; offsetY: number; rotation: number; scale: number; screenX: number; screenY: number; translationX: number; translationY: number; velocityAngular: number; velocityExpansion: number; velocityX: number; velocityY: number; initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; MSGESTURE_FLAG_BEGIN: number; MSGESTURE_FLAG_CANCEL: number; MSGESTURE_FLAG_END: number; MSGESTURE_FLAG_INERTIA: number; MSGESTURE_FLAG_NONE: number; } declare var MSGestureEvent: { prototype: MSGestureEvent; new(): MSGestureEvent; MSGESTURE_FLAG_BEGIN: number; MSGESTURE_FLAG_CANCEL: number; MSGESTURE_FLAG_END: number; MSGESTURE_FLAG_INERTIA: number; MSGESTURE_FLAG_NONE: number; } interface MSGraphicsTrust { constrictionActive: boolean; status: string; } declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; } interface MSHTMLWebViewElement extends HTMLElement { canGoBack: boolean; canGoForward: boolean; containsFullScreenElement: boolean; documentTitle: string; height: number; settings: MSWebViewSettings; src: string; width: number; addWebAllowedObject(name: string, applicationObject: any): void; buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; capturePreviewToBlobAsync(): MSWebViewAsyncOperation; captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; getDeferredPermissionRequests(): DeferredPermissionRequest[]; goBack(): void; goForward(): void; invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; navigate(uri: string): void; navigateToLocalStreamUri(source: string, streamResolver: any): void; navigateToString(contents: string): void; navigateWithHttpRequestMessage(requestMessage: any): void; refresh(): void; stop(): void; } declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; } interface MSInputMethodContext extends EventTarget { compositionEndOffset: number; compositionStartOffset: number; oncandidatewindowhide: (ev: Event) => any; oncandidatewindowshow: (ev: Event) => any; oncandidatewindowupdate: (ev: Event) => any; target: HTMLElement; getCandidateWindowClientRect(): ClientRect; getCompositionAlternatives(): string[]; hasComposition(): boolean; isCandidateWindowVisible(): boolean; addEventListener(type: "MSCandidateWindowHide", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "MSCandidateWindowShow", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "MSCandidateWindowUpdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; } interface MSManipulationEvent extends UIEvent { currentState: number; inertiaDestinationX: number; inertiaDestinationY: number; lastState: number; initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; MS_MANIPULATION_STATE_ACTIVE: number; MS_MANIPULATION_STATE_CANCELLED: number; MS_MANIPULATION_STATE_COMMITTED: number; MS_MANIPULATION_STATE_DRAGGING: number; MS_MANIPULATION_STATE_INERTIA: number; MS_MANIPULATION_STATE_PRESELECT: number; MS_MANIPULATION_STATE_SELECTING: number; MS_MANIPULATION_STATE_STOPPED: number; } declare var MSManipulationEvent: { prototype: MSManipulationEvent; new(): MSManipulationEvent; MS_MANIPULATION_STATE_ACTIVE: number; MS_MANIPULATION_STATE_CANCELLED: number; MS_MANIPULATION_STATE_COMMITTED: number; MS_MANIPULATION_STATE_DRAGGING: number; MS_MANIPULATION_STATE_INERTIA: number; MS_MANIPULATION_STATE_PRESELECT: number; MS_MANIPULATION_STATE_SELECTING: number; MS_MANIPULATION_STATE_STOPPED: number; } interface MSMediaKeyError { code: number; systemCode: number; MS_MEDIA_KEYERR_CLIENT: number; MS_MEDIA_KEYERR_DOMAIN: number; MS_MEDIA_KEYERR_HARDWARECHANGE: number; MS_MEDIA_KEYERR_OUTPUT: number; MS_MEDIA_KEYERR_SERVICE: number; MS_MEDIA_KEYERR_UNKNOWN: number; } declare var MSMediaKeyError: { prototype: MSMediaKeyError; new(): MSMediaKeyError; MS_MEDIA_KEYERR_CLIENT: number; MS_MEDIA_KEYERR_DOMAIN: number; MS_MEDIA_KEYERR_HARDWARECHANGE: number; MS_MEDIA_KEYERR_OUTPUT: number; MS_MEDIA_KEYERR_SERVICE: number; MS_MEDIA_KEYERR_UNKNOWN: number; } interface MSMediaKeyMessageEvent extends Event { destinationURL: string; message: Uint8Array; } declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; } interface MSMediaKeyNeededEvent extends Event { initData: Uint8Array; } declare var MSMediaKeyNeededEvent: { prototype: MSMediaKeyNeededEvent; new(): MSMediaKeyNeededEvent; } interface MSMediaKeySession extends EventTarget { error: MSMediaKeyError; keySystem: string; sessionId: string; close(): void; update(key: Uint8Array): void; } declare var MSMediaKeySession: { prototype: MSMediaKeySession; new(): MSMediaKeySession; } interface MSMediaKeys { keySystem: string; createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; } declare var MSMediaKeys: { prototype: MSMediaKeys; new(keySystem: string): MSMediaKeys; isTypeSupported(keySystem: string, type?: string): boolean; } interface MSMimeTypesCollection { length: number; } declare var MSMimeTypesCollection: { prototype: MSMimeTypesCollection; new(): MSMimeTypesCollection; } interface MSPluginsCollection { length: number; refresh(reload?: boolean): void; } declare var MSPluginsCollection: { prototype: MSPluginsCollection; new(): MSPluginsCollection; } interface MSPointerEvent extends MouseEvent { currentPoint: any; height: number; hwTimestamp: number; intermediatePoints: any; isPrimary: boolean; pointerId: number; pointerType: any; pressure: number; rotation: number; tiltX: number; tiltY: number; width: number; getCurrentPoint(element: Element): void; getIntermediatePoints(element: Element): void; initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; } declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; } interface MSRangeCollection { length: number; item(index: number): Range; [index: number]: Range; } declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; } interface MSSiteModeEvent extends Event { actionURL: string; buttonID: number; } declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; } interface MSStream { type: string; msClose(): void; msDetachStream(): any; } declare var MSStream: { prototype: MSStream; new(): MSStream; } interface MSStreamReader extends EventTarget, MSBaseReader { error: DOMError; readAsArrayBuffer(stream: MSStream, size?: number): void; readAsBinaryString(stream: MSStream, size?: number): void; readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; } interface MSWebViewAsyncOperation extends EventTarget { error: DOMError; oncomplete: (ev: Event) => any; onerror: (ev: Event) => any; readyState: number; result: any; target: MSHTMLWebViewElement; type: number; start(): void; COMPLETED: number; ERROR: number; STARTED: number; TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; TYPE_INVOKE_SCRIPT: number; addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var MSWebViewAsyncOperation: { prototype: MSWebViewAsyncOperation; new(): MSWebViewAsyncOperation; COMPLETED: number; ERROR: number; STARTED: number; TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; TYPE_INVOKE_SCRIPT: number; } interface MSWebViewSettings { isIndexedDBEnabled: boolean; isJavaScriptEnabled: boolean; } declare var MSWebViewSettings: { prototype: MSWebViewSettings; new(): MSWebViewSettings; } interface MediaElementAudioSourceNode extends AudioNode { } declare var MediaElementAudioSourceNode: { prototype: MediaElementAudioSourceNode; new(): MediaElementAudioSourceNode; } interface MediaError { code: number; msExtendedCode: number; MEDIA_ERR_ABORTED: number; MEDIA_ERR_DECODE: number; MEDIA_ERR_NETWORK: number; MEDIA_ERR_SRC_NOT_SUPPORTED: number; MS_MEDIA_ERR_ENCRYPTED: number; } declare var MediaError: { prototype: MediaError; new(): MediaError; MEDIA_ERR_ABORTED: number; MEDIA_ERR_DECODE: number; MEDIA_ERR_NETWORK: number; MEDIA_ERR_SRC_NOT_SUPPORTED: number; MS_MEDIA_ERR_ENCRYPTED: number; } interface MediaList { length: number; mediaText: string; appendMedium(newMedium: string): void; deleteMedium(oldMedium: string): void; item(index: number): string; toString(): string; [index: number]: string; } declare var MediaList: { prototype: MediaList; new(): MediaList; } interface MediaQueryList { matches: boolean; media: string; addListener(listener: MediaQueryListListener): void; removeListener(listener: MediaQueryListListener): void; } declare var MediaQueryList: { prototype: MediaQueryList; new(): MediaQueryList; } interface MediaSource extends EventTarget { activeSourceBuffers: SourceBufferList; duration: number; readyState: string; sourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; endOfStream(error?: number): void; removeSourceBuffer(sourceBuffer: SourceBuffer): void; } declare var MediaSource: { prototype: MediaSource; new(): MediaSource; isTypeSupported(type: string): boolean; } interface MessageChannel { port1: MessagePort; port2: MessagePort; } declare var MessageChannel: { prototype: MessageChannel; new(): MessageChannel; } interface MessageEvent extends Event { data: any; origin: string; ports: any; source: Window; initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; } declare var MessageEvent: { prototype: MessageEvent; new(type: string, eventInitDict?: MessageEventInit): MessageEvent; } interface MessagePort extends EventTarget { onmessage: (ev: MessageEvent) => any; close(): void; postMessage(message?: any, ports?: any): void; start(): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var MessagePort: { prototype: MessagePort; new(): MessagePort; } interface MimeType { description: string; enabledPlugin: Plugin; suffixes: string; type: string; } declare var MimeType: { prototype: MimeType; new(): MimeType; } interface MimeTypeArray { length: number; item(index: number): Plugin; namedItem(type: string): Plugin; [index: number]: Plugin; } declare var MimeTypeArray: { prototype: MimeTypeArray; new(): MimeTypeArray; } interface MouseEvent extends UIEvent { altKey: boolean; button: number; buttons: number; clientX: number; clientY: number; ctrlKey: boolean; fromElement: Element; layerX: number; layerY: number; metaKey: boolean; movementX: number; movementY: number; offsetX: number; offsetY: number; pageX: number; pageY: number; relatedTarget: EventTarget; screenX: number; screenY: number; shiftKey: boolean; toElement: Element; which: number; x: number; y: number; getModifierState(keyArg: string): boolean; initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; } declare var MouseEvent: { prototype: MouseEvent; new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; } interface MouseWheelEvent extends MouseEvent { wheelDelta: number; wheelDeltaX: number; wheelDeltaY: number; initMouseWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, wheelDeltaArg: number): void; } declare var MouseWheelEvent: { prototype: MouseWheelEvent; new(): MouseWheelEvent; } interface MutationEvent extends Event { attrChange: number; attrName: string; newValue: string; prevValue: string; relatedNode: Node; initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; ADDITION: number; MODIFICATION: number; REMOVAL: number; } declare var MutationEvent: { prototype: MutationEvent; new(): MutationEvent; ADDITION: number; MODIFICATION: number; REMOVAL: number; } interface MutationObserver { disconnect(): void; observe(target: Node, options: MutationObserverInit): void; takeRecords(): MutationRecord[]; } declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; } interface MutationRecord { addedNodes: NodeList; attributeName: string; attributeNamespace: string; nextSibling: Node; oldValue: string; previousSibling: Node; removedNodes: NodeList; target: Node; type: string; } declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; } interface NamedNodeMap { length: number; getNamedItem(name: string): Attr; getNamedItemNS(namespaceURI: string, localName: string): Attr; item(index: number): Attr; removeNamedItem(name: string): Attr; removeNamedItemNS(namespaceURI: string, localName: string): Attr; setNamedItem(arg: Attr): Attr; setNamedItemNS(arg: Attr): Attr; [index: number]: Attr; } declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; } interface NavigationCompletedEvent extends NavigationEvent { isSuccess: boolean; webErrorStatus: number; } declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; } interface NavigationEvent extends Event { uri: string; } declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; } interface NavigationEventWithReferrer extends NavigationEvent { referer: string; } declare var NavigationEventWithReferrer: { prototype: NavigationEventWithReferrer; new(): NavigationEventWithReferrer; } interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver { appCodeName: string; appMinorVersion: string; browserLanguage: string; connectionSpeed: number; cookieEnabled: boolean; cpuClass: string; language: string; maxTouchPoints: number; mimeTypes: MSMimeTypesCollection; msManipulationViewsEnabled: boolean; msMaxTouchPoints: number; msPointerEnabled: boolean; plugins: MSPluginsCollection; pointerEnabled: boolean; systemLanguage: string; userLanguage: string; webdriver: boolean; getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; vibrate(pattern: number | number[]): boolean; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Navigator: { prototype: Navigator; new(): Navigator; } interface Node extends EventTarget { attributes: NamedNodeMap; baseURI: string; childNodes: NodeList; firstChild: Node; lastChild: Node; localName: string; namespaceURI: string; nextSibling: Node; nodeName: string; nodeType: number; nodeValue: string; ownerDocument: Document; parentElement: HTMLElement; parentNode: Node; prefix: string; previousSibling: Node; textContent: string; appendChild(newChild: Node): Node; cloneNode(deep?: boolean): Node; compareDocumentPosition(other: Node): number; hasAttributes(): boolean; hasChildNodes(): boolean; insertBefore(newChild: Node, refChild?: Node): Node; isDefaultNamespace(namespaceURI: string): boolean; isEqualNode(arg: Node): boolean; isSameNode(other: Node): boolean; lookupNamespaceURI(prefix: string): string; lookupPrefix(namespaceURI: string): string; normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; contains(node: Node): boolean; ATTRIBUTE_NODE: number; CDATA_SECTION_NODE: number; COMMENT_NODE: number; DOCUMENT_FRAGMENT_NODE: number; DOCUMENT_NODE: number; DOCUMENT_POSITION_CONTAINED_BY: number; DOCUMENT_POSITION_CONTAINS: number; DOCUMENT_POSITION_DISCONNECTED: number; DOCUMENT_POSITION_FOLLOWING: number; DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; DOCUMENT_POSITION_PRECEDING: number; DOCUMENT_TYPE_NODE: number; ELEMENT_NODE: number; ENTITY_NODE: number; ENTITY_REFERENCE_NODE: number; NOTATION_NODE: number; PROCESSING_INSTRUCTION_NODE: number; TEXT_NODE: number; } declare var Node: { prototype: Node; new(): Node; ATTRIBUTE_NODE: number; CDATA_SECTION_NODE: number; COMMENT_NODE: number; DOCUMENT_FRAGMENT_NODE: number; DOCUMENT_NODE: number; DOCUMENT_POSITION_CONTAINED_BY: number; DOCUMENT_POSITION_CONTAINS: number; DOCUMENT_POSITION_DISCONNECTED: number; DOCUMENT_POSITION_FOLLOWING: number; DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; DOCUMENT_POSITION_PRECEDING: number; DOCUMENT_TYPE_NODE: number; ELEMENT_NODE: number; ENTITY_NODE: number; ENTITY_REFERENCE_NODE: number; NOTATION_NODE: number; PROCESSING_INSTRUCTION_NODE: number; TEXT_NODE: number; } interface NodeFilter { acceptNode(n: Node): number; } declare var NodeFilter: { FILTER_ACCEPT: number; FILTER_REJECT: number; FILTER_SKIP: number; SHOW_ALL: number; SHOW_ATTRIBUTE: number; SHOW_CDATA_SECTION: number; SHOW_COMMENT: number; SHOW_DOCUMENT: number; SHOW_DOCUMENT_FRAGMENT: number; SHOW_DOCUMENT_TYPE: number; SHOW_ELEMENT: number; SHOW_ENTITY: number; SHOW_ENTITY_REFERENCE: number; SHOW_NOTATION: number; SHOW_PROCESSING_INSTRUCTION: number; SHOW_TEXT: number; } interface NodeIterator { expandEntityReferences: boolean; filter: NodeFilter; root: Node; whatToShow: number; detach(): void; nextNode(): Node; previousNode(): Node; } declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; } interface NodeList { length: number; item(index: number): Node; [index: number]: Node; } declare var NodeList: { prototype: NodeList; new(): NodeList; } interface OES_element_index_uint { } declare var OES_element_index_uint: { prototype: OES_element_index_uint; new(): OES_element_index_uint; } interface OES_standard_derivatives { FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; } declare var OES_standard_derivatives: { prototype: OES_standard_derivatives; new(): OES_standard_derivatives; FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; } interface OES_texture_float { } declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; } interface OES_texture_float_linear { } declare var OES_texture_float_linear: { prototype: OES_texture_float_linear; new(): OES_texture_float_linear; } interface OfflineAudioCompletionEvent extends Event { renderedBuffer: AudioBuffer; } declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; } interface OfflineAudioContext extends AudioContext { oncomplete: (ev: Event) => any; startRendering(): void; addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; } interface OscillatorNode extends AudioNode { detune: AudioParam; frequency: AudioParam; onended: (ev: Event) => any; type: string; setPeriodicWave(periodicWave: PeriodicWave): void; start(when?: number): void; stop(when?: number): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; } interface PageTransitionEvent extends Event { persisted: boolean; } declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; } interface PannerNode extends AudioNode { coneInnerAngle: number; coneOuterAngle: number; coneOuterGain: number; distanceModel: string; maxDistance: number; panningModel: string; refDistance: number; rolloffFactor: number; setOrientation(x: number, y: number, z: number): void; setPosition(x: number, y: number, z: number): void; setVelocity(x: number, y: number, z: number): void; } declare var PannerNode: { prototype: PannerNode; new(): PannerNode; } interface PerfWidgetExternal { activeNetworkRequestCount: number; averageFrameTime: number; averagePaintTime: number; extraInformationEnabled: boolean; independentRenderingEnabled: boolean; irDisablingContentString: string; irStatusAvailable: boolean; maxCpuSpeed: number; paintRequestsPerSecond: number; performanceCounter: number; performanceCounterFrequency: number; addEventListener(eventType: string, callback: Function): void; getMemoryUsage(): number; getProcessCpuUsage(): number; getRecentCpuUsage(last: number): any; getRecentFrames(last: number): any; getRecentMemoryUsage(last: number): any; getRecentPaintRequests(last: number): any; removeEventListener(eventType: string, callback: Function): void; repositionWindow(x: number, y: number): void; resizeWindow(width: number, height: number): void; } declare var PerfWidgetExternal: { prototype: PerfWidgetExternal; new(): PerfWidgetExternal; } interface Performance { navigation: PerformanceNavigation; timing: PerformanceTiming; clearMarks(markName?: string): void; clearMeasures(measureName?: string): void; clearResourceTimings(): void; getEntries(): any; getEntriesByName(name: string, entryType?: string): any; getEntriesByType(entryType: string): any; getMarks(markName?: string): any; getMeasures(measureName?: string): any; mark(markName: string): void; measure(measureName: string, startMarkName?: string, endMarkName?: string): void; now(): number; setResourceTimingBufferSize(maxSize: number): void; toJSON(): any; } declare var Performance: { prototype: Performance; new(): Performance; } interface PerformanceEntry { duration: number; entryType: string; name: string; startTime: number; } declare var PerformanceEntry: { prototype: PerformanceEntry; new(): PerformanceEntry; } interface PerformanceMark extends PerformanceEntry { } declare var PerformanceMark: { prototype: PerformanceMark; new(): PerformanceMark; } interface PerformanceMeasure extends PerformanceEntry { } declare var PerformanceMeasure: { prototype: PerformanceMeasure; new(): PerformanceMeasure; } interface PerformanceNavigation { redirectCount: number; type: number; toJSON(): any; TYPE_BACK_FORWARD: number; TYPE_NAVIGATE: number; TYPE_RELOAD: number; TYPE_RESERVED: number; } declare var PerformanceNavigation: { prototype: PerformanceNavigation; new(): PerformanceNavigation; TYPE_BACK_FORWARD: number; TYPE_NAVIGATE: number; TYPE_RELOAD: number; TYPE_RESERVED: number; } interface PerformanceNavigationTiming extends PerformanceEntry { connectEnd: number; connectStart: number; domComplete: number; domContentLoadedEventEnd: number; domContentLoadedEventStart: number; domInteractive: number; domLoading: number; domainLookupEnd: number; domainLookupStart: number; fetchStart: number; loadEventEnd: number; loadEventStart: number; navigationStart: number; redirectCount: number; redirectEnd: number; redirectStart: number; requestStart: number; responseEnd: number; responseStart: number; type: string; unloadEventEnd: number; unloadEventStart: number; } declare var PerformanceNavigationTiming: { prototype: PerformanceNavigationTiming; new(): PerformanceNavigationTiming; } interface PerformanceResourceTiming extends PerformanceEntry { connectEnd: number; connectStart: number; domainLookupEnd: number; domainLookupStart: number; fetchStart: number; initiatorType: string; redirectEnd: number; redirectStart: number; requestStart: number; responseEnd: number; responseStart: number; } declare var PerformanceResourceTiming: { prototype: PerformanceResourceTiming; new(): PerformanceResourceTiming; } interface PerformanceTiming { connectEnd: number; connectStart: number; domComplete: number; domContentLoadedEventEnd: number; domContentLoadedEventStart: number; domInteractive: number; domLoading: number; domainLookupEnd: number; domainLookupStart: number; fetchStart: number; loadEventEnd: number; loadEventStart: number; msFirstPaint: number; navigationStart: number; redirectEnd: number; redirectStart: number; requestStart: number; responseEnd: number; responseStart: number; unloadEventEnd: number; unloadEventStart: number; toJSON(): any; } declare var PerformanceTiming: { prototype: PerformanceTiming; new(): PerformanceTiming; } interface PeriodicWave { } declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; } interface PermissionRequest extends DeferredPermissionRequest { state: string; defer(): void; } declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; } interface PermissionRequestedEvent extends Event { permissionRequest: PermissionRequest; } declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; } interface Plugin { description: string; filename: string; length: number; name: string; version: string; item(index: number): MimeType; namedItem(type: string): MimeType; [index: number]: MimeType; } declare var Plugin: { prototype: Plugin; new(): Plugin; } interface PluginArray { length: number; item(index: number): Plugin; namedItem(name: string): Plugin; refresh(reload?: boolean): void; [index: number]: Plugin; } declare var PluginArray: { prototype: PluginArray; new(): PluginArray; } interface PointerEvent extends MouseEvent { currentPoint: any; height: number; hwTimestamp: number; intermediatePoints: any; isPrimary: boolean; pointerId: number; pointerType: any; pressure: number; rotation: number; tiltX: number; tiltY: number; width: number; getCurrentPoint(element: Element): void; getIntermediatePoints(element: Element): void; initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; } declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; } interface PopStateEvent extends Event { state: any; initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; } declare var PopStateEvent: { prototype: PopStateEvent; new(): PopStateEvent; } interface Position { coords: Coordinates; timestamp: number; } declare var Position: { prototype: Position; new(): Position; } interface PositionError { code: number; message: string; toString(): string; PERMISSION_DENIED: number; POSITION_UNAVAILABLE: number; TIMEOUT: number; } declare var PositionError: { prototype: PositionError; new(): PositionError; PERMISSION_DENIED: number; POSITION_UNAVAILABLE: number; TIMEOUT: number; } interface ProcessingInstruction extends CharacterData { target: string; } declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; } interface ProgressEvent extends Event { lengthComputable: boolean; loaded: number; total: number; initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; } declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; } interface Range { collapsed: boolean; commonAncestorContainer: Node; endContainer: Node; endOffset: number; startContainer: Node; startOffset: number; cloneContents(): DocumentFragment; cloneRange(): Range; collapse(toStart: boolean): void; compareBoundaryPoints(how: number, sourceRange: Range): number; createContextualFragment(fragment: string): DocumentFragment; deleteContents(): void; detach(): void; expand(Unit: string): boolean; extractContents(): DocumentFragment; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; setEnd(refNode: Node, offset: number): void; setEndAfter(refNode: Node): void; setEndBefore(refNode: Node): void; setStart(refNode: Node, offset: number): void; setStartAfter(refNode: Node): void; setStartBefore(refNode: Node): void; surroundContents(newParent: Node): void; toString(): string; END_TO_END: number; END_TO_START: number; START_TO_END: number; START_TO_START: number; } declare var Range: { prototype: Range; new(): Range; END_TO_END: number; END_TO_START: number; START_TO_END: number; START_TO_START: number; } interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { target: SVGAnimatedString; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; } interface SVGAngle { unitType: number; value: number; valueAsString: string; valueInSpecifiedUnits: number; convertToSpecifiedUnits(unitType: number): void; newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; SVG_ANGLETYPE_DEG: number; SVG_ANGLETYPE_GRAD: number; SVG_ANGLETYPE_RAD: number; SVG_ANGLETYPE_UNKNOWN: number; SVG_ANGLETYPE_UNSPECIFIED: number; } declare var SVGAngle: { prototype: SVGAngle; new(): SVGAngle; SVG_ANGLETYPE_DEG: number; SVG_ANGLETYPE_GRAD: number; SVG_ANGLETYPE_RAD: number; SVG_ANGLETYPE_UNKNOWN: number; SVG_ANGLETYPE_UNSPECIFIED: number; } interface SVGAnimatedAngle { animVal: SVGAngle; baseVal: SVGAngle; } declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; } interface SVGAnimatedBoolean { animVal: boolean; baseVal: boolean; } declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; } interface SVGAnimatedEnumeration { animVal: number; baseVal: number; } declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; } interface SVGAnimatedInteger { animVal: number; baseVal: number; } declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; } interface SVGAnimatedLength { animVal: SVGLength; baseVal: SVGLength; } declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; } interface SVGAnimatedLengthList { animVal: SVGLengthList; baseVal: SVGLengthList; } declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; } interface SVGAnimatedNumber { animVal: number; baseVal: number; } declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; } interface SVGAnimatedNumberList { animVal: SVGNumberList; baseVal: SVGNumberList; } declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; } interface SVGAnimatedPreserveAspectRatio { animVal: SVGPreserveAspectRatio; baseVal: SVGPreserveAspectRatio; } declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; } interface SVGAnimatedRect { animVal: SVGRect; baseVal: SVGRect; } declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; } interface SVGAnimatedString { animVal: string; baseVal: string; } declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; } interface SVGAnimatedTransformList { animVal: SVGTransformList; baseVal: SVGTransformList; } declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; } interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { cx: SVGAnimatedLength; cy: SVGAnimatedLength; r: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; } interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { clipPathUnits: SVGAnimatedEnumeration; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; } interface SVGComponentTransferFunctionElement extends SVGElement { amplitude: SVGAnimatedNumber; exponent: SVGAnimatedNumber; intercept: SVGAnimatedNumber; offset: SVGAnimatedNumber; slope: SVGAnimatedNumber; tableValues: SVGAnimatedNumberList; type: SVGAnimatedEnumeration; SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; } declare var SVGComponentTransferFunctionElement: { prototype: SVGComponentTransferFunctionElement; new(): SVGComponentTransferFunctionElement; SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; } interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGDefsElement: { prototype: SVGDefsElement; new(): SVGDefsElement; } interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; } interface SVGElement extends Element { id: string; onclick: (ev: MouseEvent) => any; ondblclick: (ev: MouseEvent) => any; onfocusin: (ev: FocusEvent) => any; onfocusout: (ev: FocusEvent) => any; onload: (ev: Event) => any; onmousedown: (ev: MouseEvent) => any; onmousemove: (ev: MouseEvent) => any; onmouseout: (ev: MouseEvent) => any; onmouseover: (ev: MouseEvent) => any; onmouseup: (ev: MouseEvent) => any; ownerSVGElement: SVGSVGElement; viewportElement: SVGElement; xmlbase: string; className: any; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGElement: { prototype: SVGElement; new(): SVGElement; } interface SVGElementInstance extends EventTarget { childNodes: SVGElementInstanceList; correspondingElement: SVGElement; correspondingUseElement: SVGUseElement; firstChild: SVGElementInstance; lastChild: SVGElementInstance; nextSibling: SVGElementInstance; parentNode: SVGElementInstance; previousSibling: SVGElementInstance; } declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; } interface SVGElementInstanceList { length: number; item(index: number): SVGElementInstance; } declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; } interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { cx: SVGAnimatedLength; cy: SVGAnimatedLength; rx: SVGAnimatedLength; ry: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; } interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; in2: SVGAnimatedString; mode: SVGAnimatedEnumeration; SVG_FEBLEND_MODE_COLOR: number; SVG_FEBLEND_MODE_COLOR_BURN: number; SVG_FEBLEND_MODE_COLOR_DODGE: number; SVG_FEBLEND_MODE_DARKEN: number; SVG_FEBLEND_MODE_DIFFERENCE: number; SVG_FEBLEND_MODE_EXCLUSION: number; SVG_FEBLEND_MODE_HARD_LIGHT: number; SVG_FEBLEND_MODE_HUE: number; SVG_FEBLEND_MODE_LIGHTEN: number; SVG_FEBLEND_MODE_LUMINOSITY: number; SVG_FEBLEND_MODE_MULTIPLY: number; SVG_FEBLEND_MODE_NORMAL: number; SVG_FEBLEND_MODE_OVERLAY: number; SVG_FEBLEND_MODE_SATURATION: number; SVG_FEBLEND_MODE_SCREEN: number; SVG_FEBLEND_MODE_SOFT_LIGHT: number; SVG_FEBLEND_MODE_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEBlendElement: { prototype: SVGFEBlendElement; new(): SVGFEBlendElement; SVG_FEBLEND_MODE_COLOR: number; SVG_FEBLEND_MODE_COLOR_BURN: number; SVG_FEBLEND_MODE_COLOR_DODGE: number; SVG_FEBLEND_MODE_DARKEN: number; SVG_FEBLEND_MODE_DIFFERENCE: number; SVG_FEBLEND_MODE_EXCLUSION: number; SVG_FEBLEND_MODE_HARD_LIGHT: number; SVG_FEBLEND_MODE_HUE: number; SVG_FEBLEND_MODE_LIGHTEN: number; SVG_FEBLEND_MODE_LUMINOSITY: number; SVG_FEBLEND_MODE_MULTIPLY: number; SVG_FEBLEND_MODE_NORMAL: number; SVG_FEBLEND_MODE_OVERLAY: number; SVG_FEBLEND_MODE_SATURATION: number; SVG_FEBLEND_MODE_SCREEN: number; SVG_FEBLEND_MODE_SOFT_LIGHT: number; SVG_FEBLEND_MODE_UNKNOWN: number; } interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; type: SVGAnimatedEnumeration; values: SVGAnimatedNumberList; SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; SVG_FECOLORMATRIX_TYPE_MATRIX: number; SVG_FECOLORMATRIX_TYPE_SATURATE: number; SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEColorMatrixElement: { prototype: SVGFEColorMatrixElement; new(): SVGFEColorMatrixElement; SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; SVG_FECOLORMATRIX_TYPE_MATRIX: number; SVG_FECOLORMATRIX_TYPE_SATURATE: number; SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; } interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; } interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; in2: SVGAnimatedString; k1: SVGAnimatedNumber; k2: SVGAnimatedNumber; k3: SVGAnimatedNumber; k4: SVGAnimatedNumber; operator: SVGAnimatedEnumeration; SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; SVG_FECOMPOSITE_OPERATOR_ATOP: number; SVG_FECOMPOSITE_OPERATOR_IN: number; SVG_FECOMPOSITE_OPERATOR_OUT: number; SVG_FECOMPOSITE_OPERATOR_OVER: number; SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; SVG_FECOMPOSITE_OPERATOR_XOR: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFECompositeElement: { prototype: SVGFECompositeElement; new(): SVGFECompositeElement; SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; SVG_FECOMPOSITE_OPERATOR_ATOP: number; SVG_FECOMPOSITE_OPERATOR_IN: number; SVG_FECOMPOSITE_OPERATOR_OUT: number; SVG_FECOMPOSITE_OPERATOR_OVER: number; SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; SVG_FECOMPOSITE_OPERATOR_XOR: number; } interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { bias: SVGAnimatedNumber; divisor: SVGAnimatedNumber; edgeMode: SVGAnimatedEnumeration; in1: SVGAnimatedString; kernelMatrix: SVGAnimatedNumberList; kernelUnitLengthX: SVGAnimatedNumber; kernelUnitLengthY: SVGAnimatedNumber; orderX: SVGAnimatedInteger; orderY: SVGAnimatedInteger; preserveAlpha: SVGAnimatedBoolean; targetX: SVGAnimatedInteger; targetY: SVGAnimatedInteger; SVG_EDGEMODE_DUPLICATE: number; SVG_EDGEMODE_NONE: number; SVG_EDGEMODE_UNKNOWN: number; SVG_EDGEMODE_WRAP: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEConvolveMatrixElement: { prototype: SVGFEConvolveMatrixElement; new(): SVGFEConvolveMatrixElement; SVG_EDGEMODE_DUPLICATE: number; SVG_EDGEMODE_NONE: number; SVG_EDGEMODE_UNKNOWN: number; SVG_EDGEMODE_WRAP: number; } interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { diffuseConstant: SVGAnimatedNumber; in1: SVGAnimatedString; kernelUnitLengthX: SVGAnimatedNumber; kernelUnitLengthY: SVGAnimatedNumber; surfaceScale: SVGAnimatedNumber; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; } interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; in2: SVGAnimatedString; scale: SVGAnimatedNumber; xChannelSelector: SVGAnimatedEnumeration; yChannelSelector: SVGAnimatedEnumeration; SVG_CHANNEL_A: number; SVG_CHANNEL_B: number; SVG_CHANNEL_G: number; SVG_CHANNEL_R: number; SVG_CHANNEL_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEDisplacementMapElement: { prototype: SVGFEDisplacementMapElement; new(): SVGFEDisplacementMapElement; SVG_CHANNEL_A: number; SVG_CHANNEL_B: number; SVG_CHANNEL_G: number; SVG_CHANNEL_R: number; SVG_CHANNEL_UNKNOWN: number; } interface SVGFEDistantLightElement extends SVGElement { azimuth: SVGAnimatedNumber; elevation: SVGAnimatedNumber; } declare var SVGFEDistantLightElement: { prototype: SVGFEDistantLightElement; new(): SVGFEDistantLightElement; } interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEFloodElement: { prototype: SVGFEFloodElement; new(): SVGFEFloodElement; } interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { } declare var SVGFEFuncAElement: { prototype: SVGFEFuncAElement; new(): SVGFEFuncAElement; } interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { } declare var SVGFEFuncBElement: { prototype: SVGFEFuncBElement; new(): SVGFEFuncBElement; } interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { } declare var SVGFEFuncGElement: { prototype: SVGFEFuncGElement; new(): SVGFEFuncGElement; } interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { } declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; } interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; stdDeviationX: SVGAnimatedNumber; stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; } interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { preserveAspectRatio: SVGAnimatedPreserveAspectRatio; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEImageElement: { prototype: SVGFEImageElement; new(): SVGFEImageElement; } interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; } interface SVGFEMergeNodeElement extends SVGElement { in1: SVGAnimatedString; } declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; } interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; operator: SVGAnimatedEnumeration; radiusX: SVGAnimatedNumber; radiusY: SVGAnimatedNumber; SVG_MORPHOLOGY_OPERATOR_DILATE: number; SVG_MORPHOLOGY_OPERATOR_ERODE: number; SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEMorphologyElement: { prototype: SVGFEMorphologyElement; new(): SVGFEMorphologyElement; SVG_MORPHOLOGY_OPERATOR_DILATE: number; SVG_MORPHOLOGY_OPERATOR_ERODE: number; SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; } interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { dx: SVGAnimatedNumber; dy: SVGAnimatedNumber; in1: SVGAnimatedString; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; } interface SVGFEPointLightElement extends SVGElement { x: SVGAnimatedNumber; y: SVGAnimatedNumber; z: SVGAnimatedNumber; } declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; } interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; kernelUnitLengthX: SVGAnimatedNumber; kernelUnitLengthY: SVGAnimatedNumber; specularConstant: SVGAnimatedNumber; specularExponent: SVGAnimatedNumber; surfaceScale: SVGAnimatedNumber; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; } interface SVGFESpotLightElement extends SVGElement { limitingConeAngle: SVGAnimatedNumber; pointsAtX: SVGAnimatedNumber; pointsAtY: SVGAnimatedNumber; pointsAtZ: SVGAnimatedNumber; specularExponent: SVGAnimatedNumber; x: SVGAnimatedNumber; y: SVGAnimatedNumber; z: SVGAnimatedNumber; } declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; } interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; } interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { baseFrequencyX: SVGAnimatedNumber; baseFrequencyY: SVGAnimatedNumber; numOctaves: SVGAnimatedInteger; seed: SVGAnimatedNumber; stitchTiles: SVGAnimatedEnumeration; type: SVGAnimatedEnumeration; SVG_STITCHTYPE_NOSTITCH: number; SVG_STITCHTYPE_STITCH: number; SVG_STITCHTYPE_UNKNOWN: number; SVG_TURBULENCE_TYPE_FRACTALNOISE: number; SVG_TURBULENCE_TYPE_TURBULENCE: number; SVG_TURBULENCE_TYPE_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFETurbulenceElement: { prototype: SVGFETurbulenceElement; new(): SVGFETurbulenceElement; SVG_STITCHTYPE_NOSTITCH: number; SVG_STITCHTYPE_STITCH: number; SVG_STITCHTYPE_UNKNOWN: number; SVG_TURBULENCE_TYPE_FRACTALNOISE: number; SVG_TURBULENCE_TYPE_TURBULENCE: number; SVG_TURBULENCE_TYPE_UNKNOWN: number; } interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { filterResX: SVGAnimatedInteger; filterResY: SVGAnimatedInteger; filterUnits: SVGAnimatedEnumeration; height: SVGAnimatedLength; primitiveUnits: SVGAnimatedEnumeration; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; setFilterRes(filterResX: number, filterResY: number): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; } interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { height: SVGAnimatedLength; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGForeignObjectElement: { prototype: SVGForeignObjectElement; new(): SVGForeignObjectElement; } interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; } interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourcesRequired, SVGURIReference, SVGUnitTypes { gradientTransform: SVGAnimatedTransformList; gradientUnits: SVGAnimatedEnumeration; spreadMethod: SVGAnimatedEnumeration; SVG_SPREADMETHOD_PAD: number; SVG_SPREADMETHOD_REFLECT: number; SVG_SPREADMETHOD_REPEAT: number; SVG_SPREADMETHOD_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGGradientElement: { prototype: SVGGradientElement; new(): SVGGradientElement; SVG_SPREADMETHOD_PAD: number; SVG_SPREADMETHOD_REFLECT: number; SVG_SPREADMETHOD_REPEAT: number; SVG_SPREADMETHOD_UNKNOWN: number; } interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { height: SVGAnimatedLength; preserveAspectRatio: SVGAnimatedPreserveAspectRatio; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; } interface SVGLength { unitType: number; value: number; valueAsString: string; valueInSpecifiedUnits: number; convertToSpecifiedUnits(unitType: number): void; newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; SVG_LENGTHTYPE_CM: number; SVG_LENGTHTYPE_EMS: number; SVG_LENGTHTYPE_EXS: number; SVG_LENGTHTYPE_IN: number; SVG_LENGTHTYPE_MM: number; SVG_LENGTHTYPE_NUMBER: number; SVG_LENGTHTYPE_PC: number; SVG_LENGTHTYPE_PERCENTAGE: number; SVG_LENGTHTYPE_PT: number; SVG_LENGTHTYPE_PX: number; SVG_LENGTHTYPE_UNKNOWN: number; } declare var SVGLength: { prototype: SVGLength; new(): SVGLength; SVG_LENGTHTYPE_CM: number; SVG_LENGTHTYPE_EMS: number; SVG_LENGTHTYPE_EXS: number; SVG_LENGTHTYPE_IN: number; SVG_LENGTHTYPE_MM: number; SVG_LENGTHTYPE_NUMBER: number; SVG_LENGTHTYPE_PC: number; SVG_LENGTHTYPE_PERCENTAGE: number; SVG_LENGTHTYPE_PT: number; SVG_LENGTHTYPE_PX: number; SVG_LENGTHTYPE_UNKNOWN: number; } interface SVGLengthList { numberOfItems: number; appendItem(newItem: SVGLength): SVGLength; clear(): void; getItem(index: number): SVGLength; initialize(newItem: SVGLength): SVGLength; insertItemBefore(newItem: SVGLength, index: number): SVGLength; removeItem(index: number): SVGLength; replaceItem(newItem: SVGLength, index: number): SVGLength; } declare var SVGLengthList: { prototype: SVGLengthList; new(): SVGLengthList; } interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { x1: SVGAnimatedLength; x2: SVGAnimatedLength; y1: SVGAnimatedLength; y2: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGLineElement: { prototype: SVGLineElement; new(): SVGLineElement; } interface SVGLinearGradientElement extends SVGGradientElement { x1: SVGAnimatedLength; x2: SVGAnimatedLength; y1: SVGAnimatedLength; y2: SVGAnimatedLength; } declare var SVGLinearGradientElement: { prototype: SVGLinearGradientElement; new(): SVGLinearGradientElement; } interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { markerHeight: SVGAnimatedLength; markerUnits: SVGAnimatedEnumeration; markerWidth: SVGAnimatedLength; orientAngle: SVGAnimatedAngle; orientType: SVGAnimatedEnumeration; refX: SVGAnimatedLength; refY: SVGAnimatedLength; setOrientToAngle(angle: SVGAngle): void; setOrientToAuto(): void; SVG_MARKERUNITS_STROKEWIDTH: number; SVG_MARKERUNITS_UNKNOWN: number; SVG_MARKERUNITS_USERSPACEONUSE: number; SVG_MARKER_ORIENT_ANGLE: number; SVG_MARKER_ORIENT_AUTO: number; SVG_MARKER_ORIENT_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGMarkerElement: { prototype: SVGMarkerElement; new(): SVGMarkerElement; SVG_MARKERUNITS_STROKEWIDTH: number; SVG_MARKERUNITS_UNKNOWN: number; SVG_MARKERUNITS_USERSPACEONUSE: number; SVG_MARKER_ORIENT_ANGLE: number; SVG_MARKER_ORIENT_AUTO: number; SVG_MARKER_ORIENT_UNKNOWN: number; } interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { height: SVGAnimatedLength; maskContentUnits: SVGAnimatedEnumeration; maskUnits: SVGAnimatedEnumeration; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; } interface SVGMatrix { a: number; b: number; c: number; d: number; e: number; f: number; flipX(): SVGMatrix; flipY(): SVGMatrix; inverse(): SVGMatrix; multiply(secondMatrix: SVGMatrix): SVGMatrix; rotate(angle: number): SVGMatrix; rotateFromVector(x: number, y: number): SVGMatrix; scale(scaleFactor: number): SVGMatrix; scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; skewX(angle: number): SVGMatrix; skewY(angle: number): SVGMatrix; translate(x: number, y: number): SVGMatrix; } declare var SVGMatrix: { prototype: SVGMatrix; new(): SVGMatrix; } interface SVGMetadataElement extends SVGElement { } declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; } interface SVGNumber { value: number; } declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; } interface SVGNumberList { numberOfItems: number; appendItem(newItem: SVGNumber): SVGNumber; clear(): void; getItem(index: number): SVGNumber; initialize(newItem: SVGNumber): SVGNumber; insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; removeItem(index: number): SVGNumber; replaceItem(newItem: SVGNumber, index: number): SVGNumber; } declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; } interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPathData { createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; createSVGPathSegClosePath(): SVGPathSegClosePath; createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; } interface SVGPathSeg { pathSegType: number; pathSegTypeAsLetter: string; PATHSEG_ARC_ABS: number; PATHSEG_ARC_REL: number; PATHSEG_CLOSEPATH: number; PATHSEG_CURVETO_CUBIC_ABS: number; PATHSEG_CURVETO_CUBIC_REL: number; PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; PATHSEG_CURVETO_QUADRATIC_ABS: number; PATHSEG_CURVETO_QUADRATIC_REL: number; PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; PATHSEG_LINETO_ABS: number; PATHSEG_LINETO_HORIZONTAL_ABS: number; PATHSEG_LINETO_HORIZONTAL_REL: number; PATHSEG_LINETO_REL: number; PATHSEG_LINETO_VERTICAL_ABS: number; PATHSEG_LINETO_VERTICAL_REL: number; PATHSEG_MOVETO_ABS: number; PATHSEG_MOVETO_REL: number; PATHSEG_UNKNOWN: number; } declare var SVGPathSeg: { prototype: SVGPathSeg; new(): SVGPathSeg; PATHSEG_ARC_ABS: number; PATHSEG_ARC_REL: number; PATHSEG_CLOSEPATH: number; PATHSEG_CURVETO_CUBIC_ABS: number; PATHSEG_CURVETO_CUBIC_REL: number; PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; PATHSEG_CURVETO_QUADRATIC_ABS: number; PATHSEG_CURVETO_QUADRATIC_REL: number; PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; PATHSEG_LINETO_ABS: number; PATHSEG_LINETO_HORIZONTAL_ABS: number; PATHSEG_LINETO_HORIZONTAL_REL: number; PATHSEG_LINETO_REL: number; PATHSEG_LINETO_VERTICAL_ABS: number; PATHSEG_LINETO_VERTICAL_REL: number; PATHSEG_MOVETO_ABS: number; PATHSEG_MOVETO_REL: number; PATHSEG_UNKNOWN: number; } interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; largeArcFlag: boolean; r1: number; r2: number; sweepFlag: boolean; x: number; y: number; } declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; } interface SVGPathSegArcRel extends SVGPathSeg { angle: number; largeArcFlag: boolean; r1: number; r2: number; sweepFlag: boolean; x: number; y: number; } declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; } interface SVGPathSegClosePath extends SVGPathSeg { } declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; } interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; x1: number; x2: number; y: number; y1: number; y2: number; } declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; } interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; x1: number; x2: number; y: number; y1: number; y2: number; } declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; } interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; x2: number; y: number; y2: number; } declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; } interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; x2: number; y: number; y2: number; } declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; } interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; x1: number; y: number; y1: number; } declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; } interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; x1: number; y: number; y1: number; } declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; } interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; y: number; } declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; } interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; y: number; } declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; } interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; y: number; } declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; } interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; } declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; } interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; } declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; } interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; y: number; } declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; } interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; } declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; } interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; } declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; } interface SVGPathSegList { numberOfItems: number; appendItem(newItem: SVGPathSeg): SVGPathSeg; clear(): void; getItem(index: number): SVGPathSeg; initialize(newItem: SVGPathSeg): SVGPathSeg; insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; removeItem(index: number): SVGPathSeg; replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; } declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; } interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; y: number; } declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; } interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; y: number; } declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; } interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGURIReference, SVGUnitTypes { height: SVGAnimatedLength; patternContentUnits: SVGAnimatedEnumeration; patternTransform: SVGAnimatedTransformList; patternUnits: SVGAnimatedEnumeration; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; } interface SVGPoint { x: number; y: number; matrixTransform(matrix: SVGMatrix): SVGPoint; } declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; } interface SVGPointList { numberOfItems: number; appendItem(newItem: SVGPoint): SVGPoint; clear(): void; getItem(index: number): SVGPoint; initialize(newItem: SVGPoint): SVGPoint; insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; removeItem(index: number): SVGPoint; replaceItem(newItem: SVGPoint, index: number): SVGPoint; } declare var SVGPointList: { prototype: SVGPointList; new(): SVGPointList; } interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGPolygonElement: { prototype: SVGPolygonElement; new(): SVGPolygonElement; } interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; } interface SVGPreserveAspectRatio { align: number; meetOrSlice: number; SVG_MEETORSLICE_MEET: number; SVG_MEETORSLICE_SLICE: number; SVG_MEETORSLICE_UNKNOWN: number; SVG_PRESERVEASPECTRATIO_NONE: number; SVG_PRESERVEASPECTRATIO_UNKNOWN: number; SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; SVG_PRESERVEASPECTRATIO_XMAXYMID: number; SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; SVG_PRESERVEASPECTRATIO_XMIDYMID: number; SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; SVG_PRESERVEASPECTRATIO_XMINYMAX: number; SVG_PRESERVEASPECTRATIO_XMINYMID: number; SVG_PRESERVEASPECTRATIO_XMINYMIN: number; } declare var SVGPreserveAspectRatio: { prototype: SVGPreserveAspectRatio; new(): SVGPreserveAspectRatio; SVG_MEETORSLICE_MEET: number; SVG_MEETORSLICE_SLICE: number; SVG_MEETORSLICE_UNKNOWN: number; SVG_PRESERVEASPECTRATIO_NONE: number; SVG_PRESERVEASPECTRATIO_UNKNOWN: number; SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; SVG_PRESERVEASPECTRATIO_XMAXYMID: number; SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; SVG_PRESERVEASPECTRATIO_XMIDYMID: number; SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; SVG_PRESERVEASPECTRATIO_XMINYMAX: number; SVG_PRESERVEASPECTRATIO_XMINYMID: number; SVG_PRESERVEASPECTRATIO_XMINYMIN: number; } interface SVGRadialGradientElement extends SVGGradientElement { cx: SVGAnimatedLength; cy: SVGAnimatedLength; fx: SVGAnimatedLength; fy: SVGAnimatedLength; r: SVGAnimatedLength; } declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; } interface SVGRect { height: number; width: number; x: number; y: number; } declare var SVGRect: { prototype: SVGRect; new(): SVGRect; } interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { height: SVGAnimatedLength; rx: SVGAnimatedLength; ry: SVGAnimatedLength; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGRectElement: { prototype: SVGRectElement; new(): SVGRectElement; } interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { contentScriptType: string; contentStyleType: string; currentScale: number; currentTranslate: SVGPoint; height: SVGAnimatedLength; onabort: (ev: Event) => any; onerror: (ev: Event) => any; onresize: (ev: UIEvent) => any; onscroll: (ev: UIEvent) => any; onunload: (ev: Event) => any; onzoom: (ev: SVGZoomEvent) => any; pixelUnitToMillimeterX: number; pixelUnitToMillimeterY: number; screenPixelToMillimeterX: number; screenPixelToMillimeterY: number; viewport: SVGRect; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; checkEnclosure(element: SVGElement, rect: SVGRect): boolean; checkIntersection(element: SVGElement, rect: SVGRect): boolean; createSVGAngle(): SVGAngle; createSVGLength(): SVGLength; createSVGMatrix(): SVGMatrix; createSVGNumber(): SVGNumber; createSVGPoint(): SVGPoint; createSVGRect(): SVGRect; createSVGTransform(): SVGTransform; createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; deselectAll(): void; forceRedraw(): void; getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; getCurrentTime(): number; getElementById(elementId: string): Element; getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeList; getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeList; pauseAnimations(): void; setCurrentTime(seconds: number): void; suspendRedraw(maxWaitMilliseconds: number): number; unpauseAnimations(): void; unsuspendRedraw(suspendHandleID: number): void; unsuspendRedrawAll(): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "SVGAbort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "SVGError", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "SVGUnload", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "SVGZoom", listener: (ev: SVGZoomEvent) => any, useCapture?: boolean): void; addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; } interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { type: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGScriptElement: { prototype: SVGScriptElement; new(): SVGScriptElement; } interface SVGStopElement extends SVGElement, SVGStylable { offset: SVGAnimatedNumber; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGStopElement: { prototype: SVGStopElement; new(): SVGStopElement; } interface SVGStringList { numberOfItems: number; appendItem(newItem: string): string; clear(): void; getItem(index: number): string; initialize(newItem: string): string; insertItemBefore(newItem: string, index: number): string; removeItem(index: number): string; replaceItem(newItem: string, index: number): string; } declare var SVGStringList: { prototype: SVGStringList; new(): SVGStringList; } interface SVGStyleElement extends SVGElement, SVGLangSpace { media: string; title: string; type: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGStyleElement: { prototype: SVGStyleElement; new(): SVGStyleElement; } interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGSwitchElement: { prototype: SVGSwitchElement; new(): SVGSwitchElement; } interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGSymbolElement: { prototype: SVGSymbolElement; new(): SVGSymbolElement; } interface SVGTSpanElement extends SVGTextPositioningElement { } declare var SVGTSpanElement: { prototype: SVGTSpanElement; new(): SVGTSpanElement; } interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { lengthAdjust: SVGAnimatedEnumeration; textLength: SVGAnimatedLength; getCharNumAtPosition(point: SVGPoint): number; getComputedTextLength(): number; getEndPositionOfChar(charnum: number): SVGPoint; getExtentOfChar(charnum: number): SVGRect; getNumberOfChars(): number; getRotationOfChar(charnum: number): number; getStartPositionOfChar(charnum: number): SVGPoint; getSubStringLength(charnum: number, nchars: number): number; selectSubString(charnum: number, nchars: number): void; LENGTHADJUST_SPACING: number; LENGTHADJUST_SPACINGANDGLYPHS: number; LENGTHADJUST_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGTextContentElement: { prototype: SVGTextContentElement; new(): SVGTextContentElement; LENGTHADJUST_SPACING: number; LENGTHADJUST_SPACINGANDGLYPHS: number; LENGTHADJUST_UNKNOWN: number; } interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; } interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { method: SVGAnimatedEnumeration; spacing: SVGAnimatedEnumeration; startOffset: SVGAnimatedLength; TEXTPATH_METHODTYPE_ALIGN: number; TEXTPATH_METHODTYPE_STRETCH: number; TEXTPATH_METHODTYPE_UNKNOWN: number; TEXTPATH_SPACINGTYPE_AUTO: number; TEXTPATH_SPACINGTYPE_EXACT: number; TEXTPATH_SPACINGTYPE_UNKNOWN: number; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGTextPathElement: { prototype: SVGTextPathElement; new(): SVGTextPathElement; TEXTPATH_METHODTYPE_ALIGN: number; TEXTPATH_METHODTYPE_STRETCH: number; TEXTPATH_METHODTYPE_UNKNOWN: number; TEXTPATH_SPACINGTYPE_AUTO: number; TEXTPATH_SPACINGTYPE_EXACT: number; TEXTPATH_SPACINGTYPE_UNKNOWN: number; } interface SVGTextPositioningElement extends SVGTextContentElement { dx: SVGAnimatedLengthList; dy: SVGAnimatedLengthList; rotate: SVGAnimatedNumberList; x: SVGAnimatedLengthList; y: SVGAnimatedLengthList; } declare var SVGTextPositioningElement: { prototype: SVGTextPositioningElement; new(): SVGTextPositioningElement; } interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; } interface SVGTransform { angle: number; matrix: SVGMatrix; type: number; setMatrix(matrix: SVGMatrix): void; setRotate(angle: number, cx: number, cy: number): void; setScale(sx: number, sy: number): void; setSkewX(angle: number): void; setSkewY(angle: number): void; setTranslate(tx: number, ty: number): void; SVG_TRANSFORM_MATRIX: number; SVG_TRANSFORM_ROTATE: number; SVG_TRANSFORM_SCALE: number; SVG_TRANSFORM_SKEWX: number; SVG_TRANSFORM_SKEWY: number; SVG_TRANSFORM_TRANSLATE: number; SVG_TRANSFORM_UNKNOWN: number; } declare var SVGTransform: { prototype: SVGTransform; new(): SVGTransform; SVG_TRANSFORM_MATRIX: number; SVG_TRANSFORM_ROTATE: number; SVG_TRANSFORM_SCALE: number; SVG_TRANSFORM_SKEWX: number; SVG_TRANSFORM_SKEWY: number; SVG_TRANSFORM_TRANSLATE: number; SVG_TRANSFORM_UNKNOWN: number; } interface SVGTransformList { numberOfItems: number; appendItem(newItem: SVGTransform): SVGTransform; clear(): void; consolidate(): SVGTransform; createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; getItem(index: number): SVGTransform; initialize(newItem: SVGTransform): SVGTransform; insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; removeItem(index: number): SVGTransform; replaceItem(newItem: SVGTransform, index: number): SVGTransform; } declare var SVGTransformList: { prototype: SVGTransformList; new(): SVGTransformList; } interface SVGUnitTypes { SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; SVG_UNIT_TYPE_UNKNOWN: number; SVG_UNIT_TYPE_USERSPACEONUSE: number; } declare var SVGUnitTypes: SVGUnitTypes; interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { animatedInstanceRoot: SVGElementInstance; height: SVGAnimatedLength; instanceRoot: SVGElementInstance; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; } interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { viewTarget: SVGStringList; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; } interface SVGZoomAndPan { zoomAndPan: number; } declare var SVGZoomAndPan: { SVG_ZOOMANDPAN_DISABLE: number; SVG_ZOOMANDPAN_MAGNIFY: number; SVG_ZOOMANDPAN_UNKNOWN: number; } interface SVGZoomEvent extends UIEvent { newScale: number; newTranslate: SVGPoint; previousScale: number; previousTranslate: SVGPoint; zoomRectScreen: SVGRect; } declare var SVGZoomEvent: { prototype: SVGZoomEvent; new(): SVGZoomEvent; } interface Screen extends EventTarget { availHeight: number; availWidth: number; bufferDepth: number; colorDepth: number; deviceXDPI: number; deviceYDPI: number; fontSmoothingEnabled: boolean; height: number; logicalXDPI: number; logicalYDPI: number; msOrientation: string; onmsorientationchange: (ev: Event) => any; pixelDepth: number; systemXDPI: number; systemYDPI: number; width: number; msLockOrientation(orientations: string | string[]): boolean; msUnlockOrientation(): void; addEventListener(type: "MSOrientationChange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Screen: { prototype: Screen; new(): Screen; } interface ScriptNotifyEvent extends Event { callingUri: string; value: string; } declare var ScriptNotifyEvent: { prototype: ScriptNotifyEvent; new(): ScriptNotifyEvent; } interface ScriptProcessorNode extends AudioNode { bufferSize: number; onaudioprocess: (ev: AudioProcessingEvent) => any; addEventListener(type: "audioprocess", listener: (ev: AudioProcessingEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var ScriptProcessorNode: { prototype: ScriptProcessorNode; new(): ScriptProcessorNode; } interface Selection { anchorNode: Node; anchorOffset: number; focusNode: Node; focusOffset: number; isCollapsed: boolean; rangeCount: number; type: string; addRange(range: Range): void; collapse(parentNode: Node, offset: number): void; collapseToEnd(): void; collapseToStart(): void; containsNode(node: Node, partlyContained: boolean): boolean; deleteFromDocument(): void; empty(): void; extend(newNode: Node, offset: number): void; getRangeAt(index: number): Range; removeAllRanges(): void; removeRange(range: Range): void; selectAllChildren(parentNode: Node): void; setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; toString(): string; } declare var Selection: { prototype: Selection; new(): Selection; } interface SourceBuffer extends EventTarget { appendWindowEnd: number; appendWindowStart: number; audioTracks: AudioTrackList; buffered: TimeRanges; mode: string; timestampOffset: number; updating: boolean; videoTracks: VideoTrackList; abort(): void; appendBuffer(data: ArrayBuffer | ArrayBufferView): void; appendStream(stream: MSStream, maxSize?: number): void; remove(start: number, end: number): void; } declare var SourceBuffer: { prototype: SourceBuffer; new(): SourceBuffer; } interface SourceBufferList extends EventTarget { length: number; item(index: number): SourceBuffer; [index: number]: SourceBuffer; } declare var SourceBufferList: { prototype: SourceBufferList; new(): SourceBufferList; } interface StereoPannerNode extends AudioNode { pan: AudioParam; } declare var StereoPannerNode: { prototype: StereoPannerNode; new(): StereoPannerNode; } interface Storage { length: number; clear(): void; getItem(key: string): any; key(index: number): string; removeItem(key: string): void; setItem(key: string, data: string): void; [key: string]: any; [index: number]: string; } declare var Storage: { prototype: Storage; new(): Storage; } interface StorageEvent extends Event { url: string; key?: string; oldValue?: string; newValue?: string; storageArea?: Storage; } declare var StorageEvent: { prototype: StorageEvent; new (type: string, eventInitDict?: StorageEventInit): StorageEvent; } interface StyleMedia { type: string; matchMedium(mediaquery: string): boolean; } declare var StyleMedia: { prototype: StyleMedia; new(): StyleMedia; } interface StyleSheet { disabled: boolean; href: string; media: MediaList; ownerNode: Node; parentStyleSheet: StyleSheet; title: string; type: string; } declare var StyleSheet: { prototype: StyleSheet; new(): StyleSheet; } interface StyleSheetList { length: number; item(index?: number): StyleSheet; [index: number]: StyleSheet; } declare var StyleSheetList: { prototype: StyleSheetList; new(): StyleSheetList; } interface StyleSheetPageList { length: number; item(index: number): CSSPageRule; [index: number]: CSSPageRule; } declare var StyleSheetPageList: { prototype: StyleSheetPageList; new(): StyleSheetPageList; } interface SubtleCrypto { decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any; deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): any; deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): any; digest(algorithm: string | Algorithm, data: ArrayBufferView): any; encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any; exportKey(format: string, key: CryptoKey): any; generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any; importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any; sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any; unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any; verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any; wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): any; } declare var SubtleCrypto: { prototype: SubtleCrypto; new(): SubtleCrypto; } interface Text extends CharacterData { wholeText: string; replaceWholeText(content: string): Text; splitText(offset: number): Text; } declare var Text: { prototype: Text; new(): Text; } interface TextEvent extends UIEvent { data: string; inputMethod: number; locale: string; initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; DOM_INPUT_METHOD_DROP: number; DOM_INPUT_METHOD_HANDWRITING: number; DOM_INPUT_METHOD_IME: number; DOM_INPUT_METHOD_KEYBOARD: number; DOM_INPUT_METHOD_MULTIMODAL: number; DOM_INPUT_METHOD_OPTION: number; DOM_INPUT_METHOD_PASTE: number; DOM_INPUT_METHOD_SCRIPT: number; DOM_INPUT_METHOD_UNKNOWN: number; DOM_INPUT_METHOD_VOICE: number; } declare var TextEvent: { prototype: TextEvent; new(): TextEvent; DOM_INPUT_METHOD_DROP: number; DOM_INPUT_METHOD_HANDWRITING: number; DOM_INPUT_METHOD_IME: number; DOM_INPUT_METHOD_KEYBOARD: number; DOM_INPUT_METHOD_MULTIMODAL: number; DOM_INPUT_METHOD_OPTION: number; DOM_INPUT_METHOD_PASTE: number; DOM_INPUT_METHOD_SCRIPT: number; DOM_INPUT_METHOD_UNKNOWN: number; DOM_INPUT_METHOD_VOICE: number; } interface TextMetrics { width: number; } declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; } interface TextRange { boundingHeight: number; boundingLeft: number; boundingTop: number; boundingWidth: number; htmlText: string; offsetLeft: number; offsetTop: number; text: string; collapse(start?: boolean): void; compareEndPoints(how: string, sourceRange: TextRange): number; duplicate(): TextRange; execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; execCommandShowHelp(cmdID: string): boolean; expand(Unit: string): boolean; findText(string: string, count?: number, flags?: number): boolean; getBookmark(): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; inRange(range: TextRange): boolean; isEqual(range: TextRange): boolean; move(unit: string, count?: number): number; moveEnd(unit: string, count?: number): number; moveStart(unit: string, count?: number): number; moveToBookmark(bookmark: string): boolean; moveToElementText(element: Element): void; moveToPoint(x: number, y: number): void; parentElement(): Element; pasteHTML(html: string): void; queryCommandEnabled(cmdID: string): boolean; queryCommandIndeterm(cmdID: string): boolean; queryCommandState(cmdID: string): boolean; queryCommandSupported(cmdID: string): boolean; queryCommandText(cmdID: string): string; queryCommandValue(cmdID: string): any; scrollIntoView(fStart?: boolean): void; select(): void; setEndPoint(how: string, SourceRange: TextRange): void; } declare var TextRange: { prototype: TextRange; new(): TextRange; } interface TextRangeCollection { length: number; item(index: number): TextRange; [index: number]: TextRange; } declare var TextRangeCollection: { prototype: TextRangeCollection; new(): TextRangeCollection; } interface TextTrack extends EventTarget { activeCues: TextTrackCueList; cues: TextTrackCueList; inBandMetadataTrackDispatchType: string; kind: string; label: string; language: string; mode: any; oncuechange: (ev: Event) => any; onerror: (ev: Event) => any; onload: (ev: Event) => any; readyState: number; addCue(cue: TextTrackCue): void; removeCue(cue: TextTrackCue): void; DISABLED: number; ERROR: number; HIDDEN: number; LOADED: number; LOADING: number; NONE: number; SHOWING: number; addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var TextTrack: { prototype: TextTrack; new(): TextTrack; DISABLED: number; ERROR: number; HIDDEN: number; LOADED: number; LOADING: number; NONE: number; SHOWING: number; } interface TextTrackCue extends EventTarget { endTime: number; id: string; onenter: (ev: Event) => any; onexit: (ev: Event) => any; pauseOnExit: boolean; startTime: number; text: string; track: TextTrack; getCueAsHTML(): DocumentFragment; addEventListener(type: "enter", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "exit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; } interface TextTrackCueList { length: number; getCueById(id: string): TextTrackCue; item(index: number): TextTrackCue; [index: number]: TextTrackCue; } declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; } interface TextTrackList extends EventTarget { length: number; onaddtrack: (ev: TrackEvent) => any; item(index: number): TextTrack; addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [index: number]: TextTrack; } declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; } interface TimeRanges { length: number; end(index: number): number; start(index: number): number; } declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; } interface Touch { clientX: number; clientY: number; identifier: number; pageX: number; pageY: number; screenX: number; screenY: number; target: EventTarget; } declare var Touch: { prototype: Touch; new(): Touch; } interface TouchEvent extends UIEvent { altKey: boolean; changedTouches: TouchList; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; targetTouches: TouchList; touches: TouchList; } declare var TouchEvent: { prototype: TouchEvent; new(): TouchEvent; } interface TouchList { length: number; item(index: number): Touch; [index: number]: Touch; } declare var TouchList: { prototype: TouchList; new(): TouchList; } interface TrackEvent extends Event { track: any; } declare var TrackEvent: { prototype: TrackEvent; new(): TrackEvent; } interface TransitionEvent extends Event { elapsedTime: number; propertyName: string; initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; } declare var TransitionEvent: { prototype: TransitionEvent; new(): TransitionEvent; } interface TreeWalker { currentNode: Node; expandEntityReferences: boolean; filter: NodeFilter; root: Node; whatToShow: number; firstChild(): Node; lastChild(): Node; nextNode(): Node; nextSibling(): Node; parentNode(): Node; previousNode(): Node; previousSibling(): Node; } declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; } interface UIEvent extends Event { detail: number; view: Window; initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; } declare var UIEvent: { prototype: UIEvent; new(type: string, eventInitDict?: UIEventInit): UIEvent; } interface URL { createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; } declare var URL: URL; interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { mediaType: string; } declare var UnviewableContentIdentifiedEvent: { prototype: UnviewableContentIdentifiedEvent; new(): UnviewableContentIdentifiedEvent; } interface ValidityState { badInput: boolean; customError: boolean; patternMismatch: boolean; rangeOverflow: boolean; rangeUnderflow: boolean; stepMismatch: boolean; tooLong: boolean; typeMismatch: boolean; valid: boolean; valueMissing: boolean; } declare var ValidityState: { prototype: ValidityState; new(): ValidityState; } interface VideoPlaybackQuality { corruptedVideoFrames: number; creationTime: number; droppedVideoFrames: number; totalFrameDelay: number; totalVideoFrames: number; } declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; } interface VideoTrack { id: string; kind: string; label: string; language: string; selected: boolean; sourceBuffer: SourceBuffer; } declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; } interface VideoTrackList extends EventTarget { length: number; onaddtrack: (ev: TrackEvent) => any; onchange: (ev: Event) => any; onremovetrack: (ev: TrackEvent) => any; selectedIndex: number; getTrackById(id: string): VideoTrack; item(index: number): VideoTrack; addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "removetrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [index: number]: VideoTrack; } declare var VideoTrackList: { prototype: VideoTrackList; new(): VideoTrackList; } interface WEBGL_compressed_texture_s3tc { COMPRESSED_RGBA_S3TC_DXT1_EXT: number; COMPRESSED_RGBA_S3TC_DXT3_EXT: number; COMPRESSED_RGBA_S3TC_DXT5_EXT: number; COMPRESSED_RGB_S3TC_DXT1_EXT: number; } declare var WEBGL_compressed_texture_s3tc: { prototype: WEBGL_compressed_texture_s3tc; new(): WEBGL_compressed_texture_s3tc; COMPRESSED_RGBA_S3TC_DXT1_EXT: number; COMPRESSED_RGBA_S3TC_DXT3_EXT: number; COMPRESSED_RGBA_S3TC_DXT5_EXT: number; COMPRESSED_RGB_S3TC_DXT1_EXT: number; } interface WEBGL_debug_renderer_info { UNMASKED_RENDERER_WEBGL: number; UNMASKED_VENDOR_WEBGL: number; } declare var WEBGL_debug_renderer_info: { prototype: WEBGL_debug_renderer_info; new(): WEBGL_debug_renderer_info; UNMASKED_RENDERER_WEBGL: number; UNMASKED_VENDOR_WEBGL: number; } interface WEBGL_depth_texture { UNSIGNED_INT_24_8_WEBGL: number; } declare var WEBGL_depth_texture: { prototype: WEBGL_depth_texture; new(): WEBGL_depth_texture; UNSIGNED_INT_24_8_WEBGL: number; } interface WaveShaperNode extends AudioNode { curve: Float32Array; oversample: string; } declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; } interface WebGLActiveInfo { name: string; size: number; type: number; } declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; } interface WebGLBuffer extends WebGLObject { } declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; } interface WebGLContextEvent extends Event { statusMessage: string; } declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(): WebGLContextEvent; } interface WebGLFramebuffer extends WebGLObject { } declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; } interface WebGLObject { } declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; } interface WebGLProgram extends WebGLObject { } declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; } interface WebGLRenderbuffer extends WebGLObject { } declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; } interface WebGLRenderingContext { canvas: HTMLCanvasElement; drawingBufferHeight: number; drawingBufferWidth: number; activeTexture(texture: number): void; attachShader(program: WebGLProgram, shader: WebGLShader): void; bindAttribLocation(program: WebGLProgram, index: number, name: string): void; bindBuffer(target: number, buffer: WebGLBuffer): void; bindFramebuffer(target: number, framebuffer: WebGLFramebuffer): void; bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer): void; bindTexture(target: number, texture: WebGLTexture): void; blendColor(red: number, green: number, blue: number, alpha: number): void; blendEquation(mode: number): void; blendEquationSeparate(modeRGB: number, modeAlpha: number): void; blendFunc(sfactor: number, dfactor: number): void; blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; checkFramebufferStatus(target: number): number; clear(mask: number): void; clearColor(red: number, green: number, blue: number, alpha: number): void; clearDepth(depth: number): void; clearStencil(s: number): void; colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; compileShader(shader: WebGLShader): void; compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; createBuffer(): WebGLBuffer; createFramebuffer(): WebGLFramebuffer; createProgram(): WebGLProgram; createRenderbuffer(): WebGLRenderbuffer; createShader(type: number): WebGLShader; createTexture(): WebGLTexture; cullFace(mode: number): void; deleteBuffer(buffer: WebGLBuffer): void; deleteFramebuffer(framebuffer: WebGLFramebuffer): void; deleteProgram(program: WebGLProgram): void; deleteRenderbuffer(renderbuffer: WebGLRenderbuffer): void; deleteShader(shader: WebGLShader): void; deleteTexture(texture: WebGLTexture): void; depthFunc(func: number): void; depthMask(flag: boolean): void; depthRange(zNear: number, zFar: number): void; detachShader(program: WebGLProgram, shader: WebGLShader): void; disable(cap: number): void; disableVertexAttribArray(index: number): void; drawArrays(mode: number, first: number, count: number): void; drawElements(mode: number, count: number, type: number, offset: number): void; enable(cap: number): void; enableVertexAttribArray(index: number): void; finish(): void; flush(): void; framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer): void; framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture, level: number): void; frontFace(mode: number): void; generateMipmap(target: number): void; getActiveAttrib(program: WebGLProgram, index: number): WebGLActiveInfo; getActiveUniform(program: WebGLProgram, index: number): WebGLActiveInfo; getAttachedShaders(program: WebGLProgram): WebGLShader[]; getAttribLocation(program: WebGLProgram, name: string): number; getBufferParameter(target: number, pname: number): any; getContextAttributes(): WebGLContextAttributes; getError(): number; getExtension(name: string): any; getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; getParameter(pname: number): any; getProgramInfoLog(program: WebGLProgram): string; getProgramParameter(program: WebGLProgram, pname: number): any; getRenderbufferParameter(target: number, pname: number): any; getShaderInfoLog(shader: WebGLShader): string; getShaderParameter(shader: WebGLShader, pname: number): any; getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat; getShaderSource(shader: WebGLShader): string; getSupportedExtensions(): string[]; getTexParameter(target: number, pname: number): any; getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation; getVertexAttrib(index: number, pname: number): any; getVertexAttribOffset(index: number, pname: number): number; hint(target: number, mode: number): void; isBuffer(buffer: WebGLBuffer): boolean; isContextLost(): boolean; isEnabled(cap: number): boolean; isFramebuffer(framebuffer: WebGLFramebuffer): boolean; isProgram(program: WebGLProgram): boolean; isRenderbuffer(renderbuffer: WebGLRenderbuffer): boolean; isShader(shader: WebGLShader): boolean; isTexture(texture: WebGLTexture): boolean; lineWidth(width: number): void; linkProgram(program: WebGLProgram): void; pixelStorei(pname: number, param: number): void; polygonOffset(factor: number, units: number): void; readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; sampleCoverage(value: number, invert: boolean): void; scissor(x: number, y: number, width: number, height: number): void; shaderSource(shader: WebGLShader, source: string): void; stencilFunc(func: number, ref: number, mask: number): void; stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; stencilMask(mask: number): void; stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; uniform1f(location: WebGLUniformLocation, x: number): void; uniform1fv(location: WebGLUniformLocation, v: Float32Array): void; uniform1i(location: WebGLUniformLocation, x: number): void; uniform1iv(location: WebGLUniformLocation, v: Int32Array): void; uniform2f(location: WebGLUniformLocation, x: number, y: number): void; uniform2fv(location: WebGLUniformLocation, v: Float32Array): void; uniform2i(location: WebGLUniformLocation, x: number, y: number): void; uniform2iv(location: WebGLUniformLocation, v: Int32Array): void; uniform3f(location: WebGLUniformLocation, x: number, y: number, z: number): void; uniform3fv(location: WebGLUniformLocation, v: Float32Array): void; uniform3i(location: WebGLUniformLocation, x: number, y: number, z: number): void; uniform3iv(location: WebGLUniformLocation, v: Int32Array): void; uniform4f(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; uniform4fv(location: WebGLUniformLocation, v: Float32Array): void; uniform4i(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; uniform4iv(location: WebGLUniformLocation, v: Int32Array): void; uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; useProgram(program: WebGLProgram): void; validateProgram(program: WebGLProgram): void; vertexAttrib1f(indx: number, x: number): void; vertexAttrib1fv(indx: number, values: Float32Array): void; vertexAttrib2f(indx: number, x: number, y: number): void; vertexAttrib2fv(indx: number, values: Float32Array): void; vertexAttrib3f(indx: number, x: number, y: number, z: number): void; vertexAttrib3fv(indx: number, values: Float32Array): void; vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; vertexAttrib4fv(indx: number, values: Float32Array): void; vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; viewport(x: number, y: number, width: number, height: number): void; ACTIVE_ATTRIBUTES: number; ACTIVE_TEXTURE: number; ACTIVE_UNIFORMS: number; ALIASED_LINE_WIDTH_RANGE: number; ALIASED_POINT_SIZE_RANGE: number; ALPHA: number; ALPHA_BITS: number; ALWAYS: number; ARRAY_BUFFER: number; ARRAY_BUFFER_BINDING: number; ATTACHED_SHADERS: number; BACK: number; BLEND: number; BLEND_COLOR: number; BLEND_DST_ALPHA: number; BLEND_DST_RGB: number; BLEND_EQUATION: number; BLEND_EQUATION_ALPHA: number; BLEND_EQUATION_RGB: number; BLEND_SRC_ALPHA: number; BLEND_SRC_RGB: number; BLUE_BITS: number; BOOL: number; BOOL_VEC2: number; BOOL_VEC3: number; BOOL_VEC4: number; BROWSER_DEFAULT_WEBGL: number; BUFFER_SIZE: number; BUFFER_USAGE: number; BYTE: number; CCW: number; CLAMP_TO_EDGE: number; COLOR_ATTACHMENT0: number; COLOR_BUFFER_BIT: number; COLOR_CLEAR_VALUE: number; COLOR_WRITEMASK: number; COMPILE_STATUS: number; COMPRESSED_TEXTURE_FORMATS: number; CONSTANT_ALPHA: number; CONSTANT_COLOR: number; CONTEXT_LOST_WEBGL: number; CULL_FACE: number; CULL_FACE_MODE: number; CURRENT_PROGRAM: number; CURRENT_VERTEX_ATTRIB: number; CW: number; DECR: number; DECR_WRAP: number; DELETE_STATUS: number; DEPTH_ATTACHMENT: number; DEPTH_BITS: number; DEPTH_BUFFER_BIT: number; DEPTH_CLEAR_VALUE: number; DEPTH_COMPONENT: number; DEPTH_COMPONENT16: number; DEPTH_FUNC: number; DEPTH_RANGE: number; DEPTH_STENCIL: number; DEPTH_STENCIL_ATTACHMENT: number; DEPTH_TEST: number; DEPTH_WRITEMASK: number; DITHER: number; DONT_CARE: number; DST_ALPHA: number; DST_COLOR: number; DYNAMIC_DRAW: number; ELEMENT_ARRAY_BUFFER: number; ELEMENT_ARRAY_BUFFER_BINDING: number; EQUAL: number; FASTEST: number; FLOAT: number; FLOAT_MAT2: number; FLOAT_MAT3: number; FLOAT_MAT4: number; FLOAT_VEC2: number; FLOAT_VEC3: number; FLOAT_VEC4: number; FRAGMENT_SHADER: number; FRAMEBUFFER: number; FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; FRAMEBUFFER_BINDING: number; FRAMEBUFFER_COMPLETE: number; FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; FRAMEBUFFER_UNSUPPORTED: number; FRONT: number; FRONT_AND_BACK: number; FRONT_FACE: number; FUNC_ADD: number; FUNC_REVERSE_SUBTRACT: number; FUNC_SUBTRACT: number; GENERATE_MIPMAP_HINT: number; GEQUAL: number; GREATER: number; GREEN_BITS: number; HIGH_FLOAT: number; HIGH_INT: number; IMPLEMENTATION_COLOR_READ_FORMAT: number; IMPLEMENTATION_COLOR_READ_TYPE: number; INCR: number; INCR_WRAP: number; INT: number; INT_VEC2: number; INT_VEC3: number; INT_VEC4: number; INVALID_ENUM: number; INVALID_FRAMEBUFFER_OPERATION: number; INVALID_OPERATION: number; INVALID_VALUE: number; INVERT: number; KEEP: number; LEQUAL: number; LESS: number; LINEAR: number; LINEAR_MIPMAP_LINEAR: number; LINEAR_MIPMAP_NEAREST: number; LINES: number; LINE_LOOP: number; LINE_STRIP: number; LINE_WIDTH: number; LINK_STATUS: number; LOW_FLOAT: number; LOW_INT: number; LUMINANCE: number; LUMINANCE_ALPHA: number; MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; MAX_CUBE_MAP_TEXTURE_SIZE: number; MAX_FRAGMENT_UNIFORM_VECTORS: number; MAX_RENDERBUFFER_SIZE: number; MAX_TEXTURE_IMAGE_UNITS: number; MAX_TEXTURE_SIZE: number; MAX_VARYING_VECTORS: number; MAX_VERTEX_ATTRIBS: number; MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; MAX_VERTEX_UNIFORM_VECTORS: number; MAX_VIEWPORT_DIMS: number; MEDIUM_FLOAT: number; MEDIUM_INT: number; MIRRORED_REPEAT: number; NEAREST: number; NEAREST_MIPMAP_LINEAR: number; NEAREST_MIPMAP_NEAREST: number; NEVER: number; NICEST: number; NONE: number; NOTEQUAL: number; NO_ERROR: number; ONE: number; ONE_MINUS_CONSTANT_ALPHA: number; ONE_MINUS_CONSTANT_COLOR: number; ONE_MINUS_DST_ALPHA: number; ONE_MINUS_DST_COLOR: number; ONE_MINUS_SRC_ALPHA: number; ONE_MINUS_SRC_COLOR: number; OUT_OF_MEMORY: number; PACK_ALIGNMENT: number; POINTS: number; POLYGON_OFFSET_FACTOR: number; POLYGON_OFFSET_FILL: number; POLYGON_OFFSET_UNITS: number; RED_BITS: number; RENDERBUFFER: number; RENDERBUFFER_ALPHA_SIZE: number; RENDERBUFFER_BINDING: number; RENDERBUFFER_BLUE_SIZE: number; RENDERBUFFER_DEPTH_SIZE: number; RENDERBUFFER_GREEN_SIZE: number; RENDERBUFFER_HEIGHT: number; RENDERBUFFER_INTERNAL_FORMAT: number; RENDERBUFFER_RED_SIZE: number; RENDERBUFFER_STENCIL_SIZE: number; RENDERBUFFER_WIDTH: number; RENDERER: number; REPEAT: number; REPLACE: number; RGB: number; RGB565: number; RGB5_A1: number; RGBA: number; RGBA4: number; SAMPLER_2D: number; SAMPLER_CUBE: number; SAMPLES: number; SAMPLE_ALPHA_TO_COVERAGE: number; SAMPLE_BUFFERS: number; SAMPLE_COVERAGE: number; SAMPLE_COVERAGE_INVERT: number; SAMPLE_COVERAGE_VALUE: number; SCISSOR_BOX: number; SCISSOR_TEST: number; SHADER_TYPE: number; SHADING_LANGUAGE_VERSION: number; SHORT: number; SRC_ALPHA: number; SRC_ALPHA_SATURATE: number; SRC_COLOR: number; STATIC_DRAW: number; STENCIL_ATTACHMENT: number; STENCIL_BACK_FAIL: number; STENCIL_BACK_FUNC: number; STENCIL_BACK_PASS_DEPTH_FAIL: number; STENCIL_BACK_PASS_DEPTH_PASS: number; STENCIL_BACK_REF: number; STENCIL_BACK_VALUE_MASK: number; STENCIL_BACK_WRITEMASK: number; STENCIL_BITS: number; STENCIL_BUFFER_BIT: number; STENCIL_CLEAR_VALUE: number; STENCIL_FAIL: number; STENCIL_FUNC: number; STENCIL_INDEX: number; STENCIL_INDEX8: number; STENCIL_PASS_DEPTH_FAIL: number; STENCIL_PASS_DEPTH_PASS: number; STENCIL_REF: number; STENCIL_TEST: number; STENCIL_VALUE_MASK: number; STENCIL_WRITEMASK: number; STREAM_DRAW: number; SUBPIXEL_BITS: number; TEXTURE: number; TEXTURE0: number; TEXTURE1: number; TEXTURE10: number; TEXTURE11: number; TEXTURE12: number; TEXTURE13: number; TEXTURE14: number; TEXTURE15: number; TEXTURE16: number; TEXTURE17: number; TEXTURE18: number; TEXTURE19: number; TEXTURE2: number; TEXTURE20: number; TEXTURE21: number; TEXTURE22: number; TEXTURE23: number; TEXTURE24: number; TEXTURE25: number; TEXTURE26: number; TEXTURE27: number; TEXTURE28: number; TEXTURE29: number; TEXTURE3: number; TEXTURE30: number; TEXTURE31: number; TEXTURE4: number; TEXTURE5: number; TEXTURE6: number; TEXTURE7: number; TEXTURE8: number; TEXTURE9: number; TEXTURE_2D: number; TEXTURE_BINDING_2D: number; TEXTURE_BINDING_CUBE_MAP: number; TEXTURE_CUBE_MAP: number; TEXTURE_CUBE_MAP_NEGATIVE_X: number; TEXTURE_CUBE_MAP_NEGATIVE_Y: number; TEXTURE_CUBE_MAP_NEGATIVE_Z: number; TEXTURE_CUBE_MAP_POSITIVE_X: number; TEXTURE_CUBE_MAP_POSITIVE_Y: number; TEXTURE_CUBE_MAP_POSITIVE_Z: number; TEXTURE_MAG_FILTER: number; TEXTURE_MIN_FILTER: number; TEXTURE_WRAP_S: number; TEXTURE_WRAP_T: number; TRIANGLES: number; TRIANGLE_FAN: number; TRIANGLE_STRIP: number; UNPACK_ALIGNMENT: number; UNPACK_COLORSPACE_CONVERSION_WEBGL: number; UNPACK_FLIP_Y_WEBGL: number; UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; UNSIGNED_BYTE: number; UNSIGNED_INT: number; UNSIGNED_SHORT: number; UNSIGNED_SHORT_4_4_4_4: number; UNSIGNED_SHORT_5_5_5_1: number; UNSIGNED_SHORT_5_6_5: number; VALIDATE_STATUS: number; VENDOR: number; VERSION: number; VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; VERTEX_ATTRIB_ARRAY_ENABLED: number; VERTEX_ATTRIB_ARRAY_NORMALIZED: number; VERTEX_ATTRIB_ARRAY_POINTER: number; VERTEX_ATTRIB_ARRAY_SIZE: number; VERTEX_ATTRIB_ARRAY_STRIDE: number; VERTEX_ATTRIB_ARRAY_TYPE: number; VERTEX_SHADER: number; VIEWPORT: number; ZERO: number; } declare var WebGLRenderingContext: { prototype: WebGLRenderingContext; new(): WebGLRenderingContext; ACTIVE_ATTRIBUTES: number; ACTIVE_TEXTURE: number; ACTIVE_UNIFORMS: number; ALIASED_LINE_WIDTH_RANGE: number; ALIASED_POINT_SIZE_RANGE: number; ALPHA: number; ALPHA_BITS: number; ALWAYS: number; ARRAY_BUFFER: number; ARRAY_BUFFER_BINDING: number; ATTACHED_SHADERS: number; BACK: number; BLEND: number; BLEND_COLOR: number; BLEND_DST_ALPHA: number; BLEND_DST_RGB: number; BLEND_EQUATION: number; BLEND_EQUATION_ALPHA: number; BLEND_EQUATION_RGB: number; BLEND_SRC_ALPHA: number; BLEND_SRC_RGB: number; BLUE_BITS: number; BOOL: number; BOOL_VEC2: number; BOOL_VEC3: number; BOOL_VEC4: number; BROWSER_DEFAULT_WEBGL: number; BUFFER_SIZE: number; BUFFER_USAGE: number; BYTE: number; CCW: number; CLAMP_TO_EDGE: number; COLOR_ATTACHMENT0: number; COLOR_BUFFER_BIT: number; COLOR_CLEAR_VALUE: number; COLOR_WRITEMASK: number; COMPILE_STATUS: number; COMPRESSED_TEXTURE_FORMATS: number; CONSTANT_ALPHA: number; CONSTANT_COLOR: number; CONTEXT_LOST_WEBGL: number; CULL_FACE: number; CULL_FACE_MODE: number; CURRENT_PROGRAM: number; CURRENT_VERTEX_ATTRIB: number; CW: number; DECR: number; DECR_WRAP: number; DELETE_STATUS: number; DEPTH_ATTACHMENT: number; DEPTH_BITS: number; DEPTH_BUFFER_BIT: number; DEPTH_CLEAR_VALUE: number; DEPTH_COMPONENT: number; DEPTH_COMPONENT16: number; DEPTH_FUNC: number; DEPTH_RANGE: number; DEPTH_STENCIL: number; DEPTH_STENCIL_ATTACHMENT: number; DEPTH_TEST: number; DEPTH_WRITEMASK: number; DITHER: number; DONT_CARE: number; DST_ALPHA: number; DST_COLOR: number; DYNAMIC_DRAW: number; ELEMENT_ARRAY_BUFFER: number; ELEMENT_ARRAY_BUFFER_BINDING: number; EQUAL: number; FASTEST: number; FLOAT: number; FLOAT_MAT2: number; FLOAT_MAT3: number; FLOAT_MAT4: number; FLOAT_VEC2: number; FLOAT_VEC3: number; FLOAT_VEC4: number; FRAGMENT_SHADER: number; FRAMEBUFFER: number; FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; FRAMEBUFFER_BINDING: number; FRAMEBUFFER_COMPLETE: number; FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; FRAMEBUFFER_UNSUPPORTED: number; FRONT: number; FRONT_AND_BACK: number; FRONT_FACE: number; FUNC_ADD: number; FUNC_REVERSE_SUBTRACT: number; FUNC_SUBTRACT: number; GENERATE_MIPMAP_HINT: number; GEQUAL: number; GREATER: number; GREEN_BITS: number; HIGH_FLOAT: number; HIGH_INT: number; IMPLEMENTATION_COLOR_READ_FORMAT: number; IMPLEMENTATION_COLOR_READ_TYPE: number; INCR: number; INCR_WRAP: number; INT: number; INT_VEC2: number; INT_VEC3: number; INT_VEC4: number; INVALID_ENUM: number; INVALID_FRAMEBUFFER_OPERATION: number; INVALID_OPERATION: number; INVALID_VALUE: number; INVERT: number; KEEP: number; LEQUAL: number; LESS: number; LINEAR: number; LINEAR_MIPMAP_LINEAR: number; LINEAR_MIPMAP_NEAREST: number; LINES: number; LINE_LOOP: number; LINE_STRIP: number; LINE_WIDTH: number; LINK_STATUS: number; LOW_FLOAT: number; LOW_INT: number; LUMINANCE: number; LUMINANCE_ALPHA: number; MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; MAX_CUBE_MAP_TEXTURE_SIZE: number; MAX_FRAGMENT_UNIFORM_VECTORS: number; MAX_RENDERBUFFER_SIZE: number; MAX_TEXTURE_IMAGE_UNITS: number; MAX_TEXTURE_SIZE: number; MAX_VARYING_VECTORS: number; MAX_VERTEX_ATTRIBS: number; MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; MAX_VERTEX_UNIFORM_VECTORS: number; MAX_VIEWPORT_DIMS: number; MEDIUM_FLOAT: number; MEDIUM_INT: number; MIRRORED_REPEAT: number; NEAREST: number; NEAREST_MIPMAP_LINEAR: number; NEAREST_MIPMAP_NEAREST: number; NEVER: number; NICEST: number; NONE: number; NOTEQUAL: number; NO_ERROR: number; ONE: number; ONE_MINUS_CONSTANT_ALPHA: number; ONE_MINUS_CONSTANT_COLOR: number; ONE_MINUS_DST_ALPHA: number; ONE_MINUS_DST_COLOR: number; ONE_MINUS_SRC_ALPHA: number; ONE_MINUS_SRC_COLOR: number; OUT_OF_MEMORY: number; PACK_ALIGNMENT: number; POINTS: number; POLYGON_OFFSET_FACTOR: number; POLYGON_OFFSET_FILL: number; POLYGON_OFFSET_UNITS: number; RED_BITS: number; RENDERBUFFER: number; RENDERBUFFER_ALPHA_SIZE: number; RENDERBUFFER_BINDING: number; RENDERBUFFER_BLUE_SIZE: number; RENDERBUFFER_DEPTH_SIZE: number; RENDERBUFFER_GREEN_SIZE: number; RENDERBUFFER_HEIGHT: number; RENDERBUFFER_INTERNAL_FORMAT: number; RENDERBUFFER_RED_SIZE: number; RENDERBUFFER_STENCIL_SIZE: number; RENDERBUFFER_WIDTH: number; RENDERER: number; REPEAT: number; REPLACE: number; RGB: number; RGB565: number; RGB5_A1: number; RGBA: number; RGBA4: number; SAMPLER_2D: number; SAMPLER_CUBE: number; SAMPLES: number; SAMPLE_ALPHA_TO_COVERAGE: number; SAMPLE_BUFFERS: number; SAMPLE_COVERAGE: number; SAMPLE_COVERAGE_INVERT: number; SAMPLE_COVERAGE_VALUE: number; SCISSOR_BOX: number; SCISSOR_TEST: number; SHADER_TYPE: number; SHADING_LANGUAGE_VERSION: number; SHORT: number; SRC_ALPHA: number; SRC_ALPHA_SATURATE: number; SRC_COLOR: number; STATIC_DRAW: number; STENCIL_ATTACHMENT: number; STENCIL_BACK_FAIL: number; STENCIL_BACK_FUNC: number; STENCIL_BACK_PASS_DEPTH_FAIL: number; STENCIL_BACK_PASS_DEPTH_PASS: number; STENCIL_BACK_REF: number; STENCIL_BACK_VALUE_MASK: number; STENCIL_BACK_WRITEMASK: number; STENCIL_BITS: number; STENCIL_BUFFER_BIT: number; STENCIL_CLEAR_VALUE: number; STENCIL_FAIL: number; STENCIL_FUNC: number; STENCIL_INDEX: number; STENCIL_INDEX8: number; STENCIL_PASS_DEPTH_FAIL: number; STENCIL_PASS_DEPTH_PASS: number; STENCIL_REF: number; STENCIL_TEST: number; STENCIL_VALUE_MASK: number; STENCIL_WRITEMASK: number; STREAM_DRAW: number; SUBPIXEL_BITS: number; TEXTURE: number; TEXTURE0: number; TEXTURE1: number; TEXTURE10: number; TEXTURE11: number; TEXTURE12: number; TEXTURE13: number; TEXTURE14: number; TEXTURE15: number; TEXTURE16: number; TEXTURE17: number; TEXTURE18: number; TEXTURE19: number; TEXTURE2: number; TEXTURE20: number; TEXTURE21: number; TEXTURE22: number; TEXTURE23: number; TEXTURE24: number; TEXTURE25: number; TEXTURE26: number; TEXTURE27: number; TEXTURE28: number; TEXTURE29: number; TEXTURE3: number; TEXTURE30: number; TEXTURE31: number; TEXTURE4: number; TEXTURE5: number; TEXTURE6: number; TEXTURE7: number; TEXTURE8: number; TEXTURE9: number; TEXTURE_2D: number; TEXTURE_BINDING_2D: number; TEXTURE_BINDING_CUBE_MAP: number; TEXTURE_CUBE_MAP: number; TEXTURE_CUBE_MAP_NEGATIVE_X: number; TEXTURE_CUBE_MAP_NEGATIVE_Y: number; TEXTURE_CUBE_MAP_NEGATIVE_Z: number; TEXTURE_CUBE_MAP_POSITIVE_X: number; TEXTURE_CUBE_MAP_POSITIVE_Y: number; TEXTURE_CUBE_MAP_POSITIVE_Z: number; TEXTURE_MAG_FILTER: number; TEXTURE_MIN_FILTER: number; TEXTURE_WRAP_S: number; TEXTURE_WRAP_T: number; TRIANGLES: number; TRIANGLE_FAN: number; TRIANGLE_STRIP: number; UNPACK_ALIGNMENT: number; UNPACK_COLORSPACE_CONVERSION_WEBGL: number; UNPACK_FLIP_Y_WEBGL: number; UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; UNSIGNED_BYTE: number; UNSIGNED_INT: number; UNSIGNED_SHORT: number; UNSIGNED_SHORT_4_4_4_4: number; UNSIGNED_SHORT_5_5_5_1: number; UNSIGNED_SHORT_5_6_5: number; VALIDATE_STATUS: number; VENDOR: number; VERSION: number; VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; VERTEX_ATTRIB_ARRAY_ENABLED: number; VERTEX_ATTRIB_ARRAY_NORMALIZED: number; VERTEX_ATTRIB_ARRAY_POINTER: number; VERTEX_ATTRIB_ARRAY_SIZE: number; VERTEX_ATTRIB_ARRAY_STRIDE: number; VERTEX_ATTRIB_ARRAY_TYPE: number; VERTEX_SHADER: number; VIEWPORT: number; ZERO: number; } interface WebGLShader extends WebGLObject { } declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; } interface WebGLShaderPrecisionFormat { precision: number; rangeMax: number; rangeMin: number; } declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; } interface WebGLTexture extends WebGLObject { } declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; } interface WebGLUniformLocation { } declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; } interface WebKitCSSMatrix { a: number; b: number; c: number; d: number; e: number; f: number; m11: number; m12: number; m13: number; m14: number; m21: number; m22: number; m23: number; m24: number; m31: number; m32: number; m33: number; m34: number; m41: number; m42: number; m43: number; m44: number; inverse(): WebKitCSSMatrix; multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; setMatrixValue(value: string): void; skewX(angle: number): WebKitCSSMatrix; skewY(angle: number): WebKitCSSMatrix; toString(): string; translate(x: number, y: number, z?: number): WebKitCSSMatrix; } declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; } interface WebKitPoint { x: number; y: number; } declare var WebKitPoint: { prototype: WebKitPoint; new(x?: number, y?: number): WebKitPoint; } interface WebSocket extends EventTarget { binaryType: string; bufferedAmount: number; extensions: string; onclose: (ev: CloseEvent) => any; onerror: (ev: Event) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; protocol: string; readyState: number; url: string; close(code?: number, reason?: string): void; send(data: any): void; CLOSED: number; CLOSING: number; CONNECTING: number; OPEN: number; addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var WebSocket: { prototype: WebSocket; new(url: string, protocols?: string | string[]): WebSocket; CLOSED: number; CLOSING: number; CONNECTING: number; OPEN: number; } interface WheelEvent extends MouseEvent { deltaMode: number; deltaX: number; deltaY: number; deltaZ: number; getCurrentPoint(element: Element): void; initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; DOM_DELTA_LINE: number; DOM_DELTA_PAGE: number; DOM_DELTA_PIXEL: number; } declare var WheelEvent: { prototype: WheelEvent; new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; DOM_DELTA_LINE: number; DOM_DELTA_PAGE: number; DOM_DELTA_PIXEL: number; } interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { animationStartTime: number; applicationCache: ApplicationCache; clientInformation: Navigator; closed: boolean; crypto: Crypto; defaultStatus: string; devicePixelRatio: number; doNotTrack: string; document: Document; event: Event; external: External; frameElement: Element; frames: Window; history: History; innerHeight: number; innerWidth: number; length: number; location: Location; locationbar: BarProp; menubar: BarProp; msAnimationStartTime: number; name: string; navigator: Navigator; offscreenBuffering: string | boolean; onabort: (ev: Event) => any; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; onblur: (ev: FocusEvent) => any; oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; onchange: (ev: Event) => any; onclick: (ev: MouseEvent) => any; oncompassneedscalibration: (ev: Event) => any; oncontextmenu: (ev: PointerEvent) => any; ondblclick: (ev: MouseEvent) => any; ondevicemotion: (ev: DeviceMotionEvent) => any; ondeviceorientation: (ev: DeviceOrientationEvent) => any; ondrag: (ev: DragEvent) => any; ondragend: (ev: DragEvent) => any; ondragenter: (ev: DragEvent) => any; ondragleave: (ev: DragEvent) => any; ondragover: (ev: DragEvent) => any; ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; ondurationchange: (ev: Event) => any; onemptied: (ev: Event) => any; onended: (ev: Event) => any; onerror: ErrorEventHandler; onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; oninput: (ev: Event) => any; onkeydown: (ev: KeyboardEvent) => any; onkeypress: (ev: KeyboardEvent) => any; onkeyup: (ev: KeyboardEvent) => any; onload: (ev: Event) => any; onloadeddata: (ev: Event) => any; onloadedmetadata: (ev: Event) => any; onloadstart: (ev: Event) => any; onmessage: (ev: MessageEvent) => any; onmousedown: (ev: MouseEvent) => any; onmouseenter: (ev: MouseEvent) => any; onmouseleave: (ev: MouseEvent) => any; onmousemove: (ev: MouseEvent) => any; onmouseout: (ev: MouseEvent) => any; onmouseover: (ev: MouseEvent) => any; onmouseup: (ev: MouseEvent) => any; onmousewheel: (ev: MouseWheelEvent) => any; onmsgesturechange: (ev: MSGestureEvent) => any; onmsgesturedoubletap: (ev: MSGestureEvent) => any; onmsgestureend: (ev: MSGestureEvent) => any; onmsgesturehold: (ev: MSGestureEvent) => any; onmsgesturestart: (ev: MSGestureEvent) => any; onmsgesturetap: (ev: MSGestureEvent) => any; onmsinertiastart: (ev: MSGestureEvent) => any; onmspointercancel: (ev: MSPointerEvent) => any; onmspointerdown: (ev: MSPointerEvent) => any; onmspointerenter: (ev: MSPointerEvent) => any; onmspointerleave: (ev: MSPointerEvent) => any; onmspointermove: (ev: MSPointerEvent) => any; onmspointerout: (ev: MSPointerEvent) => any; onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; onoffline: (ev: Event) => any; ononline: (ev: Event) => any; onorientationchange: (ev: Event) => any; onpagehide: (ev: PageTransitionEvent) => any; onpageshow: (ev: PageTransitionEvent) => any; onpause: (ev: Event) => any; onplay: (ev: Event) => any; onplaying: (ev: Event) => any; onpopstate: (ev: PopStateEvent) => any; onprogress: (ev: ProgressEvent) => any; onratechange: (ev: Event) => any; onreadystatechange: (ev: ProgressEvent) => any; onreset: (ev: Event) => any; onresize: (ev: UIEvent) => any; onscroll: (ev: UIEvent) => any; onseeked: (ev: Event) => any; onseeking: (ev: Event) => any; onselect: (ev: UIEvent) => any; onstalled: (ev: Event) => any; onstorage: (ev: StorageEvent) => any; onsubmit: (ev: Event) => any; onsuspend: (ev: Event) => any; ontimeupdate: (ev: Event) => any; ontouchcancel: any; ontouchend: any; ontouchmove: any; ontouchstart: any; onunload: (ev: Event) => any; onvolumechange: (ev: Event) => any; onwaiting: (ev: Event) => any; opener: Window; orientation: string | number; outerHeight: number; outerWidth: number; pageXOffset: number; pageYOffset: number; parent: Window; performance: Performance; personalbar: BarProp; screen: Screen; screenLeft: number; screenTop: number; screenX: number; screenY: number; scrollX: number; scrollY: number; scrollbars: BarProp; self: Window; status: string; statusbar: BarProp; styleMedia: StyleMedia; toolbar: BarProp; top: Window; window: Window; URL: URL; alert(message?: any): void; blur(): void; cancelAnimationFrame(handle: number): void; captureEvents(): void; close(): void; confirm(message?: string): boolean; focus(): void; getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; getSelection(): Selection; matchMedia(mediaQuery: string): MediaQueryList; moveBy(x?: number, y?: number): void; moveTo(x?: number, y?: number): void; msCancelRequestAnimationFrame(handle: number): void; msMatchMedia(mediaQuery: string): MediaQueryList; msRequestAnimationFrame(callback: FrameRequestCallback): number; msWriteProfilerMark(profilerMarkName: string): void; open(url?: string, target?: string, features?: string, replace?: boolean): Window; postMessage(message: any, targetOrigin: string, ports?: any): void; print(): void; prompt(message?: string, _default?: string): string; releaseEvents(): void; requestAnimationFrame(callback: FrameRequestCallback): number; resizeBy(x?: number, y?: number): void; resizeTo(x?: number, y?: number): void; scroll(x?: number, y?: number): void; scrollBy(x?: number, y?: number): void; scrollTo(x?: number, y?: number): void; webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "compassneedscalibration", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; addEventListener(type: "hashchange", listener: (ev: HashChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; [index: number]: Window; } declare var Window: { prototype: Window; new(): Window; } interface Worker extends EventTarget, AbstractWorker { onmessage: (ev: MessageEvent) => any; postMessage(message: any, ports?: any): void; terminate(): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; } interface XMLDocument extends Document { } declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readyState: number; response: any; responseBody: any; responseText: string; responseType: string; responseXML: any; status: number; statusText: string; timeout: number; upload: XMLHttpRequestUpload; withCredentials: boolean; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string; msCachingEnabled(): boolean; open(method: string, url: string, async?: boolean, user?: string, password?: string): void; overrideMimeType(mime: string): void; send(data?: Document): void; send(data?: string): void; send(data?: any): void; setRequestHeader(header: string, value: string): void; DONE: number; HEADERS_RECEIVED: number; LOADING: number; OPENED: number; UNSENT: number; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var XMLHttpRequest: { prototype: XMLHttpRequest; new(): XMLHttpRequest; DONE: number; HEADERS_RECEIVED: number; LOADING: number; OPENED: number; UNSENT: number; create(): XMLHttpRequest; } interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; } interface XMLSerializer { serializeToString(target: Node): string; } declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; } interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver?: Node): XPathNSResolver; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; } declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; } interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult): XPathExpression; } declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; } interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; } declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; } interface XPathResult { booleanValue: boolean; invalidIteratorState: boolean; numberValue: number; resultType: number; singleNodeValue: Node; snapshotLength: number; stringValue: string; iterateNext(): Node; snapshotItem(index: number): Node; ANY_TYPE: number; ANY_UNORDERED_NODE_TYPE: number; BOOLEAN_TYPE: number; FIRST_ORDERED_NODE_TYPE: number; NUMBER_TYPE: number; ORDERED_NODE_ITERATOR_TYPE: number; ORDERED_NODE_SNAPSHOT_TYPE: number; STRING_TYPE: number; UNORDERED_NODE_ITERATOR_TYPE: number; UNORDERED_NODE_SNAPSHOT_TYPE: number; } declare var XPathResult: { prototype: XPathResult; new(): XPathResult; ANY_TYPE: number; ANY_UNORDERED_NODE_TYPE: number; BOOLEAN_TYPE: number; FIRST_ORDERED_NODE_TYPE: number; NUMBER_TYPE: number; ORDERED_NODE_ITERATOR_TYPE: number; ORDERED_NODE_SNAPSHOT_TYPE: number; STRING_TYPE: number; UNORDERED_NODE_ITERATOR_TYPE: number; UNORDERED_NODE_SNAPSHOT_TYPE: number; } interface XSLTProcessor { clearParameters(): void; getParameter(namespaceURI: string, localName: string): any; importStylesheet(style: Node): void; removeParameter(namespaceURI: string, localName: string): void; reset(): void; setParameter(namespaceURI: string, localName: string, value: any): void; transformToDocument(source: Node): Document; transformToFragment(source: Node, document: Document): DocumentFragment; } declare var XSLTProcessor: { prototype: XSLTProcessor; new(): XSLTProcessor; } interface AbstractWorker { onerror: (ev: Event) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } interface ChildNode { remove(): void; } interface DOML2DeprecatedColorProperty { color: string; } interface DOML2DeprecatedSizeProperty { size: number; } interface DocumentEvent { createEvent(eventInterface:"AnimationEvent"): AnimationEvent; createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; createEvent(eventInterface:"CloseEvent"): CloseEvent; createEvent(eventInterface:"CommandEvent"): CommandEvent; createEvent(eventInterface:"CompositionEvent"): CompositionEvent; createEvent(eventInterface:"CustomEvent"): CustomEvent; createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface:"DragEvent"): DragEvent; createEvent(eventInterface:"ErrorEvent"): ErrorEvent; createEvent(eventInterface:"Event"): Event; createEvent(eventInterface:"Events"): Event; createEvent(eventInterface:"FocusEvent"): FocusEvent; createEvent(eventInterface:"GamepadEvent"): GamepadEvent; createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; createEvent(eventInterface:"MessageEvent"): MessageEvent; createEvent(eventInterface:"MouseEvent"): MouseEvent; createEvent(eventInterface:"MouseEvents"): MouseEvent; createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent; createEvent(eventInterface:"MutationEvent"): MutationEvent; createEvent(eventInterface:"MutationEvents"): MutationEvent; createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; createEvent(eventInterface:"NavigationEvent"): NavigationEvent; createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; createEvent(eventInterface:"PointerEvent"): PointerEvent; createEvent(eventInterface:"PopStateEvent"): PopStateEvent; createEvent(eventInterface:"ProgressEvent"): ProgressEvent; createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; createEvent(eventInterface:"StorageEvent"): StorageEvent; createEvent(eventInterface:"TextEvent"): TextEvent; createEvent(eventInterface:"TouchEvent"): TouchEvent; createEvent(eventInterface:"TrackEvent"): TrackEvent; createEvent(eventInterface:"TransitionEvent"): TransitionEvent; createEvent(eventInterface:"UIEvent"): UIEvent; createEvent(eventInterface:"UIEvents"): UIEvent; createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; createEvent(eventInterface:"WheelEvent"): WheelEvent; createEvent(eventInterface: string): Event; } interface ElementTraversal { childElementCount: number; firstElementChild: Element; lastElementChild: Element; nextElementSibling: Element; previousElementSibling: Element; } interface GetSVGDocument { getSVGDocument(): Document; } interface GlobalEventHandlers { onpointercancel: (ev: PointerEvent) => any; onpointerdown: (ev: PointerEvent) => any; onpointerenter: (ev: PointerEvent) => any; onpointerleave: (ev: PointerEvent) => any; onpointermove: (ev: PointerEvent) => any; onpointerout: (ev: PointerEvent) => any; onpointerover: (ev: PointerEvent) => any; onpointerup: (ev: PointerEvent) => any; onwheel: (ev: WheelEvent) => any; addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } interface HTMLTableAlignment { /** * Sets or retrieves a value that you can use to implement your own ch functionality for the object. */ ch: string; /** * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. */ chOff: string; /** * Sets or retrieves how text and other content are vertically aligned within the object that contains them. */ vAlign: string; } interface IDBEnvironment { indexedDB: IDBFactory; msIndexedDB: IDBFactory; } interface LinkStyle { sheet: StyleSheet; } interface MSBaseReader { onabort: (ev: Event) => any; onerror: (ev: Event) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; readyState: number; result: any; abort(): void; DONE: number; EMPTY: number; LOADING: number; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } interface MSFileSaver { msSaveBlob(blob: any, defaultName?: string): boolean; msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; } interface MSNavigatorDoNotTrack { confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; confirmWebWideTrackingException(args: ExceptionInformation): boolean; removeSiteSpecificTrackingException(args: ExceptionInformation): void; removeWebWideTrackingException(args: ExceptionInformation): void; storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; storeWebWideTrackingException(args: StoreExceptionsInformation): void; } interface NavigatorContentUtils { } interface NavigatorGeolocation { geolocation: Geolocation; } interface NavigatorID { appName: string; appVersion: string; platform: string; product: string; productSub: string; userAgent: string; vendor: string; vendorSub: string; } interface NavigatorOnLine { onLine: boolean; } interface NavigatorStorageUtils { } interface NodeSelector { querySelector(selectors: string): Element; querySelectorAll(selectors: string): NodeListOf<Element>; } interface RandomSource { getRandomValues(array: ArrayBufferView): ArrayBufferView; } interface SVGAnimatedPathData { pathSegList: SVGPathSegList; } interface SVGAnimatedPoints { animatedPoints: SVGPointList; points: SVGPointList; } interface SVGExternalResourcesRequired { externalResourcesRequired: SVGAnimatedBoolean; } interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { height: SVGAnimatedLength; result: SVGAnimatedString; width: SVGAnimatedLength; x: SVGAnimatedLength; y: SVGAnimatedLength; } interface SVGFitToViewBox { preserveAspectRatio: SVGAnimatedPreserveAspectRatio; viewBox: SVGAnimatedRect; } interface SVGLangSpace { xmllang: string; xmlspace: string; } interface SVGLocatable { farthestViewportElement: SVGElement; nearestViewportElement: SVGElement; getBBox(): SVGRect; getCTM(): SVGMatrix; getScreenCTM(): SVGMatrix; getTransformToElement(element: SVGElement): SVGMatrix; } interface SVGStylable { className: any; style: CSSStyleDeclaration; } interface SVGTests { requiredExtensions: SVGStringList; requiredFeatures: SVGStringList; systemLanguage: SVGStringList; hasExtension(extension: string): boolean; } interface SVGTransformable extends SVGLocatable { transform: SVGAnimatedTransformList; } interface SVGURIReference { href: SVGAnimatedString; } interface WindowBase64 { atob(encodedString: string): string; btoa(rawString: string): string; } interface WindowConsole { console: Console; } interface WindowLocalStorage { localStorage: Storage; } interface WindowSessionStorage { sessionStorage: Storage; } interface WindowTimers extends Object, WindowTimersExtension { clearInterval(handle: number): void; clearTimeout(handle: number): void; setInterval(handler: any, timeout?: any, ...args: any[]): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } interface WindowTimersExtension { clearImmediate(handle: number): void; msClearImmediate(handle: number): void; msSetImmediate(expression: any, ...args: any[]): number; setImmediate(expression: any, ...args: any[]): number; } interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; onerror: (ev: Event) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; ontimeout: (ev: ProgressEvent) => any; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } interface StorageEventInit extends EventInit { key?: string; oldValue?: string; newValue?: string; url: string; storageArea?: Storage; } interface IDBObjectStoreParameters { keyPath?: string | string[]; autoIncrement?: boolean; } interface IDBIndexParameters { unique?: boolean; multiEntry?: boolean; } interface NodeListOf<TNode extends Node> extends NodeList { length: number; item(index: number): TNode; [index: number]: TNode; } interface BlobPropertyBag { type?: string; endings?: string; } interface FilePropertyBag { type?: string; lastModified?: number; } interface EventListenerObject { handleEvent(evt: Event): void; } interface MessageEventInit extends EventInit { data?: any; origin?: string; lastEventId?: string; channel?: string; source?: any; ports?: MessagePort[]; } interface ProgressEventInit extends EventInit { lengthComputable?: boolean; loaded?: number; total?: number; } interface HTMLTemplateElement extends HTMLElement { content: DocumentFragment; } declare var HTMLTemplateElement: { prototype: HTMLTemplateElement; new(): HTMLTemplateElement; } interface HTMLPictureElement extends HTMLElement { } declare var HTMLPictureElement: { prototype: HTMLPictureElement; new(): HTMLPictureElement; } declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; } interface PositionCallback { (position: Position): void; } interface PositionErrorCallback { (error: PositionError): void; } interface MediaQueryListListener { (mql: MediaQueryList): void; } interface MSLaunchUriCallback { (): void; } interface FrameRequestCallback { (time: number): void; } interface MSUnsafeFunctionCallback { (): any; } interface MSExecAtPriorityFunctionCallback { (...args: any[]): any; } interface MutationCallback { (mutations: MutationRecord[], observer: MutationObserver): void; } interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } interface DecodeErrorCallback { (error: DOMException): void; } interface FunctionStringCallback { (data: string): void; } declare var Audio: {new(src?: string): HTMLAudioElement; }; declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; declare var animationStartTime: number; declare var applicationCache: ApplicationCache; declare var clientInformation: Navigator; declare var closed: boolean; declare var crypto: Crypto; declare var defaultStatus: string; declare var devicePixelRatio: number; declare var doNotTrack: string; declare var document: Document; declare var event: Event; declare var external: External; declare var frameElement: Element; declare var frames: Window; declare var history: History; declare var innerHeight: number; declare var innerWidth: number; declare var length: number; declare var location: Location; declare var locationbar: BarProp; declare var menubar: BarProp; declare var msAnimationStartTime: number; declare var name: string; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; declare var onabort: (ev: Event) => any; declare var onafterprint: (ev: Event) => any; declare var onbeforeprint: (ev: Event) => any; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; declare var onblur: (ev: FocusEvent) => any; declare var oncanplay: (ev: Event) => any; declare var oncanplaythrough: (ev: Event) => any; declare var onchange: (ev: Event) => any; declare var onclick: (ev: MouseEvent) => any; declare var oncompassneedscalibration: (ev: Event) => any; declare var oncontextmenu: (ev: PointerEvent) => any; declare var ondblclick: (ev: MouseEvent) => any; declare var ondevicemotion: (ev: DeviceMotionEvent) => any; declare var ondeviceorientation: (ev: DeviceOrientationEvent) => any; declare var ondrag: (ev: DragEvent) => any; declare var ondragend: (ev: DragEvent) => any; declare var ondragenter: (ev: DragEvent) => any; declare var ondragleave: (ev: DragEvent) => any; declare var ondragover: (ev: DragEvent) => any; declare var ondragstart: (ev: DragEvent) => any; declare var ondrop: (ev: DragEvent) => any; declare var ondurationchange: (ev: Event) => any; declare var onemptied: (ev: Event) => any; declare var onended: (ev: Event) => any; declare var onerror: ErrorEventHandler; declare var onfocus: (ev: FocusEvent) => any; declare var onhashchange: (ev: HashChangeEvent) => any; declare var oninput: (ev: Event) => any; declare var onkeydown: (ev: KeyboardEvent) => any; declare var onkeypress: (ev: KeyboardEvent) => any; declare var onkeyup: (ev: KeyboardEvent) => any; declare var onload: (ev: Event) => any; declare var onloadeddata: (ev: Event) => any; declare var onloadedmetadata: (ev: Event) => any; declare var onloadstart: (ev: Event) => any; declare var onmessage: (ev: MessageEvent) => any; declare var onmousedown: (ev: MouseEvent) => any; declare var onmouseenter: (ev: MouseEvent) => any; declare var onmouseleave: (ev: MouseEvent) => any; declare var onmousemove: (ev: MouseEvent) => any; declare var onmouseout: (ev: MouseEvent) => any; declare var onmouseover: (ev: MouseEvent) => any; declare var onmouseup: (ev: MouseEvent) => any; declare var onmousewheel: (ev: MouseWheelEvent) => any; declare var onmsgesturechange: (ev: MSGestureEvent) => any; declare var onmsgesturedoubletap: (ev: MSGestureEvent) => any; declare var onmsgestureend: (ev: MSGestureEvent) => any; declare var onmsgesturehold: (ev: MSGestureEvent) => any; declare var onmsgesturestart: (ev: MSGestureEvent) => any; declare var onmsgesturetap: (ev: MSGestureEvent) => any; declare var onmsinertiastart: (ev: MSGestureEvent) => any; declare var onmspointercancel: (ev: MSPointerEvent) => any; declare var onmspointerdown: (ev: MSPointerEvent) => any; declare var onmspointerenter: (ev: MSPointerEvent) => any; declare var onmspointerleave: (ev: MSPointerEvent) => any; declare var onmspointermove: (ev: MSPointerEvent) => any; declare var onmspointerout: (ev: MSPointerEvent) => any; declare var onmspointerover: (ev: MSPointerEvent) => any; declare var onmspointerup: (ev: MSPointerEvent) => any; declare var onoffline: (ev: Event) => any; declare var ononline: (ev: Event) => any; declare var onorientationchange: (ev: Event) => any; declare var onpagehide: (ev: PageTransitionEvent) => any; declare var onpageshow: (ev: PageTransitionEvent) => any; declare var onpause: (ev: Event) => any; declare var onplay: (ev: Event) => any; declare var onplaying: (ev: Event) => any; declare var onpopstate: (ev: PopStateEvent) => any; declare var onprogress: (ev: ProgressEvent) => any; declare var onratechange: (ev: Event) => any; declare var onreadystatechange: (ev: ProgressEvent) => any; declare var onreset: (ev: Event) => any; declare var onresize: (ev: UIEvent) => any; declare var onscroll: (ev: UIEvent) => any; declare var onseeked: (ev: Event) => any; declare var onseeking: (ev: Event) => any; declare var onselect: (ev: UIEvent) => any; declare var onstalled: (ev: Event) => any; declare var onstorage: (ev: StorageEvent) => any; declare var onsubmit: (ev: Event) => any; declare var onsuspend: (ev: Event) => any; declare var ontimeupdate: (ev: Event) => any; declare var ontouchcancel: any; declare var ontouchend: any; declare var ontouchmove: any; declare var ontouchstart: any; declare var onunload: (ev: Event) => any; declare var onvolumechange: (ev: Event) => any; declare var onwaiting: (ev: Event) => any; declare var opener: Window; declare var orientation: string | number; declare var outerHeight: number; declare var outerWidth: number; declare var pageXOffset: number; declare var pageYOffset: number; declare var parent: Window; declare var performance: Performance; declare var personalbar: BarProp; declare var screen: Screen; declare var screenLeft: number; declare var screenTop: number; declare var screenX: number; declare var screenY: number; declare var scrollX: number; declare var scrollY: number; declare var scrollbars: BarProp; declare var self: Window; declare var status: string; declare var statusbar: BarProp; declare var styleMedia: StyleMedia; declare var toolbar: BarProp; declare var top: Window; declare var window: Window; declare var URL: URL; declare function alert(message?: any): void; declare function blur(): void; declare function cancelAnimationFrame(handle: number): void; declare function captureEvents(): void; declare function close(): void; declare function confirm(message?: string): boolean; declare function focus(): void; declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; declare function getSelection(): Selection; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function moveBy(x?: number, y?: number): void; declare function moveTo(x?: number, y?: number): void; declare function msCancelRequestAnimationFrame(handle: number): void; declare function msMatchMedia(mediaQuery: string): MediaQueryList; declare function msRequestAnimationFrame(callback: FrameRequestCallback): number; declare function msWriteProfilerMark(profilerMarkName: string): void; declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; declare function postMessage(message: any, targetOrigin: string, ports?: any): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string; declare function releaseEvents(): void; declare function requestAnimationFrame(callback: FrameRequestCallback): number; declare function resizeBy(x?: number, y?: number): void; declare function resizeTo(x?: number, y?: number): void; declare function scroll(x?: number, y?: number): void; declare function scrollBy(x?: number, y?: number): void; declare function scrollTo(x?: number, y?: number): void; declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; declare function toString(): string; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function clearImmediate(handle: number): void; declare function msClearImmediate(handle: number): void; declare function msSetImmediate(expression: any, ...args: any[]): number; declare function setImmediate(expression: any, ...args: any[]): number; declare var sessionStorage: Storage; declare var localStorage: Storage; declare var console: Console; declare var onpointercancel: (ev: PointerEvent) => any; declare var onpointerdown: (ev: PointerEvent) => any; declare var onpointerenter: (ev: PointerEvent) => any; declare var onpointerleave: (ev: PointerEvent) => any; declare var onpointermove: (ev: PointerEvent) => any; declare var onpointerout: (ev: PointerEvent) => any; declare var onpointerover: (ev: PointerEvent) => any; declare var onpointerup: (ev: PointerEvent) => any; declare var onwheel: (ev: WheelEvent) => any; declare var indexedDB: IDBFactory; declare var msIndexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; declare function addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "compassneedscalibration", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "hashchange", listener: (ev: HashChangeEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
apache-2.0
ivanhristov92/bookingCalendar
node_modules/react-virtualized/dist/commonjs/Grid/utils/getOverscanIndices.js
1702
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getOverscanIndices; var SCROLL_DIRECTION_BACKWARD = exports.SCROLL_DIRECTION_BACKWARD = -1; var SCROLL_DIRECTION_FIXED = exports.SCROLL_DIRECTION_FIXED = 0; var SCROLL_DIRECTION_FORWARD = exports.SCROLL_DIRECTION_FORWARD = 1; /** * Calculates the number of cells to overscan before and after a specified range. * This function ensures that overscanning doesn't exceed the available cells. * * @param cellCount Number of rows or columns in the current axis * @param scrollDirection One of SCROLL_DIRECTION_BACKWARD * @param overscanCellsCount Maximum number of cells to over-render in either direction * @param startIndex Begin of range of visible cells * @param stopIndex End of range of visible cells */ function getOverscanIndices(_ref) { var cellCount = _ref.cellCount; var overscanCellsCount = _ref.overscanCellsCount; var scrollDirection = _ref.scrollDirection; var startIndex = _ref.startIndex; var stopIndex = _ref.stopIndex; var overscanStartIndex = void 0; var overscanStopIndex = void 0; if (scrollDirection === SCROLL_DIRECTION_FORWARD) { overscanStartIndex = startIndex; overscanStopIndex = stopIndex + overscanCellsCount * 2; } else if (scrollDirection === SCROLL_DIRECTION_BACKWARD) { overscanStartIndex = startIndex - overscanCellsCount * 2; overscanStopIndex = stopIndex; } else { overscanStartIndex = startIndex - overscanCellsCount; overscanStopIndex = stopIndex + overscanCellsCount; } return { overscanStartIndex: Math.max(0, overscanStartIndex), overscanStopIndex: Math.min(cellCount - 1, overscanStopIndex) }; }
apache-2.0
alvinkwekel/camel
components/camel-braintree/src/generated/java/org/apache/camel/component/braintree/DisputeGatewayEndpointConfigurationConfigurer.java
7987
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.braintree; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.component.braintree.DisputeGatewayEndpointConfiguration; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class DisputeGatewayEndpointConfigurationConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.braintree.DisputeGatewayEndpointConfiguration target = (org.apache.camel.component.braintree.DisputeGatewayEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "AccessToken": target.setAccessToken(property(camelContext, java.lang.String.class, value)); return true; case "apiname": case "ApiName": target.setApiName(property(camelContext, org.apache.camel.component.braintree.internal.BraintreeApiName.class, value)); return true; case "content": case "Content": target.setContent(property(camelContext, java.lang.String.class, value)); return true; case "disputeid": case "DisputeId": target.setDisputeId(property(camelContext, java.lang.String.class, value)); return true; case "documentid": case "DocumentId": target.setDocumentId(property(camelContext, java.lang.String.class, value)); return true; case "environment": case "Environment": target.setEnvironment(property(camelContext, java.lang.String.class, value)); return true; case "evidenceid": case "EvidenceId": target.setEvidenceId(property(camelContext, java.lang.String.class, value)); return true; case "fileevidencerequest": case "FileEvidenceRequest": target.setFileEvidenceRequest(property(camelContext, com.braintreegateway.FileEvidenceRequest.class, value)); return true; case "httploglevel": case "HttpLogLevel": target.setHttpLogLevel(property(camelContext, java.lang.String.class, value)); return true; case "httplogname": case "HttpLogName": target.setHttpLogName(property(camelContext, java.lang.String.class, value)); return true; case "httpreadtimeout": case "HttpReadTimeout": target.setHttpReadTimeout(property(camelContext, java.lang.Integer.class, value)); return true; case "id": case "Id": target.setId(property(camelContext, java.lang.String.class, value)); return true; case "loghandlerenabled": case "LogHandlerEnabled": target.setLogHandlerEnabled(property(camelContext, boolean.class, value)); return true; case "merchantid": case "MerchantId": target.setMerchantId(property(camelContext, java.lang.String.class, value)); return true; case "methodname": case "MethodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "privatekey": case "PrivateKey": target.setPrivateKey(property(camelContext, java.lang.String.class, value)); return true; case "proxyhost": case "ProxyHost": target.setProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "proxyport": case "ProxyPort": target.setProxyPort(property(camelContext, java.lang.Integer.class, value)); return true; case "publickey": case "PublicKey": target.setPublicKey(property(camelContext, java.lang.String.class, value)); return true; case "query": case "Query": target.setQuery(property(camelContext, com.braintreegateway.DisputeSearchRequest.class, value)); return true; case "textevidencerequest": case "TextEvidenceRequest": target.setTextEvidenceRequest(property(camelContext, com.braintreegateway.TextEvidenceRequest.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { Map<String, Object> answer = new CaseInsensitiveMap(); answer.put("AccessToken", java.lang.String.class); answer.put("ApiName", org.apache.camel.component.braintree.internal.BraintreeApiName.class); answer.put("Content", java.lang.String.class); answer.put("DisputeId", java.lang.String.class); answer.put("DocumentId", java.lang.String.class); answer.put("Environment", java.lang.String.class); answer.put("EvidenceId", java.lang.String.class); answer.put("FileEvidenceRequest", com.braintreegateway.FileEvidenceRequest.class); answer.put("HttpLogLevel", java.lang.String.class); answer.put("HttpLogName", java.lang.String.class); answer.put("HttpReadTimeout", java.lang.Integer.class); answer.put("Id", java.lang.String.class); answer.put("LogHandlerEnabled", boolean.class); answer.put("MerchantId", java.lang.String.class); answer.put("MethodName", java.lang.String.class); answer.put("PrivateKey", java.lang.String.class); answer.put("ProxyHost", java.lang.String.class); answer.put("ProxyPort", java.lang.Integer.class); answer.put("PublicKey", java.lang.String.class); answer.put("Query", com.braintreegateway.DisputeSearchRequest.class); answer.put("TextEvidenceRequest", com.braintreegateway.TextEvidenceRequest.class); return answer; } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.braintree.DisputeGatewayEndpointConfiguration target = (org.apache.camel.component.braintree.DisputeGatewayEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "AccessToken": return target.getAccessToken(); case "apiname": case "ApiName": return target.getApiName(); case "content": case "Content": return target.getContent(); case "disputeid": case "DisputeId": return target.getDisputeId(); case "documentid": case "DocumentId": return target.getDocumentId(); case "environment": case "Environment": return target.getEnvironment(); case "evidenceid": case "EvidenceId": return target.getEvidenceId(); case "fileevidencerequest": case "FileEvidenceRequest": return target.getFileEvidenceRequest(); case "httploglevel": case "HttpLogLevel": return target.getHttpLogLevel(); case "httplogname": case "HttpLogName": return target.getHttpLogName(); case "httpreadtimeout": case "HttpReadTimeout": return target.getHttpReadTimeout(); case "id": case "Id": return target.getId(); case "loghandlerenabled": case "LogHandlerEnabled": return target.isLogHandlerEnabled(); case "merchantid": case "MerchantId": return target.getMerchantId(); case "methodname": case "MethodName": return target.getMethodName(); case "privatekey": case "PrivateKey": return target.getPrivateKey(); case "proxyhost": case "ProxyHost": return target.getProxyHost(); case "proxyport": case "ProxyPort": return target.getProxyPort(); case "publickey": case "PublicKey": return target.getPublicKey(); case "query": case "Query": return target.getQuery(); case "textevidencerequest": case "TextEvidenceRequest": return target.getTextEvidenceRequest(); default: return null; } } }
apache-2.0
robertamarton/incubator-trafodion
core/conn/jdbc_type2/src/main/java/org/trafodion/jdbc/t2/TDataSource.java
6331
// @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ /* -*-java-*- * Filename : TDataSource.java * Description : * * -------------------------------------------------------------------- */ package org.trafodion.jdbc.t2; import java.io.PrintWriter; import java.sql.*; import javax.sql.DataSource; import java.util.Properties; import javax.naming.Referenceable; import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.StringRefAddr; import java.util.Date; import java.util.logging.Logger; public class TDataSource implements javax.sql.DataSource, java.io.Serializable, Referenceable { // javax.sql.DataSource interface methods public Connection getConnection() throws SQLException { Connection connect; if (ds_ != null) { if (out_ != null) out_.println(getTraceId() + "getConnection()"); connect = ds_.getConnection(); if (out_ != null) out_.println(getTraceId() + "getConnection() returns Connection [" + System.identityHashCode(connect) + "]"); return new TConnection(connect, out_); } else throw new SQLException("Trace Data Source" + traceDataSource_ + "Not found"); } public Connection getConnection(String username, String Password) throws SQLException { Connection connect; if (ds_ != null) { if (out_ != null) out_.println(getTraceId() + "getConnection(\"" + username + "\", \"****\")"); connect = ds_.getConnection(); if (out_ != null) out_.println(getTraceId() + "getConnection(\"" + username + "\", \"****\") returns Connection [" + System.identityHashCode(connect) + "]"); return new TConnection(connect, out_); } else throw new SQLException("Trace Data Source" + traceDataSource_ + "Not found"); } public int getLoginTimeout() throws SQLException { if (out_ != null) out_.println(getTraceId() + "getLoginTimeout()"); int retValue; if (ds_ != null) { retValue = ds_.getLoginTimeout(); return retValue; } else throw new SQLException("Trace Data Source" + traceDataSource_ + "Not found"); } public PrintWriter getLogWriter() throws SQLException { if (out_ != null) out_.println(getTraceId() + "getLogWriter()"); PrintWriter retValue; if (ds_ != null) { retValue = ds_.getLogWriter(); return retValue; } else throw new SQLException("Trace Data Source" + traceDataSource_ + "Not found"); } public void setLoginTimeout(int seconds) throws SQLException { if (out_ != null) out_.println(getTraceId() + "setLoginTimeout("+ seconds + ")"); if (ds_ != null) ds_.setLoginTimeout(seconds); else throw new SQLException("Trace Data Source" + traceDataSource_ + "Not found"); } public void setLogWriter(PrintWriter out) throws SQLException { out_ = out; if (out_ != null) { out_.println(org.trafodion.jdbc.t2.T2Driver.printTraceVproc); out_.println(getTraceId() + "setLogWriter("+ out + ")"); } if (ds_ != null) ds_.setLogWriter(out); else throw new SQLException("Trace Data Source" + traceDataSource_ + "Not found"); } public Reference getReference() throws NamingException { if (out_ != null) out_.println(getTraceId() + "getReference()"); Reference ref; ref = new Reference(this.getClass().getName(), "org.trafodion.jdbc.t2.TDataSourceFactory", null); ref.add(new StringRefAddr("description", description_)); ref.add(new StringRefAddr("traceDataSource", traceDataSource_)); return ref; } // Get-Set Property methods public void setDescription(String description) { description_ = description; } public String getDescription() { return description_; } public void setTraceDataSource(String traceDataSource) { traceDataSource_ = traceDataSource; } public String getTraceDataSource() { return traceDataSource_; } TDataSource(String traceDataSource, DataSource ds) { String className = null; traceDataSource_ = traceDataSource; ds_ = ds; if (ds_ != null) className = ds_.getClass().getName(); // Build up jdbcTrace output entry setTraceId(org.trafodion.jdbc.t2.T2Driver.traceText + org.trafodion.jdbc.t2.T2Driver.dateFormat.format(new Date()) + "]:[" + Thread.currentThread() + "]:[" + System.identityHashCode(ds_) + "]:" + className.substring(org.trafodion.jdbc.t2.T2Driver.REMOVE_PKG_NAME,className.length()) + "."); } public TDataSource() { } public void setTraceId(String traceId_) { this.traceId_ = traceId_; } public String getTraceId() { // Build up jdbcTrace output entry setTraceId(org.trafodion.jdbc.t2.T2Driver.traceText + org.trafodion.jdbc.t2.T2Driver.dateFormat.format(new Date()) + "]:[" + Thread.currentThread() + "]:[" + System.identityHashCode(this) + "]:" + getClass().getName().substring(org.trafodion.jdbc.t2.T2Driver.REMOVE_PKG_NAME,getClass().getName().length()) + "."); return traceId_; } // fields PrintWriter out_; String traceDataSource_; DataSource ds_; private String traceId_; String description_; // serialVersionUID set to resolve JDK5.0 javax -Xlint:serial definition warning. private static final long serialVersionUID = 2L; public Logger getParentLogger() throws SQLFeatureNotSupportedException { // TODO Auto-generated method stub return null; } public Object unwrap(Class iface) throws SQLException { // TODO Auto-generated method stub return null; } public boolean isWrapperFor(Class iface) throws SQLException { // TODO Auto-generated method stub return false; } }
apache-2.0
formalin14/HAL
src/JSContext.cpp
12109
/** * HAL * * Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License. * Please see the LICENSE included with this distribution for details. */ #include "HAL/JSContext.hpp" #include "HAL/JSClass.hpp" #include "HAL/JSString.hpp" #include "HAL/JSValue.hpp" #include "HAL/JSUndefined.hpp" #include "HAL/JSNull.hpp" #include "HAL/JSBoolean.hpp" #include "HAL/JSNumber.hpp" #include "HAL/JSObject.hpp" #include "HAL/JSArray.hpp" #include "HAL/JSDate.hpp" #include "HAL/JSError.hpp" #include "HAL/JSFunction.hpp" #include "HAL/JSRegExp.hpp" #include "HAL/detail/JSUtil.hpp" #include <cassert> namespace HAL { JSObject JSContext::get_global_object() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSObject(JSContext(js_global_context_ref__), JSContextGetGlobalObject(js_global_context_ref__)); } JSValue JSContext::CreateValueFromJSON(const JSString& js_string) const { HAL_JSCONTEXT_LOCK_GUARD; return JSValue(JSContext(js_global_context_ref__), js_string, true); } JSValue JSContext::CreateString() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSValue(JSContext(js_global_context_ref__), JSString(), false); } JSValue JSContext::CreateString(const JSString& js_string) const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSValue(JSContext(js_global_context_ref__), js_string, false); } JSValue JSContext::CreateString(const char* string) const HAL_NOEXCEPT { return CreateString(JSString(string)); } JSValue JSContext::CreateString(const std::string& string) const HAL_NOEXCEPT { return CreateString(JSString(string)); } JSUndefined JSContext::CreateUndefined() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSUndefined(JSContext(js_global_context_ref__)); } JSNull JSContext::CreateNull() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSNull(JSContext(js_global_context_ref__)); } JSValue JSContext::CreateNativeNull() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; // Use JSNull to represent native nullptr auto value = JSNull(JSContext(js_global_context_ref__)); value.MarkAsNativeNull(); return value; } JSBoolean JSContext::CreateBoolean(bool boolean) const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSBoolean(JSContext(js_global_context_ref__), boolean); } JSNumber JSContext::CreateNumber(double number) const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSNumber(JSContext(js_global_context_ref__), number); } JSNumber JSContext::CreateNumber(int32_t number) const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSNumber(JSContext(js_global_context_ref__), number); } JSNumber JSContext::CreateNumber(uint32_t number) const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSNumber(JSContext(js_global_context_ref__), number); } JSObject JSContext::CreateObject() const HAL_NOEXCEPT { return CreateObject(JSClass()); } JSObject JSContext::CreateObject(const JSClass& js_class) const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSObject(JSContext(js_global_context_ref__), js_class); } JSObject JSContext::CreateObject(const std::unordered_map<std::string, JSValue>& properties) const HAL_NOEXCEPT { return CreateObject(JSClass(), properties); } JSObject JSContext::CreateObject(const JSClass& js_class, const std::unordered_map<std::string, JSValue>& properties) const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; auto object = CreateObject(); for (const auto kv : properties) { object.SetProperty(kv.first, kv.second); } return object; } JSArray JSContext::CreateArray() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSArray(JSContext(js_global_context_ref__)); } JSArray JSContext::CreateArray(const std::vector<JSValue>& arguments) const { HAL_JSCONTEXT_LOCK_GUARD; return JSArray(JSContext(js_global_context_ref__), arguments); } JSDate JSContext::CreateDate() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSDate(JSContext(js_global_context_ref__)); } JSDate JSContext::CreateDate(const std::vector<JSValue>& arguments) const { HAL_JSCONTEXT_LOCK_GUARD; return JSDate(JSContext(js_global_context_ref__), arguments); } JSError JSContext::CreateError() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSError(JSContext(js_global_context_ref__)); } JSError JSContext::CreateError(const std::vector<JSValue>& arguments) const { HAL_JSCONTEXT_LOCK_GUARD; return JSError(JSContext(js_global_context_ref__), arguments); } JSRegExp JSContext::CreateRegExp() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; return JSRegExp(JSContext(js_global_context_ref__)); } JSRegExp JSContext::CreateRegExp(const std::vector<JSValue>& arguments) const { HAL_JSCONTEXT_LOCK_GUARD; return JSRegExp(JSContext(js_global_context_ref__), arguments); } JSFunction JSContext::CreateFunction(const JSString& body) const { return CreateFunction(body, std::vector<JSString>(), JSString(), JSString()); } JSFunction JSContext::CreateFunction(const JSString& body, const std::vector<JSString>& parameter_names) const { return CreateFunction(body, parameter_names, JSString(), JSString()); } JSFunction JSContext::CreateFunction(const JSString& body, const std::vector<JSString>& parameter_names, const JSString& function_name) const { return CreateFunction(body, parameter_names, function_name, JSString()); } JSFunction JSContext::CreateFunction(const JSString& body, const std::vector<JSString>& parameter_names, const JSString& function_name, const JSString& source_url, int starting_line_number) const { HAL_JSCONTEXT_LOCK_GUARD; return JSFunction(JSContext(js_global_context_ref__), body, parameter_names, function_name, source_url, starting_line_number); } JSFunction JSContext::CreateFunction() const { JSFunctionCallback noop = [](const std::vector<JSValue>, JSObject& this_object){ return this_object.get_context().CreateUndefined(); }; return CreateFunction(noop); } JSFunction JSContext::CreateFunction(JSFunctionCallback& callback) const { return CreateFunction(JSString(), callback); } JSFunction JSContext::CreateFunction(const JSString& function_name, JSFunctionCallback& callback) const { HAL_JSCONTEXT_LOCK_GUARD; return JSFunction(JSContext(js_global_context_ref__), function_name, callback); } JSValue JSContext::JSEvaluateScript(const JSString& script) const { return JSEvaluateScript(script, get_global_object(), JSString()); } JSValue JSContext::JSEvaluateScript(const JSString& script, const JSString& source_url, int starting_line_number) const { HAL_JSCONTEXT_LOCK_GUARD; return JSEvaluateScript(script, get_global_object(), source_url, starting_line_number); } JSValue JSContext::JSEvaluateScript(const JSString& script, JSObject this_object) const { return JSEvaluateScript(script, this_object, JSString()); } JSValue JSContext::JSEvaluateScript(const JSString& script, JSObject this_object, const JSString& source_url, int starting_line_number) const { HAL_JSCONTEXT_LOCK_GUARD; JSValueRef js_value_ref { nullptr }; const JSStringRef source_url_ref = (source_url.length() > 0) ? static_cast<JSStringRef>(source_url) : nullptr; JSValueRef exception { nullptr }; js_value_ref = ::JSEvaluateScript(js_global_context_ref__, static_cast<JSStringRef>(script), static_cast<JSObjectRef>(this_object), source_url_ref, starting_line_number, &exception); if (exception) { // If this assert fails then we need to JSValueUnprotect // js_value_ref. assert(!js_value_ref); detail::ThrowRuntimeError("JSContext", JSValue(JSContext(js_global_context_ref__), exception), source_url, starting_line_number); } return JSValue(JSContext(js_global_context_ref__), js_value_ref); } bool JSContext::JSCheckScriptSyntax(const JSString& script) const HAL_NOEXCEPT { return JSCheckScriptSyntax(script, JSString()); } bool JSContext::JSCheckScriptSyntax(const JSString& script, const JSString& source_url, int starting_line_number) const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; const JSStringRef source_url_ref = (source_url.length() > 0) ? static_cast<JSStringRef>(source_url) : nullptr; JSValueRef exception { nullptr }; bool result = ::JSCheckScriptSyntax(js_global_context_ref__, static_cast<JSStringRef>(script), source_url_ref, starting_line_number, &exception); if (exception) { detail::ThrowRuntimeError("JSContext", JSValue(JSContext(js_global_context_ref__), exception)); } return result; } void JSContext::GarbageCollect() const HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; JSGarbageCollect(js_global_context_ref__); } #ifdef DEBUG extern "C" void JSSynchronousGarbageCollectForDebugging(JSContextRef); extern "C" void JSSynchronousEdenCollectForDebugging(JSContextRef); void JSContext::SynchronousGarbageCollectForDebugging() const { HAL_JSCONTEXT_LOCK_GUARD; JSSynchronousGarbageCollectForDebugging(js_global_context_ref__); } void JSContext::SynchronousEdenCollectForDebugging() const { HAL_JSCONTEXT_LOCK_GUARD; JSSynchronousEdenCollectForDebugging(js_global_context_ref__); } #endif JSContext::~JSContext() HAL_NOEXCEPT { HAL_LOG_TRACE("JSContext:: dtor ", this); HAL_LOG_TRACE("JSContext:: release ", js_global_context_ref__, " for ", this); JSGlobalContextRelease(js_global_context_ref__); } JSContext::JSContext(const JSContext& rhs) HAL_NOEXCEPT : js_context_group__(rhs.js_context_group__) , js_global_context_ref__(rhs.js_global_context_ref__) { HAL_LOG_TRACE("JSContext:: copy ctor ", this); HAL_LOG_TRACE("JSContext:: retain ", js_global_context_ref__, " for ", this); JSGlobalContextRetain(js_global_context_ref__); } JSContext::JSContext(JSContext&& rhs) HAL_NOEXCEPT : js_context_group__(std::move(rhs.js_context_group__)) , js_global_context_ref__(rhs.js_global_context_ref__) { HAL_LOG_TRACE("JSContext:: move ctor ", this); HAL_LOG_TRACE("JSContext:: retain ", js_global_context_ref__, " for ", this); JSGlobalContextRetain(js_global_context_ref__); } JSContext& JSContext::operator=(JSContext rhs) HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; HAL_LOG_TRACE("JSContext:: assignment ", this); swap(rhs); return *this; } void JSContext::swap(JSContext& other) HAL_NOEXCEPT { HAL_JSCONTEXT_LOCK_GUARD; HAL_LOG_TRACE("JSContext:: swap ", this); using std::swap; // By swapping the members of two classes, the two classes are // effectively swapped. swap(js_context_group__ , other.js_context_group__); swap(js_global_context_ref__, other.js_global_context_ref__); } JSContext::JSContext(const JSContextGroup& js_context_group, const JSClass& global_object_class) HAL_NOEXCEPT : js_context_group__(js_context_group) , js_global_context_ref__(JSGlobalContextCreateInGroup(static_cast<JSContextGroupRef>(js_context_group), static_cast<JSClassRef>(global_object_class))) { HAL_LOG_TRACE("JSContext:: ctor 1 ", this); HAL_LOG_TRACE("JSContext:: retain ", js_global_context_ref__, " (implicit) for ", this); } JSContext::JSContext(JSContextRef js_context_ref) HAL_NOEXCEPT : JSContext(JSContextGetGlobalContext(js_context_ref)) { } // For interoperability with the JavaScriptCore C API. JSContext::JSContext(JSGlobalContextRef js_global_context_ref) HAL_NOEXCEPT : js_context_group__(JSContextGetGroup(js_global_context_ref)) , js_global_context_ref__(js_global_context_ref) { HAL_LOG_TRACE("JSContext:: ctor 2 ", this); assert(js_global_context_ref__); HAL_LOG_TRACE("JSContext:: retain ", js_global_context_ref__, " for ", this); JSGlobalContextRetain(js_global_context_ref__); } } // namespace HAL {
apache-2.0
develar/intellij-sdk-docs
code_samples/run_configuration/src/org/jetbrains/tutorials/run/configuration/DemoConfigurationFactory.java
807
package org.jetbrains.tutorials.run.configuration; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.project.Project; /** * @author Anna Bulenkova */ public class DemoConfigurationFactory extends ConfigurationFactory { private static final String FACTORY_NAME = "Demo configuration factory"; protected DemoConfigurationFactory(ConfigurationType type) { super(type); } @Override public RunConfiguration createTemplateConfiguration(Project project) { return new DemoRunConfiguration(project, this, "Demo"); } @Override public String getName() { return FACTORY_NAME; } }
apache-2.0
firebase/firebase-ios-sdk
Firestore/core/test/unit/util/string_format_test.cc
3346
/* * Copyright 2018 Google * * 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. */ #include "Firestore/core/src/util/string_format.h" #include "absl/strings/string_view.h" #include "gtest/gtest.h" namespace firebase { namespace firestore { namespace util { TEST(StringFormatTest, Empty) { EXPECT_EQ("", StringFormat("")); EXPECT_EQ("", StringFormat("%s", std::string().c_str())); EXPECT_EQ("", StringFormat("%s", "")); } TEST(StringFormatTest, CString) { EXPECT_EQ("Hello World", StringFormat("Hello %s", "World")); EXPECT_EQ("Hello World", StringFormat("%s World", "Hello")); EXPECT_EQ("Hello World", StringFormat("Hello%sWorld", " ")); const char* value = "World"; EXPECT_EQ("Hello World", StringFormat("Hello %s", value)); value = nullptr; EXPECT_EQ("Hello null", StringFormat("Hello %s", value)); } TEST(StringFormatTest, String) { EXPECT_EQ("Hello World", StringFormat("Hello %s", std::string{"World"})); std::string value{"World"}; EXPECT_EQ("Hello World", StringFormat("Hello %s", value)); } TEST(StringFormatTest, StringView) { EXPECT_EQ("Hello World", StringFormat("Hello %s", absl::string_view{"World"})); EXPECT_EQ("Hello World", StringFormat("%s World", absl::string_view{"Hello"})); EXPECT_EQ("Hello World", StringFormat("Hello%sWorld", absl::string_view{" "})); } TEST(StringFormatTest, Int) { std::string value = StringFormat("Hello %s", 123); EXPECT_EQ("Hello 123", value); } TEST(StringFormatTest, Float) { std::string value = StringFormat("Hello %s", 1.5); EXPECT_EQ("Hello 1.5", value); } TEST(StringFormatTest, Bool) { EXPECT_EQ("Hello true", StringFormat("Hello %s", true)); EXPECT_EQ("Hello false", StringFormat("Hello %s", false)); } TEST(StringFormatTest, Pointer) { // pointers implicitly convert to bool. Make sure this doesn't happen in // this API. int value = 4; EXPECT_NE("Hello true", StringFormat("Hello %s", &value)); EXPECT_EQ("Hello null", StringFormat("Hello %s", nullptr)); } TEST(StringFormatTest, Mixed) { EXPECT_EQ("string=World, bool=true, int=42, float=1.5", StringFormat("string=%s, bool=%s, int=%s, float=%s", "World", true, 42, 1.5)); EXPECT_EQ("World%true%42%1.5", StringFormat("%s%%%s%%%s%%%s", "World", true, 42, 1.5)); } TEST(StringFormatTest, Literal) { EXPECT_EQ("Hello %", StringFormat("Hello %%")); EXPECT_EQ("% World", StringFormat("%% World")); } TEST(StringFormatTest, Invalid) { EXPECT_EQ("Hello <invalid>", StringFormat("Hello %@", 42)); } TEST(StringFormatTest, Missing) { EXPECT_EQ("Hello <missing>", StringFormat("Hello %s")); } TEST(StringFormatTest, Excess) { EXPECT_EQ("Hello World", StringFormat("Hello %s", "World", 42)); } } // namespace util } // namespace firestore } // namespace firebase
apache-2.0
mtrmac/docker
volume/store/store.go
17553
package store import ( "bytes" "encoding/json" "net" "os" "path/filepath" "sync" "time" "github.com/pkg/errors" "github.com/Sirupsen/logrus" "github.com/boltdb/bolt" "github.com/docker/docker/pkg/locker" "github.com/docker/docker/volume" "github.com/docker/docker/volume/drivers" ) const ( volumeDataDir = "volumes" volumeBucketName = "volumes" ) type volumeMetadata struct { Name string Labels map[string]string Options map[string]string } type volumeWrapper struct { volume.Volume labels map[string]string scope string options map[string]string } func (v volumeWrapper) Options() map[string]string { options := map[string]string{} for key, value := range v.options { options[key] = value } return options } func (v volumeWrapper) Labels() map[string]string { return v.labels } func (v volumeWrapper) Scope() string { return v.scope } func (v volumeWrapper) CachedPath() string { if vv, ok := v.Volume.(interface { CachedPath() string }); ok { return vv.CachedPath() } return v.Volume.Path() } // New initializes a VolumeStore to keep // reference counting of volumes in the system. func New(rootPath string) (*VolumeStore, error) { vs := &VolumeStore{ locks: &locker.Locker{}, names: make(map[string]volume.Volume), refs: make(map[string][]string), labels: make(map[string]map[string]string), options: make(map[string]map[string]string), } if rootPath != "" { // initialize metadata store volPath := filepath.Join(rootPath, volumeDataDir) if err := os.MkdirAll(volPath, 750); err != nil { return nil, err } dbPath := filepath.Join(volPath, "metadata.db") var err error vs.db, err = bolt.Open(dbPath, 0600, &bolt.Options{Timeout: 1 * time.Second}) if err != nil { return nil, errors.Wrap(err, "error while opening volume store metadata database") } // initialize volumes bucket if err := vs.db.Update(func(tx *bolt.Tx) error { if _, err := tx.CreateBucketIfNotExists([]byte(volumeBucketName)); err != nil { return errors.Wrap(err, "error while setting up volume store metadata database") } return nil }); err != nil { return nil, err } } return vs, nil } func (s *VolumeStore) getNamed(name string) (volume.Volume, bool) { s.globalLock.Lock() v, exists := s.names[name] s.globalLock.Unlock() return v, exists } func (s *VolumeStore) setNamed(v volume.Volume, ref string) { s.globalLock.Lock() s.names[v.Name()] = v if len(ref) > 0 { s.refs[v.Name()] = append(s.refs[v.Name()], ref) } s.globalLock.Unlock() } // getRefs gets the list of refs for a given name // Callers of this function are expected to hold the name lock. func (s *VolumeStore) getRefs(name string) []string { s.globalLock.Lock() refs := s.refs[name] s.globalLock.Unlock() return refs } // Purge allows the cleanup of internal data on docker in case // the internal data is out of sync with volumes driver plugins. func (s *VolumeStore) Purge(name string) { s.globalLock.Lock() delete(s.names, name) delete(s.refs, name) delete(s.labels, name) delete(s.options, name) s.globalLock.Unlock() } // VolumeStore is a struct that stores the list of volumes available and keeps track of their usage counts type VolumeStore struct { locks *locker.Locker globalLock sync.Mutex // names stores the volume name -> volume relationship. // This is used for making lookups faster so we don't have to probe all drivers names map[string]volume.Volume // refs stores the volume name and the list of things referencing it refs map[string][]string // labels stores volume labels for each volume labels map[string]map[string]string // options stores volume options for each volume options map[string]map[string]string db *bolt.DB } // List proxies to all registered volume drivers to get the full list of volumes // If a driver returns a volume that has name which conflicts with another volume from a different driver, // the first volume is chosen and the conflicting volume is dropped. func (s *VolumeStore) List() ([]volume.Volume, []string, error) { vols, warnings, err := s.list() if err != nil { return nil, nil, &OpErr{Err: err, Op: "list"} } var out []volume.Volume for _, v := range vols { name := normaliseVolumeName(v.Name()) s.locks.Lock(name) storedV, exists := s.getNamed(name) // Note: it's not safe to populate the cache here because the volume may have been // deleted before we acquire a lock on its name if exists && storedV.DriverName() != v.DriverName() { logrus.Warnf("Volume name %s already exists for driver %s, not including volume returned by %s", v.Name(), storedV.DriverName(), v.DriverName()) s.locks.Unlock(v.Name()) continue } out = append(out, v) s.locks.Unlock(v.Name()) } return out, warnings, nil } // list goes through each volume driver and asks for its list of volumes. func (s *VolumeStore) list() ([]volume.Volume, []string, error) { var ( ls []volume.Volume warnings []string ) drivers, err := volumedrivers.GetAllDrivers() if err != nil { return nil, nil, err } type vols struct { vols []volume.Volume err error driverName string } chVols := make(chan vols, len(drivers)) for _, vd := range drivers { go func(d volume.Driver) { vs, err := d.List() if err != nil { chVols <- vols{driverName: d.Name(), err: &OpErr{Err: err, Name: d.Name(), Op: "list"}} return } for i, v := range vs { vs[i] = volumeWrapper{v, s.labels[v.Name()], d.Scope(), s.options[v.Name()]} } chVols <- vols{vols: vs} }(vd) } badDrivers := make(map[string]struct{}) for i := 0; i < len(drivers); i++ { vs := <-chVols if vs.err != nil { warnings = append(warnings, vs.err.Error()) badDrivers[vs.driverName] = struct{}{} logrus.Warn(vs.err) } ls = append(ls, vs.vols...) } if len(badDrivers) > 0 { for _, v := range s.names { if _, exists := badDrivers[v.DriverName()]; exists { ls = append(ls, v) } } } return ls, warnings, nil } // CreateWithRef creates a volume with the given name and driver and stores the ref // This ensures there's no race between creating a volume and then storing a reference. func (s *VolumeStore) CreateWithRef(name, driverName, ref string, opts, labels map[string]string) (volume.Volume, error) { name = normaliseVolumeName(name) s.locks.Lock(name) defer s.locks.Unlock(name) v, err := s.create(name, driverName, opts, labels) if err != nil { return nil, &OpErr{Err: err, Name: name, Op: "create"} } s.setNamed(v, ref) return v, nil } // Create creates a volume with the given name and driver. // This is just like CreateWithRef() except we don't store a reference while holding the lock. func (s *VolumeStore) Create(name, driverName string, opts, labels map[string]string) (volume.Volume, error) { return s.CreateWithRef(name, driverName, "", opts, labels) } // checkConflict checks the local cache for name collisions with the passed in name, // for existing volumes with the same name but in a different driver. // This is used by `Create` as a best effort to prevent name collisions for volumes. // If a matching volume is found that is not a conflict that is returned so the caller // does not need to perform an additional lookup. // When no matching volume is found, both returns will be nil // // Note: This does not probe all the drivers for name collisions because v1 plugins // are very slow, particularly if the plugin is down, and cause other issues, // particularly around locking the store. // TODO(cpuguy83): With v2 plugins this shouldn't be a problem. Could also potentially // use a connect timeout for this kind of check to ensure we aren't blocking for a // long time. func (s *VolumeStore) checkConflict(name, driverName string) (volume.Volume, error) { // check the local cache v, _ := s.getNamed(name) if v != nil { vDriverName := v.DriverName() if driverName != "" && vDriverName != driverName { // we have what looks like a conflict // let's see if there are existing refs to this volume, if so we don't need // to go any further since we can assume the volume is legit. if len(s.getRefs(name)) > 0 { return nil, errors.Wrapf(errNameConflict, "driver '%s' already has volume '%s'", vDriverName, name) } // looks like there is a conflict, but nothing is referencing it... // let's check if the found volume ref // is stale by checking with the driver if it still exists vd, err := volumedrivers.GetDriver(vDriverName) if err != nil { // play it safe and return the error // TODO(cpuguy83): maybe when when v2 plugins are ubiquitous, we should // just purge this from the cache return nil, errors.Wrapf(errNameConflict, "found reference to volume '%s' in driver '%s', but got an error while checking the driver: %v", name, vDriverName, err) } // now check if it still exists in the driver v2, err := vd.Get(name) err = errors.Cause(err) if err != nil { if _, ok := err.(net.Error); ok { // got some error related to the driver connectivity // play it safe and return the error // TODO(cpuguy83): When when v2 plugins are ubiquitous, maybe we should // just purge this from the cache return nil, errors.Wrapf(errNameConflict, "found reference to volume '%s' in driver '%s', but got an error while checking the driver: %v", name, vDriverName, err) } // a driver can return whatever it wants, so let's make sure this is nil if v2 == nil { // purge this reference from the cache s.Purge(name) return nil, nil } } if v2 != nil { return nil, errors.Wrapf(errNameConflict, "driver '%s' already has volume '%s'", vDriverName, name) } } return v, nil } return nil, nil } // create asks the given driver to create a volume with the name/opts. // If a volume with the name is already known, it will ask the stored driver for the volume. // If the passed in driver name does not match the driver name which is stored // for the given volume name, an error is returned after checking if the reference is stale. // If the reference is stale, it will be purged and this create can continue. // It is expected that callers of this function hold any necessary locks. func (s *VolumeStore) create(name, driverName string, opts, labels map[string]string) (volume.Volume, error) { // Validate the name in a platform-specific manner valid, err := volume.IsVolumeNameValid(name) if err != nil { return nil, err } if !valid { return nil, &OpErr{Err: errInvalidName, Name: name, Op: "create"} } v, err := s.checkConflict(name, driverName) if err != nil { return nil, err } if v != nil { return v, nil } // Since there isn't a specified driver name, let's see if any of the existing drivers have this volume name if driverName == "" { v, _ := s.getVolume(name) if v != nil { return v, nil } } vd, err := volumedrivers.CreateDriver(driverName) if err != nil { return nil, &OpErr{Op: "create", Name: name, Err: err} } logrus.Debugf("Registering new volume reference: driver %q, name %q", vd.Name(), name) if v, _ := vd.Get(name); v != nil { return v, nil } v, err = vd.Create(name, opts) if err != nil { return nil, err } s.globalLock.Lock() s.labels[name] = labels s.options[name] = opts s.globalLock.Unlock() if s.db != nil { metadata := &volumeMetadata{ Name: name, Labels: labels, Options: opts, } volData, err := json.Marshal(metadata) if err != nil { return nil, err } if err := s.db.Update(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(volumeBucketName)) err := b.Put([]byte(name), volData) return err }); err != nil { return nil, errors.Wrap(err, "error while persisting volume metadata") } } return volumeWrapper{v, labels, vd.Scope(), opts}, nil } // GetWithRef gets a volume with the given name from the passed in driver and stores the ref // This is just like Get(), but we store the reference while holding the lock. // This makes sure there are no races between checking for the existence of a volume and adding a reference for it func (s *VolumeStore) GetWithRef(name, driverName, ref string) (volume.Volume, error) { name = normaliseVolumeName(name) s.locks.Lock(name) defer s.locks.Unlock(name) vd, err := volumedrivers.GetDriver(driverName) if err != nil { return nil, &OpErr{Err: err, Name: name, Op: "get"} } v, err := vd.Get(name) if err != nil { return nil, &OpErr{Err: err, Name: name, Op: "get"} } s.setNamed(v, ref) return volumeWrapper{v, s.labels[name], vd.Scope(), s.options[name]}, nil } // Get looks if a volume with the given name exists and returns it if so func (s *VolumeStore) Get(name string) (volume.Volume, error) { name = normaliseVolumeName(name) s.locks.Lock(name) defer s.locks.Unlock(name) v, err := s.getVolume(name) if err != nil { return nil, &OpErr{Err: err, Name: name, Op: "get"} } s.setNamed(v, "") return v, nil } // getVolume requests the volume, if the driver info is stored it just accesses that driver, // if the driver is unknown it probes all drivers until it finds the first volume with that name. // it is expected that callers of this function hold any necessary locks func (s *VolumeStore) getVolume(name string) (volume.Volume, error) { labels := map[string]string{} options := map[string]string{} if s.db != nil { // get meta if err := s.db.Update(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(volumeBucketName)) data := b.Get([]byte(name)) if string(data) == "" { return nil } var meta volumeMetadata buf := bytes.NewBuffer(data) if err := json.NewDecoder(buf).Decode(&meta); err != nil { return err } labels = meta.Labels options = meta.Options return nil }); err != nil { return nil, err } } logrus.Debugf("Getting volume reference for name: %s", name) s.globalLock.Lock() v, exists := s.names[name] s.globalLock.Unlock() if exists { vd, err := volumedrivers.GetDriver(v.DriverName()) if err != nil { return nil, err } vol, err := vd.Get(name) if err != nil { return nil, err } return volumeWrapper{vol, labels, vd.Scope(), options}, nil } logrus.Debugf("Probing all drivers for volume with name: %s", name) drivers, err := volumedrivers.GetAllDrivers() if err != nil { return nil, err } for _, d := range drivers { v, err := d.Get(name) if err != nil { continue } return volumeWrapper{v, labels, d.Scope(), options}, nil } return nil, errNoSuchVolume } // Remove removes the requested volume. A volume is not removed if it has any refs func (s *VolumeStore) Remove(v volume.Volume) error { name := normaliseVolumeName(v.Name()) s.locks.Lock(name) defer s.locks.Unlock(name) refs := s.getRefs(name) if len(refs) > 0 { return &OpErr{Err: errVolumeInUse, Name: v.Name(), Op: "remove", Refs: refs} } vd, err := volumedrivers.RemoveDriver(v.DriverName()) if err != nil { return &OpErr{Err: err, Name: vd.Name(), Op: "remove"} } logrus.Debugf("Removing volume reference: driver %s, name %s", v.DriverName(), name) vol := unwrapVolume(v) if err := vd.Remove(vol); err != nil { return &OpErr{Err: err, Name: name, Op: "remove"} } s.Purge(name) return nil } // Dereference removes the specified reference to the volume func (s *VolumeStore) Dereference(v volume.Volume, ref string) { s.locks.Lock(v.Name()) defer s.locks.Unlock(v.Name()) s.globalLock.Lock() defer s.globalLock.Unlock() var refs []string for _, r := range s.refs[v.Name()] { if r != ref { refs = append(refs, r) } } s.refs[v.Name()] = refs } // Refs gets the current list of refs for the given volume func (s *VolumeStore) Refs(v volume.Volume) []string { s.locks.Lock(v.Name()) defer s.locks.Unlock(v.Name()) refs := s.getRefs(v.Name()) refsOut := make([]string, len(refs)) copy(refsOut, refs) return refsOut } // FilterByDriver returns the available volumes filtered by driver name func (s *VolumeStore) FilterByDriver(name string) ([]volume.Volume, error) { vd, err := volumedrivers.GetDriver(name) if err != nil { return nil, &OpErr{Err: err, Name: name, Op: "list"} } ls, err := vd.List() if err != nil { return nil, &OpErr{Err: err, Name: name, Op: "list"} } for i, v := range ls { options := map[string]string{} for key, value := range s.options[v.Name()] { options[key] = value } ls[i] = volumeWrapper{v, s.labels[v.Name()], vd.Scope(), options} } return ls, nil } // FilterByUsed returns the available volumes filtered by if they are in use or not. // `used=true` returns only volumes that are being used, while `used=false` returns // only volumes that are not being used. func (s *VolumeStore) FilterByUsed(vols []volume.Volume, used bool) []volume.Volume { return s.filter(vols, func(v volume.Volume) bool { s.locks.Lock(v.Name()) l := len(s.getRefs(v.Name())) s.locks.Unlock(v.Name()) if (used && l > 0) || (!used && l == 0) { return true } return false }) } // filterFunc defines a function to allow filter volumes in the store type filterFunc func(vol volume.Volume) bool // filter returns the available volumes filtered by a filterFunc function func (s *VolumeStore) filter(vols []volume.Volume, f filterFunc) []volume.Volume { var ls []volume.Volume for _, v := range vols { if f(v) { ls = append(ls, v) } } return ls } func unwrapVolume(v volume.Volume) volume.Volume { if vol, ok := v.(volumeWrapper); ok { return vol.Volume } return v }
apache-2.0
GaneshSPatil/gocd
api/api-stage-instance-v2/src/main/java/com/thoughtworks/go/apiv2/stageinstance/representers/StageRepresenter.java
2383
/* * Copyright 2021 ThoughtWorks, 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. */ package com.thoughtworks.go.apiv2.stageinstance.representers; import com.thoughtworks.go.api.base.OutputWriter; import com.thoughtworks.go.domain.Stage; import com.thoughtworks.go.domain.StageResult; public class StageRepresenter { public static void toJSON(OutputWriter jsonWriter, Stage stage) { jsonWriter.add("name", stage.getName()); jsonWriter.add("counter", stage.getCounter()); jsonWriter.add("approval_type", stage.getApprovalType()); jsonWriter.add("approved_by", stage.getApprovedBy()); if (stage.getResult() != null) { jsonWriter.add("result", stage.getResult().toString()); if (stage.getResult() == StageResult.Cancelled) { jsonWriter.add("cancelled_by", stage.getCancelledBy() == null? "GoCD" : stage.getCancelledBy()); } } if (stage.getRerunOfCounter() == null) { jsonWriter.add("rerun_of_counter", (String) null); } else { jsonWriter.add("rerun_of_counter", stage.getRerunOfCounter()); } jsonWriter.add("fetch_materials", stage.shouldFetchMaterials()); jsonWriter.add("clean_working_directory", stage.shouldCleanWorkingDir()); jsonWriter.add("artifacts_deleted", stage.isArtifactsDeleted()); if (stage.getIdentifier() != null) { jsonWriter.add("pipeline_name", stage.getIdentifier().getPipelineName()); jsonWriter.add("pipeline_counter", stage.getIdentifier().getPipelineCounter()); } jsonWriter.addChildList("jobs", jobsWriter -> stage.getJobInstances().forEach( jobInstance -> jobsWriter.addChild( jobInstanceWriter -> JobInstanceRepresenter.toJSON(jobInstanceWriter, jobInstance)))); } }
apache-2.0
brendanluu/CO2BLACK
Co2BlackUnityProject/Assets/Mapbox/Core/Plugins/ThirdParty/Mapbox.IO.Compression/Inflater.cs
27933
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // zlib.h -- interface of the 'zlib' general purpose compression library // version 1.2.1, November 17th, 2003 // // Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // // ==--== namespace Mapbox.IO.Compression { using System; using System.Diagnostics; internal class Inflater { // const tables used in decoding: // Extra bits for length code 257 - 285. private static readonly byte[] extraLengthBits = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; // The base length for length code 257 - 285. // The formula to get the real length for a length code is lengthBase[code - 257] + (value stored in extraBits) private static readonly int[] lengthBase = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258}; // The base distance for distance code 0 - 29 // The real distance for a distance code is distanceBasePosition[code] + (value stored in extraBits) private static readonly int[] distanceBasePosition= { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; // code lengths for code length alphabet is stored in following order private static readonly byte[] codeOrder = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; private static readonly byte[] staticDistanceTreeTable = { 0x00,0x10,0x08,0x18,0x04,0x14,0x0c,0x1c,0x02,0x12,0x0a,0x1a, 0x06,0x16,0x0e,0x1e,0x01,0x11,0x09,0x19,0x05,0x15,0x0d,0x1d, 0x03,0x13,0x0b,0x1b,0x07,0x17,0x0f,0x1f, }; private OutputWindow output; private InputBuffer input; HuffmanTree literalLengthTree; HuffmanTree distanceTree; InflaterState state; bool hasFormatReader; int bfinal; BlockType blockType; // uncompressed block byte[] blockLengthBuffer = new byte[4]; int blockLength; // compressed block private int length; private int distanceCode; private int extraBits; private int loopCounter; private int literalLengthCodeCount; private int distanceCodeCount; private int codeLengthCodeCount; private int codeArraySize; private int lengthCode; private byte[] codeList; // temporary array to store the code length for literal/Length and distance private byte[] codeLengthTreeCodeLength; HuffmanTree codeLengthTree; IFileFormatReader formatReader; // class to decode header and footer (e.g. gzip) public Inflater() { output = new OutputWindow(); input = new InputBuffer(); codeList = new byte[HuffmanTree.MaxLiteralTreeElements + HuffmanTree.MaxDistTreeElements]; codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements]; Reset(); } internal void SetFileFormatReader(IFileFormatReader reader) { formatReader = reader; hasFormatReader = true; Reset(); } private void Reset() { if ( hasFormatReader) { state = InflaterState.ReadingHeader; // start by reading Header info } else { state = InflaterState.ReadingBFinal; // start by reading BFinal bit } } public void SetInput(byte[] inputBytes, int offset, int length) { input.SetInput(inputBytes, offset, length); // append the bytes } public bool Finished() { return (state == InflaterState.Done || state== InflaterState.VerifyingFooter); } public int AvailableOutput{ get { return output.AvailableBytes; } } public bool NeedsInput(){ return input.NeedsInput(); } public int Inflate(byte[] bytes, int offset, int length) { // copy bytes from output to outputbytes if we have aviable bytes // if buffer is not filled up. keep decoding until no input are available // if decodeBlock returns false. Throw an exception. int count = 0; do { int copied = output.CopyTo(bytes, offset, length); if( copied > 0) { if( hasFormatReader) { formatReader.UpdateWithBytesRead(bytes, offset, copied); } offset += copied; count += copied; length -= copied; } if (length == 0) { // filled in the bytes array break; } // Decode will return false when more input is needed } while ( !Finished() && Decode()); if( state == InflaterState.VerifyingFooter) { // finished reading CRC // In this case finished is true and output window has all the data. // But some data in output window might not be copied out. if( output.AvailableBytes == 0) { formatReader.Validate(); } } return count; } //Each block of compressed data begins with 3 header bits // containing the following data: // first bit BFINAL // next 2 bits BTYPE // Note that the header bits do not necessarily begin on a byte // boundary, since a block does not necessarily occupy an integral // number of bytes. // BFINAL is set if and only if this is the last block of the data // set. // BTYPE specifies how the data are compressed, as follows: // 00 - no compression // 01 - compressed with fixed Huffman codes // 10 - compressed with dynamic Huffman codes // 11 - reserved (error) // The only difference between the two compressed cases is how the // Huffman codes for the literal/length and distance alphabets are // defined. // // This function returns true for success (end of block or output window is full,) // false if we are short of input // private bool Decode() { bool eob = false; bool result = false; if( Finished()) { return true; } if (hasFormatReader) { if (state == InflaterState.ReadingHeader) { if (!formatReader.ReadHeader(input)) { return false; } state = InflaterState.ReadingBFinal; } else if (state == InflaterState.StartReadingFooter || state == InflaterState.ReadingFooter) { if (!formatReader.ReadFooter(input)) return false; state = InflaterState.VerifyingFooter; return true; } } if( state == InflaterState.ReadingBFinal) { // reading bfinal bit // Need 1 bit if (!input.EnsureBitsAvailable(1)) return false; bfinal = input.GetBits(1); state = InflaterState.ReadingBType; } if( state == InflaterState.ReadingBType) { // Need 2 bits if (!input.EnsureBitsAvailable(2)) { state = InflaterState.ReadingBType; return false; } blockType = (BlockType)input.GetBits(2); if (blockType == BlockType.Dynamic) { //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "Decoding Dynamic Block", "Compression"); state = InflaterState.ReadingNumLitCodes; } else if (blockType == BlockType.Static) { //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "Decoding Static Block", "Compression"); literalLengthTree = HuffmanTree.StaticLiteralLengthTree; distanceTree = HuffmanTree.StaticDistanceTree; state = InflaterState.DecodeTop; } else if (blockType == BlockType.Uncompressed) { //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "Decoding UnCompressed Block", "Compression"); state = InflaterState.UncompressedAligning; } else { throw new InvalidDataException(SR.GetString(SR.UnknownBlockType)); } } if (blockType == BlockType.Dynamic) { if (state < InflaterState.DecodeTop) { // we are reading the header result = DecodeDynamicBlockHeader(); } else { result = DecodeBlock(out eob); // this can returns true when output is full } } else if (blockType == BlockType.Static) { result = DecodeBlock(out eob); } else if (blockType == BlockType.Uncompressed) { result = DecodeUncompressedBlock(out eob); } else { throw new InvalidDataException(SR.GetString(SR.UnknownBlockType)); } // // If we reached the end of the block and the block we were decoding had // bfinal=1 (final block) // if (eob && (bfinal != 0)) { if (hasFormatReader) state = InflaterState.StartReadingFooter; else state = InflaterState.Done; } return result; } // Format of Non-compressed blocks (BTYPE=00): // // Any bits of input up to the next byte boundary are ignored. // The rest of the block consists of the following information: // // 0 1 2 3 4... // +---+---+---+---+================================+ // | LEN | NLEN |... LEN bytes of literal data...| // +---+---+---+---+================================+ // // LEN is the number of data bytes in the block. NLEN is the // one's complement of LEN. bool DecodeUncompressedBlock(out bool end_of_block) { end_of_block = false; while(true) { switch( state) { case InflaterState.UncompressedAligning: // intial state when calling this function // we must skip to a byte boundary input.SkipToByteBoundary(); state = InflaterState.UncompressedByte1; goto case InflaterState.UncompressedByte1; case InflaterState.UncompressedByte1: // decoding block length case InflaterState.UncompressedByte2: case InflaterState.UncompressedByte3: case InflaterState.UncompressedByte4: int bits = input.GetBits(8); if( bits < 0) { return false; } blockLengthBuffer[state - InflaterState.UncompressedByte1] = (byte)bits; if( state == InflaterState.UncompressedByte4) { blockLength = blockLengthBuffer[0] + ((int)blockLengthBuffer[1]) * 256; int blockLengthComplement= blockLengthBuffer[2] + ((int)blockLengthBuffer[3]) * 256; // make sure complement matches if ((ushort) blockLength != (ushort)(~blockLengthComplement)) { throw new InvalidDataException(SR.GetString(SR.InvalidBlockLength)); } } state += 1; break; case InflaterState.DecodingUncompressed: // copying block data // Directly copy bytes from input to output. int bytesCopied = output.CopyFrom(input, blockLength); blockLength -= bytesCopied; if (blockLength == 0) { // Done with this block, need to re-init bit buffer for next block state = InflaterState.ReadingBFinal; end_of_block = true; //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "End of Block", "Compression"); return true; } // We can fail to copy all bytes for two reasons: // Running out of Input // running out of free space in output window if(output.FreeBytes == 0) { return true; } return false; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.GetString(SR.UnknownState)); } } } bool DecodeBlock(out bool end_of_block_code_seen) { end_of_block_code_seen = false; int freeBytes = output.FreeBytes; // it is a little bit faster than frequently accessing the property while(freeBytes > 258) { // 258 means we can safely do decoding since maximum repeat length is 258 int symbol; switch (state) { case InflaterState.DecodeTop: // decode an element from the literal tree // symbol = literalLengthTree.GetNextSymbol(input); if( symbol < 0) { // running out of input return false; } if (symbol < 256) { // literal output.Write((byte)symbol); --freeBytes; } else if( symbol == 256) { // end of block end_of_block_code_seen = true; //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "End of Block", "Compression"); // Reset state state = InflaterState.ReadingBFinal; return true; // *********** } else { // length/distance pair symbol -= 257; // length code started at 257 if( symbol < 8) { symbol += 3; // match length = 3,4,5,6,7,8,9,10 extraBits = 0; } else if( symbol == 28) { // extra bits for code 285 is 0 symbol = 258; // code 285 means length 258 extraBits = 0; } else { if( symbol < 0 || symbol >= extraLengthBits.Length ) { throw new InvalidDataException(SR.GetString(SR.GenericInvalidData)); } extraBits = extraLengthBits[symbol]; Debug.Assert(extraBits != 0, "We handle other cases seperately!"); } length = symbol; goto case InflaterState.HaveInitialLength; } break; case InflaterState.HaveInitialLength: if( extraBits > 0) { state = InflaterState.HaveInitialLength; int bits = input.GetBits(extraBits); if( bits < 0) { return false; } if( length < 0 || length >= lengthBase.Length ) { throw new InvalidDataException(SR.GetString(SR.GenericInvalidData)); } length = lengthBase[length] + bits; } state = InflaterState.HaveFullLength; goto case InflaterState.HaveFullLength; case InflaterState.HaveFullLength: if( blockType == BlockType.Dynamic) { distanceCode = distanceTree.GetNextSymbol(input); } else { // get distance code directly for static block distanceCode = input.GetBits(5); if( distanceCode >= 0 ) { distanceCode = staticDistanceTreeTable[distanceCode]; } } if( distanceCode < 0) { // running out input return false; } state = InflaterState.HaveDistCode; goto case InflaterState.HaveDistCode; case InflaterState.HaveDistCode: // To avoid a table lookup we note that for distanceCode >= 2, // extra_bits = (distanceCode-2) >> 1 int offset; if( distanceCode > 3) { extraBits = (distanceCode-2) >> 1; int bits = input.GetBits(extraBits); if( bits < 0 ) { return false; } offset = distanceBasePosition[distanceCode] + bits; } else { offset = distanceCode + 1; } Debug.Assert(freeBytes>= 258, "following operation is not safe!"); output.WriteLengthDistance(length, offset); freeBytes -= length; state = InflaterState.DecodeTop; break; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.GetString(SR.UnknownState)); } } return true; } // Format of the dynamic block header: // 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286) // 5 Bits: HDIST, # of Distance codes - 1 (1 - 32) // 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19) // // (HCLEN + 4) x 3 bits: code lengths for the code length // alphabet given just above, in the order: 16, 17, 18, // 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 // // These code lengths are interpreted as 3-bit integers // (0-7); as above, a code length of 0 means the // corresponding symbol (literal/length or distance code // length) is not used. // // HLIT + 257 code lengths for the literal/length alphabet, // encoded using the code length Huffman code // // HDIST + 1 code lengths for the distance alphabet, // encoded using the code length Huffman code // // The code length repeat codes can cross from HLIT + 257 to the // HDIST + 1 code lengths. In other words, all code lengths form // a single sequence of HLIT + HDIST + 258 values. bool DecodeDynamicBlockHeader() { switch (state) { case InflaterState.ReadingNumLitCodes: literalLengthCodeCount = input.GetBits(5); if( literalLengthCodeCount < 0) { return false; } literalLengthCodeCount += 257; state = InflaterState.ReadingNumDistCodes; goto case InflaterState.ReadingNumDistCodes; case InflaterState.ReadingNumDistCodes: distanceCodeCount = input.GetBits(5); if( distanceCodeCount < 0) { return false; } distanceCodeCount += 1; state = InflaterState.ReadingNumCodeLengthCodes; goto case InflaterState.ReadingNumCodeLengthCodes; case InflaterState.ReadingNumCodeLengthCodes: codeLengthCodeCount = input.GetBits(4); if( codeLengthCodeCount < 0) { return false; } codeLengthCodeCount += 4; loopCounter = 0; state = InflaterState.ReadingCodeLengthCodes; goto case InflaterState.ReadingCodeLengthCodes; case InflaterState.ReadingCodeLengthCodes: while(loopCounter < codeLengthCodeCount) { int bits = input.GetBits(3); if( bits < 0) { return false; } codeLengthTreeCodeLength[codeOrder[loopCounter]] = (byte)bits; ++loopCounter; } for (int i = codeLengthCodeCount; i < codeOrder.Length; i++) { codeLengthTreeCodeLength[ codeOrder[i] ] = 0; } // create huffman tree for code length codeLengthTree = new HuffmanTree(codeLengthTreeCodeLength); codeArraySize = literalLengthCodeCount + distanceCodeCount; loopCounter = 0; // reset loop count state = InflaterState.ReadingTreeCodesBefore; goto case InflaterState.ReadingTreeCodesBefore; case InflaterState.ReadingTreeCodesBefore: case InflaterState.ReadingTreeCodesAfter: while (loopCounter < codeArraySize) { if( state == InflaterState.ReadingTreeCodesBefore) { if( (lengthCode = codeLengthTree.GetNextSymbol(input)) < 0) { return false; } } // The alphabet for code lengths is as follows: // 0 - 15: Represent code lengths of 0 - 15 // 16: Copy the previous code length 3 - 6 times. // The next 2 bits indicate repeat length // (0 = 3, ... , 3 = 6) // Example: Codes 8, 16 (+2 bits 11), // 16 (+2 bits 10) will expand to // 12 code lengths of 8 (1 + 6 + 5) // 17: Repeat a code length of 0 for 3 - 10 times. // (3 bits of length) // 18: Repeat a code length of 0 for 11 - 138 times // (7 bits of length) if (lengthCode <= 15) { codeList[loopCounter++] = (byte)lengthCode; } else { if( !input.EnsureBitsAvailable(7)) { // it doesn't matter if we require more bits here state = InflaterState.ReadingTreeCodesAfter; return false; } int repeatCount; if (lengthCode == 16) { if (loopCounter == 0) { // can't have "prev code" on first code throw new InvalidDataException(); } byte previousCode = codeList[loopCounter-1]; repeatCount = input.GetBits(2) + 3; if (loopCounter + repeatCount > codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { codeList[loopCounter++] = previousCode; } } else if (lengthCode == 17) { repeatCount = input.GetBits(3) + 3; if (loopCounter + repeatCount > codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { codeList[loopCounter++] = 0; } } else { // code == 18 repeatCount = input.GetBits(7) + 11; if (loopCounter + repeatCount > codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { codeList[loopCounter++] = 0; } } } state = InflaterState.ReadingTreeCodesBefore; // we want to read the next code. } break; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.GetString(SR.UnknownState)); } byte[] literalTreeCodeLength = new byte[HuffmanTree.MaxLiteralTreeElements]; byte[] distanceTreeCodeLength = new byte[HuffmanTree.MaxDistTreeElements]; // Create literal and distance tables Array.Copy(codeList, literalTreeCodeLength, literalLengthCodeCount); Array.Copy(codeList, literalLengthCodeCount, distanceTreeCodeLength, 0, distanceCodeCount); // Make sure there is an end-of-block code, otherwise how could we ever end? if (literalTreeCodeLength[HuffmanTree.EndOfBlockCode] == 0) { throw new InvalidDataException(); } literalLengthTree = new HuffmanTree(literalTreeCodeLength); distanceTree = new HuffmanTree(distanceTreeCodeLength); state = InflaterState.DecodeTop; return true; } } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-sheets/v4/1.30.1/com/google/api/services/sheets/v4/model/DimensionGroup.java
4841
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.sheets.v4.model; /** * A group over an interval of rows or columns on a sheet, which can contain or be contained within * other groups. A group can be collapsed or expanded as a unit on the sheet. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Google Sheets API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class DimensionGroup extends com.google.api.client.json.GenericJson { /** * This field is true if this group is collapsed. A collapsed group remains collapsed if an * overlapping group at a shallower depth is expanded. A true value does not imply that all * dimensions within the group are hidden, since a dimension's visibility can change independently * from this group property. However, when this property is updated, all dimensions within it are * set to hidden if this field is true, or set to visible if this field is false. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean collapsed; /** * The depth of the group, representing how many groups have a range that wholly contains the * range of this group. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer depth; /** * The range over which this group exists. * The value may be {@code null}. */ @com.google.api.client.util.Key private DimensionRange range; /** * This field is true if this group is collapsed. A collapsed group remains collapsed if an * overlapping group at a shallower depth is expanded. A true value does not imply that all * dimensions within the group are hidden, since a dimension's visibility can change independently * from this group property. However, when this property is updated, all dimensions within it are * set to hidden if this field is true, or set to visible if this field is false. * @return value or {@code null} for none */ public java.lang.Boolean getCollapsed() { return collapsed; } /** * This field is true if this group is collapsed. A collapsed group remains collapsed if an * overlapping group at a shallower depth is expanded. A true value does not imply that all * dimensions within the group are hidden, since a dimension's visibility can change independently * from this group property. However, when this property is updated, all dimensions within it are * set to hidden if this field is true, or set to visible if this field is false. * @param collapsed collapsed or {@code null} for none */ public DimensionGroup setCollapsed(java.lang.Boolean collapsed) { this.collapsed = collapsed; return this; } /** * The depth of the group, representing how many groups have a range that wholly contains the * range of this group. * @return value or {@code null} for none */ public java.lang.Integer getDepth() { return depth; } /** * The depth of the group, representing how many groups have a range that wholly contains the * range of this group. * @param depth depth or {@code null} for none */ public DimensionGroup setDepth(java.lang.Integer depth) { this.depth = depth; return this; } /** * The range over which this group exists. * @return value or {@code null} for none */ public DimensionRange getRange() { return range; } /** * The range over which this group exists. * @param range range or {@code null} for none */ public DimensionGroup setRange(DimensionRange range) { this.range = range; return this; } @Override public DimensionGroup set(String fieldName, Object value) { return (DimensionGroup) super.set(fieldName, value); } @Override public DimensionGroup clone() { return (DimensionGroup) super.clone(); } }
apache-2.0
thomasbecker/jetty-7
jetty-server/src/main/java/org/eclipse/jetty/server/ResourceCache.java
17092
// ======================================================================== // Copyright (c) 2000-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.server; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Comparator; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.eclipse.jetty.http.HttpContent; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.View; import org.eclipse.jetty.io.nio.DirectNIOBuffer; import org.eclipse.jetty.io.nio.IndirectNIOBuffer; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.resource.ResourceFactory; /* ------------------------------------------------------------ */ /** * */ public class ResourceCache { private static final Logger LOG = Log.getLogger(ResourceCache.class); private final ConcurrentMap<String,Content> _cache; private final AtomicInteger _cachedSize; private final AtomicInteger _cachedFiles; private final ResourceFactory _factory; private final ResourceCache _parent; private final MimeTypes _mimeTypes; private boolean _useFileMappedBuffer=true; private int _maxCachedFileSize =4*1024*1024; private int _maxCachedFiles=2048; private int _maxCacheSize =32*1024*1024; /* ------------------------------------------------------------ */ public ResourceCache(ResourceCache parent, ResourceFactory factory, MimeTypes mimeTypes,boolean useFileMappedBuffer) { this(parent,factory,mimeTypes); setUseFileMappedBuffer(useFileMappedBuffer); } /* ------------------------------------------------------------ */ /** Constructor. * @param mimeTypes Mimetype to use for meta data */ public ResourceCache(ResourceCache parent, ResourceFactory factory, MimeTypes mimeTypes) { _factory = factory; _cache=new ConcurrentHashMap<String,Content>(); _cachedSize=new AtomicInteger(); _cachedFiles=new AtomicInteger(); _mimeTypes=mimeTypes; _parent=parent; } /* ------------------------------------------------------------ */ public int getCachedSize() { return _cachedSize.get(); } /* ------------------------------------------------------------ */ public int getCachedFiles() { return _cachedFiles.get(); } /* ------------------------------------------------------------ */ public int getMaxCachedFileSize() { return _maxCachedFileSize; } /* ------------------------------------------------------------ */ public void setMaxCachedFileSize(int maxCachedFileSize) { _maxCachedFileSize = maxCachedFileSize; shrinkCache(); } /* ------------------------------------------------------------ */ public int getMaxCacheSize() { return _maxCacheSize; } /* ------------------------------------------------------------ */ public void setMaxCacheSize(int maxCacheSize) { _maxCacheSize = maxCacheSize; shrinkCache(); } /* ------------------------------------------------------------ */ /** * @return Returns the maxCachedFiles. */ public int getMaxCachedFiles() { return _maxCachedFiles; } /* ------------------------------------------------------------ */ /** * @param maxCachedFiles The maxCachedFiles to set. */ public void setMaxCachedFiles(int maxCachedFiles) { _maxCachedFiles = maxCachedFiles; shrinkCache(); } /* ------------------------------------------------------------ */ public boolean isUseFileMappedBuffer() { return _useFileMappedBuffer; } /* ------------------------------------------------------------ */ public void setUseFileMappedBuffer(boolean useFileMappedBuffer) { _useFileMappedBuffer = useFileMappedBuffer; } /* ------------------------------------------------------------ */ public void flushCache() { if (_cache!=null) { while (_cache.size()>0) { for (String path : _cache.keySet()) { Content content = _cache.remove(path); if (content!=null) content.invalidate(); } } } } /* ------------------------------------------------------------ */ /** Get a Entry from the cache. * Get either a valid entry object or create a new one if possible. * * @param pathInContext The key into the cache * @return The entry matching <code>pathInContext</code>, or a new entry * if no matching entry was found. If the content exists but is not cachable, * then a {@link HttpContent.ResourceAsHttpContent} instance is return. If * the resource does not exist, then null is returned. * @throws IOException Problem loading the resource */ public HttpContent lookup(String pathInContext) throws IOException { // Is the content in this cache? Content content =_cache.get(pathInContext); if (content!=null && (content).isValid()) return content; // try loading the content from our factory. Resource resource=_factory.getResource(pathInContext); HttpContent loaded = load(pathInContext,resource); if (loaded!=null) return loaded; // Is the content in the parent cache? if (_parent!=null) { HttpContent httpContent=_parent.lookup(pathInContext); if (httpContent!=null) return httpContent; } return null; } /* ------------------------------------------------------------ */ /** * @param resource * @return True if the resource is cacheable. The default implementation tests the cache sizes. */ protected boolean isCacheable(Resource resource) { long len = resource.length(); // Will it fit in the cache? return (len>0 && len<_maxCachedFileSize && len<_maxCacheSize); } /* ------------------------------------------------------------ */ private HttpContent load(String pathInContext, Resource resource) throws IOException { Content content=null; if (resource==null || !resource.exists()) return null; // Will it fit in the cache? if (!resource.isDirectory() && isCacheable(resource)) { // Create the Content (to increment the cache sizes before adding the content content = new Content(pathInContext,resource); // reduce the cache to an acceptable size. shrinkCache(); // Add it to the cache. Content added = _cache.putIfAbsent(pathInContext,content); if (added!=null) { content.invalidate(); content=added; } return content; } return new HttpContent.ResourceAsHttpContent(resource,_mimeTypes.getMimeByExtension(resource.toString()),getMaxCachedFileSize()); } /* ------------------------------------------------------------ */ private void shrinkCache() { // While we need to shrink while (_cache.size()>0 && (_cachedFiles.get()>_maxCachedFiles || _cachedSize.get()>_maxCacheSize)) { // Scan the entire cache and generate an ordered list by last accessed time. SortedSet<Content> sorted= new TreeSet<Content>( new Comparator<Content>() { public int compare(Content c1, Content c2) { if (c1._lastAccessed<c2._lastAccessed) return -1; if (c1._lastAccessed>c2._lastAccessed) return 1; if (c1._length<c2._length) return -1; return c1._key.compareTo(c2._key); } }); for (Content content : _cache.values()) sorted.add(content); // Invalidate least recently used first for (Content content : sorted) { if (_cachedFiles.get()<=_maxCachedFiles && _cachedSize.get()<=_maxCacheSize) break; if (content==_cache.remove(content.getKey())) content.invalidate(); } } } /* ------------------------------------------------------------ */ protected Buffer getIndirectBuffer(Resource resource) { try { int len=(int)resource.length(); if (len<0) { LOG.warn("invalid resource: "+String.valueOf(resource)+" "+len); return null; } Buffer buffer = new IndirectNIOBuffer(len); InputStream is = resource.getInputStream(); buffer.readFrom(is,len); is.close(); return buffer; } catch(IOException e) { LOG.warn(e); return null; } } /* ------------------------------------------------------------ */ protected Buffer getDirectBuffer(Resource resource) { try { if (_useFileMappedBuffer && resource.getFile()!=null) return new DirectNIOBuffer(resource.getFile()); int len=(int)resource.length(); if (len<0) { LOG.warn("invalid resource: "+String.valueOf(resource)+" "+len); return null; } Buffer buffer = new DirectNIOBuffer(len); InputStream is = resource.getInputStream(); buffer.readFrom(is,len); is.close(); return buffer; } catch(IOException e) { LOG.warn(e); return null; } } /* ------------------------------------------------------------ */ public String toString() { return "ResourceCache["+_parent+","+_factory+"]@"+hashCode(); } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /** MetaData associated with a context Resource. */ public class Content implements HttpContent { final Resource _resource; final int _length; final String _key; final long _lastModified; final Buffer _lastModifiedBytes; final Buffer _contentType; volatile long _lastAccessed; AtomicReference<Buffer> _indirectBuffer=new AtomicReference<Buffer>(); AtomicReference<Buffer> _directBuffer=new AtomicReference<Buffer>(); /* ------------------------------------------------------------ */ Content(String pathInContext,Resource resource) { _key=pathInContext; _resource=resource; _contentType=_mimeTypes.getMimeByExtension(_resource.toString()); boolean exists=resource.exists(); _lastModified=exists?resource.lastModified():-1; _lastModifiedBytes=_lastModified<0?null:new ByteArrayBuffer(HttpFields.formatDate(_lastModified)); _length=exists?(int)resource.length():0; _cachedSize.addAndGet(_length); _cachedFiles.incrementAndGet(); _lastAccessed=System.currentTimeMillis(); } /* ------------------------------------------------------------ */ public String getKey() { return _key; } /* ------------------------------------------------------------ */ public boolean isCached() { return _key!=null; } /* ------------------------------------------------------------ */ public boolean isMiss() { return false; } /* ------------------------------------------------------------ */ public Resource getResource() { return _resource; } /* ------------------------------------------------------------ */ boolean isValid() { if (_lastModified==_resource.lastModified()) { _lastAccessed=System.currentTimeMillis(); return true; } if (this==_cache.remove(_key)) invalidate(); return false; } /* ------------------------------------------------------------ */ protected void invalidate() { // Invalidate it _cachedSize.addAndGet(-_length); _cachedFiles.decrementAndGet(); _resource.release(); } /* ------------------------------------------------------------ */ public Buffer getLastModified() { return _lastModifiedBytes; } /* ------------------------------------------------------------ */ public Buffer getContentType() { return _contentType; } /* ------------------------------------------------------------ */ public void release() { // don't release while cached. Release when invalidated. } /* ------------------------------------------------------------ */ public Buffer getIndirectBuffer() { Buffer buffer = _indirectBuffer.get(); if (buffer==null) { Buffer buffer2=ResourceCache.this.getIndirectBuffer(_resource); if (buffer2==null) LOG.warn("Could not load "+this); else if (_indirectBuffer.compareAndSet(null,buffer2)) buffer=buffer2; else buffer=_indirectBuffer.get(); } if (buffer==null) return null; return new View(buffer); } /* ------------------------------------------------------------ */ public Buffer getDirectBuffer() { Buffer buffer = _directBuffer.get(); if (buffer==null) { Buffer buffer2=ResourceCache.this.getDirectBuffer(_resource); if (buffer2==null) LOG.warn("Could not load "+this); else if (_directBuffer.compareAndSet(null,buffer2)) buffer=buffer2; else buffer=_directBuffer.get(); } if (buffer==null) return null; return new View(buffer); } /* ------------------------------------------------------------ */ public long getContentLength() { return _length; } /* ------------------------------------------------------------ */ public InputStream getInputStream() throws IOException { Buffer indirect = getIndirectBuffer(); if (indirect!=null && indirect.array()!=null) return new ByteArrayInputStream(indirect.array(),indirect.getIndex(),indirect.length()); return _resource.getInputStream(); } /* ------------------------------------------------------------ */ @Override public String toString() { return String.format("%s %s %d %s %s",_resource,_resource.exists(),_resource.lastModified(),_contentType,_lastModifiedBytes); } } }
apache-2.0
jamox/google-api-ruby-client
generated/google/apis/content_v2/service.rb
102263
# Copyright 2015 Google 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. require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module ContentV2 # Content API for Shopping # # Manage product items, inventory, and Merchant Center accounts for Google # Shopping. # # @example # require 'google/apis/content_v2' # # Content = Google::Apis::ContentV2 # Alias the module # service = Content::ShoppingContentService.new # # @see https://developers.google.com/shopping-content/v2/ class ShoppingContentService < Google::Apis::Core::BaseService # @return [String] # API key. Your API key identifies your project and provides you with API access, # quota, and reports. Required unless you provide an OAuth 2.0 token. attr_accessor :key # @return [String] # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. attr_accessor :quota_user # @return [String] # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. attr_accessor :user_ip def initialize super('https://www.googleapis.com/', 'content/v2/') end # Returns information about the authenticated user. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::AccountsAuthInfoResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::AccountsAuthInfoResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_account_authinfo(fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'accounts/authinfo' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::AccountsAuthInfoResponse::Representation command.response_class = Google::Apis::ContentV2::AccountsAuthInfoResponse command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves, inserts, updates, and deletes multiple Merchant Center (sub-) # accounts in a single request. # @param [Google::Apis::ContentV2::BatchAccountsRequest] batch_accounts_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchAccountsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchAccountsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_account(batch_accounts_request_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'accounts/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchAccountsRequest::Representation command.request_object = batch_accounts_request_object command.response_representation = Google::Apis::ContentV2::BatchAccountsResponse::Representation command.response_class = Google::Apis::ContentV2::BatchAccountsResponse command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Deletes a Merchant Center sub-account. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [NilClass] No result returned for this method # @yieldparam err [StandardError] error object if request failed # # @return [void] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def delete_account(merchant_id, account_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounts/{accountId}' command = make_simple_command(:delete, path, options) command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves a Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Account] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Account] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_account(merchant_id, account_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounts/{accountId}' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::Account::Representation command.response_class = Google::Apis::ContentV2::Account command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Creates a Merchant Center sub-account. # @param [String] merchant_id # The ID of the managing account. # @param [Google::Apis::ContentV2::Account] account_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Account] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Account] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def insert_account(merchant_id, account_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounts' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::Account::Representation command.request_object = account_object command.response_representation = Google::Apis::ContentV2::Account::Representation command.response_class = Google::Apis::ContentV2::Account command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Lists the sub-accounts in your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [Fixnum] max_results # The maximum number of accounts to return in the response, used for paging. # @param [String] page_token # The token returned by the previous request. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ListAccountsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ListAccountsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_accounts(merchant_id, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounts' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ListAccountsResponse::Representation command.response_class = Google::Apis::ContentV2::ListAccountsResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['maxResults'] = max_results unless max_results.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates a Merchant Center account. This method supports patch semantics. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account. # @param [Google::Apis::ContentV2::Account] account_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Account] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Account] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_account(merchant_id, account_id, account_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounts/{accountId}' command = make_simple_command(:patch, path, options) command.request_representation = Google::Apis::ContentV2::Account::Representation command.request_object = account_object command.response_representation = Google::Apis::ContentV2::Account::Representation command.response_class = Google::Apis::ContentV2::Account command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates a Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account. # @param [Google::Apis::ContentV2::Account] account_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Account] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Account] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_account(merchant_id, account_id, account_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounts/{accountId}' command = make_simple_command(:put, path, options) command.request_representation = Google::Apis::ContentV2::Account::Representation command.request_object = account_object command.response_representation = Google::Apis::ContentV2::Account::Representation command.response_class = Google::Apis::ContentV2::Account command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves and updates the shipping settings of multiple accounts in a single # request. # @param [Google::Apis::ContentV2::BatchAccountShippingRequest] batch_account_shipping_request_object # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchAccountShippingResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchAccountShippingResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_account_shipping(batch_account_shipping_request_object = nil, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'accountshipping/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchAccountShippingRequest::Representation command.request_object = batch_account_shipping_request_object command.response_representation = Google::Apis::ContentV2::BatchAccountShippingResponse::Representation command.response_class = Google::Apis::ContentV2::BatchAccountShippingResponse command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves the shipping settings of the account. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account for which to get/update account shipping settings. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::AccountShipping] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::AccountShipping] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_account_shipping(merchant_id, account_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accountshipping/{accountId}' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::AccountShipping::Representation command.response_class = Google::Apis::ContentV2::AccountShipping command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Lists the shipping settings of the sub-accounts in your Merchant Center # account. # @param [String] merchant_id # The ID of the managing account. # @param [Fixnum] max_results # The maximum number of shipping settings to return in the response, used for # paging. # @param [String] page_token # The token returned by the previous request. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ListAccountShippingResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ListAccountShippingResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_account_shippings(merchant_id, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accountshipping' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ListAccountShippingResponse::Representation command.response_class = Google::Apis::ContentV2::ListAccountShippingResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['maxResults'] = max_results unless max_results.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates the shipping settings of the account. This method supports patch # semantics. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account for which to get/update account shipping settings. # @param [Google::Apis::ContentV2::AccountShipping] account_shipping_object # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::AccountShipping] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::AccountShipping] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_account_shipping(merchant_id, account_id, account_shipping_object = nil, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accountshipping/{accountId}' command = make_simple_command(:patch, path, options) command.request_representation = Google::Apis::ContentV2::AccountShipping::Representation command.request_object = account_shipping_object command.response_representation = Google::Apis::ContentV2::AccountShipping::Representation command.response_class = Google::Apis::ContentV2::AccountShipping command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates the shipping settings of the account. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account for which to get/update account shipping settings. # @param [Google::Apis::ContentV2::AccountShipping] account_shipping_object # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::AccountShipping] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::AccountShipping] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_account_shipping(merchant_id, account_id, account_shipping_object = nil, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accountshipping/{accountId}' command = make_simple_command(:put, path, options) command.request_representation = Google::Apis::ContentV2::AccountShipping::Representation command.request_object = account_shipping_object command.response_representation = Google::Apis::ContentV2::AccountShipping::Representation command.response_class = Google::Apis::ContentV2::AccountShipping command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # # @param [Google::Apis::ContentV2::BatchAccountStatusesRequest] batch_account_statuses_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchAccountStatusesResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchAccountStatusesResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_account_status(batch_account_statuses_request_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'accountstatuses/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchAccountStatusesRequest::Representation command.request_object = batch_account_statuses_request_object command.response_representation = Google::Apis::ContentV2::BatchAccountStatusesResponse::Representation command.response_class = Google::Apis::ContentV2::BatchAccountStatusesResponse command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves the status of a Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::AccountStatus] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::AccountStatus] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_account_status(merchant_id, account_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accountstatuses/{accountId}' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::AccountStatus::Representation command.response_class = Google::Apis::ContentV2::AccountStatus command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Lists the statuses of the sub-accounts in your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [Fixnum] max_results # The maximum number of account statuses to return in the response, used for # paging. # @param [String] page_token # The token returned by the previous request. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ListAccountStatusesResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ListAccountStatusesResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_account_statuses(merchant_id, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accountstatuses' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ListAccountStatusesResponse::Representation command.response_class = Google::Apis::ContentV2::ListAccountStatusesResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['maxResults'] = max_results unless max_results.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves and updates tax settings of multiple accounts in a single request. # @param [Google::Apis::ContentV2::BatchAccountTaxRequest] batch_account_tax_request_object # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchAccountTaxResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchAccountTaxResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_account_tax(batch_account_tax_request_object = nil, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'accounttax/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchAccountTaxRequest::Representation command.request_object = batch_account_tax_request_object command.response_representation = Google::Apis::ContentV2::BatchAccountTaxResponse::Representation command.response_class = Google::Apis::ContentV2::BatchAccountTaxResponse command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves the tax settings of the account. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account for which to get/update account tax settings. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::AccountTax] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::AccountTax] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_account_tax(merchant_id, account_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounttax/{accountId}' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::AccountTax::Representation command.response_class = Google::Apis::ContentV2::AccountTax command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Lists the tax settings of the sub-accounts in your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [Fixnum] max_results # The maximum number of tax settings to return in the response, used for paging. # @param [String] page_token # The token returned by the previous request. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ListAccountTaxResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ListAccountTaxResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_account_taxes(merchant_id, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounttax' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ListAccountTaxResponse::Representation command.response_class = Google::Apis::ContentV2::ListAccountTaxResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['maxResults'] = max_results unless max_results.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates the tax settings of the account. This method supports patch semantics. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account for which to get/update account tax settings. # @param [Google::Apis::ContentV2::AccountTax] account_tax_object # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::AccountTax] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::AccountTax] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_account_tax(merchant_id, account_id, account_tax_object = nil, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounttax/{accountId}' command = make_simple_command(:patch, path, options) command.request_representation = Google::Apis::ContentV2::AccountTax::Representation command.request_object = account_tax_object command.response_representation = Google::Apis::ContentV2::AccountTax::Representation command.response_class = Google::Apis::ContentV2::AccountTax command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates the tax settings of the account. # @param [String] merchant_id # The ID of the managing account. # @param [String] account_id # The ID of the account for which to get/update account tax settings. # @param [Google::Apis::ContentV2::AccountTax] account_tax_object # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::AccountTax] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::AccountTax] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_account_tax(merchant_id, account_id, account_tax_object = nil, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/accounttax/{accountId}' command = make_simple_command(:put, path, options) command.request_representation = Google::Apis::ContentV2::AccountTax::Representation command.request_object = account_tax_object command.response_representation = Google::Apis::ContentV2::AccountTax::Representation command.response_class = Google::Apis::ContentV2::AccountTax command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['accountId'] = account_id unless account_id.nil? command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # # @param [Google::Apis::ContentV2::BatchDatafeedsRequest] batch_datafeeds_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchDatafeedsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchDatafeedsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_datafeed(batch_datafeeds_request_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'datafeeds/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchDatafeedsRequest::Representation command.request_object = batch_datafeeds_request_object command.response_representation = Google::Apis::ContentV2::BatchDatafeedsResponse::Representation command.response_class = Google::Apis::ContentV2::BatchDatafeedsResponse command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Deletes a datafeed from your Merchant Center account. # @param [String] merchant_id # @param [String] datafeed_id # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [NilClass] No result returned for this method # @yieldparam err [StandardError] error object if request failed # # @return [void] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def delete_datafeed(merchant_id, datafeed_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/datafeeds/{datafeedId}' command = make_simple_command(:delete, path, options) command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['datafeedId'] = datafeed_id unless datafeed_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves a datafeed from your Merchant Center account. # @param [String] merchant_id # @param [String] datafeed_id # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Datafeed] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Datafeed] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_datafeed(merchant_id, datafeed_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/datafeeds/{datafeedId}' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::Datafeed::Representation command.response_class = Google::Apis::ContentV2::Datafeed command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['datafeedId'] = datafeed_id unless datafeed_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Registers a datafeed with your Merchant Center account. # @param [String] merchant_id # @param [Google::Apis::ContentV2::Datafeed] datafeed_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Datafeed] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Datafeed] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def insert_datafeed(merchant_id, datafeed_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/datafeeds' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::Datafeed::Representation command.request_object = datafeed_object command.response_representation = Google::Apis::ContentV2::Datafeed::Representation command.response_class = Google::Apis::ContentV2::Datafeed command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Lists the datafeeds in your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [Fixnum] max_results # The maximum number of products to return in the response, used for paging. # @param [String] page_token # The token returned by the previous request. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ListDatafeedsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ListDatafeedsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_datafeeds(merchant_id, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/datafeeds' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ListDatafeedsResponse::Representation command.response_class = Google::Apis::ContentV2::ListDatafeedsResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['maxResults'] = max_results unless max_results.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates a datafeed of your Merchant Center account. This method supports patch # semantics. # @param [String] merchant_id # @param [String] datafeed_id # @param [Google::Apis::ContentV2::Datafeed] datafeed_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Datafeed] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Datafeed] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_datafeed(merchant_id, datafeed_id, datafeed_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/datafeeds/{datafeedId}' command = make_simple_command(:patch, path, options) command.request_representation = Google::Apis::ContentV2::Datafeed::Representation command.request_object = datafeed_object command.response_representation = Google::Apis::ContentV2::Datafeed::Representation command.response_class = Google::Apis::ContentV2::Datafeed command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['datafeedId'] = datafeed_id unless datafeed_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates a datafeed of your Merchant Center account. # @param [String] merchant_id # @param [String] datafeed_id # @param [Google::Apis::ContentV2::Datafeed] datafeed_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Datafeed] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Datafeed] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_datafeed(merchant_id, datafeed_id, datafeed_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/datafeeds/{datafeedId}' command = make_simple_command(:put, path, options) command.request_representation = Google::Apis::ContentV2::Datafeed::Representation command.request_object = datafeed_object command.response_representation = Google::Apis::ContentV2::Datafeed::Representation command.response_class = Google::Apis::ContentV2::Datafeed command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['datafeedId'] = datafeed_id unless datafeed_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # # @param [Google::Apis::ContentV2::BatchDatafeedStatusesRequest] batch_datafeed_statuses_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchDatafeedStatusesResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchDatafeedStatusesResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_datafeed_status(batch_datafeed_statuses_request_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'datafeedstatuses/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchDatafeedStatusesRequest::Representation command.request_object = batch_datafeed_statuses_request_object command.response_representation = Google::Apis::ContentV2::BatchDatafeedStatusesResponse::Representation command.response_class = Google::Apis::ContentV2::BatchDatafeedStatusesResponse command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves the status of a datafeed from your Merchant Center account. # @param [String] merchant_id # @param [String] datafeed_id # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::DatafeedStatus] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::DatafeedStatus] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_datafeed_status(merchant_id, datafeed_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/datafeedstatuses/{datafeedId}' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::DatafeedStatus::Representation command.response_class = Google::Apis::ContentV2::DatafeedStatus command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['datafeedId'] = datafeed_id unless datafeed_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Lists the statuses of the datafeeds in your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [Fixnum] max_results # The maximum number of products to return in the response, used for paging. # @param [String] page_token # The token returned by the previous request. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ListDatafeedStatusesResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ListDatafeedStatusesResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_datafeed_statuses(merchant_id, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/datafeedstatuses' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ListDatafeedStatusesResponse::Representation command.response_class = Google::Apis::ContentV2::ListDatafeedStatusesResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['maxResults'] = max_results unless max_results.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates price and availability for multiple products or stores in a single # request. # @param [Google::Apis::ContentV2::BatchInventoryRequest] batch_inventory_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchInventoryResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchInventoryResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_inventory(batch_inventory_request_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'inventory/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchInventoryRequest::Representation command.request_object = batch_inventory_request_object command.response_representation = Google::Apis::ContentV2::BatchInventoryResponse::Representation command.response_class = Google::Apis::ContentV2::BatchInventoryResponse command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Updates price and availability of a product in your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [String] store_code # The code of the store for which to update price and availability. Use online # to update price and availability of an online product. # @param [String] product_id # The ID of the product for which to update price and availability. # @param [Google::Apis::ContentV2::SetInventoryRequest] set_inventory_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::SetInventoryResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::SetInventoryResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def set_inventory(merchant_id, store_code, product_id, set_inventory_request_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/inventory/{storeCode}/products/{productId}' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::SetInventoryRequest::Representation command.request_object = set_inventory_request_object command.response_representation = Google::Apis::ContentV2::SetInventoryResponse::Representation command.response_class = Google::Apis::ContentV2::SetInventoryResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['storeCode'] = store_code unless store_code.nil? command.params['productId'] = product_id unless product_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves, inserts, and deletes multiple products in a single request. # @param [Google::Apis::ContentV2::BatchProductsRequest] batch_products_request_object # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchProductsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchProductsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_product(batch_products_request_object = nil, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'products/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchProductsRequest::Representation command.request_object = batch_products_request_object command.response_representation = Google::Apis::ContentV2::BatchProductsResponse::Representation command.response_class = Google::Apis::ContentV2::BatchProductsResponse command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Deletes a product from your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [String] product_id # The ID of the product. # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [NilClass] No result returned for this method # @yieldparam err [StandardError] error object if request failed # # @return [void] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def delete_product(merchant_id, product_id, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/products/{productId}' command = make_simple_command(:delete, path, options) command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['productId'] = product_id unless product_id.nil? command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Retrieves a product from your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [String] product_id # The ID of the product. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Product] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Product] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_product(merchant_id, product_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/products/{productId}' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::Product::Representation command.response_class = Google::Apis::ContentV2::Product command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['productId'] = product_id unless product_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Uploads a product to your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [Google::Apis::ContentV2::Product] product_object # @param [Boolean] dry_run # Flag to run the request in dry-run mode. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::Product] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::Product] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def insert_product(merchant_id, product_object = nil, dry_run: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/products' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::Product::Representation command.request_object = product_object command.response_representation = Google::Apis::ContentV2::Product::Representation command.response_class = Google::Apis::ContentV2::Product command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['dryRun'] = dry_run unless dry_run.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Lists the products in your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [Fixnum] max_results # The maximum number of products to return in the response, used for paging. # @param [String] page_token # The token returned by the previous request. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ListProductsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ListProductsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_products(merchant_id, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/products' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ListProductsResponse::Representation command.response_class = Google::Apis::ContentV2::ListProductsResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['maxResults'] = max_results unless max_results.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Gets the statuses of multiple products in a single request. # @param [Google::Apis::ContentV2::BatchProductStatusesRequest] batch_product_statuses_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::BatchProductStatusesResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::BatchProductStatusesResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def batch_product_status(batch_product_statuses_request_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = 'productstatuses/batch' command = make_simple_command(:post, path, options) command.request_representation = Google::Apis::ContentV2::BatchProductStatusesRequest::Representation command.request_object = batch_product_statuses_request_object command.response_representation = Google::Apis::ContentV2::BatchProductStatusesResponse::Representation command.response_class = Google::Apis::ContentV2::BatchProductStatusesResponse command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Gets the status of a product from your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [String] product_id # The ID of the product. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ProductStatus] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ProductStatus] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_product_status(merchant_id, product_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/productstatuses/{productId}' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ProductStatus::Representation command.response_class = Google::Apis::ContentV2::ProductStatus command.params['merchantId'] = merchant_id unless merchant_id.nil? command.params['productId'] = product_id unless product_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end # Lists the statuses of the products in your Merchant Center account. # @param [String] merchant_id # The ID of the managing account. # @param [Fixnum] max_results # The maximum number of product statuses to return in the response, used for # paging. # @param [String] page_token # The token returned by the previous request. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # Overrides userIp if both are provided. # @param [String] user_ip # IP address of the site where the request originates. Use this if you want to # enforce per-user limits. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::ContentV2::ListProductStatusesResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::ContentV2::ListProductStatusesResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_product_statuses(merchant_id, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block) path = '{merchantId}/productstatuses' command = make_simple_command(:get, path, options) command.response_representation = Google::Apis::ContentV2::ListProductStatusesResponse::Representation command.response_class = Google::Apis::ContentV2::ListProductStatusesResponse command.params['merchantId'] = merchant_id unless merchant_id.nil? command.query['maxResults'] = max_results unless max_results.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? execute_or_queue_command(command, &block) end protected def apply_command_defaults(command) command.query['key'] = key unless key.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? command.query['userIp'] = user_ip unless user_ip.nil? end end end end end
apache-2.0